Compare commits

..
158 Commits
Author SHA1 Message Date
duffyduckandClaude Opus 4.7 a361015ff4 fix: WebSocket max_size hochgedreht — voice_upload sprengte Default 1MB
Symptom: aria-whisper-bridge bekam beim ersten internen stt_request
(via voice_upload mit WAV als base64, ~2.4MB) den Frame zu Gesicht,
default ws-max ist 1MB → mit Close-Code 1009 abgewiesen → Verbindung
tot → naechster stt_request lief in Timeout → lokales Fallback.

Fixes:
- whisper-bridge: max_size=50*1024*1024 in websockets.connect()
  (gleicher Wert wie f5tts-bridge schon hat)
- RVS-Server: maxPayload=50*1024*1024 in WebSocketServer-Optionen,
  damit der Server die Frames nicht selbst auf 1MB cappt bevor er
  sie an die Bridge weiterleitet.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:54:36 +02:00
duffyduckandClaude Opus 4.7 d83b555209 fix(whisper): kein eager preload mehr — wartet auf config-Broadcast
Vorher: Container-Start lud erst 'small' (env default), dann nochmal
das in Diagnostic konfigurierte Modell (z.B. large-v3) wenn die
config-Broadcast vom aria-bridge ankam. Doppelter Download, doppelte
Wartezeit, doppelter VRAM-Peak.

Jetzt:
- Initial wird NICHTS geladen
- aria-bridge sendet die persistierte voice_config.json kurz nach
  RVS-Connect → whisper-bridge sieht den richtigen Modellnamen
- config-Handler erkennt: noch nichts geladen ODER Wechsel
  → loading-Broadcast → ensure_loaded → ready-Broadcast
- stt_request-Handler: gleicher Status-Broadcast falls Race-Condition
  (Spracheingabe in den ersten 1-2s nach Container-Start)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:50:46 +02:00
duffyduck a029267d9d release: bump version to 0.0.5.6 2026-04-24 16:25:53 +02:00
duffyduckandClaude Opus 4.7 8ba6a71a49 feat(app): service_status Banner oben in ChatScreen
App-Pendant zum Diagnostic-Banner. Wenn die Gamebox-Bridges (F5-TTS /
Whisper) ihren Lade-Status broadcasten, zeigt die App oben unter der
Verbindungs-Statusleiste ein farbiges Banner:
  Gelb  = irgendwas laedt   (NICHT wegtippbar)
  Gruen = alles bereit      (tippbar zum Schliessen)
  Rot   = Fehler

Banner aggregiert beide Services in einer Kachel. Dismiss-State wird
zurueckgesetzt sobald irgendein Service wieder in 'loading' geht
(z.B. Modell-Wechsel via Diagnostic).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:24:47 +02:00
duffyduckandClaude Opus 4.7 2f625572fc feat: HF-Cache raus + service_status Banner in Diagnostic
Stefan akzeptiert die ~5min Modell-Download-Zeit nach jedem Container-
Start, dafuer keine 50GB Cache-Bloat mehr und kein Bind-Mount-Verzeichnis
zu pflegen.

- xtts/docker-compose.yml: hf-cache Bind-Mount entfernt fuer beide
  Bridges. Modelle werden im writable Container-Layer abgelegt und mit
  jedem `docker compose down` automatisch weggeraeumt.
- xtts/.gitignore: hf-cache/ Eintrag raus
- RVS ALLOWED_TYPES: service_status hinzu

Bridges broadcasten Lade-Status:
- f5tts-bridge: bei Connect 'loading' -> ensure_loaded -> 'ready'.
  Auch bei config-getriggertem Modell-Wechsel: erst 'loading' Broadcast,
  dann reload, dann 'ready'.
- whisper-bridge: gleiches Pattern. Modell wird jetzt erst nach
  RVS-Connect geladen damit der loading-Broadcast tatsaechlich rausgeht.

Diagnostic:
- server.js: service_status wird an Browser durchgereicht
- index.html: neues Banner unten rechts (fixed position) zeigt Status
  fuer beide Services. Aggregiert: Icon ist Lupe waehrend Loading,
  Check wenn alles ready, X bei Error.
- Wenn alles ready: X-Button erscheint (manuell schliessen) +
  nach 8s automatisches Fade-Out.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:21:19 +02:00
duffyduckandClaude Opus 4.7 ac56916eb0 fix(android): minSdkVersion 23 -> 24 (Porcupine erfordert Android 7+)
@picovoice/porcupine-react-native deklariert minSdkVersion 24, dadurch
schlug der Manifest-Merger fehl wenn die App weiter auf 23 stand.
Android 7.0 ist eh das pragmatische Minimum (Geraete <7.0 sind <1% Markt).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:08:10 +02:00
duffyduckandClaude Opus 4.7 ae08a5051c fix(deps): porcupine-react-native 3.0.6 existiert nicht — auf 3.0.5 pinnen
3.0.6 war geraten und gibt's nicht im npm Registry. Aktuelle stabile 3.x
ist 3.0.5; 4.0.0 hat Breaking Changes. Beide Picovoice-Packages auf
exakte Version gepinnt damit keine Auto-Bumps fies werden.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:03:35 +02:00
duffyduckandClaude Opus 4.7 d372cd638e release: bump version to 0.0.5.5
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:02:37 +02:00
duffyduckandClaude Opus 4.7 60c5cb7e59 fix(cleanup-windows): ASCII-only damit Windows-PowerShell 5.1 parsen kann
Windows-PowerShell 5.1 liest .ps1 ohne UTF-8 BOM als Windows-1252;
em-dashes (-), Pfeile (->), Box-Zeichen, Emojis (OK/FAIL/WARN) wurden
als Mojibake interpretiert ("â€"" fuer "-") und sprengten den Parser.

Loesung: alle Sonderzeichen durch ASCII-Aequivalente ersetzt:
  - "-" / "->" statt em-dash / Pfeil
  - "===" statt Box-Linien
  - "[OK]" / "[FAIL]" / "[WARN]" statt Emojis
Funktioniert jetzt zuverlaessig auf jeder Windows-PS-Version ohne BOM.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 16:01:56 +02:00
duffyduckandClaude Opus 4.7 607a4c9ff8 add: cleanup-windows Self-Elevation + .bat-Wrapper
cleanup-windows.ps1:
  - Defensive Set-ExecutionPolicy Bypass am Anfang
  - Self-Elevation: wenn nicht als Admin gestartet, relauncht das Script
    sich selbst als Admin mit -ExecutionPolicy Bypass + Original-Args.
    User muss nur einmal UAC bestaetigen, kein extra Befehl mehr noetig.

cleanup-windows.bat:
  - Wrapper der powershell.exe mit -ExecutionPolicy Bypass aufruft.
  - Funktioniert auch wenn Windows die .ps1 direkt blockt (z.B. unsignierte
    Scripts global gesperrt).
  - Aufruf: cleanup-windows.bat stefan [-SkipPrune] [-PruneOnly]

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:59:55 +02:00
duffyduckandClaude Opus 4.7 4ea16cfa8f add: cleanup-windows.ps1 — VHDX-Cleanup fuer Gamebox
Ein Script das auf der Gamebox (Windows + Docker Desktop + WSL2) alle
.vhdx Files findet und via diskpart compactet. Gibt den Speicherplatz
zurueck den man IN den Distros/Containern geloescht hat aber von der
VHDX bisher nicht freigegeben wurde.

Nutzung (PowerShell als ADMIN):
  .\cleanup-windows.ps1 stefan
  .\cleanup-windows.ps1 -User stefan -SkipPrune    # nur compacten
  .\cleanup-windows.ps1 -User stefan -PruneOnly    # nur prune

Default-Flow:
  1. docker system prune -a --volumes -f + builder prune
  2. wsl --shutdown
  3. Alle gefundenen ext4.vhdx (Docker Desktop + WSL-Distros) compacten
     via diskpart 'compact vdisk' (kein Hyper-V noetig)

Zeigt fuer jedes File "vor → nach (gespart X GB)" und am Ende eine
Gesamt-Summary.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:54:27 +02:00
duffyduckandClaude Opus 4.7 6ce9880bc0 fix: HF-Modell-Cache als Bind-Mount statt Docker Volume
Beide Bridges teilen sich jetzt einen Bind-Mount ./hf-cache:/root/.cache/
huggingface. Vorher waren das zwei getrennte Named Volumes
(f5tts-models + whisper-models), die unter Docker Desktop / Windows
in der docker-desktop-data.vhdx gelandet sind und die VHDX nie wieder
freigegeben haben — auch nach docker volume rm bleibt der belegte Platz
in der VHDX bis zum Factory Reset.

Bind-Mount loest beides:
  - Files direkt im xtts/hf-cache/ sichtbar, einfach im Explorer zu loeschen
  - Kein VHDX-Bloat mehr
  - Beide Container teilen sich den Cache (HF-Struktur identisch, keine
    Konflikte da andere Modelle)

Cleanup von vorhandenen 50GB:
  docker compose down
  docker volume rm xtts_f5tts-models xtts_whisper-models  (oder via
    Docker Desktop UI)
  Anschliessend in Docker Desktop: Settings -> Resources -> Disk image
    location -> Disk usage -> "Clean up" / Reset wenn die VHDX nicht
    schrumpft.

xtts/.gitignore: hf-cache/ + voices/ + .env

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:47:18 +02:00
duffyduckandClaude Opus 4.7 187ffad7ee feat: F5-TTS Tuning ueber Diagnostic statt .env
Folgt der "keine neuen Settings in .env" Regel.

f5tts/bridge.py:
  - F5TTS_MODEL/CKPT_FILE/VOCAB_FILE/CFG_STRENGTH/NFE_STEP ENV-Vars raus
  - Hard-coded Defaults im Code (DEFAULT_F5TTS_*)
  - F5Runner besitzt Live-Settings als Instance-Vars + update_config()
  - config-Broadcast triggert Modell-Reload nur wenn Modell-relevantes
    sich aendert (cfg_strength/nfe_step ohne Reload)
  - F5TTS_DEVICE bleibt ENV (Hardware-Bootstrap)

xtts/docker-compose.yml: F5TTS_* ENV-Vars rausgenommen, Kommentar
verweist auf Diagnostic-Config.

aria-bridge: nimmt f5tts*-Felder im config-Handler entgegen, persistiert
sie in voice_config.json. Beim RVS-Connect broadcastet die Bridge die
persistierte Config einmalig — damit die f5tts-bridge nach Container-
Restart automatisch die zuletzt gewaehlten Settings bekommt, ohne dass
der User in Diagnostic was klicken muss.

Diagnostic UI:
  - Neuer aufklappbarer "F5-TTS Modell-Tuning (advanced)" Bereich
  - Felder: Modell-ID, Custom-Checkpoint, Vocab, cfg_strength, nfe_step
  - voice_config beim Laden: Felder werden zurueck in die UI gesetzt
  - sendVoiceConfig schickt die neuen Felder mit
  - Server: send_voice_config persistiert die Felder, leere Strings
    werden geloescht damit die Hard-Defaults greifen

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:44:58 +02:00
duffyduckandClaude Opus 4.7 467f95424e fix: F5-TTS Voice-Referenztext + Standard-Eintrag raus
Bug-Root: voice_upload schrieb "Das ist ein Referenz Audio." als Platzhalter
wenn die whisper-bridge nicht erreichbar war. F5-TTS bekam dann diesen Text
als Sprach-Anker, sah aber im WAV ganz andere Worte → verwirrtes Modell,
halluziniert in beliebiger Sprache (z.B. Spanisch).

Fixes:
- handle_voice_upload: schreibt KEINE Platzhalter-.txt mehr. Bei Failure
  bleibt die .txt weg → naechste TTS-Nutzung zieht via on-the-fly retry
  nach.
- _do_tts: Legacy-Platzhalter wird beim Render erkannt und geloescht,
  Transkription on-the-fly neu angezogen. Bestehende kaputte voices
  reparieren sich automatisch beim ersten Render.

UI-Aufraeumung: F5-TTS hat keine "Standard"-Stimme — der Eintrag ist raus
in App SettingsScreen + Diagnostic. Diagnostic-Dropdown hat jetzt einen
disabled-Hinweis "(keine Stimme gewaehlt)".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:33:53 +02:00
duffyduckandClaude Opus 4.7 c1a5518fb7 fix(f5tts): cfg_strength hochgezogen damit Deutsch nicht ins Spanische rutscht
F5TTS_v1_Base ist hauptsaechlich auf Englisch+Chinesisch trainiert; bei
Deutsch (oder anderen Romance/Germanic-Sprachen) schwimmt der Generator
ohne starkes Conditioning gerne in eine andere Sprache.

- cfg_strength 2.0 → 2.5 (per ENV F5TTS_CFG_STRENGTH ueberschreibbar)
- nfe_step bleibt 32 (per ENV ueberschreibbar)
- F5TTS_CKPT_FILE / F5TTS_VOCAB_FILE als ENV — damit man eine Community-
  German-Checkpoint einhaengen kann ohne Code-Aenderung

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:30:08 +02:00
duffyduckandClaude Opus 4.7 22fa4b3ccf feat: Porcupine Wake-Word Integration (Built-In Keywords, "Jarvis" default)
WakeWordService wrappt jetzt Picovoice Porcupine:
  - loadFromStorage(): Access Key + Keyword aus AsyncStorage, init Porcupine
  - configure(key, keyword): Settings-Wechsel, Re-Init
  - start(): wenn Porcupine bereit → 'armed' (passives Lauschen),
    sonst Fallback auf direktes 'conversing' (klassischer Modus)
  - onWakeDetected: Porcupine pausieren → 'conversing' → wakeCallback
  - endConversation: Porcupine wieder starten → 'armed' (Wake-Word weiter
    aktiv im Hintergrund, kein erneuter Tap noetig)
  - Pro Geraet eigene Wahl: jeder User kann sein eigenes Wake-Word haben

Settings: neuer Bereich "Wake-Word"
  - Picovoice Access Key Input (mit Eye-Toggle), kostenlos auf
    console.picovoice.ai
  - Built-In Keyword Chips: jarvis, computer, picovoice, porcupine,
    bumblebee, terminator, alexa, hey google, ok google, hey siri
  - "Speichern + Aktivieren" Button mit Status-Feedback
  - Hinweis dass "ARIA" Custom-Keyword spaeter via Diagnostic kommt

ChatScreen: ruft wakeWordService.loadFromStorage() beim Mount.

package.json: @picovoice/porcupine-react-native + react-native-voice-processor
hinzugefuegt — npm install + native rebuild noetig.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:23:51 +02:00
duffyduckandClaude Opus 4.7 1b8a51aad0 feat: Conversation-Window — Gespraech endet nach Stille statt Endlos-Loop
Der Gespraechsmodus war bisher ein Endless-Loop: Mikro hat sich nach
jeder ARIA-Antwort wieder geoeffnet bis MAX_RECORDING_MS, danach Speech-
Gate verworfen und neu starten. Das Ohr blieb ewig an.

Neue Logik:
  audio.ts: startRecording(autoStop, noSpeechTimeoutMs?) — wenn der User
    innerhalb des Timeouts nicht anfaengt zu sprechen, wird Stille
    gemeldet → stopRecording → Speech-Gate verwirft → result=null.
  wakeword.ts: drei States off/armed/conversing. start() geht direkt in
    'conversing' (kein Wake-Word verfuegbar; Stub fuer spaetere Porcupine-
    Integration). endConversation() bei No-Speech.
  ChatScreen: Aufnahme bekommt das Window aus AsyncStorage durchgereicht.
    Bei null-Result → endConversation, UI-State synchron.
  Settings: neuer +/- Block "Konversations-Fenster" 3-20s (Default 8).

Mit dem Stub ist die Architektur bereit fuer Porcupine: dann geht
endConversation auf 'armed' statt 'off' und der Wake-Word-Detector
laeuft passiv weiter.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:14:01 +02:00
duffyduckandClaude Opus 4.7 578ade3544 docs: README + issue.md auf Stand mit F5-TTS, Whisper-Gamebox, App-Settings
README:
- Architektur-Diagramm: Gamebox-Stack mit f5tts-bridge + whisper-bridge
- Voice Bridge: STT primaer remote (Gamebox), TTS via F5-TTS
- Diagnostic-Section: Voice-Status, Disk-Voll Banner, Auto-Transkription
- App-Features: VAD-Toleranz/Pre-Roll/Audio-Pause konfigurierbar
- XTTS-Section ersetzt durch "Gamebox-Stack — F5-TTS + Whisper"
- Roadmap Phase 1: alle juengsten Erledigungen ergaenzt

issue.md: alle erledigten Punkte der letzten Iterationen aufgenommen
(Pre-Roll, Decimal-TTS, voice_ready, Whisper-Gamebox, F5-TTS, AudioFocus
Pause, VAD-Setting, ...). Offene Liste auf den aktuellen Stand reduziert.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 14:51:27 +02:00
duffyduck ed2f1bb5ee release: bump version to 0.0.5.4 2026-04-24 14:45:17 +02:00
duffyduckandClaude Opus 4.7 0a04972455 feat: Stille-Toleranz fuer Aufnahme einstellbar in App-Settings
Neuer +/- Block in SettingsScreen → Spracheingabe → "Stille-Toleranz",
1.0-8.0s, Default 2.8s. Wert in AsyncStorage (aria_vad_silence_sec).
audio.ts liest den Wert beim Aufnahme-Start und nutzt ihn fuer den
VAD-Auto-Stop-Schwellwert.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 14:44:17 +02:00
duffyduck 2a4379eb64 release: bump version to 0.0.5.3 2026-04-24 14:41:59 +02:00
duffyduckandClaude Opus 4.7 e64df23bb7 fix: TTS pausiert andere Apps statt zu ducken + VAD/Mic laenger
AudioFocus.requestDuck nutzt jetzt AUDIOFOCUS_GAIN_TRANSIENT (statt
TRANSIENT_MAY_DUCK) — Spotify/YouTube pausieren komplett solange ARIA
spricht und kommen nicht mitten drin wieder hoch.

PcmStreamPlayer.end() resolved jetzt erst wenn der native Writer-Thread
wirklich fertig ist (alle Samples aus dem Pre-Roll-Puffer ausgespielt).
audio.ts wartet entsprechend, bevor AudioFocus.release() gerufen wird —
behebt das "Musik dreht hoch waehrend Antwort noch laeuft"-Problem.

Mic-Aufnahme: VAD_SILENCE_DURATION_MS 1800 → 2800ms (mehr Toleranz fuer
Sprechpausen), MAX_RECORDING_MS 30s → 120s (laengere Erklaerungen
moeglich, Notbremse bleibt).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 14:40:58 +02:00
duffyduckandClaude Opus 4.7 576ae925dd feat(phase2): XTTS durch F5-TTS ersetzt — Voice Cloning auf der Gamebox
Neuer aria-f5tts-bridge Container:
  - Python-Service, laedt F5TTS_v1_Base beim Start
  - Empfaengt xtts_request via RVS, synthetisiert mit Voice-Cloning,
    streamt PCM-Chunks (audio_pcm, 16-bit s16le) wie zuvor die XTTS-Bridge
  - Teilt lange Texte an Satzgrenzen, streamt satzweise
  - Fade-In auf erstem Chunk, Queue gegen parallel-Render

Voice-Management:
  - Speicherort weiterhin /voices/, aber jetzt als Paar
    {name}.wav + {name}.txt (F5-TTS braucht Referenz-Transkription)
  - voice_upload: WAV speichern, intern stt_request an whisper-bridge
    senden, Transkription als .txt ablegen → user muss nichts eintippen
  - On-the-fly Transkribierung: wenn eine WAV ohne .txt liegt, wird
    bei erstem Render/Preload nachgezogen
  - Bestehende RVS-Messages (voice_upload/xtts_list_voices/... etc.)
    bleiben unveraendert → keine App/Diagnostic-Aenderung noetig

Gaming-PC docker-compose:
  - xtts + xtts-bridge Services entfernt
  - f5tts-bridge + whisper-bridge bleiben/kommen rein
  - Volume xtts-models → f5tts-models

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 14:34:11 +02:00
duffyduckandClaude Opus 4.7 e170991222 fix: _send_to_rvs gibt Success-Bool zurueck, _stt_remote bricht bei
Send-Fehler sofort ab statt in den 45s-Timeout zu laufen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 14:16:08 +02:00
duffyduckandClaude Opus 4.7 a1343ee18f debug: Logs beim stt_request-Roundtrip — aria-bridge loggt beim Senden,
whisper-bridge loggt eingehende stt_request (id + Audio-Groesse).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 14:13:41 +02:00
duffyduckandClaude Opus 4.7 b2d3c935d8 fix(whisper): requests explizit als Dependency — faster-whisper 1.0.3
zieht sie selber nicht rein, Container crashed sonst beim Import.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 13:59:59 +02:00
duffyduck 49089eee4b release: bump version to 0.0.5.2 2026-04-24 13:50:19 +02:00
duffyduckandClaude Opus 4.7 e544992c9f feat(phase1): Whisper STT auf die Gamebox ausgelagert
Neuer Container aria-whisper-bridge auf der Gamebox — faster-whisper
CUDA mit float16. Der Container verbindet sich per WebSocket an den RVS,
nimmt stt_request entgegen, laeuft ffmpeg+Whisper, antwortet mit
stt_response. Hoert zusaetzlich auf config-Broadcasts und lädt das
Modell hot-swap bei Diagnostic-Wechsel.

aria-bridge ruft jetzt primaer die Gamebox an; nur wenn die nicht binnen
45s antwortet, faellt auf lokales Whisper (CPU) zurueck. Das lokale
Modell wird lazy geladen, spart RAM auf der VM.

RVS: stt_request/stt_response zur ALLOWED_TYPES-Liste.

Diagnostic-Voice-Config (whisperModel-Feld) bleibt unveraendert —
die Auswahl wird an die Gamebox durchgereicht.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 13:42:07 +02:00
duffyduck 97a1a3089a release: bump version to 0.0.5.1 2026-04-23 22:02:17 +02:00
duffyduck 64f18e97a0 release: bump version to 0.0.5.0 2026-04-23 15:31:18 +02:00
duffyduckandClaude Opus 4.7 9cbea27455 feat: voice_preload/voice_ready — Feedback wenn neue Stimme geladen ist
XTTS-Bridge:
  - empfaengt neuen voice_preload Type, rendert stumm "ja." fuer die Stimme
    via TTS-Queue (damit kein Konflikt mit echtem TTS)
  - horcht zusaetzlich auf config-Broadcasts: wenn Diagnostic global die
    Stimme wechselt, wird auto-preloaded
  - broadcastet voice_ready mit Dauer (loadMs) oder error

RVS: voice_preload + voice_ready zur ALLOWED_TYPES-Liste.

App (SettingsScreen): beim Wechsel senden wir voice_preload, zeigen einen
Spinner in der Voice-Row und einen Toast mit "Stimme X bereit (Ns)".
App (ChatScreen): Toast auch hier — falls User gerade nicht in Settings ist.

Diagnostic (server+UI): voice_ready wird an Browser durchgereicht, ein
Status-Text unter dem Voice-Dropdown zeigt "wird geladen" → "bereit".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:24:08 +02:00
duffyduck c8881f9e4d release: bump version to 0.0.4.9 2026-04-22 23:02:28 +02:00
duffyduckandClaude Opus 4.7 028e3b2240 fix: Voice-Auswahl funktioniert endlich + Diagnostic setzt alle Apps zurueck
XTTS-Bridge: im daswer123 local-Mode erwartet der Server speaker_wav als
Basename (z.B. "Maia"), nicht als Pfad. Wir haben bisher "/voices/Maia.wav"
geschickt, was der Server stumm verwirft und Default nimmt. Jetzt: speaker
name pur senden + Warnlog wenn File fehlt.

App: ChatScreen + SettingsScreen horchen auf type "config" vom RVS —
wenn in Diagnostic die globale XTTS-Voice gewechselt wird, werden alle
Apps auf den neuen Wert zurueckgesetzt (wie vom User gewuenscht).
Lokale App-Wahl bleibt sonst intakt und gewinnt pro Request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 19:32:40 +02:00
duffyduckandClaude Opus 4.7 c042f27106 feat: generisches Buchstabieren fuer unbekannte Akronyme
Nach der expliziten _UNIT_WORDS-Liste greift eine Fallback-Regel:
alle verbleibenden 2-5-Zeichen-Grossbuchstaben-Woerter werden
buchstabiert. XTTS → X T T S, USB → U S B, DNS → D N S, JSON → J S O N.

Spezielle Faelle (WLAN, NATO — als Wort gesprochen) koennen bei
Bedarf in _UNIT_WORDS explizit ueberschrieben werden.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 19:17:04 +02:00
duffyduck 4ceadf8be5 release: bump version to 0.0.4.8 2026-04-22 19:08:00 +02:00
duffyduckandClaude Opus 4.7 ddd30b3059 feat: Pre-Roll-Buffer fuer TTS einstellbar in App-Settings
- Kotlin start() nimmt jetzt prerollSeconds als dritten Parameter
  (1.0-6.0s geclampt, Fallback 3.5s bei ungueltigem Wert)
- audio.ts liest Wert aus AsyncStorage vor jedem Stream-Start,
  exportiert Default/Min/Max/Key als Konstanten
- SettingsScreen: +/- Buttons direkt unter dem TTS-Toggle,
  Default auf 3.5s (von 2.5s) angehoben

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 19:06:55 +02:00
duffyduckandClaude Opus 4.7 6c8ba5fe2d fix: Fade-In auf ersten PCM-Chunk — maskiert XTTS-Warmup-Glitches
XTTS daswer123 hat am Anfang jedes Renders Warmup-Artefakte — die
ersten autoregressiv generierten Tokens haben wenig Kontext und klingen
verzerrt. Ein 120ms Linear-Fade-In auf den ersten ausgehenden PCM-Chunk
blendet das sanft auf und versteckt die Glitches, ohne dass das echte
Audio danach leiser klingt.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 19:01:36 +02:00
duffyduckandClaude Opus 4.7 32ddac002f fix: stream_chunk_size auf 250 erhoeht — weniger Render-Artefakte
XTTS daswer123 erzeugt an Chunk-Grenzen oft Glitches in den Worten
die ueber die Grenze gehen. 100 → 250 = weniger Grenzen pro Satz =
sauberere Sprachausgabe. Erste-Audio-Latenz steigt um ein paar Sekunden,
was aber OK ist seit die App Pre-Roll gepuffert ist.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:56:00 +02:00
duffyduck bbbe69d928 release: bump version to 0.0.4.7 2026-04-22 18:46:25 +02:00
duffyduckandClaude Opus 4.7 23c39d5bba feat: Dezimalzahlen fuer TTS ausschreiben + Leading-Silence im Stream
- aria_bridge clean_text_for_tts: "0.1" / "0,5" / "1,25" wird jetzt als
  "null komma eins" / "null komma fuenf" / "eins komma zwei fuenf"
  ausgeschrieben. Lookahead verhindert Match auf IP-artige Strings.
- PcmStreamPlayer: 200ms Stille am Stream-Anfang, damit AudioTrack
  sauber anfaehrt und die ersten Worte nicht verschluckt werden.
  (XTTS-Warmup + play()-Startup-Latenz)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:44:38 +02:00
duffyduck 5328dc8595 release: bump version to 0.0.4.6 2026-04-22 18:32:31 +02:00
duffyduckandClaude Opus 4.7 0c03b4f161 fix: Stream-Ende wartet auf playbackHeadPosition vor release()
AudioTrack.stop() + release() direkt nach dem letzten write() killt die
letzten Sekunden Audio — die Samples sind zwar im Buffer, aber noch
nicht durch die Hardware rausgespielt. Deshalb brach die Sprachausgabe
mitten im Satz ab (z.B. bei "diesmal").

Fix: Writer-Thread wartet im finally-Block bis playbackHeadPosition die
Anzahl geschriebener Frames erreicht, dann erst stop()/release().
Safety: 2s Stall-Detection, falls AudioTrack haengen bleibt.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:31:12 +02:00
duffyduck 31fe70bab5 release: bump version to 0.0.4.5 2026-04-22 18:18:20 +02:00
duffyduckandClaude Opus 4.7 39251b3d32 feat: AudioTrack Pre-Roll — Playback startet erst nach 2.5s Vorrat
User-Diagnose: Erneutes Abspielen aus Cache funktioniert komplett, aber
Live-Stream bricht ab. Bedeutet: PCM kommt an, Cache ist okay — Problem
ist Buffer-Underrun im AudioTrack wenn XTTS (RTF 1.48 auf RTX 3060)
langsamer rendert als Echtzeit-Playback konsumiert.

Fix: AudioTrack.play() wird NICHT mehr sofort beim start() aufgerufen.
Stattdessen:
- start() baut AudioTrack, Writer-Thread startet, spielt aber noch nicht
- writeChunk() fuellt queue, Writer schreibt in AudioTrack-internen Buffer
  (blocked wenn der voll ist)
- Sobald bytesBuffered >= 2.5s Audio im Buffer: play() aufrufen
- Falls end() kommt bevor Pre-Roll erreicht (kurze Texte): trotzdem play()

Das gibt dem Stream Zeit Vorrat aufzubauen. XTTS kann dann pausieren
zwischen Text-Chunks ohne dass Playback stottert.

Pre-Roll 2.5s reicht fuer typische Render-Pausen zwischen Chunks.
Buffer groesse = 2x Pre-Roll damit wir auch extrem bursty Delivery
puffern koennen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:16:02 +02:00
duffyduckandClaude Opus 4.7 0623de32a0 tune: stream_chunk_size 200 -> 100 gegen 6s Initial-Latenz
Mit RTF 1.48 (RTX 3060) rechnet XTTS fuer 200 chars ca. 6s bis erster
PCM-Chunk rauskommt — User wartet nach ARIA-Antwort 6s auf Sprachausgabe.

stream_chunk_size=100: Erster Chunk in ~3s bereit, reduziert
Initial-Latenz um ~50%. 100 chars sind auch noch gross genug dass
der AudioTrack-Buffer (128KB ≈ 2.7s Audio) zwischen Render-Chunks
nicht leerlaeuft → kein mid-sentence Abbruch wie bei 40.

Falls bei bestimmten Texten doch Gaps: stream_chunk_size zurueck auf
150, oder pre-roll im Android PcmStreamPlayer einbauen (nur starten
wenn X ms gepuffert sind).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:08:10 +02:00
duffyduckandClaude Opus 4.7 cd5e6e7ee6 fix: stream_chunk_size 40 -> 200 gegen Audio-Abbrueche mid-sentence
Bei stream_chunk_size=40 teilte XTTS Text in ~40-char Batches.
Zwischen Batches pausiert XTTS (RTF 1.48 auf RTX 3060 → langsamer
als Realtime-Wiedergabe). AudioTrack-Buffer lief leer, Track
stoppte, nachkommender PCM kam zu spaet → Audio bricht mid-sentence
ab (User-Bug: bei 73-char Text Abbruch nach Wort 'diesmal' was genau
an der 40-char Grenze lag).

stream_chunk_size=200:
- Kurze Saetze (<200 chars) komplett in einem Render → kein Abbruch
- Laengere Texte: groessere Chunks, laenger Audio pro Chunk als
  Render-Pause → Buffer bleibt gefuellt
- Kompromiss: first-audio-latency etwas hoeher, aber keine Abbrueche

Wenn spaeter Audio-Abbrueche bei langen Texten: stream_chunk_size
noch groesser setzen ODER einen "pre-roll" Buffer in der App.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:06:25 +02:00
duffyduckandClaude Opus 4.7 ee3e0a0af6 fix: XTTS local-Mode per ENV statt command-Override
Das Image-Default-CMD liest Konfig aus ENV Variablen:
  CMD: ... -ms \${MODEL_SOURCE:-"apiManual"}

Also reicht MODEL_SOURCE=local — command bleibt Image-Default und wir
sparen uns den brueckigen Override der schief ging (python nicht da,
flag-Namen raten, etc.).

Zusaetzlich: EXAMPLE_FOLDER=/voices damit der Speaker-Folder auf unser
gemountetes /voices zeigt (sonst /app/example was nur die Demo-Voices
enthaelt).

Kein command override mehr noetig — das Image macht alles wie vorher,
nur mit local-Mode.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:59:39 +02:00
duffyduckandClaude Opus 4.7 0783b1b99d fix: XTTS command nutzt python3 statt python
Image hat nur /usr/bin/python3, kein 'python'-Symlink.
Vorher ging's weil kein command override — das Image-Default CMD
lief durch. Wir ueberschreiben nur damit wir -ms local setzen koennen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:58:29 +02:00
duffyduckandClaude Opus 4.7 5492c7a46f fix: XTTS command braucht 'python -m xtts_api_server' als erstes Arg
NVIDIA-Entrypoint fuehrt 'exec \$@' aus — erstes Arg muss ein
ausfuehrbares sein. Nur Flags zu geben ('--listen') fuehrt zu
'exec: --: invalid option'.

Fix: command=['python','-m','xtts_api_server','-ms','local',...]
Damit wird der xtts_api_server Python-Modul gestartet und im
local-Mode konfiguriert.

Ob die Flag-Namen exakt stimmen (-hs/-p/-ms/-o/-mf/-sf) — falls
nicht, poppt ein klarer Python-Fehler im Log.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:49:29 +02:00
duffyduckandClaude Opus 4.7 4cbe184faa feat: XTTS auf local-Mode (dauerhaft im VRAM) + /tts_stream + Fallback
Root cause der langen Render-Zeiten und /tts_stream 400-Errors:
daswer123 default ist apiManual/api-Mode — Modell wird pro Request
gefetched/reloaded, Streaming unsupported.

Fix in xtts/docker-compose.yml:
  command: ['--listen', '-p', '8020', '-t', 'http://0.0.0.0:8020',
            '-ms', 'local',
            '-o', '/app/output', '-mf', '/app/xtts_models', '-sf', '/voices']

-ms local:
  - Modell dauerhaft im GPU-VRAM (~2GB, passt auf RTX 3060 mit 12GB)
  - Render startet sofort, kein per-Request-Load mehr
  - /tts_stream unterstuetzt → echtes progressive streaming
  - time-to-first-audio ~500ms statt 8-11s

xtts/bridge.js:
  /tts_stream primary, /tts_to_audio/ als Fallback wenn Stream fehlt.
  Robust: wenn User spaeter den Mode wieder umstellt, fallback greift.

Erste Ladung nach dem Wechsel dauert einmalig laenger (Modell ins VRAM
laden). Danach: schnell + streaming.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:38:53 +02:00
duffyduckandClaude Opus 4.7 647a1cb726 fix: XTTS nutzt direkt /tts_to_audio/ — /tts_stream nicht verfuegbar
XTTS-Server (daswer123) im API-Modus antwortet auf /tts_stream mit:
  HTTP 400: "HTTP Streaming is only supported for local models"

Das Feature braucht MODE=local in der XTTS-Config (Modell direkt im
Server-Prozess). Userbetreibt im Remote-Modus → kein Streaming.

Der try /tts_stream + fallback /tts_to_audio Ansatz war reine Ver-
schwendung: jeder Request wartete 6ms auf 400, bevor der Fallback
griff. Jetzt geht's direkt an /tts_to_audio/.

Kein echtes Streaming, aber:
- Queue sorgt fuer sequentielle Verarbeitung (kein Overlap mehr)
- 32x AudioTrack-Buffer faengt den bursty Response ab
- aria-bridge spiegelt audio_pcm nicht mehr (kein Doppel-Audio)

Wenn User spaeter /tts_stream haben will:
  XTTS-Server mit MODE=local oder --streaming-mode starten,
  dann kann man /tts_stream als primary einfuehren.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:23:55 +02:00
duffyduckandClaude Opus 4.7 73263b69a6 fix: /tts_stream — speaker_wav muss IMMER als query-param gesetzt sein
XTTS-Server (daswer123) markiert speaker_wav als required Pydantic-Feld.
Mein 'if (speakerWav) qs.set(...)' hat den Key bei default-voice
weggelassen → HTTP 422 'Field required, input: null' → Fallback auf
/tts_to_audio/ hat gegriffen, aber Streaming nie gefunden.

Log-Beweis vom User:
  XTTS /tts_stream 422: {"detail":[{"type":"missing","loc":["query",
    "speaker_wav"],"msg":"Field required","input":null}]}

Fix: Key immer setzen, leerer String bei default-voice. POST-Variante
(/tts_to_audio/ JSON-Body) hat das auch so akzeptiert — GET-Query nun
gleiches Verhalten.

Ab jetzt sollte /tts_stream endlich greifen und echte Streaming-Latenz
(~300-500ms) zeigen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 16:47:28 +02:00
duffyduckandClaude Opus 4.7 c62ceafdc2 fix: XTTS-Endpoint mit Fallback-Chain + Diagnose-Logs
Problem: /tts_stream hat bei User nicht funktioniert → keine
Sprachausgabe mehr. Server hatte vorher 405 fuer POST geantwortet,
meine Umstellung auf GET scheint aber einen anderen Fehler zu
produzieren der nicht geloggt wurde.

Fix:
- streamXTTSAsPCM() = /tts_stream (GET, Streaming) mit ausfuehrlichem
  Error-Logging bei non-200 Response
- streamXTTSBatch() = /tts_to_audio/ (POST, Batch) als Fallback
- handleTTSRequest versucht Stream zuerst, bei Exception Fallback
  auf Batch — so gibt's IMMER Audio, auch wenn /tts_stream kaputt ist
- Log zeigt welcher Pfad benutzt wurde

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 15:53:10 +02:00
duffyduckandClaude Opus 4.7 9b5a35cb4a fix: /tts_stream als GET mit Query-Params (war 405 Method Not Allowed)
daswer123 xtts-api-server hat /tts_stream nur als GET:
  allow: GET → POST gab 405 → Request hing.

Umstellung:
- method: 'GET'
- text/language/speaker_wav/stream_chunk_size als URLSearchParams
  im Query-String
- kein body mehr (kein req.write, kein Content-Length)

Ab jetzt echter streaming-Flow: Samples kommen waehrend XTTS noch
rendert, time-to-first-audio ~300-500ms.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 16:52:16 +02:00
duffyduckandClaude Opus 4.7 5ac1a0a522 revert: XTTS-Endpoint zurueck auf /tts_to_audio/
/tts_stream war bei der aktiven daswer123-Version nicht erreichbar —
Requests hingen stille, App bekam kein Audio.

Zurueck auf /tts_to_audio/ + Queue + 32x AudioTrack-Buffer. Das ist
zwar nicht echt-streaming aber stabil. Ueberlappung sollte durch die
Queue weg sein, Buffer toleriert den bursty Delivery.

Echt-Streaming-Migration spaeter mit verifizierter Server-Version
oder anderem Endpoint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 16:48:27 +02:00
duffyduck a28b46a809 release: bump version to 0.0.4.4 2026-04-20 16:42:19 +02:00
duffyduckandClaude Opus 4.7 59c8d36a3d fix: Streaming TTS nutzt jetzt echt den /tts_stream Endpoint von XTTS
Vorher: /tts_to_audio/ — XTTS rendert kompletten WAV BEVOR es
antwortet. Mein "streaming" war nur fake-chunking des fertigen WAV.
Time-to-first-audio = komplette Render-Zeit (2-4s), dann Burst,
dann Stille. Plus bei langen Antworten: Queue blockiert.

Jetzt: /tts_stream — daswer123's chunked-transfer endpoint.
Samples flutschen waehrend der Generierung durch die Response raus.

Parameter:
- stream_chunk_size=40 → XTTS rendert in ~40-char Haeppchen intern,
  time-to-first-audio ~300-500ms statt 2-4s
- WAV-Header kommt wie gewohnt am Anfang (44 Bytes), danach raw PCM
  → mein existierender Header-Parser + 8KB-Chunker passen weiter

Voraussetzung: daswer123/xtts-api-server hat diesen Endpoint (ab
Version ~0.8.x). Sollte bei der aktuellen Version drin sein.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 16:35:55 +02:00
duffyduck 79ba7b8487 release: bump version to 0.0.4.3 2026-04-20 08:01:46 +02:00
duffyduckandClaude Opus 4.7 ba62cec78c fix: Disk-Banner — Safe-Cleanup als Default + Aggressiv hinter Expander
Safe-Variante (Default):
  docker builder prune -a -f && docker image prune -a -f
  → Build-Cache + ungenutzte Images, KEINE Volumes angefasst.
  → 90% des Platzproblems geloest, Null Datenverlust-Risiko.

Aggressive Variante (nur auf Wunsch, hinter 'Mehr'-Button):
  docker system prune -a --volumes -f
  → Zusaetzlich ungenutzte Volumes.
  → Nur sicher wenn alle ARIA-Container LAUFEN (sonst werden
     openclaw-config/claude-config/aria-shared als "ungenutzt"
     behandelt und zerstoert — Sessions weg).
  → Hinweistext orange hervorgehoben mit Warnung.

Banner-Button 'Sicher aufraeumen' kopiert die sichere Variante.
'Mehr' klappt die Erklaerung der aggressiven Variante aus.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:39:22 +02:00
duffyduckandClaude Opus 4.7 f15b3f583f feat: Disk-Space Banner im Diagnostic mit Cleanup-Command zum Kopieren
Server:
- checkDiskSpace() prueft alle 30s 'df -B1 /shared' (zeigt Host-Disk
  da /shared ein Volume auf dem Docker-FS ist)
- 4 Stufen: ok (<70%), info (70%), warn (85%), critical (95%)
- Broadcastet disk_status nur bei Aenderung (Level oder Prozent)
- currentDiskStatus wird gecached → neu verbundene Clients bekommen
  den aktuellen Stand sofort beim 'init'

UI:
- Sticky Banner ganz oben, versteckt wenn Disk ok
- Farbe nach Level: gelb (info), orange (warn), rot (critical)
- Zeigt Prozent, Used/Total/Avail in GB, konkrete Situation
- Cleanup-Command als monospace Code mit Copy-Button ('docker system
  prune -a --volumes -f') — Click auf Code oder Button kopiert ins
  Clipboard, Fallback auf Range-Selektion
- 'Schliessen' Button fuer temporaeres Ausblenden (kommt aber wieder
  bei naechster Aenderung)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:36:36 +02:00
duffyduckandClaude Opus 4.7 402bddc18a fix: Streaming TTS — Queue in XTTS-Bridge + groesserer Android-Buffer
1) Ueberlappende Streams
   Wenn zwei xtts_requests schnell hintereinander kamen, rannten
   sie parallel durch handleTTSRequest. Beide HTTP-Requests an XTTS
   liefen gleichzeitig, beide streamen PCM an App → Chunks aus BEIDEN
   Renders landeten interleaved in der AudioTrack-Queue → Chaos.

   Fix: ttsQueue als Promise-Chain — handleTTSRequest() haengt sich
   ans Ende der Kette an. Requests werden sequenziell abgearbeitet.

2) AudioTrack-Buffer zu klein fuer bursty Delivery
   XTTS /tts_to_audio/ ist NICHT echt streaming — der Server rendert
   intern den kompletten WAV und schickt ihn dann burst-weise. Der
   alte 8x-MinBuffer (ca 200-400ms) war zu klein um das abzufangen.

   Fix: Buffer auf 32x MinSize / mind. 128KB = ca. 2.7s bei 24kHz.
   Das toleriert typische XTTS-Render-Latenz.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:27:16 +02:00
duffyduckandClaude Opus 4.7 350069d371 fix: Streaming TTS — doppeltes Audio + Gaps zwischen Saetzen
Zwei Probleme gefunden:

1) DOPPELTES AUDIO (Kern-Ursache der Artefakte)
   aria-bridge hat audio_pcm von XTTS-Bridge empfangen und per
   _send_to_rvs rebroadcastet. RVS broadcast geht an ALLE Clients
   ausser Sender — die App bekam jeden Chunk also zwei mal:
     XTTS-Bridge → RVS → App + aria-bridge
     aria-bridge → RVS → App (nochmal!) + XTTS-Bridge
   Zwei ueberlagerte PCM-Streams klingen wie Doubled/Artefakte.
   Fix: aria-bridge ignoriert audio_pcm jetzt. messageId schickt
   XTTS-Bridge selbst im Payload (via xtts_request -> messageId).

2) GAPS ZWISCHEN SAETZEN (abgehackt)
   xtts/bridge.js teilte Text in ~150-char Chunks und rief pro Chunk
   einen eigenen /tts_to_audio/ Request. Zwischen Chunks lag die
   XTTS-Render-Zeit (1-3s) → hoerbare Pausen.
   Fix: cleanText geht JETZT in einem Request komplett an XTTS.
   Ein zusammenhaengender Stream → keine Satz-Gaps mehr.
   Kompromiss: Erste Samples kommen spaeter (ganze Text-Render dauert
   laenger als der erste Satz alleine), aber dann kontinuierlich
   ohne Unterbrechung.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 23:15:57 +02:00
duffyduck 019c078393 release: bump version to 0.0.4.2 2026-04-19 23:01:55 +02:00
duffyduckandClaude Opus 4.7 d411df4074 feat: Mode-Wechsel auch aus Diagnostic global syncronisiert
Vorher: Diagnostic's setMode sendete einen faked chat mit der
Aktivierungsphrase ('ARIA, Hangar-Modus') — das wurde erst in
_process_core_response auf dem ARIA-Antwort-Text detected, war
unzuverlaessig und nutzte nicht den sauberen mode-Message-Path.

Nachher: sauberer set_mode-Pfad mit Live-Sync.

diagnostic/server.js:
- Neue action 'set_mode' → sendet type=mode an RVS direkt
- RVS-Message-Handler: type=mode Broadcast von Bridge wird an
  Browser-Clients durchgereicht

diagnostic/index.html:
- setMode() nutzt jetzt action=set_mode (keine Phrase mehr)
- updateModeUI separat — wird bei Broadcast auch aufgerufen
- Mode-Broadcast vom Server syncs UI live (andere Diagnostic/App
  hat gewechselt → unser UI aktualisiert sofort)
- Button data-mode + MODE_LABELS auf kanonische IDs umgestellt
  (nicht_stoeren, fluester statt dnd, whisper)

bridge/modes.py:
- canonical_id() liefert die IDs die App + Diagnostic kennen
  (nicht_stoeren, fluester, ...) — damit Broadcast-ID zur UI-ID passt

bridge/aria_bridge.py:
- _broadcast_current_mode nutzt canonical_id statt enum.name.lower()

Flow jetzt:
  Diagnostic wechselt Mode → set_mode → Bridge → persist + broadcast
  → alle Apps + alle Diagnostic-Browser-Tabs aktualisieren sofort

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:57:41 +02:00
duffyduckandClaude Opus 4.7 763e0d79ab feat: Betriebsmodus global + persistent + Live-Sync
Vorher:
- Modus war nur in-memory in der Bridge, Restart = zurueck auf NORMAL
- App-Wechsel wurde zwar empfangen, aber nicht an andere Geraete
  gebroadcastet (nur Bestaetigung an den Sender)
- Neue App-Verbindung wusste nicht welcher Modus gerade aktiv ist

Jetzt:
- Persistiert in /shared/config/mode.json beim Wechsel
- Beim Bridge-Start: _load_persisted_mode() holt letzten aktiven Modus
- _broadcast_current_mode() sendet an ALLE Clients (Broadcast) —
  jedes verbundene Geraet bekommt live den Wechsel mit
- Bei RVS-Reconnect: sofortiger Broadcast damit neu verbundene Apps/
  Diagnostic ihre UI syncen koennen
- Loop-Schutz: payload.sender=="bridge" wird im mode-Handler ignoriert
  (sonst echo → Broadcast-Storm bei verbundenem RVS)

Beispiel-Flow:
  Geraet A aktiviert 'Hangar'
  → Bridge empfaengt mode-msg
  → persist in mode.json
  → broadcast an alle Clients (mit sender="bridge")
  → Geraet B/C/Diagnostic empfangen → UI updated sofort
  → Bridge-Restart spaeter: HANGAR wird wieder geladen

Anmerkung zu echten OS-Push bei geschlossener App:
Das braucht FCM/Firebase + BackgroundService — deutlich mehr Arbeit,
ist separat als Feature fuer spaeter zu sehen. Live-Sync bei geoeffneter
App (WebSocket verbunden) funktioniert jetzt zuverlaessig.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:53:47 +02:00
duffyduckandClaude Opus 4.7 47fe4ad655 fix: Modus-Wechsel via App/ID funktioniert jetzt
Bug: App ModeSelector sendet rvs.send('mode', { mode: 'normal' })
mit ID, Bridge's detect_mode_switch() sucht aber nach Aktivierungs-
phrasen wie 'aria, normal-modus' → kein Match → Modus-Wechsel
wurde ignoriert, TTS-Verhalten blieb auf NORMAL haengen.

Fix:
- modes.py: mode_from_id() mappt IDs zu Mode-Enum
  ('normal', 'dnd', 'nicht_stoeren', 'fluester', 'whisper',
   'hangar', 'gaming' — flexibel)
- aria_bridge.py: mode-Handler versucht erst ID-Mapping, dann
  Phrasen-Erkennung als Fallback
- Unbekannte Modi werden geloggt
- Bestaetigung wird an alle Clients zurueckgesendet damit App-UI
  synchron bleibt

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:51:18 +02:00
duffyduckandClaude Opus 4.7 99cb83202e feat: App XTTS-Voice-Auswahl + Aufnahme + Loeschen (geraetelokal)
App Settings: Voice-Sektion (nur wenn TTS an)
- Liste aller XTTS-Server-Stimmen mit Auswahl-Radio + X zum Loeschen
- 'Standard' fuer Diagnostic-Default-Voice (keine lokale Ueberschreibung)
- 'Aktualisieren' Button laedt Liste neu (xtts_list_voices via RVS)
- 'Eigene Stimme aufnehmen' oeffnet VoiceCloneModal

VoiceCloneModal: 30s Aufnahme + Upload
- Vorlese-Text (>30s Lesedauer, thematisch passend)
- Rot-pulsierender Stop-Button, live Timer + Progressbar
- Auto-Stop bei 30s, Hinweise ab 15s ('genug fuer gute Clonung')
- Nach Stop: Namenseingabe (a-Z, 0-9, _, -), Upload via voice_upload
- Nach Upload: Modal schliesst, Settings bekommt xtts_voice_saved
  und setzt automatisch die neue Stimme als gewaehlt

Voice-Flow App → Bridge → XTTS (geraetelokal):
- Jeder chat/audio/tts_request schickt aria_xtts_voice (AsyncStorage)
  mit der Message mit
- Bridge speichert _next_voice_override bei chat/audio Empfang,
  nutzt es fuer die naechste ARIA-Antwort und resettet dann
- Fallback: globale xtts_voice aus voice_config.json (Diagnostic)

Ergebnis:
- Gerat A hat 'stefan' geclont → ARIA antwortet Geraet A mit stefan
- Gerat B hat nichts gewaehlt → ARIA antwortet Geraet B mit Default
- Diagnostic-Einstellung wirkt als fallback-default fuer neue Geraete

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:48:24 +02:00
duffyduckandClaude Opus 4.7 fc2438be2d fix/feat: XTTS-Voice korrekt persistiert, Loeschen + Voice-per-Request
Bug-Fix: Voice-Auswahl verschwand nach Page-Load
- xtts_voices_list Handler rebuildet das Dropdown — vorheriger select.value
  ging dabei verloren. Jetzt wird der Wert gemerkt und nach Rebuild
  wiederhergestellt (falls die Stimme noch existiert).

Feature: Stimmen loeschen (Diagnostic)
- XTTS-Bridge: neuer handleDeleteVoice — entfernt /voices/<name>.wav
  und schickt aktualisierte Liste per xtts_voices_list
- RVS: xtts_delete_voice in ALLOWED_TYPES
- Diagnostic Server: Action xtts_delete_voice forwarded via RVS
- Diagnostic UI: renderVoiceList zeigt alle Custom-Voices mit X-Button
  Bei Loeschen der gerade aktiven Stimme: auf Default zuruecksetzen

Feature: Voice-per-Request in Bridge
- App kann mit jedem Chat ein voice-Feld mitschicken
- Bridge merkt sich _next_voice_override, nutzt es fuer die NAECHSTE
  ARIA-Antwort (einmalig, dann reset)
- tts_request (Play-Button) akzeptiert voice im Payload als Override
- Fallback: globale xtts_voice aus voice_config.json
- So kann jedes Geraet seine eigene Stimme haben ohne den globalen
  Default zu aendern

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:43:26 +02:00
duffyduckandClaude Opus 4.7 40e48b046b feat: App TTS-Einstellungen vereinfacht + Mund-Button fuer lokales Muten
SettingsScreen:
- Piper-Reste entfernt (defaultVoice, highlightVoice, Speed-Slider,
  Highlight-Trigger-Info)
- Nur noch EIN Toggle 'Sprachausgabe auf diesem Geraet' — geraetelokal,
  persistent in aria_tts_enabled (AsyncStorage)
- Keine Config-Propagation mehr via RVS (das waere ja global gewesen)
- Hinweis dass Stimme + Voice-Cloning zentral in der Diagnose sind

ChatScreen: Mund-Button (👄 / 🤐)
- Neben Ohr-Button im Eingabebereich, NUR sichtbar wenn TTS im Setting
  grundsaetzlich aktiv ist
- Tap toggelt Mute: 👄 an / 🤐 rot gemutet
- Persistent in aria_tts_muted (AsyncStorage)
- Stoppt bei Muten sofort laufende Wiedergabe (stopPlayback)
- Settings-Toggle wird alle 2s gepollt damit Aenderungen greifen
  (einfache Loesung ohne globalen State-Context)

Audio-Handling respektiert lokalen Zustand
- Incoming audio/audio_pcm: nur abspielen wenn ttsDeviceEnabled && !ttsMuted
- Cache wird TROTZDEM immer geschrieben — Play-Button funktioniert
  spaeter aus Cache, auch waehrend Mute
- audioService.handlePcmChunk akzeptiert silent-Flag: skipt AudioTrack
  aber baut weiterhin den WAV-Cache pro messageId

Jedes Android-Geraet mit der App hat seinen eigenen Mute-Zustand.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:33:36 +02:00
duffyduckandClaude Opus 4.7 f801d99748 feat: Piper komplett entfernt — nur noch XTTS v2 als TTS
Breaking Change: wenn XTTS-Bridge (Gaming-PC) offline ist, bleibt ARIA
stumm. Chat-Antworten kommen weiter an, aber kein Audio. Das ist
bewusst akzeptiert — XTTS klingt einfach grauenhaft viel besser.

Bridge (aria_bridge.py):
- from piper import ... raus
- VoiceEngine-Klasse komplett entfernt (synthesize, speak, select_voice)
- EPIC_TRIGGERS + load_epic_triggers raus (Highlight-Voice-Feature
  ohne Piper sinnlos)
- self.voice_engine, voice_name, requested_voice Aufrufe weg
- _process_core_response: immer XTTS, kein Fallback
- tts_request Handler: immer XTTS
- config Handler: nur ttsEnabled + xttsVoice + whisperModel
- import wave raus

bridge/requirements.txt: piper-tts raus
bridge/Dockerfile: Kommentar aktualisiert
docker-compose.yml: ./aria-data/voices Mount raus
aria-data/config/aria.env.example: PIPER_RAMONA/PIPER_THORSTEN raus
get-voices.sh: komplett geloescht (war nur Piper-Downloader)

Diagnostic UI (index.html):
- Piper Panel (Standard-Stimme / Highlight-Stimme / Speed-Sliders) weg
- TTS Engine Dropdown weg (immer XTTS)
- TTS Diagnose Tab zeigt nur noch XTTS-Status + Test-Button
- sendVoiceConfig sendet nur noch ttsEnabled/xttsVoice/whisperModel
- toggleXTTSPanel als no-op Legacy-Stub (JS-Calls bleiben safe)

Diagnostic Server (server.js):
- handleSendVoiceConfig: nur noch ttsEnabled + xttsVoice + whisperModel
- handleTestTTS: via xtts_request (nicht mehr Piper subprocess)
- handleCheckTTS: via xtts_list_voices ueber RVS
- handleGetVoiceConfig/Defaults bereinigt
- Highlight-Trigger UI bleibt, wird aber von Bridge nicht mehr
  ausgewertet (dead-code im UI, spaeter ggf. fuer XTTS-Voice-Switch)

README + issue.md aktualisiert.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:24:42 +02:00
duffyduckandClaude Opus 4.7 6ab6196739 feat: Streaming TTS — PCM-Stream statt WAV-Chunks (Weg A)
Pipeline: XTTS-Server → xtts-bridge → aria-bridge → RVS → App AudioTrack

XTTS-Bridge (Gaming-PC):
- streamXTTSAsPCM(): liest /tts_to_audio/ Response inkrementell,
  parst WAV-Header (samplerate/channels), teilt PCM in 8KB-Chunks
  (~170ms bei 24kHz s16 mono) und sendet jeden als audio_pcm.
- Finaler Chunk mit final=true nach letztem Text-Chunk

aria-bridge:
- audio_pcm Handler leitet payload 1:1 weiter, filled messageId aus
  requestId → messageId Map falls XTTS-Bridge messageId nicht hatte
- Alter xtts_response Pfad bleibt als Legacy-Fallback (WAV)

RVS: audio_pcm in ALLOWED_TYPES

Android Native:
- PcmStreamPlayerModule (Kotlin): AudioTrack MODE_STREAM mit
  Writer-Thread und BlockingQueue. start(rate, ch) / writeChunk(b64)
  / end() / stop()
- 8x MinBufferSize grosszuegig dimensioniert, glatt auch bei
  Netz-Aussetzern
- Registered im MainApplication via PcmStreamPlayerPackage

App JS:
- audioService.handlePcmChunk(): erkennt neue Session (messageId-Wechsel),
  started nativen Stream, cached PCM-Bytes pro Message. Bei final=true
  Stream sauber schliessen + _savePcmBufferAsWav → WAV-File im
  tts_cache/<messageId>.wav
- _savePcmBufferAsWav: baut 44-byte WAV-Header (PCM s16le, korrekte
  samplerate/channels), haengt alle gesammelten base64-PCM-Chunks an
- stopPlayback beendet auch aktiven PCM-Stream
- ChatScreen routet type=audio_pcm an handlePcmChunk, bei final
  setzt audioPath in der Message

Play-Button: falls messageId einen audioPath hat → WAV aus Cache
(Sound-basiert), egal ob Original-TTS Piper oder XTTS war.

Audio-Focus:
- requestDuck() beim Stream-Start, release() bei Stream-Ende
- Andere Apps (Spotify etc.) werden leiser waehrend ARIA spricht

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:01:27 +02:00
duffyduckandClaude Opus 4.7 eb12281dfc feat: TTS-Zeitbereiche + Diagnostic-Debug-Toggle + Play-Button respektiert Engine
TTS-Cleanup erweitert:
- Zeitbereiche: '8:00-9:00 Uhr' / '8-9 Uhr' → 'acht bis neun Uhr'
- Uhrzeiten: '8:30 Uhr' → 'acht Uhr dreissig', '15 Uhr' → 'fuenfzehn Uhr'
- Kleine Zahlen-Bereiche: '5-6' → 'fuenf bis sechs' (nur ≤24)
- Zahlen 0-59 als deutsche Woerter (inkl. 'einundzwanzig', 'fuenfundvierzig')

Diagnostic: TTS-Debug Einblenden
- Checkbox 'TTS-Text einblenden' in der Chat-Test Kopfzeile
- Unter ARIA-Nachrichten erscheint die aufbereitete Variante
  (blauer Border + Label 'TTS:')
- Nur in Diagnostic, nicht in der App
- LocalStorage persistiert den Toggle-Zustand
- Minimaler JS-Port von clean_text_for_tts als Fallback

Play-Button respektiert Engine:
- Bridge: tts_request nutzt jetzt die aktive TTS-Engine (Piper/XTTS),
  Text wird durch clean_text_for_tts aufbereitet
- messageId wird vom Play-Button mitgeschickt → Bridge verknuepft
  generiertes Audio mit der urspruenglichen Message
- XTTS-Chunks: requestId → messageId Map (LRU 100 Eintraege),
  beim xtts_response wird die Basis-UUID extrahiert und die
  messageId dem audio-Frame angehaengt
- App cached auch XTTS-Audio jetzt (letzter Satz pro Message —
  echte Chunk-Konkatenation bleibt TODO)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 21:48:32 +02:00
duffyduck 1fb1fdef9e release: bump version to 0.0.4.1 2026-04-19 21:00:49 +02:00
duffyduckandClaude Opus 4.7 593d26e0ff fix: QR-Code overflowed Container — auf SVG umgestellt mit width/height 100%
Der QR wurde mit createImgTag() als fester Pixel-IMG gerendert und
ueberlappte den Warnhinweis + Button rechts daneben. Fix:

- createSvgTag mit cellSize=4 + scalable=true
- SVG skaliert auf width:100%/height:100% der 220x220 Box
- Container: flex-shrink:0 (damit Flex ihn nicht weiter schrumpft)
- overflow:hidden als Sicherheit

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:28:41 +02:00
duffyduckandClaude Opus 4.7 394abb58be fix: Runtime-Config Layout + Eye-Toggle fuer Token-Felder
- Eingabefelder haben jetzt width:100% + box-sizing:border-box,
  keine Ueberlappung mehr im Grid
- Token-Felder haben einen Augen-Button daneben (👁/👀) zum
  Anzeigen/Verbergen des Inhalts
- Kleineres Label-Grid (140px statt 150px), grosszuegigerer Gap

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:27:56 +02:00
duffyduckandClaude Opus 4.7 fc3bee6d05 feat: Runtime-Config via Diagnostic UI — kein .env-Sync mehr
Framework fuer zentrale Runtime-Konfiguration:
- /api/runtime-config (GET/POST) persistiert in /shared/config/runtime.json
- Werte haben Vorrang ueber die ENV-Variablen aus aria.env
- Feldliste: RVS_HOST/PORT/TLS/TOKEN, ARIA_AUTH_TOKEN, WHISPER_MODEL/LANGUAGE
- Atomic write (tmp + rename) fuer Konsistenz

Bridge:
- load_config() liest nach aria.env noch runtime.json und ueberschreibt
  die Werte. Aenderungen werden beim Neustart der Bridge uebernommen.

Diagnostic UI:
- Neue Sektion "Runtime-Konfiguration" in Einstellungen
- Formular fuer RVS-Credentials + Aria-Auth-Token
- "Speichern" persistiert, triggert auch QR-Code-Regenerierung
- Hinweis: Diagnostic-Container selbst bleibt auf ENV (erstmal)

issue.md konsolidiert — 6 groessere Tasks dieser Session als erledigt.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:18:37 +02:00
duffyduckandClaude Opus 4.7 b203503fd8 feat: QR-Code Onboarding + TTS-Audio-Cache im Filesystem
QR-Code Onboarding
- Diagnostic: GET /api/onboarding gibt RVS-Credentials zurueck
- Einstellungen-UI: neue Sektion mit QR-Code (qrcode-generator via CDN)
- Format kompatibel mit bestehendem QRScanner.parseQRData (host/port/tls/token)
- App-SettingsScreen hatte QR-Scanner bereits — funktioniert out of the box
- Warnhinweis zu Token im Klartext

TTS-Audio-Cache
- Bridge: jede ARIA-Chat-Nachricht bekommt eine messageId (UUID)
  Audio-Payload wird mit messageId verknuepft (Piper-Pfade)
- ChatScreen: messageId + audioPath in ChatMessage Interface
- audioService.cacheAudio(): speichert Base64 in DocumentDirectory/tts_cache/<id>.wav
- audioService.playFromPath(): spielt aus Cache ohne Regenerierung
- Play-Button: wenn audioPath gesetzt → aus Cache, sonst tts_request
- cleanupOldTTSCache(): alte unreferenzierte WAVs (>30 Tage) weg
- Persistiert via AsyncStorage — ueberlebt App-Restart

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:16:25 +02:00
duffyduckandClaude Opus 4.7 8b0a72dc9b feat: NO_REPLY-Filter + Audio-Ducking + TTS-Cleanup
1) NO_REPLY Token wird in Bridge und Diagnostic erkannt und still
   verworfen. Toleranz fuer Variationen (Whitespace, Punkt, Quotes).
   Kein Chat-Eintrag, kein TTS.

2) AudioFocusModule (Kotlin) mit requestDuck / requestExclusive /
   release. AudioService ruft:
   - requestExclusive() bei Aufnahme-Start → andere Apps pausieren
   - requestDuck() bei TTS-Playback-Start → andere Apps leiser
   - release() bei Stop/Queue-Ende
   MainApplication registriert AudioFocusPackage.

3) clean_text_for_tts() in Bridge — zentrale Aufbereitung:
   - <voice>...</voice> Tag wird bevorzugt (falls ARIA es schreibt)
   - Code-Bloecke (``` und `) komplett raus
   - Markdown (Fett/Kursiv/Links/Headings/Listen) geschleift
   - Einheiten ausgeschrieben: 22GB → 22 Gigabyte, 85% → 85 Prozent
   - Abkuerzungen buchstabiert: CPU → C P U, API → A P I
   - URLs durch "ein Link" ersetzt
   Genutzt in VoiceEngine.synthesize und im XTTS-Request — Chat-Text
   an die App bleibt unveraendert (original Markdown), nur TTS kriegt
   die aufbereitete Version.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 16:10:54 +02:00
duffyduckandClaude Opus 4.7 23add7a107 docs: Neue Issues - TTS-Cleanup, Audio-Ducking, Config-UI, NO_REPLY-Bug
- Bug: NO_REPLY wird als "NO" angezeigt
- Audio-Ducking + Mute waehrend Aufnahme
- Spracheingabe-Timeout erhoehen
- TTS-Text-Aufbereitung (Code raus, Einheiten ausschreiben)
- Audio-Cache in Messages (kein Regenerieren beim Play-Button)
- Piper evtl. entfernen
- .env → Diagnostic UI migrieren
- QR-Code Onboarding
- XTTS Web-Oberflaeche / zentral via Diagnostic
- Root-Cause OpenClaw Session-Reset pruefen

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 14:04:47 +02:00
duffyduckandClaude Opus 4.7 caf84196fb fix: Reset-File-Regex - Timestamp endet mit Z (ohne Punkt davor)
Die OpenClaw Reset-Files heissen <uuid>.jsonl.reset.<iso>Z
(nicht <uuid>.jsonl.reset.<iso>.Z). Der falsche Regex matchte
nie, alle Archive wurden als "verwaist" angezeigt statt als "archiv".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 12:32:24 +02:00
duffyduck 099b9651a6 release: bump version to 0.0.4.0 2026-04-18 12:28:08 +02:00
duffyduckandClaude Opus 4.7 76d72a1eef feat: Archivierte Session-Versionen (OpenClaw .reset.* Files) in Diagnostic
OpenClaw resettet Sessions beim ersten chat.send nach Container-Restart
(wenn abortedLastRun / systemSent Inkonsistenz erkannt wurde) und
benennt die alte .jsonl in .jsonl.reset.<timestamp>.Z um. Der Inhalt
war also gar nicht verloren, nur unsichtbar.

Diagnostic:
- handleListSessions scannt jetzt auch *.jsonl.reset.* Files
- Reset-Files bekommen archived:true + resetAt-Timestamp
- Neue UI-Sektion "Archivierte Versionen" (collapsible <details>)
  mit Export-Button, zeigt aufklappbar alle gesicherten alten Sessions
- Aktivieren ist fuer Archive deaktiviert (zerstoert aktive Session)
- Loeschen + Export stehen zur Verfuegung

tools/export-jsonl-to-md.js:
- Standalone Node-Script zum Konvertieren beliebiger .jsonl (auch reset-Files)
- Nutzbar via stdin, exakt gleiche Export-Logik wie Diagnostic
- Fuer Rettungsaktionen direkt auf der VM

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 12:24:54 +02:00
duffyduckandClaude Opus 4.7 87deede078 fix: Session Msgs-Counter zaehlt echte Nachrichten, nicht alle Zeilen
Vorher: wc -l auf der .jsonl — zaehlt auch Tool-Calls, Run-Events,
Metadata-Eintraege mit. Diagnostic zeigte z.B. "10 Msgs" fuer eine
Session mit 6 echten User/Assistant-Nachrichten.

Jetzt: grep -cE '"role":"(user|assistant)"' — zaehlt nur echte
Konversations-Messages. Matcht wie der Export und die Chat-History
das interpretieren.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 12:09:01 +02:00
duffyduckandClaude Opus 4.7 6fec8588c1 fix: Gespraechsmodus - strenger Speech-Gate + Crash-Prevention
Probleme:
- Hintergrundgeraeusche wurden als Sprache erkannt und an Whisper geschickt
- App stuerzte nach laengerem Zuhoeren ab (OOM / Cache-Ueberlauf)

Aenderungen:
- VAD_SPEECH_THRESHOLD_DB -35 -> -28 (filtert Raum-Ambient)
- VAD_SPEECH_MIN_MS 300 -> 500 (keine Huestler/Klopfer mehr)
- Max-Aufnahmedauer 30s (Notbremse gegen Runaway-Loops)
- _cleanupStaleCacheFiles(): alte aria_recording_/aria_tts_ Files (>30s)
  werden vor jeder neuen Aufnahme geloescht
- ChatScreen: capMessages() begrenzt Messages-Array auf 500 Eintraege
  (OOM-Schutz in langen Gespraechen)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 12:05:15 +02:00
duffyduckandClaude Opus 4.7 aafdbcd57a fix: Thinking indicator beim Seitenladen nicht mehr sichtbar
Zwei display:-Deklarationen im inline-style der Diagnostic-Chat-Leiste
haben sich gegenseitig ueberschrieben — 'display:flex' war die zweite
und hat 'display:none' aushebelt. Indicator war so beim Seitenaufbau
sichtbar bis JS ein idle-Event empfing.

- HTML: 'display:flex' aus inline-style entfernt
- JS: beim Anzeigen explizit display='flex' setzen (statt 'block')

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:58:39 +02:00
duffyduck 08da28f475 release: bump version to 0.0.3.9 2026-04-18 11:52:53 +02:00
duffyduckandClaude Opus 4.7 8c1014d281 fix: Thinking indicator respringt nach chat:final durch trailing events
Nach chat:final kommen oft noch agent-Events rein (Core raeumt nach),
die den Thinking-Indicator wieder anspringen liessen.

- Diagnostic: 3s-Settled-Window nach chat:final, agent_activity-Broadcasts
  werden in dem Fenster unterdrueckt (idle kommt weiter durch).
- Bridge: Gleiches Fenster in _emit_activity() — App bekommt keine
  trailing thinking/tool-Events mehr nach dem finalen Antwort.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:51:22 +02:00
duffyduckandClaude Opus 4.7 271fc4edf6 docs: cleanup.sh + README updates for latest features
- cleanup.sh: sicherer (default) + aggressiver (--full) Docker-Cleanup
  mit Speicher-Report vor/nach
- README: Phase-1-Liste, Diagnostic-Features und App-Features um die
  neuen Punkte ergaenzt (Speech Gate, Session-Persistenz, Session-Export,
  App Thinking-Indicator, Whisper-Modellauswahl, 16kHz-Aufnahme)
- README: Neuer Abschnitt "Docker-Cleanup" mit cleanup.sh Usage

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:46:12 +02:00
duffyduck cd390a4115 release: bump version to 0.0.3.8 2026-04-18 11:41:12 +02:00
duffyduckandClaude Opus 4.7 a65ed579d2 feat: Whisper model selector + 16kHz mono recording
- App: AudioSamplingRateAndroid 16000 + AudioChannelsAndroid 1
  → Whisper bekommt direkt sein Ziel-Format, kein Resample mehr
- Bridge: STTEngine.reload() laedt Modell zur Laufzeit neu
  (tiny/base/small/medium/large-v3)
- Bridge: Config-Message triggert Hot-Reload wenn whisperModel sich aendert
- Bridge: Default auf 'medium' (besser als 'small' bei aehnlicher Latenz)
- Diagnostic: Neue Sektion "Whisper (Spracherkennung)" mit Dropdown,
  auto-save bei Auswahl, beim Laden wird der gespeicherte Wert gesetzt
- Diagnostic/Server: send_voice_config merged whisperModel in voice_config.json
- aria.env.example: WHISPER_MODEL + WHISPER_LANGUAGE dokumentiert

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:37:27 +02:00
duffyduckandClaude Opus 4.7 2ad1f57382 feat: Thinking indicator + cancel button in the app
- Bridge: _emit_activity() spiegelt OpenClaw agent events als agent_activity
  an RVS, dedupliziert State-Wechsel. chat:final/error senden idle.
- Bridge: Neuer cancel_request-Handler ruft Diagnostic /api/cancel per HTTP.
- Diagnostic: Neuer POST /api/cancel Endpoint (gleiche Logik wie WS-Cancel).
- RVS: agent_activity + cancel_request in ALLOWED_TYPES.
- App: Gelber Indicator ueber der Input-Bar mit Text je nach Activity,
  roter Abbrechen-Button. Cancel sendet cancel_request via RVS.
- issue.md: Erledigte Bugfixes + Features konsolidiert.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:22:02 +02:00
duffyduckandClaude Opus 4.7 58e3cfd3e6 feat: Session export as markdown in Diagnostic
- ⬇ Button per Session-Zeile — exportiert auch inaktive Sessions
- Server parst JSONL, extrahiert User/Assistant-Nachrichten mit Timestamp
- Metadata-Prefix wird entfernt, Markdown mit # Session-Header generiert
- Browser-Download via Blob + download-Attribut

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:14:15 +02:00
duffyduckandClaude Opus 4.7 7de4ee8f5b fix: Stuck "ARIA denkt..." indicator after pipeline ends
- pipelineEnd() now broadcasts agent_activity: idle unconditionally
- chat:error and chat:final paths broadcast idle outside of active pipeline
- Gateway close event ends active pipeline + broadcasts idle
- Prevents indicator from hanging after timeout/error/disconnect

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:11:12 +02:00
duffyduckandClaude Opus 4.7 213edac3a7 fix: Session persistence - respect user choice across container restarts
- sessionFromFile flag prevents auto-pick after first start
- Atomic write (temp + rename) with loud error logging
- Auto-pick filters out aria-bridge/aria-diagnostic when user sessions exist
- handleSetActiveSession reports persistence failures to client

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 11:03:26 +02:00
duffyduckandClaude Opus 4.6 acc13aef6b fix: Speech gate - only send recording if actual speech detected
- VAD_SPEECH_THRESHOLD_DB = -35 (louder than silence threshold)
- Needs 300ms of speech before counting as real speech
- Recording discarded if only background noise detected
- Prevents sending garbage to Whisper in conversation mode

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 18:20:05 +02:00
duffyduck 4bbc6f7787 release: bump version to 0.0.3.7 2026-04-11 13:18:17 +02:00
duffyduckandClaude Opus 4.6 20f2ea1829 fix: Conversation mode starts recording immediately when ear button tapped
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 13:15:26 +02:00
duffyduckandClaude Opus 4.6 2d23f0668b docs: update README with conversation mode, multi-attachments, markdown cleanup
- Conversation mode (ear button) documented in App Features
- Multiple attachments + paste support
- Markdown cleanup for TTS
- Auto-Update FileProvider + check button
- Roadmap: 22 items in Phase 1 completed

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:43:09 +02:00
duffyduckandClaude Opus 4.6 d6030a06b7 docs: update issue.md - move completed items, clean up open list
28 items completed, 10 remaining open

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:23:04 +02:00
duffyduck 0df76e2af6 release: bump version to 0.0.3.6 2026-04-11 12:19:00 +02:00
duffyduckandClaude Opus 4.6 f80fe1df93 fix: Inverted FlatList - newest messages always visible at bottom
- No more scrollToEnd/scrollToIndex needed
- FlatList inverted=true with reversed data
- New messages appear at bottom automatically
- User scrolls up to see history (natural chat behavior)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:17:32 +02:00
duffyduck cff421bc53 release: bump version to 0.0.3.5 2026-04-11 12:13:41 +02:00
duffyduckandClaude Opus 4.6 bca925d385 fix: Use scrollToIndex with viewPosition:1 for reliable bottom scroll
- scrollToIndex targets last message at bottom of viewport
- onScrollToIndexFailed fallback to scrollToEnd
- More reliable than scrollToEnd with dynamic heights

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:12:24 +02:00
duffyduck 9abde89805 release: bump version to 0.0.3.4 2026-04-11 12:09:23 +02:00
duffyduckandClaude Opus 4.6 ea4f639fcb fix: Auto-scroll retry with multiple delays (100, 300, 600, 1000ms)
FlatList needs time to render - single setTimeout(150) was unreliable.
Now tries 4 times on initial load, 2 times for new messages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:07:54 +02:00
duffyduck 64cd5f7d52 release: bump version to 0.0.3.3 2026-04-11 12:04:37 +02:00
duffyduckandClaude Opus 4.6 843ebe1d8f fix: Remove duplicate closure ending in ChatScreen (build error)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 12:03:20 +02:00
duffyduckandClaude Opus 4.6 764619f076 fix: Comprehensive markdown/formatting cleanup for TTS (Piper + XTTS)
- Remove **bold**, *italic*, `code`, code blocks, links, headers, quotes, lists
- Replace newlines with natural pauses (period/comma)
- Remove quotation marks, empty brackets
- Fixes text being swallowed/garbled by TTS engines

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 11:47:04 +02:00
duffyduckandClaude Opus 4.6 e3a0cfb55a docs: mark conversation mode as done, keep Porcupine as Phase 2
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 11:42:33 +02:00
duffyduckandClaude Opus 4.6 2929749314 feat: Conversation mode (ear button) - auto-record after ARIA speaks
- Ear button activates conversation mode (green dot)
- After TTS playback finishes → 800ms pause → auto-start recording
- VAD stops recording on silence → sends to ARIA → ARIA answers → TTS → loop
- Like a natural conversation / walkie-talkie mode
- Audio service fires onPlaybackFinished when queue empty

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 11:40:55 +02:00
duffyduckandClaude Opus 4.6 51b9512f4e docs: mark scroll bugs as fixed in issue.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 11:37:53 +02:00
duffyduckandClaude Opus 4.6 ffcfa44eef fix: Auto-scroll to last message on app start + new messages
- useEffect on messages array instead of onContentSizeChange
- Instant jump (no animation) when loading history
- Animated scroll for single new messages
- Scroll pauses when user scrolls up, resumes at bottom

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 11:37:30 +02:00
duffyduckandClaude Opus 4.6 6363da97b1 feat: Multiple attachments + paste support (App + Diagnostic)
App:
- Multiple pending attachments (horizontal scroll preview)
- Individual remove (X) or clear all
- Send button shows when any attachment pending
- All files sent before text message

Diagnostic:
- Clip icon for file selection (multiple)
- Paste images/files from clipboard (Ctrl+V)
- Pending preview with thumbnails
- Files sent via RVS before text message

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 11:34:33 +02:00
duffyduckandClaude Opus 4.6 07ed2cdcf6 docs: mark attachment text feature as done in issue.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 10:06:13 +02:00
duffyduckandClaude Opus 4.6 5ad68b7dfc feat: Attachments not sent immediately - add text/voice before sending
- File/photo selection stores as pending (not sent immediately)
- Preview bar shows pending attachment above input field
- User can add text message before sending (e.g. "Was siehst du?")
- Send button appears when attachment is pending (even without text)
- Placeholder changes to "Text zum Anhang (optional)..."
- X button to cancel pending attachment
- File + text sent together (file first, then chat message)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 10:05:50 +02:00
duffyduckandClaude Opus 4.6 8a6ee018ea docs: mark text message bug as fixed in issue.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 09:59:48 +02:00
duffyduckandClaude Opus 4.6 b42590ff95 docs: mark auto-update bugs as fixed in issue.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 09:54:57 +02:00
duffyduck 056b579c47 release: bump version to 0.0.3.2 2026-04-11 09:53:54 +02:00
duffyduckandClaude Opus 4.6 576e612cd0 fix: release.sh clears Metro + Gradle cache before build (version consistency)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 09:51:41 +02:00
duffyduck c2faa06a15 release: bump version to 0.0.3.1 2026-04-10 23:19:40 +02:00
duffyduckandClaude Opus 4.6 d3ed3556eb fix: Bridge chat handler was missing send_to_core (text messages ignored)
The chat handler checked sender but never forwarded the text to aria-core.
Only voice messages worked because they went through the audio→STT→send_to_core path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 23:13:29 +02:00
duffyduck d960d125c0 release: bump version to 0.0.3.0 2026-04-10 09:07:20 +02:00
duffyduck 89d5d7ec0a release: bump version to 0.0.2.9 2026-04-10 09:01:47 +02:00
duffyduckandClaude Opus 4.6 ea0c13936b fix: release.sh deletes old APKs on RVS before uploading new one
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 09:00:45 +02:00
duffyduckandClaude Opus 4.6 773c976822 fix: Auto-update APK install via FileProvider + dynamic version
- Native ApkInstallerModule: FileProvider content:// URI for Android 7+
- REQUEST_INSTALL_PACKAGES permission in AndroidManifest
- file_paths.xml for FileProvider cache access
- APP_VERSION reads from package.json (not hardcoded)
- "Auf Updates pruefen" button in Settings
- Version display reads from package.json dynamically

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 08:59:52 +02:00
duffyduckandClaude Opus 4.6 cd05ed2379 docs: add auto-update FileProvider bug + update check button to issue.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 08:55:30 +02:00
duffyduck 054e4057d8 release: bump version to 0.0.2.8 2026-04-10 08:49:47 +02:00
duffyduckandClaude Opus 4.6 3943e79bb1 docs: document .env.example with detailed comments, explain both tokens in README
- ARIA_AUTH_TOKEN: Gateway auth (who can talk to ARIA)
- RVS_TOKEN: Pairing token (same room in RVS relay)
- RVS_UPDATE_HOST: SSH target for auto-update APK copy
- All variables with German comments and examples

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 08:45:26 +02:00
duffyduckandClaude Opus 4.6 87f4317c15 docs: add auto-update APK not reaching RVS bug to issue.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 08:39:59 +02:00
duffyduckandClaude Opus 4.6 50aa793910 fix: Proxy SSH volume read-write (ARIA can manage keys without -F workaround)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 08:34:35 +02:00
duffyduckandClaude Opus 4.6 5efc9865a8 docs: add 6 new bugs/features to issue.md
- Session persistence on container restart
- App: text/image/attachment messages not working (only voice)
- App: audio stops randomly
- App: auto-scroll to last message on start + new messages
- App: add text/voice to attachments
- Prioritized bugs section

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 08:31:49 +02:00
duffyduckandClaude Opus 4.6 949c573c49 fix: XTTS chunk size 150 chars (faster render, preload overlaps playback)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:52:56 +02:00
duffyduckandClaude Opus 4.6 f7f450a09d fix: XTTS streaming mode - send each chunk immediately, comma between sentences
- Back to streaming: render chunk → send immediately → next chunk
- App plays with preloading queue (no waiting for all chunks)
- Comma instead of dot between sentences in chunk (no "Punkt" read aloud)
- Sentence-ending dots already removed

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:48:50 +02:00
duffyduckandClaude Opus 4.6 81f7c38383 fix: XTTS splits concatenated audio into ~8s parts (seamless with preload)
- All chunks rendered and PCM concatenated (consistent voice)
- Split into ~8 second WAV parts (not per-sentence)
- 8s is long enough for preload overlap, small enough for WebSocket
- Parts include part/totalParts metadata

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:41:14 +02:00
duffyduckandClaude Opus 4.6 2c785cb37a feat: XTTS concatenates chunks into seamless WAV (no stuttering)
- All chunks rendered sequentially, PCM data concatenated
- Single WAV with proper header sent back (no queue needed in app)
- If total > 800KB, split into parts (WebSocket limit)
- Eliminates stuttering between sentences

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:40:16 +02:00
duffyduckandClaude Opus 4.6 57e65b061c docs: update issue.md with XTTS streaming as next priority
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:38:21 +02:00
duffyduck aa54765b03 release: bump version to 0.0.2.7 2026-04-10 02:24:58 +02:00
duffyduckandClaude Opus 4.6 8929bc99bb fix: XTTS groups sentences into ~250 char chunks for consistent voice quality
- 2-3 sentences per chunk (more context = stable voice/volume)
- Max 250 chars per chunk (keeps WebSocket packets manageable)
- Dots re-added between sentences within a chunk (natural pauses)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:23:29 +02:00
duffyduckandClaude Opus 4.6 0428c06612 fix: Audio preloading to prevent stuttering, remove trailing dots for XTTS
- Preload next audio while current plays (eliminates gap between sentences)
- Remove trailing dots from sentences (XTTS reads them aloud)
- stopPlayback cleans up preloaded audio

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:21:19 +02:00
duffyduck a7eb3cf433 release: bump version to 0.0.2.6 2026-04-10 02:11:04 +02:00
duffyduckandClaude Opus 4.6 e4e0e793a8 fix: Audio queue for sequential TTS playback (no overlap/skip)
- Audio packets queued instead of stopping previous
- _playNext() plays sequentially, each sentence after the previous
- stopPlayback() clears queue
- Fixes overlapping/skipping with XTTS sentence-by-sentence rendering

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:09:35 +02:00
duffyduckandClaude Opus 4.6 b3d3b8b6bc fix: XTTS bridge splits text into sentences sequentially
- XTTS-Bridge does sentence splitting (not ARIA-Bridge)
- Sequential rendering: correct order guaranteed
- Each sentence sent as separate xtts_response
- Markdown removal before splitting
- App starts playback after first sentence (faster UX)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 02:03:29 +02:00
duffyduckandClaude Opus 4.6 06bc456221 fix: XTTS splits long text into sentences before sending (WebSocket size limit)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:56:25 +02:00
duffyduckandClaude Opus 4.6 3461f45207 docs: update README with XTTS v2 setup details, voice cloning guide
- Architecture diagram for XTTS flow (Gaming-PC ↔ RVS ↔ ARIA-VM)
- Port 8020 (not 8000), token must match, model caching
- Voice cloning step-by-step guide
- TTS engine switching (Piper/XTTS) with fallback
- Known limitation: RVS zombie connections

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:49:08 +02:00
duffyduckandClaude Opus 4.6 a17d4acc13 fix: XTTS bridge shares /voices volume with XTTS server
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:40:41 +02:00
duffyduckandClaude Opus 4.6 62fd9193a1 fix: XTTS voice dropdown shows saved voice after page reload
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:34:00 +02:00
duffyduckandClaude Opus 4.6 2329645df4 fix: XTTS voices list + upload use fresh RVS connection with response wait
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:24:55 +02:00
duffyduckandClaude Opus 4.6 8a435ddf6c fix: voice upload uses send() via server, not client-side sendToRVS_raw
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:15:29 +02:00
duffyduckandClaude Opus 4.6 25b754ba31 fix: voice upload Base64 conversion (chunked, no stack overflow)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 01:08:32 +02:00
duffyduckandClaude Opus 4.6 b734593bf2 fix: Bridge _send_to_rvs ping-check before send, force reconnect on zombie
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 00:37:22 +02:00
duffyduckandClaude Opus 4.6 16847ce6f7 fix: TTS toggle global above engine selector, health check /docs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 00:27:55 +02:00
duffyduckandClaude Opus 4.6 6300829317 fix: XTTS model cache volume path /app/xtts_models
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 23:44:29 +02:00
duffyduckandClaude Opus 4.6 a1e1ee31bd fix: XTTS bridge port 8020, longer startup wait
- XTTS API runs on port 8020 (not 8000)
- Bridge waits up to 5min for model download (30x10s)
- Health check uses / instead of /docs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 23:39:45 +02:00
duffyduck 7ed70b876d updated image public path 2026-04-07 23:06:26 +02:00
duffyduck 3ca85da906 release: bump version to 0.0.2.5 2026-04-05 20:12:56 +02:00
duffyduck d6a89168ef release: bump version to 0.0.2.4 2026-04-05 19:51:19 +02:00
duffyduckandClaude Opus 4.6 cb33a20694 docs: update README with XTTS, auto-update, watchdog, TTS settings
- Architecture: Added XTTS v2 (Gaming-PC) and auto-update flow
- Diagnostic: Thinking indicator, cancel button, TTS tab, voice cloning
- App: Play button, chat search, auto-update, voice speed settings
- RVS: Auto-update APK distribution over WebSocket
- Watchdog: 2min warning → 5min doctor --fix → 8min container restart
- Roadmap: Phase 1 fully completed, updated Phase 2+3

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:46:16 +02:00
duffyduckandClaude Opus 4.6 a242693751 feat: XTTS v2 integration, auto-update system, TTS engine abstraction
- XTTS v2: Docker setup for Gaming-PC (GPU), bridge via RVS relay
- XTTS: Voice cloning UI in Diagnostic (multi-file upload)
- XTTS: Engine selectable (Piper local vs XTTS remote) with fallback
- Auto-Update: RVS serves APK over WebSocket (no HTTP needed)
- Auto-Update: App checks version on start, prompts install
- Auto-Update: release.sh copies APK to RVS via scp
- Bridge: TTS engine abstraction (piper/xtts), config persistent
- Bridge: xtts_response handler, tts_request on-demand
- Diagnostic: TTS engine dropdown, XTTS voice panel, voice cloning
- App: Play button on ARIA messages, chat search, update service
- Wake word: Disabled LiveAudioStream (crash fix), Phase 1 placeholder
- Watchdog: Container restart after 8min stuck
- Chat backup: on-the-fly to /shared/config/chat_backup.jsonl

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:42:10 +02:00
197 changed files with 3379 additions and 52249 deletions
-15
View File
@@ -1,15 +0,0 @@
# Wo erreicht die Dev-Maschine die aria-wohnung VM?
# Kopiere diese Datei nach .claude/aria-vm.env und passe die IP an.
# .claude/aria-vm.env ist gitignored (lokal pro Maschine).
#
# Verwendung in Bash:
# source .claude/aria-vm.env
# curl -s "$ARIA_BRAIN_URL/memory/stats"
#
# Im docker-compose-Netz aria-net laufen die Hostnamen ohnehin direkt
# (aria-brain, aria-bridge, aria-qdrant). Diese Datei brauchen nur
# Hosts AUSSERHALB der VM (z.B. die Dev-Maschine wo Claude Code laeuft).
ARIA_VM_HOST=192.0.2.1
ARIA_DIAG_URL=http://192.0.2.1:3001
ARIA_BRAIN_URL=http://192.0.2.1:3001/api/brain
+1 -26
View File
@@ -15,22 +15,12 @@ ARIA_AUTH_TOKEN=change-me-to-a-long-random-string
# App, Bridge, Diagnostic und XTTS-Bridge verbinden sich hierueber.
# Alle muessen den gleichen Host, Port und Token nutzen.
# Hostname des RVS-Servers (z.B. rvs.example.de oder example.com)
# WICHTIG: muss oeffentlich aufloesbar sein (DNS), nicht nur intern.
# Wird auch fuer OAuth-Callback-URLs verwendet — Spotify/Google/etc.
# redirecten Stefan im Browser an https://{RVS_HOST}/oauth/callback/{service}.
# Hostname des RVS-Servers (z.B. rvs.example.de oder mobil.hacker-net.de)
RVS_HOST=rvs.example.de
# Port auf dem der RVS laeuft (muss mit rvs/docker-compose.yml uebereinstimmen)
RVS_PORT=443
# Oeffentlich erreichbarer TLS-Port — was Browser/Provider von aussen sehen.
# Meist identisch mit RVS_PORT, kann aber abweichen wenn ein TLS-Terminator
# (Caddy/Nginx) davor steht der z.B. 444 auf intern 3000 mappt. Wird fuer
# die OAuth-Callback-URL benutzt; muss zu dem Eintrag im Provider-Dashboard
# passen. Leer/ungesetzt = RVS_PORT wird verwendet.
RVS_PORT_PUBLIC=
# TLS (wss://) verwenden? true = verschluesselt, false = unverschluesselt (ws://)
RVS_TLS=true
@@ -45,21 +35,6 @@ RVS_TLS_FALLBACK=true
# Generieren: ./generate-token.sh (traegt den Token automatisch ein)
RVS_TOKEN=
# ── Brain-Timeouts ───────────────────────────────
# Brain redet via HTTP mit dem Proxy-Container. Da der Proxy non-streaming
# antwortet (Response kommt erst nach subprocess-close), kann ein Brain-Call
# bei langen Agent-Sessions (Pentests, Multi-Step-Tasks) >1h dauern.
# PROXY_TIMEOUT_SEC ist der httpx-Read-Timeout im Brain — wir setzen ihn
# bewusst hoch (24h), der Proxy hat einen eigenen Idle-Watchdog
# (ARIA_IDLE_TIMEOUT_MS in der proxy-Logik, default 20min Inaktivitaet)
# der den Subprocess killt wenn wirklich was haengt.
# Connect/Write/Pool bleiben klein damit toter Proxy in 10s erkannt wird.
PROXY_TIMEOUT_SEC=86400
# Diese drei sind defensive Defaults — aendern nur wenn netzwerk-bedingt noetig.
# PROXY_CONNECT_TIMEOUT_SEC=10
# PROXY_WRITE_TIMEOUT_SEC=30
# PROXY_POOL_TIMEOUT_SEC=10
# ── Gitea — Release-Verwaltung ───────────────────
# Wird von release.sh genutzt um APKs auf Gitea zu veroeffentlichen.
# Kennwort wird beim Release interaktiv abgefragt (nicht in .env!).
+9 -38
View File
@@ -9,41 +9,15 @@
.env.*
!.env.example
!.env.*.example
aria-data/config/*.env
!aria-data/config/*.env.example
!aria-data/config/openclaw.env
# Lokale Dev-Maschinen-Settings fuer Claude Code (z.B. wie erreicht die
# Dev-Maschine die aria-wohnung-VM). .example ist Repo-Inhalt, echte
# Werte pro Maschine selbst pflegen.
.claude/*.env
!.claude/*.env.example
# Lokale Claude-Permission-Allowlist mit echten Server-IPs — nicht ins (oeffentliche) Repo.
.claude/settings.json
# ── ARIAs Gedächtnis (nur per tar gesichert) ────
aria-data/brain/
# brain-import/ ist nur ein Drop-Folder: Stefan packt MDs rein wenn er
# was migrieren will, klickt im Diagnostic „Migration aus brain-import/",
# fertig. Die MDs gehoeren NICHT ins Repo (koennen private Daten enthalten,
# sind eh ephemeral). Verzeichnis selbst bleibt im Git via .gitkeep,
# README erklaert den Zweck.
aria-data/brain-import/*
!aria-data/brain-import/.gitkeep
!aria-data/brain-import/README.md
# .aria-debug/ — App-Crash-Logs die tools/fetch-app-logs.sh hier ablegt.
# Komplett lokal, enthaelt potentiell private Stacktraces / Daten.
.aria-debug/
# ── ARIAs Gedächtnis (Vector-DB, Skills, Models) ──
# Backup via Diagnostic → Gehirn-Export (tar.gz), nicht via Git.
aria-data/brain/data/
aria-data/brain/qdrant/
# Diagnostic-State (aktive Session etc.)
aria-data/config/diag-state/
# ── Shared Volume (Bind-Mount statt Docker-managed) ──
# Enthaelt User-Uploads, Voice-Cloning-Samples, OAuth-Tokens,
# chat_backup.jsonl, Memory-Attachments, runtime-state. Hunderte MB,
# enthaelt PRIVATE Daten. Backup via Diagnostic, nicht via Git.
aria-shared/
# ── Stimmen (große Binärdateien) ─────────────────
aria-data/voices/
# ── Node / npm ──────────────────────────────────
node_modules/
@@ -72,6 +46,7 @@ desktop/dist/
__pycache__/
*.pyc
*.pyo
bridge/__pycache__/
# ── macOS ────────────────────────────────────────
.DS_Store
@@ -80,8 +55,4 @@ __pycache__/
.vscode/settings.json
.idea/
*.swp
*.swo
# Lokale LLM-Modelle (Plan B) — GGUF/HF-Cache sind mehrere GB, nicht ins Repo
xtts/models/*
!xtts/models/.gitkeep
*.swo
-310
View File
@@ -2,316 +2,6 @@
Alle Änderungen am Projekt. Format: [Keep a Changelog](https://keepachangelog.com/de/1.1.0/)
> **Hinweis:** Dieser Changelog hatte eine große Lücke — er endete bei `0.0.0.5`
> (2026-03), das Projekt lief aber bis `0.2.0.2` (2026-07) weiter (u. a. OAuth,
> Voice-Streaming, Speaker-ID, Datei-Manager). Ab dem Projekte-/Multi-Threading-
> Epos (2026-07) wird wieder gepflegt; die dazwischenliegenden Versionen
> `0.0.0.6``0.1.9.6` sind nicht rückwirkend nacherfasst.
---
## [0.2.3.0] — 2026-07-19 — Satelliten: ARIAs Augen & Hände in fremden Netzen 🛰️
### Hinzugefügt
**Neuer eigenständiger Container `satellite/`** — ein Außenposten, den du in einem beliebigen Netz (Büro, Werkstatt …) deployst. Er verbindet sich als RVS-Client in deinen Raum und gibt ARIA Zugriff auf **genau dieses Netz**, ohne dass der Haupt-Stack dort steht.
- **Entdeckung (Info):** mDNS/Zeroconf (Chromecast, AirPlay, Sonos, Drucker, NAS …), SSDP/UPnP + **DIAL** (Smart-TVs, Fire TV), ARP-Tabelle (rohe Hosts) → Live-Inventar.
- **Steuerung (mit Guards):** **DIAL-App-Launch** (z.B. „ARIA, spiel YouTube-Video X auf dem Büro-Stick" → Fire TV), **Wake-on-LAN**, generisches **HTTP**. Nur wenn `CONTROL_ENABLED=true`, nur Aktionen aus der `CONTROL_ALLOWLIST`, alles geloggt, read-only per `.env` abschaltbar. Reagiert nur auf den eigenen RVS-Raum (Token). Keine offenen Ports.
- **Adressierung** über `SATELLITE_LOCATION` (z.B. „Büro") — mehrere Satelliten im selben Raum, jeder mit eigenem Namen.
**End-to-end verdrahtet:**
- `satellite/`: eigener Stack (`docker compose` mit `network_mode: host`), `.env.example`, README.
- RVS: neue Message-Typen `sat_hello / sat_discover / sat_devices / sat_command / sat_result`.
- Bridge: Satelliten-Registry (`sat_hello`) + Future-Relay (`/internal/satellite`, `/internal/satellite-list`) analog zum flux-Muster.
- Brain: Tools `satellite_list`, `satellite_devices`, `satellite_command` + Seed-Regel, die ARIA den Ablauf beibringt (erst list, dann devices, dann command).
- **Diagnostic: neuer Tab „Satelliten"** — zeigt live welche Satelliten verbunden sind (online/offline, Standort, Capabilities, read-only vs. steuerbar) und pro Satellit ein „Geräte scannen" (löst `sat_discover` aus → erkannte Geräte mit Typ/IP/Modell/DIAL/MAC).
### Deploy
Satellit im Ziel-Netz: `cd satellite && cp .env.example .env && docker compose up -d --build`. Haupt-Stack: `git pull && docker compose up -d --build brain bridge` + RVS-Stack `up -d --build`. Kein APK-Rebuild.
---
## [0.2.2.3] — 2026-07-17 — ARIA liest andere Projekt-Chats wirklich (volle Historie)
### Behoben
- **`project_summary` fand fast nie Inhalte.** Es las nur ARIAs rollendes Kontextfenster (~50 Turns über ALLE Projekte) — ältere/andere Projekt-Chats sind da längst rausdistilliert. „Hol dir die Infos aus Projekt X" lieferte deshalb leere Ergebnisse, und ARIA wusste nicht, wie sie an die Historie kommt. Jetzt liest das Tool die **echte, volle Historie aus `chat_backup.jsonl`** (im Brain gemountet) — die letzten ~20 Turns des Zielprojekts, unabhängig davon wie lange man da nicht war. Standort-Hints in User-Turns werden rausgefiltert. Fallback aufs Fenster, falls das Backup fehlt. Tool-Beschreibung geschärft, damit ARIA es direkt aufruft.
- Nebenbei bereinigt: `mac_os_update_fehler` war durch den alten `set_project_kind`-Bug (0.2.2.1) fälschlich `kind=code` — auf `chat` zurückgesetzt.
### Deploy
`git pull && docker compose up -d --build brain` (kein APK-Rebuild nötig).
---
## [0.2.2.2] — 2026-07-17 — Voice-Projektwechsel zurück — aber gerätelokal
### Hinzugefügt
- **„ARIA, geh in Projekt X" per Sprache wechselt wieder das Projekt** — aber **nur auf dem Gerät, das den Befehl gab**. Andere App-Instanzen und das Diagnostic bleiben in ihrem Projekt.
- Umsetzung: Jedes Gerät merkt sich die IDs seiner eigenen Anfragen (Text-`clientMsgId` + Voice-`audioRequestId`). Der Brain/Voice-Router hängt an jedes `project_changed`-Event die auslösende `clientMsgId` an; die App folgt dem Wechsel nur, wenn die ID eine **eigene** ist. Deckt beide Voice-Pfade ab (ARIAs `project_enter`/`exit` via `send_to_core` **und** den Bridge-Voice-Router „für Projekt X: …" / „zurück zum Hauptchat").
- Manuelles Umschalten bleibt wie gehabt gerätelokal über den Drawer.
### Deploy
`git pull && docker compose up -d --build bridge` + APK 0.2.2.2 (kein Brain-Rebuild nötig).
---
## [0.2.2.1] — 2026-07-17 — Projekt-Fokus wirklich pro Gerät unabhängig
### Behoben
- **`set_project_kind` markierte das falsche Projekt.** Es nutzte den **globalen** `active_project` (geräteübergreifend) statt des Projekts, in dem der aktuelle Request läuft. Folge: Obwohl auf der App „Basic os" aktiv war, bekam das global-aktive „Mac OS Update Fehler" `kind=code`. Jetzt wirkt das Tool auf die pro Request mitgesendete `project_id` (in `_dispatch_tool` durchgereicht) — jede App-/Diagnostic-Instanz markiert ihr eigenes Projekt.
- **App wurde von fremden `project_changed`-Broadcasts ins andere Projekt gezogen.** Ein Projektwechsel/anlegen durch ARIA, das Diagnostic oder eine andere App-Instanz erzwang auf **allen** Geräten einen Fokuswechsel. Der Projekt-Fokus ist jetzt **rein gerätelokal**: Broadcasts aktualisieren nur Namen + Typ, wechseln aber nicht mehr das Projekt. Umschalten geht ausschließlich lokal über den Projekt-Drawer. So arbeitet jedes Gerät unabhängig in seinem eigenen Projekt (auch mehrere App-Instanzen).
- Hinweis: „ARIA, geh in Projekt X" per Sprache wechselt das App-Projekt dadurch **nicht mehr** automatisch — bewusst, damit Geräte unabhängig bleiben. Wechseln über den Drawer.
### Deploy
`git pull && docker compose up -d --build brain` + APK 0.2.2.1 neu bauen.
---
## [0.2.2.0] — 2026-07-17 — Workbench: Taskleisten-Dock statt Zoom-Landkarte + bedienbare VNC-Konsole
### Geändert
**Cockpit-Navigation neu gedacht — Dock statt Pinch-Canvas**
- Die Zoom-Landkarte (mit 2 Fingern rauszoomen, Kachel finden, reintippen) fühlte sich auf 5 Zoll fummelig an. Ersetzt durch eine **Taskleiste unten im Daumenbereich** (Chat · Code · Desktop): **ein Tap wechselt sofort** das Panel, ein animierter Indikator gleitet unter das aktive Icon. Desktop-*Umfang*, Handy-*Ergonomie*.
- Jedes Panel ist **bildschirmfüllend** und Handy-optimiert; alle bleiben gemountet (nur das aktive ist sichtbar) → kein Remount, Chat behält RVS/Audio/Queue, WebViews ihren Zustand.
- Das Dock **blendet bei offener Tastatur aus** (mehr Platz zum Tippen) und respektiert die Gesten-Navigationsleiste (Safe-Area).
- **Aktivitäts-Punkte** am Dock: Code blau, sobald Dateien da sind; Desktop grün, wenn die VM verbunden ist.
- Entfällt: Pinch/Pan-Canvas, Übersichts-Button im Header, die „Landkarten"-Thumbnails.
**noVNC-Konsole endlich bedienbar**
- Steuerungs-Leiste im Desktop-Panel: **⌨ Tastatur** (blendet die Handy-Tastatur ein, tippt direkt in die VM — inkl. Enter/Backspace/Pfeiltasten), **Strg+Alt+Entf**, und **⤢ Fit ↔ 1:1**. Tippen/Ziehen steuert weiterhin die Maus.
### Deploy
Nur **App neu bauen** (kein Backend). APK 0.2.2.0.
---
## [0.2.1.9] — 2026-07-17 — Kompakt ↔ Cockpit: Umschalter für den Kachel-Desktop
### Hinzugefügt
- **Ansichts-Umschalter im Header** („⧉ Kompakt" / „⧉ Cockpit"): Die App startet in **Kompakt** — der klassische Vollbild-Chat, **exakt wie vor dem Umbau** (Default, Mama-tauglich). Ein Tap auf den Button oben rechts schaltet auf **Cockpit** — den zoom-/verschiebbaren Kachel-Desktop. Persistiert über Neustart (`aria_view_mode`).
- **Warum:** Nach dem 0.2.1.8-Deploy sah die App „unverändert" aus — korrekt, denn im normalen Chat gibt es nur eine Kachel (= Vollbild-Chat). Der Umschalter macht den Cockpit-Modus jetzt **explizit sichtbar/steuerbar**, statt nur bei Code-Projekten aufzutauchen.
- Im Cockpit ist die **Übersicht jetzt immer erreichbar** (auch im Hauptchat): „⤢ Übersicht" sitzt **im Header links** (kollidiert nicht mehr mit dem Abbrechen-Button der „ARIA denkt"-Leiste), dazu 2-Finger-Pinch/Pan und Hardware-Back.
- Im Cockpit werden **immer alle vier Kacheln** gezeigt (Chat/Editor/Desktop/Vorschau) — Editor/Desktop/Vorschau als Platzhalter mit Status-Untertitel („kein Code-Projekt" / „kein Desktop"), bis ARIA ein Code-Projekt startet bzw. eine VM läuft. Vorher wirkten sie „verschwunden", weil sie erst bei Code-Projekten auftauchten.
---
## [0.2.1.8] — 2026-07-17 — Desktop-Workspace: zoombarer Canvas, Live-Code-Editor, QEMU/VNC
### Hinzugefügt
**Zoom-/verschiebbarer Workspace-Canvas (App)**
- Die App ist jetzt eine desktop-artige Arbeitsfläche: rausgezoomt sieht man eine **Landkarte aus Kacheln** (Chat, Editor, Desktop, Vorschau), die man mit **2 Fingern zoomt und verschiebt**. Tippt man eine Kachel an, zoomt sie voll auf und wird **echt bedienbar** („Übersicht + Fokus"). „⤢ Übersicht" bzw. der Hardware-Back führen zurück zur Landkarte.
- Technisch: `react-native-gesture-handler` + `react-native-reanimated` (60 fps auf dem UI-Thread). Zwei Ebenen — eine skalierte Thumbnail-Welt und eine **Identity-Content-Ebene** (Scale 1), in der die schweren Inhalte (ChatScreen + WebViews) immer gemountet sind und nur die fokussierte sichtbar ist. Dadurch bleiben Touch-Koordinaten/Keyboard korrekt und nichts remountet beim Fokuswechsel. **Reiner Chat verhält sich exakt wie bisher** (eine Kachel, dauerhaft fokussiert).
**Live-Code-Editor für Code-Projekte (App + Bridge + Proxy)**
- Wird ein Projekt zum Code-Projekt (ARIA ruft `set_project_kind('code')`), erscheinen Editor- und Desktop-Kachel. Der Editor (WebView, selbstenthaltener Highlight-Editor, offline) **zeigt live, was ARIA schreibt** — und Stefan kann selbst editieren; Änderungen gehen zurück an ARIA.
- Fluss: ARIAs `Write`/`Edit` unter `/shared/projects/<projekt-id>/` werden im Proxy abgefangen und als `code_file` über die Bridge/RVS an die App gespiegelt; Stefans Edits kommen als `code_file_edit` pfad-sicher zurück ins selbe Verzeichnis.
**QEMU für alle Architekturen + Live-Desktop per VNC (Host + Bridge + App)**
- ARIA kann jetzt VMs für **jede Architektur** bauen/testen (x86, ARM, MIPS, PPC, RISC-V, SPARC) — Host-Helper `aria-vm` (`create/boot/screenshot/list/stop`), installiert via `host-provisioning/qemu-setup.sh`. KVM für x86-Gäste, sonst TCG. Beispiel: ein Win-3.11-System bauen und in QEMU testen.
- Der **VNC-Live-Desktop wird durch den RVS-Server getunnelt**: die Bridge brückt rohes RFB-TCP (QEMU `127.0.0.1:5901`) ↔ RVS (`vnc_data`/`vnc_input`, Base64-in-JSON), der noVNC-Client läuft in der App-WebView (`window.WebSocket`-Shim). Stefan bedient die VM **live mit Maus/Tastatur** in der Desktop-Kachel — NAT-sicher, kein offener Port am Host, kein websockify/noVNC auf dem Host nötig.
**Kleineres**
- Pro-Projekt-Layout: die zuletzt fokussierte Kachel wird pro Projekt gemerkt (`aria_workspace_layout`).
- Projekt-Modell bekommt `kind` ('chat'|'code'); Seed-Regel lehrt ARIA den Code-Projekt-Workflow (Arbeitsverzeichnis `/shared/projects/<id>/`, `aria-vm`, VNC landet automatisch in der App).
### Deploy
`git pull && docker compose up -d --build brain bridge proxy` · RVS-Stack `up -d --build` · Host: `bash host-provisioning/qemu-setup.sh` (einmalig, als root) · APK neu bauen (nach `npm install` einmalig `npm start --reset-cache` + `gradlew clean`, wegen der neuen nativen Module).
---
## [0.2.1.5] — 2026-07-12 — Pro-Projekt-Queue mit Rückfrage-Loop
### Hinzugefügt
**Nachrichten-Queue pro Projekt (App + Diagnostic)**
- Eine zweite Nachricht, während ARIA am aktuellen Task arbeitet, wird jetzt **angestellt** statt den laufenden Task abzubrechen (vorher: Barge-In-Cancel). Sie läuft der Reihe nach, **pro Projekt unabhängig** (paralleles Arbeiten in mehreren Projekten bleibt). Wartende Nachrichten zeigen als ⏸-Bubble — tippen entfernt sie aus der Warteschlange.
- **Rückfrage-Loop:** Stellt ARIA eine echte, blockierende Rückfrage, **pausiert** die Queue und deine nächste Eingabe beantwortet sie — bis eine finale Antwort kommt, dann läuft der nächste Queue-Eintrag (gleiches Muster). Banner „❓ ARIA fragt nach — deine Eingabe beantwortet das". Der Stop-Button bricht den aktuellen Task ab und schaltet zum nächsten.
- ARIA signalisiert eine Rückfrage über einen **unsichtbaren `[[AWAIT]]`-Marker** — wie speak/converse deklariert das Modell den Zustand selbst (kein „endet-mit-?"-Raten). Brain strippt ihn, gibt `awaiting_reply` durch `chat()``ChatOut` → Bridge-Chat-Payload. Local (tool-los) und Fast-Path markieren nie.
**Pro-Projekt-Textfeld-Entwürfe (App + Diagnostic)**
- Der Feldinhalt bleibt beim Projektwechsel erhalten: in Projekt X tippen, zu Y wechseln (leeres Feld), zurück zu X → dein Entwurf steht wieder da. In Storage persistiert.
**TTS-Abspiel-Queue (App)**
- Zwei fast gleichzeitig fertige Antworten sprechen jetzt garantiert **nacheinander** statt sich gegenseitig abzuschneiden. Vorher war das Timing-Glück (`PcmStreamPlayer.start()` ruft `stopInternal()` = flush/release, hätte die laufende gecuttet). Jetzt: „spielt hörbar" gilt bis zum echten `PcmPlaybackFinished` (nicht nur bis Stream-Ende); eine neue hörbare Antwort, die währenddessen ankommt, wird gepuffert und danach nachgespielt (Kette für 3, 4, …). Harter Stop/Barge-In/Mund-Button verwirft die Queue.
### Geändert
- **Voice bricht nicht mehr ab:** eine neue Sprachnachricht während ARIA arbeitet stoppt nur akustisch das TTS (sauberes Mikro) und wird über den Brain-Projekt-Lock serialisiert, statt den laufenden Task abzubrechen (passend zu „immer anstellen + Stop-Button"). Text-Senden erkennt Brain-busy als Fallback, damit auch nach einem voice-gestarteten Turn korrekt angestellt wird. Grenze: eine per Sprache gestartete Aufgabe erscheint nicht als löschbare ⏸-Bubble (Aufnahme wird live gestreamt, nicht app-seitig gepuffert).
---
## [0.2.1.4] — 2026-07-12 — Lokales LLM: der ehrliche Rückbau
### Geändert
**Lokales LLM wieder tool-los (B1a) — ein 8B ist ein schlechter Tool-Caller**
- B1b hatte dem lokalen Modell Werkzeuge (`run_*`/`web_search`) gegeben — die gemeinsame Wurzel von **zwei** Problemen: (1) ein 8B erfindet mit Werkzeug in der Hand lieber eine plausible Antwort („der Song ist X") statt es zu rufen → Halluzination; (2) das erzwang per-Skill-Guards (skaliert nicht). Local ist jetzt wieder **tool-los** = reines Reden; alles mit Grundwahrheit (Fakt/Live-Zustand/Gedächtnis/Aktion) gehört an Claude oder den deterministischen Fast-Path. Kein Skill-Ergebnis mehr fälschbar
- **Keine Input-Wortliste im Router:** eine kurz eingeführte `_LIVE_HINTS`-Blacklist (Wetter/Musik/… → Claude) wieder entfernt — aus offenem Freitext die Absicht per Wortliste zu raten ist nie vollständig, jeder Miss = ein Halo (nur von per-Skill auf per-Wort verschoben). Generisch = das Modell entscheidet **selbst** (`<<ESCALATE>>`); ein stärkeres lokales Modell übernimmt die Selbst-Erkennung später, bis dahin ist local per Einstellung abschaltbar (aus, nicht raus)
- Expliziter Nutzer-Wunsch „nimm Claude/Clodi" wird im Router respektiert (geht nie lokal)
### Behoben
- **Info-Halluzination:** local nannte manchmal aktuellen Song/Restzeit/Skip-Titel ohne `run_spotify` zu rufen (mal echt, mal frei erfunden — „Midnight City von M83" nie aufgerufen). Neuer Output-Guard `_claims_live_media_state` eskaliert behauptete Live-Auskünfte ohne echten Skill-Call an Claude; Local-Prompt zusätzlich gehärtet (nie Titel/Zeit/Gerät ohne Tool-Ergebnis; bei „OK: next" keinen Titel erfinden)
- **Leeres `<voice></voice>` machte TTS stumm:** Claude hängt reflexartig manchmal ein leeres Voice-Tag an → `clean_text_for_tts` nahm den leeren Inhalt → gar keine Sprachausgabe (Playlist „Fliegen" gesprochen, „Prodigy" stumm — reiner Claude-Output-Zufall, nicht Skill/Playlist-Name). Leeres/whitespace-Tag wird jetzt ignoriert, der normale Anzeigetext gelesen
- **Datei-Anhang erschien erst nach Seitenwechsel:** die Live-`chat`-Payload trug keine `files` (Anhänge kamen nur als separates `file_from_aria`-Event) → an der Nachricht tauchte die Datei erst nach Reload aus `chat_backup` auf. Bridge schickt die `files` jetzt in der chat-Payload, App hängt sie live an die Text-Bubble (wie der Reload-Pfad) und entfernt die redundante Solo-Bubble
- **TDZ-Zeitbombe (App):** `sendTextMessage` stand vor seinen Dependencies (`interruptAriaIfBusy`, `sendPendingAttachments`) im deps-Array — Temporal Dead Zone; lief nur dank Babels `const``var`-Hebung, ein strengerer Bundler hätte beim Mount weißgescreent. Deklaration hinter die Deps verschoben
- **QRScanner tsc-clean:** toter Prop `colorForScannerFrame` (existiert in `react-native-camera-kit` v13 nicht) entfernt; die fehlerhaften Lib-Typen (optionale Props als required markiert) lokal + dokumentiert umgangen → **Projekt komplett tsc-clean (0 Fehler)**
**Spotify-Skill — von ARIA live im Gespräch weiter geschärft**
- Skip (`next`/`previous`) sagt jetzt den **echten** neuen Titel an (holt den Track nach dem Skip via API) statt local einen erfinden zu lassen
- `playlist_play`/`search_and_play`/`play` nennen das **tatsächliche** Wiedergabegerät (aus `GET /v1/me/player`, kein Raten — verhinderte den Fehler, dass Claude ein falsch geratenes Gerät auch noch ansteuerte) und lesen konsistent vor; saubere „Sprach-Grammatik": Ansagen sprechen, Steuerbefehle (play/pause/transfer/volume) schweigen
- `yt-dlp-download`-Skill um einen MP3-Modus erweitert — ARIA hat das fehlende Werkzeug **selbst gebaut**, als eine deutsche Titelmelodie nicht auf Spotify lag (Web-Suche → YouTube-Download → MP3 in den Chat, in <1 min)
---
## [0.2.1.3] — 2026-07-11
### Hinzugefügt
- **`skill_get`-Tool:** ARIA liest den echten Quellcode + Manifest + Readme eines Skills, **bevor** sie ihn ändert — kein Blind-Rewrite mehr (vorher wurde ein guter Skill durch eine schlechtere Neufassung ersetzt, weil das referenzierte `skill_get` gar nicht existierte)
### Behoben
- **`converse` folgt dem Skill (Fast-Path):** auch ein Fast-Path-Befehl kann einen Skill auslösen, nach dem noch etwas zu sagen ist — `converse` kommt jetzt aus Manifest/Skill-Output statt hart auf `False`
- **Sprachnachricht-Bubble verschwand nach manuellem Stop:** bei „ohne Ohr" aufgenommener Sprachnachricht + Stop entfernte ein leeres stream-end-Endpoint die schon gefüllte Bubble; jetzt wird nur noch der unaufgelöste Platzhalter entfernt
---
## [0.2.1.2] — 2026-07-11 — Standort-Intelligenz + Skill steuert seine Ausgabe
### Hinzugefügt
**GPS → Ortsname im Standort-Präfix (keyless, keine Tokens)**
- Reverse-Geocoding der Koordinaten in der Bridge (Nominatim zoom=18: Straße+Hausnr, PLZ+Ort, Bundesland; Straßen-Ref + Autobahn-km via Overpass) — damit das lokale Modell nicht „Berlin" für Oldenburg rät; Ortsname wird **vor** dem Präfix-Bau awaited (rechtzeitig für die erste Nachricht)
- Fahrtrichtung als Himmelsrichtung **+ exakte Peilung in Grad** (Haversine/Bearing aus aufeinanderfolgenden Fixes, `MIN_MOVE_M`-Schwelle gegen Zittern)
**Skill steuert seine Ausgabe selbst — `speak` + `converse` pro Aufruf**
- Ein Skill entscheidet per JSON-Output `{speak, converse}` pro Operation, ob vorgelesen wird und ob danach 30 s weitergelauscht wird (Manifest-Default, Output überschreibt) — z. B. „was läuft" vorlesen aber kein Dialog, „nächstes Lied" stumm. In der Skill-Bauanleitung **mit dem WARUM** dokumentiert, damit die KI die Flags beim Bauen versteht (kein Hardcode im Brain)
### Behoben / Geändert
- **Generischer Skill-Prompt (kein Hardcode):** der Router beschreibt `run_*`-Skills generisch (weiß nicht mehr, welche „schwer" sind); ein Stop im 30-s-Lauschen beendet dieses jetzt wirklich (kein zweiter Gong / erneutes Öffnen)
- **Anti-Halluzination:** behauptet local eine Steuerbefehl-Quittung („Spotify: …", „Playlist abspielen") ohne das Tool wirklich zu rufen → Eskalation an Claude statt erfundene Bestätigung durchzulassen
---
## [0.2.1.1] — 2026-07-11
### Hinzugefügt
- **Skill entscheidet selbst, ob vorgelesen wird (`manifest.speak`):** Grundlage der späteren `speak`/`converse`-Architektur — der `speak`-Flag greift sowohl im lokalen als auch im Claude-Pfad, statt am fragilen leeren `<voice></voice>`-Hack zu hängen
---
## [0.2.0.6] — 2026-07-11
### Hinzugefügt
**Diagnostic + App — Projekte verstecken**
- Neues `hidden`-Flag pro Projekt (bleibt voll nutzbar, nur aus Listen ausgeblendet — unabhängig von `status`/`archived`); `PATCH /projects/{id} {hidden}`
- Diagnostic: 👁-Auge pro Projekt-Bubble (🙈 verstecken / 👁 dauerhaft sichtbar), Header-Toggle „Versteckte anzeigen (N)" blendet sie temporär gedimmt + „versteckt"-Badge ein — zum Ansehen/Auswählen ohne permanentes Enttarnen
- App (`ProjectsBrowser`): versteckte standardmäßig ausgeblendet (Mama sieht sie nicht), Auge pro Zeile + Toggle spiegeln das Diagnostic-Verhalten; geteilter `hidden`-Status übers Brain
**Diagnostic — Token-Ersparnis durch lokales LLM**
- `metrics.jsonl` trägt jetzt `source` (claude | local | fast-path); lokale Calls nutzen echte `usage`-Tokens vom Adapter, Fast-Path = 0 Prompt-Tokens (`by_source`-Aggregation, rückwärts-kompatibel)
- Neue Card „Lokales LLM & Claude-Ersparnis": pro Fenster (1h/5h/24h/30d) gesparte Claude-Calls (local + fast-path) + lokale Token-Last (eigene HW, kein Quota)
**Spotify-Skill — von ARIA selbst geschärft**
- Geräte-Transfer startet die Wiedergabe direkt mit (`play=true`) statt nur zu übertragen, inkl. Verifikation (`is_playing`-Check + expliziter Play-Fallback), Fuzzy-Gerätenamen und sauberen Exit-Codes; neue semantische Actions `play_on_device`/`search_and_play`/`playlist_play`/`queue_add`
### Behoben
- **Spotify-Resume (App):** nach einem Voice-Befehl blieb Spotify auf dem Handy pausiert. Statt des auf manchen Geräten (OnePlus) flakigen Audio-Focus-Nudge jetzt ein echter `KEYCODE_MEDIA_PLAY`-KeyEvent an die aktive MediaSession — gegated: nur wenn vor dem Dialog Musik lief (`isMusicActive`). Deterministisch, geräteunabhängig
- **TTS-Zahlen:** freistehende Ganzzahlen werden jetzt tag-unabhängig ausgeschrieben („23°C" → „dreiundzwanzig Grad Celsius", „100%" → „einhundert Prozent"). Regression, seit das lokale LLM (bewusst ohne `<voice>`-Tag) leichte Turns übernahm; neuer vollständiger Zahl→Wort-Konverter (0…999999) am Ende von `clean_text_for_tts`, lange Ziffernfolgen (IDs) bleiben Ziffern
- **„ARIA denkt" hängt:** Indikator + Abbrechen blieben stehen, obwohl der Turn laut Diagnostic fertig war. Die App räumt den kontext-scoped Indikator jetzt beim Eintreffen der Antwort selbst; die Bridge sendet zusätzlich ein `idle` für die Request-`projectId`, falls der Turn umgeroutet wurde (thinking ging mit Request-, idle mit Turn-`projectId`)
- **Lokale Tool-Fehler:** Action-Skills, die bei Exit 0 einen Fehlschlag nur im stdout-Text melden (Spotify: „Fehler beim Übertragen", „Gerät nicht gefunden"), eskalieren jetzt generisch an Claude statt vom lokalen LLM vorgelesen zu werden (Info-Tools wie web_search ausgenommen)
---
## [0.2.0.4 0.2.0.5] — 2026-07-11 — Plan B: Lokales LLM („Gemini-Feeling")
Ein kleines, schnelles Modell (**Qwen3 8B** via llama.cpp/llama-swap auf der AI-Box-GPU) übernimmt einfache Turns in **<1 s**; alles Schwere/Technische/Werkzeug-artige reicht ein Router automatisch an **Claude** weiter. Ziel: schnelle Antworten ohne die Claude-Max-Subscription aufzugeben.
### Hinzugefügt
**Lokales LLM (Brain + Bridge + Adapter)**
- Router (B1a): Heuristik + `<<ESCALATE>>`-Selbstabbruch entscheidet pro Turn lokal vs. Claude; schlanker System-Prompt mit demselben `IDENTITY_ANCHOR` wie Claude (Rolle hält), nur letzte 8 Turns (Speed)
- Lokale Tool-Fast-Lane (B1b): kuratierte Tools — `web_search` (self-hosted **SearXNG**, local-only), `memory_search`, `trigger_timer`, Spotify; Eskalation bei Tool-Fehler statt Raten
- Consumer-Kette gespiegelt zu FLUX: Brain → Bridge `/internal/local-llm` → RVS → `llm-adapter` → llama.cpp; `enable_thinking:false` (Qwen wickelte sonst die ganze Antwort in `<think>`)
- **B0.5:** llama-swap (Hot-Swap der Modelle on-demand) + Modellauswahl-Dropdown + Live-Lade-Status (loading/ready + Download-Hinweis) in Diagnostic
- **SearXNG** als 6. Container auf der ARIA-VM (keyless Meta-Suche, JSON-API)
**Quell-Badge (local / claude / fast-path)**
- Diagnostic: immer an den ARIA-Bubbles
- App: optionaler Schalter in den Einstellungen, pro Gerät gemerkt, default aus („ich will's, meine Mama nicht")
**TTS — System-Flag `speak` (ja/nein) pro Antwort**
- Die Quelle entscheidet übers Vorlesen (Fast-Path/Steuerbefehl = stumm, ARIA-Antwort = vorlesen), robust statt des fragilen leeren `<voice></voice>`-Hacks der beim Skill-Rebuild verloren ging
### Behoben / Geändert
- **Identität (Hauptchat):** Proxy nutzt jetzt `--system-prompt` (voller Replace) statt `--append-system-prompt` — die Claude-Code-Basis-Identität leakt nicht mehr in den Hauptchat (ARIA antwortete dort als „Claude Code" bzw. deutete die Persona als Injection). Dazu `IDENTITY_SEED` (synthetischer Grounding-Turn) + Gift-Wächter (Identity-Breaks werden nie in die History persistiert, Retry+Fallback) + Cleanup-Script gegen bereits vergiftete Turns
- **Datenschutz (kritisch):** harte Diskretions-Regel im `IDENTITY_ANCHOR` — ARIA kennt intime/private Details, gibt sie aber **NIE ungefragt** preis (nicht in Vorstellungen, „was weißt du über mich", Zusammenfassungen, Triggern); nur auf konkrete Nachfrage, knapp. Bereits ausgeplauderte Turns bereinigt. Lokales Tier eskaliert Personen-/Beziehungs-/Gedächtnisfragen an Claude (kennt das Gedächtnis + antwortet diskret)
- **Lokale Antwort nicht in `<voice>`** wickeln (Qwen imitierte den Tag aus dem Kontext → Anzeige war leer); **generische** Tool-Fehler-Eskalation statt per-Skill-Router-Hardcode (Router muss nicht wissen, welche Skills „schwer" sind)
---
## [0.2.0.3] — 2026-07-10
### Hinzugefügt
**Proxy — ARIA-Persona über echten System-Prompt-Kanal**
- Persona + Tool-Use-Format gehen jetzt über `--append-system-prompt` der Claude-CLI statt als `<system>`-getaggter User-Content im Prompt (`openai-to-cli.js`: Prompt = nur Verlauf, `systemPrompt` separat; neue `sed`-Zeile schleust `--append-system-prompt`,`options.systemPrompt` ins `buildArgs`-Array von `manager.js`)
**Multi-Threading — echte Parallelität in der App**
- `agent_activity`-Events tragen jetzt die `projectId` (Brain → Proxy `aria_project_id` → Bridge → App); der „ARIA denkt"-Indikator zeigt nur noch den **fokussierten** Kontext statt global zu flackern (`agentActivityByCtx`-Map)
- Kontext-scoped Cancel: neuer Proxy-Endpoint `/cancel {projectId}` killt nur die Subprozesse *eines* Kontexts (`/cancel-all` bleibt fürs NOT-AUS); Bridge-soft-Cancel + App-Abbrechen tragen die fokussierte `projectId`
**Diagnostic — Datei-Zuordnung**
- Projekt-Dropdown pro Datei im Datei-Manager (nutzt `/api/files-set-project`) — auch alt-hochgeladene Dateien nachträglich einem Projekt zuweisen
### Behoben
- **Identität:** fester `IDENTITY_ANCHOR` ganz oben im System-Prompt — ARIA verliert in (Pentest-)Projekten nicht mehr die Rolle bzw. deutet ihre eigene Aufgabe nicht mehr als Prompt-Injection
- **Barge-In kontext-scoped:** eine Frage im Hauptchat blockiert/killt nicht mehr die parallele Arbeit in einem Projekt (Busy-Status kontextgenau aus `queueStatus` statt global)
---
## [0.1.9.7 0.2.0.2] — 2026-07-02 … 2026-07-10 — Projekte & Multi-Threading
Der große Epos: Themen-Bündel („Projekte") im Hauptchat, echt nebenläufig verarbeitet.
### Hinzugefügt
**Projekte (Brain + App + Diagnostic)**
- Named Themen-Bündel, im Hauptchat verankert, per Sprache adressierbar („steige in Projekt X ein", „für Frankreich: …"), CRUD via Meta-Tools + UI
- App: Focus-One-View + Drawer + Queue-Status-Dots + „← Hauptchat"-Button
- Diagnostic: Kontext-Strip + Focus-Filter + Queue-Polling
- Dateien pro Projekt getaggt (Manifest `file_projects.json`, Filter im Datei-Manager)
**Multi-Threading (Brain)**
- Per-Request `project_id` statt globalem `active_project`; per-Projekt-`asyncio.Lock` = Queue-Verhalten pro Kontext, verschiedene Kontexte laufen parallel
- Queue-Aware-Prompting (spätere Nachricht kann laufenden Task als überholt markieren) ohne Extra-LLM-Call
**Voice-Router (Bridge)**
- 30s-Sticky-Kontext, Prefix-Adressierung, Meta-Command-Interception („zurück zum Hauptchat" ohne Brain-Call), Voice folgt App-Focus
**Migration**
- Alt-getaggte Projekt-Nachrichten (in `conversation.jsonl`, aber ohne Tag im `chat_backup.jsonl`) werden nachträglich einsortiert — idempotent, nicht-destruktiv, reihenfolge-erhaltend
### Behoben
- **Leere Projekte:** Drawer resettete den App-Focus beim Öffnen auf `status.active` (im Multi-Threading = null); Diagnostic warf `project_id` beim `chat_history`-Reload weg (server.js + Renderer); untagged ARIA-Bubbles/Backup-Writes aus dem toten Gateway-Watch-Pfad
- **Voice → falscher Kontext:** Registry-Race (`stt_stream_end` poppte die Focus-`projectId` vor dem finalen `stt_endpoint`); App übernimmt jetzt die autoritative Server-`projectId` der STT-Bubble
- **STT-Endpointing:** akustische Stille als robustes Signal statt rein semantischer Stagnation (nicht mehr „hört nach zwei Worten auf" / „merkt Ende nicht")
- **Anhänge:** Bild/Datei + Frage landen im gewählten Projekt statt im Hauptchat (projectId durch die ganze Anhang-Kette)
- **Bild-Bubbles im Diagnostic:** ARIA-Datei-Bubbles tragen `project_id`, werden nicht mehr fälschlich vom Focus-Filter ausgeblendet
---
## [0.0.0.5] — 2026-03-13
Binary file not shown.
+245 -660
View File
File diff suppressed because it is too large Load Diff
+5 -83
View File
@@ -6,19 +6,13 @@
*/
import React, { useEffect } from 'react';
import { AppState, AppStateStatus, PermissionsAndroid, Platform, StatusBar, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { StatusBar, StyleSheet } from 'react-native';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import WorkspaceScreen from './src/workspace/WorkspaceScreen';
import ChatScreen from './src/screens/ChatScreen';
import SettingsScreen from './src/screens/SettingsScreen';
import ViewModeToggle from './src/components/ViewModeToggle';
import rvs from './src/services/rvs';
import { initLogger, installGlobalCrashReporter } from './src/services/logger';
import { acquireBackgroundAudio } from './src/services/backgroundAudio';
import gpsTrackingService from './src/services/gpsTracking';
// --- Navigation ---
@@ -50,13 +44,6 @@ const TAB_ICONS: Record<string, { active: string; inactive: string }> = {
const App: React.FC = () => {
// Beim Start: gespeicherte RVS-Konfiguration laden und verbinden
useEffect(() => {
// Verbose-Logging-Setting laden BEVOR andere Module loslegen.
// initLogger ist async aber blockt nichts — solange er noch laueft,
// loggen wir normal (Default an), danach respektiert console.log das Setting.
initLogger().catch(() => {});
// Crash-Reporter installieren — ungefangene JS-Errors landen via RVS
// bei der Bridge (sichtbar in /shared/logs/app.log + Diagnostic-API)
installGlobalCrashReporter();
const initConnection = async () => {
const config = await rvs.loadConfig();
if (config) {
@@ -66,75 +53,14 @@ const App: React.FC = () => {
};
initConnection();
// Hintergrund-Modus: Foreground-Service starten damit JS-Engine +
// WebSocket auch ueberleben wenn die App im Hintergrund ist.
// Trigger-Replies, Reconnects, Timer-Erinnerungen kommen sonst nicht
// durch weil Android nach ~30s die JS-Engine pausiert.
//
// Default an, kann in Settings → Hintergrund-Modus deaktiviert werden.
// Braucht POST_NOTIFICATIONS Permission ab Android 13.
const initBackground = async () => {
const setting = await AsyncStorage.getItem('aria_background_mode');
if (setting === 'false') {
console.log('[App] Hintergrund-Modus deaktiviert (Settings)');
return;
}
// Permission fuer die persistente Notification
if (Platform.OS === 'android' && Platform.Version >= 33) {
try {
await PermissionsAndroid.request(
'android.permission.POST_NOTIFICATIONS' as any,
{
title: 'Hintergrund-Modus',
message: 'ARIA zeigt eine Notification damit Trigger und Reconnects auch laufen wenn die App im Hintergrund ist.',
buttonPositive: 'Erlauben',
buttonNegative: 'Spaeter',
},
);
} catch {}
}
try {
await acquireBackgroundAudio('background');
console.log('[App] Hintergrund-Modus aktiv');
} catch (err: any) {
console.warn('[App] Hintergrund-Modus konnte nicht starten:', err?.message || err);
}
};
initBackground();
// GPS-Tracking-Status aus AsyncStorage wiederherstellen (war
// bisher nur an SettingsScreen-Mount gekoppelt; wenn Stefan
// direkt im Chat startete blieb GPS aus bis er Settings oeffnete).
gpsTrackingService.restoreFromStorage().catch((err) => {
console.warn('[App] GPS-Tracking restore fehlgeschlagen:', err?.message || err);
});
// AppState-Listener: nach Hintergrund-Rueckkehr aktiv die WS-
// Verbindung neu aufbauen. Hintergrund: Android kann den TCP-Socket
// im Background killen, JS-State zeigt aber noch OPEN → Stefan musste
// manuell in Settings auf "Verbinden" tippen, oft mehrfach. Mit dem
// force-Reconnect bei "active" greift das automatisch.
let lastAppState: AppStateStatus = AppState.currentState;
const appStateSub = AppState.addEventListener('change', (next) => {
const wasBg = lastAppState !== 'active';
lastAppState = next;
if (next === 'active' && wasBg) {
console.log('[App] Foreground-Resume — force-reconnect zum RVS');
try { rvs.connect(true); } catch (e: any) {
console.warn('[App] force-reconnect fehlgeschlagen:', e?.message || e);
}
}
});
// Beim Beenden: Verbindung sauber trennen
return () => {
appStateSub.remove();
rvs.disconnect();
};
}, []);
return (
<GestureHandlerRootView style={styles.root}>
<>
<StatusBar barStyle="light-content" backgroundColor="#0D0D1A" />
<NavigationContainer theme={DarkTheme}>
<Tab.Navigator
@@ -167,11 +93,10 @@ const App: React.FC = () => {
>
<Tab.Screen
name="Chat"
component={WorkspaceScreen}
component={ChatScreen}
options={{
title: 'ARIA Chat',
headerTitle: 'ARIA Cockpit',
headerRight: () => <ViewModeToggle />,
}}
/>
<Tab.Screen
@@ -183,16 +108,13 @@ const App: React.FC = () => {
/>
</Tab.Navigator>
</NavigationContainer>
</GestureHandlerRootView>
</>
);
};
// --- Styles ---
const styles = StyleSheet.create({
root: {
flex: 1,
},
header: {
backgroundColor: '#12122A',
elevation: 0,
+2 -18
View File
@@ -79,8 +79,8 @@ android {
applicationId "com.ariacockpit"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 20500
versionName "0.2.5.0"
versionCode 506
versionName "0.0.5.6"
// Fallback fuer Libraries mit Product Flavors
missingDimensionStrategy 'react-native-camera', 'general'
}
@@ -104,19 +104,6 @@ android {
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// ABI-Split: nur arm64-v8a (jedes Android-Phone seit ~2017). Bringt die
// APK von ~136 MB auf ~35 MB — relevant weil ONNX Runtime + die anderen
// Native-Libs sonst pro Architektur dazukommen. Wer 32-bit oder Emulator
// braucht, kann hier "armeabi-v7a", "x86_64" etc. ergaenzen.
splits {
abi {
enable true
reset()
include "arm64-v8a"
universalApk false
}
}
}
dependencies {
@@ -124,9 +111,6 @@ dependencies {
implementation("com.facebook.react:react-android")
implementation("com.facebook.react:flipper-integration")
// ONNX Runtime fuer on-device Wake-Word (openWakeWord ONNX-Modelle in assets/openwakeword/)
implementation("com.microsoft.onnxruntime:onnxruntime-android:1.17.1")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
@@ -4,31 +4,6 @@
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Anruf-State lesen damit TTS bei klingelndem Telefon pausiert -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Optional: GPS-Position der Frage anhaengen (nur wenn User in Settings aktiviert) -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Background-Location ist OPT-IN (Settings → GPS auch im Hintergrund).
Muss vom User explizit in Android-Einstellungen auf "Immer erlauben"
gesetzt werden — kann nicht ueber den normalen Permission-Dialog
angefordert werden (Android 10+). Default: aus. -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- Foreground-Service damit TTS auch bei minimierter App weiterlaeuft.
FOREGROUND_SERVICE_MICROPHONE ist Pflicht ab Android 14 wenn der
Service waehrend des Backgrounds aufs Mikro zugreift (Wake-Word,
Aufnahme im Gespraechsmodus). LOCATION wird nur aktiv wenn der
User Background-GPS in Settings einschaltet. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- WAKE_LOCK damit Wake-Word + JS-Bridge auch bei aus-Display und Doze
arbeiten: ohne Lock pausiert Android die CPU, Native-AudioRecord
laeuft weiter aber JS-Bridge frisst die DeviceEvents nicht mehr ->
Wake-Word wird erkannt aber callbacks feuern erst beim App-Resume. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name=".MainApplication"
@@ -60,10 +35,5 @@
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<service
android:name=".AriaPlaybackService"
android:exported="false"
android:foregroundServiceType="mediaPlayback|microphone|location" />
</application>
</manifest>
@@ -7,7 +7,7 @@ import com.facebook.react.uimanager.ViewManager
class ApkInstallerPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(ApkInstallerModule(reactContext), FileOpenerModule(reactContext))
return listOf(ApkInstallerModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
@@ -1,147 +0,0 @@
package com.ariacockpit
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
/**
* Foreground-Service der den App-Prozess waehrend TTS-Wiedergabe am Leben
* haelt — Android killt sonst den Prozess sobald die App im Hintergrund ist
* und ARIA verstummt mitten im Satz.
*
* Notification ist persistent (ongoing) waehrend der Service laeuft.
* Tap auf die Notification bringt MainActivity zurueck nach vorne.
*
* foregroundServiceType="mediaPlayback" ist Pflicht ab Android 14, sonst
* wirft startForeground() eine SecurityException.
*/
class AriaPlaybackService : Service() {
companion object {
private const val TAG = "AriaPlaybackService"
private const val CHANNEL_ID = "aria_playback"
private const val NOTIFICATION_ID = 1042
const val EXTRA_REASON = "reason" // "tts" | "wake" | "rec" | ""
}
private var currentReason: String = ""
// PARTIAL_WAKE_LOCK haelt die CPU wach solange der Foreground-Service
// aktiv ist. Damit bleibt die JS-Bridge im Doze ansprechbar und die
// gesamte Sprach-Pipeline (Wake → Aufnahme → POST → ARIA → TTS → wieder
// Wake) laeuft durchgehend im Hintergrund. Ein einziger Lock fuer den
// ganzen Foreground-Cycle, nicht pro Sub-Modul.
private var wakeLock: PowerManager.WakeLock? = null
override fun onCreate() {
super.onCreate()
ensureNotificationChannel()
acquireWakeLock()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val reason = intent?.getStringExtra(EXTRA_REASON) ?: ""
currentReason = reason
Log.i(TAG, "Foreground-Service start/update (reason=$reason)")
// Falls der Lock zwischendurch released wurde (z.B. nach onCreate-
// race oder OS-quirk), hier sicherheits-halber erneut anfordern.
acquireWakeLock()
try {
startForeground(NOTIFICATION_ID, buildNotification(reason))
} catch (e: Exception) {
Log.e(TAG, "startForeground fehlgeschlagen", e)
stopSelf()
}
// START_NOT_STICKY: wenn Android den Service killt, NICHT automatisch
// wieder starten — die App entscheidet wann der Service noetig ist.
return START_NOT_STICKY
}
override fun onDestroy() {
releaseWakeLock()
Log.i(TAG, "Foreground-Service gestoppt")
super.onDestroy()
}
private fun acquireWakeLock() {
if (wakeLock?.isHeld == true) return
try {
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"AriaCockpit:Pipeline").apply {
setReferenceCounted(false)
acquire(8 * 60 * 60 * 1000L) // 8h Sicherheits-Cap
}
Log.i(TAG, "WakeLock acquired (CPU bleibt wach im Hintergrund)")
} catch (e: Exception) {
Log.w(TAG, "WakeLock acquire fehlgeschlagen: ${e.message}")
}
}
private fun releaseWakeLock() {
try {
wakeLock?.takeIf { it.isHeld }?.release()
if (wakeLock != null) Log.i(TAG, "WakeLock released")
} catch (e: Exception) {
Log.w(TAG, "WakeLock release fehlgeschlagen: ${e.message}")
}
wakeLock = null
}
override fun onBind(intent: Intent?): IBinder? = null
private fun ensureNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val nm = getSystemService(NotificationManager::class.java) ?: return
if (nm.getNotificationChannel(CHANNEL_ID) == null) {
val channel = NotificationChannel(
CHANNEL_ID,
"ARIA Audio-Wiedergabe",
NotificationManager.IMPORTANCE_LOW,
).apply {
description = "Notification waehrend ARIA spricht (haelt die App im Hintergrund am Leben)"
setShowBadge(false)
}
nm.createNotificationChannel(channel)
}
}
}
private fun buildNotification(reason: String): Notification {
val launchIntent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val pendingFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
else
PendingIntent.FLAG_UPDATE_CURRENT
val pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, pendingFlags)
val (title, body) = when (reason) {
"tts" -> "ARIA spricht" to "Antwort wird abgespielt — antippen oeffnet die App"
"rec" -> "ARIA hoert zu" to "Sprachaufnahme laeuft — antippen oeffnet die App"
"wake" -> "ARIA bereit" to "Wake-Word lauscht passiv — antippen oeffnet die App"
else -> "ARIA aktiv" to "Hintergrund-Modus — antippen oeffnet die App"
}
return NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setShowWhen(false)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build()
}
}
@@ -5,73 +5,26 @@ import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import android.os.SystemClock
import android.util.Log
import android.view.KeyEvent
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
/**
* Steuert Audio-Focus fuer Ducking/Muten anderer Apps + emittiert Loss-Events
* an JS damit ARIA bei VoIP-Anrufen (WhatsApp/Signal/Discord/...) aufhoert
* zu sprechen — diese Anrufe gehen nicht ueber TelephonyManager, sondern
* requestn AudioFocus_GAIN_TRANSIENT_EXCLUSIVE was wir hier mitbekommen.
* Steuert Audio-Focus fuer Ducking/Muten anderer Apps.
*
* - requestDuck() → andere Apps werden leiser (ARIA spricht TTS)
* - requestExclusive() → andere Apps werden pausiert (Mikrofon-Aufnahme)
* - release() → Focus abgeben, andere Apps duerfen wieder
*
* Events:
* - "AudioFocusChanged" mit type:
* "loss" — endgueltiger Verlust (Anruf, andere App permanent)
* "loss_transient" — vorruebergehender Verlust (kurze Unterbrechung)
* "gain" — Fokus zurueck
*/
class AudioFocusModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "AudioFocus"
companion object { private const val TAG = "AudioFocus" }
private var currentRequest: AudioFocusRequest? = null
private fun audioManager(): AudioManager? =
reactApplicationContext.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
private fun emitFocusChange(type: String) {
try {
val params = Arguments.createMap().apply { putString("type", type) }
reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("AudioFocusChanged", params)
} catch (e: Exception) {
Log.w(TAG, "emit failed: ${e.message}")
}
}
private val focusListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_LOSS -> {
Log.i(TAG, "AUDIOFOCUS_LOSS (z.B. Anruf, anderer Player permanent)")
emitFocusChange("loss")
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
Log.i(TAG, "AUDIOFOCUS_LOSS_TRANSIENT (kurze Unterbrechung)")
emitFocusChange("loss_transient")
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
// Notification-Sound o.ae. — wir ignorieren das, ARIA macht weiter
Log.d(TAG, "AUDIOFOCUS_LOSS_CAN_DUCK ignoriert")
}
AudioManager.AUDIOFOCUS_GAIN -> {
Log.i(TAG, "AUDIOFOCUS_GAIN")
emitFocusChange("gain")
}
}
}
private fun requestFocus(durationHint: Int, usage: Int, promise: Promise) {
val am = audioManager()
if (am == null) {
@@ -88,13 +41,13 @@ class AudioFocusModule(reactContext: ReactApplicationContext) : ReactContextBase
.build()
val req = AudioFocusRequest.Builder(durationHint)
.setAudioAttributes(attrs)
.setOnAudioFocusChangeListener(focusListener)
.setOnAudioFocusChangeListener { /* kein Callback noetig */ }
.build()
currentRequest = req
am.requestAudioFocus(req)
} else {
@Suppress("DEPRECATION")
am.requestAudioFocus(focusListener, AudioManager.STREAM_MUSIC, durationHint)
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, durationHint)
}
promise.resolve(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
@@ -133,182 +86,14 @@ class AudioFocusModule(reactContext: ReactApplicationContext) : ReactContextBase
promise.resolve(true)
}
/** Sanfter Spotify-Resume-Nudge: kurz USAGE_MEDIA mit TRANSIENT
* requesten und sofort abandonen. Spotify bekommt das als
* Focus-Frei-Signal und resumed automatisch — aber weil TRANSIENT
* (nicht GAIN permanent), interpretiert Spotify das NICHT als
* "user stopped" was Auto-Resume verhindert haette.
*
* Hintergrund: ARIA spricht TTS via USAGE_ASSISTANT GAIN_TRANSIENT,
* Spotify pausiert. ARIA released. Spotify SOLLTE nach
* TRANSIENT-Loss + Abandon automatisch resumen, tut es aber bei
* manchen Versionen / Geraeten nicht zuverlaessig. Dieser Nudge
* triggert den Focus-Stack-Refresh ohne den Spotify-Auto-Stop-Bug
* der alten kickReleaseMedia mit GAIN permanent.
*/
@ReactMethod
fun nudgeMediaResume(promise: Promise) {
val am = audioManager()
if (am == null) {
promise.resolve(false)
return
}
Thread {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val attrs = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
val nudgeListener = AudioManager.OnAudioFocusChangeListener { /* ignorieren */ }
val nudgeReq = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(attrs)
.setOnAudioFocusChangeListener(nudgeListener)
.build()
am.requestAudioFocus(nudgeReq)
Thread.sleep(100)
am.abandonAudioFocusRequest(nudgeReq)
} else {
val nudgeListener = AudioManager.OnAudioFocusChangeListener { /* ignorieren */ }
@Suppress("DEPRECATION")
am.requestAudioFocus(nudgeListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
Thread.sleep(100)
@Suppress("DEPRECATION")
am.abandonAudioFocus(nudgeListener)
}
Log.i(TAG, "nudgeMediaResume: USAGE_MEDIA TRANSIENT request+abandon (Spotify-Resume-Trigger)")
} catch (e: Exception) {
Log.w(TAG, "nudgeMediaResume failed: ${e.message}")
}
}.start()
promise.resolve(true)
}
/** Zuverlaessiger Spotify-Resume: einen echten MEDIA_PLAY-Tastendruck an die
* aktive MediaSession schicken — exakt das Signal der Play-Taste am
* Bluetooth-Kopfhoerer. Anders als nudgeMediaResume (Focus-Stack-Trick,
* auf manchen OEMs/Spotify-Versionen unzuverlaessig) spricht das Spotifys
* MediaSession DIREKT an und startet die Wiedergabe deterministisch wieder.
*
* Wir senden bewusst KEYCODE_MEDIA_PLAY (nicht PLAY_PAUSE) — das kann nur
* starten, nie pausieren. Aufrufer muss also selbst gaten (nur senden wenn
* vor dem Gespraech wirklich Musik lief, siehe isMusicActive()).
*/
@ReactMethod
fun dispatchMediaPlay(promise: Promise) {
val am = audioManager()
if (am == null) {
promise.resolve(false)
return
}
try {
val now = SystemClock.uptimeMillis()
val down = KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY, 0)
val up = KeyEvent(now, now, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY, 0)
am.dispatchMediaKeyEvent(down)
am.dispatchMediaKeyEvent(up)
Log.i(TAG, "dispatchMediaPlay: KEYCODE_MEDIA_PLAY an aktive MediaSession gesendet")
promise.resolve(true)
} catch (e: Exception) {
Log.w(TAG, "dispatchMediaPlay failed: ${e.message}")
promise.resolve(false)
}
}
/** Ob gerade Musik/Media aktiv abgespielt wird (AudioManager.isMusicActive).
* Der Aufrufer merkt sich das VOR dem Focus-Grab, um am Dialog-Ende zu
* entscheiden ob ein dispatchMediaPlay-Resume ueberhaupt gewuenscht ist. */
@ReactMethod
fun isMusicActive(promise: Promise) {
val am = audioManager()
if (am == null) {
promise.resolve(false)
return
}
promise.resolve(am.isMusicActive)
}
/** Den USAGE_MEDIA-Focus-Stack im System aufmischen, damit Spotify/YouTube
* resumen wenn ein anderer Player (z.B. react-native-sound) seinen Focus
* nicht ordnungsgemaess released hat. Strategie: kurz selbst USAGE_MEDIA
* GAIN beanspruchen — das System invalidiert dabei den haengenden Stack-
* Eintrag des anderen Players — und sofort wieder abandonen. Spotify
* bekommt den Focus-Gain und resumed.
*
* Workaround fuer das react-native-sound-Bug: Sound.stop()/release()
* laesst den AudioFocusRequest haengen.
*
* ⚠️ ACHTUNG: nutzt AUDIOFOCUS_GAIN (permanent), Spotify kann das als
* "user-action stopp" interpretieren und Auto-Resume verhindern.
* Fuer Spotify-Resume nach TTS lieber nudgeMediaResume() nehmen (sanfter).
*/
@ReactMethod
fun kickReleaseMedia(promise: Promise) {
val am = audioManager()
if (am == null) {
promise.resolve(false)
return
}
// Async laufen lassen — wir wollen einen request, Pause, dann abandon.
// Ohne Pause merkt das System (und damit Spotify) die kurze Owner-
// Wechsel oft gar nicht. 250ms reicht erfahrungsgemaess fuer den
// Focus-Stack-Refresh.
Thread {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val attrs = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
val kickListener = AudioManager.OnAudioFocusChangeListener { /* ignorieren */ }
val kickReq = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(attrs)
.setOnAudioFocusChangeListener(kickListener)
.build()
am.requestAudioFocus(kickReq)
Thread.sleep(250)
am.abandonAudioFocusRequest(kickReq)
} else {
val kickListener = AudioManager.OnAudioFocusChangeListener { /* ignorieren */ }
@Suppress("DEPRECATION")
am.requestAudioFocus(kickListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
Thread.sleep(250)
@Suppress("DEPRECATION")
am.abandonAudioFocus(kickListener)
}
Log.i(TAG, "kickReleaseMedia: USAGE_MEDIA-Stack aufgemischt (250ms Pause)")
} catch (e: Exception) {
Log.w(TAG, "kickReleaseMedia failed: ${e.message}")
}
}.start()
promise.resolve(true)
}
private fun release() {
val am = audioManager() ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
currentRequest?.let { am.abandonAudioFocusRequest(it) }
} else {
@Suppress("DEPRECATION")
am.abandonAudioFocus(focusListener)
am.abandonAudioFocus(null)
}
currentRequest = null
}
/** Aktueller Audio-Mode: NORMAL=0, IN_CALL=2, IN_COMMUNICATION=3, CALL_SCREENING=4.
* IN_COMMUNICATION ist der typische VoIP-Anruf-Mode (WhatsApp, Signal, etc.) —
* kann gepollt werden um zu erkennen wann der Anruf vorbei ist (zurueck NORMAL). */
@ReactMethod
fun getMode(promise: Promise) {
val am = audioManager()
if (am == null) {
promise.resolve(0)
return
}
promise.resolve(am.mode)
}
@ReactMethod fun addListener(eventName: String) {}
@ReactMethod fun removeListeners(count: Int) {}
}
@@ -1,59 +0,0 @@
package com.ariacockpit
import android.content.Intent
import android.os.Build
import android.util.Log
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
/**
* RN-Bridge fuer den AriaPlaybackService.
*
* Wird vom JS waehrend einer TTS-Wiedergabe gestartet damit Android den
* App-Prozess nicht killt wenn die App im Hintergrund ist (= ARIA spricht
* weiter, auch wenn Stefan die App minimiert hat).
*
* Service stoppt entweder explizit per stop() oder wird von Android
* mitgekillt wenn der Prozess weg ist (was bei Foreground-Service nur
* passiert wenn der User die App force-stopped).
*/
class BackgroundAudioModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "BackgroundAudio"
companion object { private const val TAG = "BackgroundAudio" }
@ReactMethod
fun start(reason: String, promise: Promise) {
try {
val ctx = reactApplicationContext
val intent = Intent(ctx, AriaPlaybackService::class.java)
intent.putExtra(AriaPlaybackService.EXTRA_REASON, reason ?: "")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ctx.startForegroundService(intent)
} else {
ctx.startService(intent)
}
promise.resolve(true)
} catch (e: Exception) {
Log.w(TAG, "start fehlgeschlagen: ${e.message}")
promise.reject("START_FAILED", e.message ?: "Unbekannter Fehler", e)
}
}
@ReactMethod
fun stop(promise: Promise) {
try {
val ctx = reactApplicationContext
ctx.stopService(Intent(ctx, AriaPlaybackService::class.java))
promise.resolve(true)
} catch (e: Exception) {
Log.w(TAG, "stop fehlgeschlagen: ${e.message}")
promise.reject("STOP_FAILED", e.message ?: "Unbekannter Fehler", e)
}
}
@ReactMethod fun addListener(eventName: String) {}
@ReactMethod fun removeListeners(count: Int) {}
}
@@ -1,16 +0,0 @@
package com.ariacockpit
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class BackgroundAudioPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(BackgroundAudioModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
@@ -1,55 +0,0 @@
package com.ariacockpit
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import java.io.File
/**
* Oeffnet eine beliebige Datei (PDF, Bild, Office-Doc, ...) mit der vom User
* gewaehlten App via Android-Intent-Picker. Nutzt FileProvider damit auch
* Android 7+ (content:// statt file://) das URI lesen darf.
*
* MIME-Type wird vom Caller bestimmt — App-Auswahl ist davon abhaengig (PDF
* geht an PDF-Viewer, image/jpeg an Galerie, etc.).
*/
class FileOpenerModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "FileOpener"
@ReactMethod
fun open(filePath: String, mimeType: String, promise: Promise) {
try {
val cleanPath = filePath.removePrefix("file://")
val file = File(cleanPath)
if (!file.exists()) {
promise.reject("FILE_NOT_FOUND", "Datei nicht gefunden: $cleanPath")
return
}
val context = reactApplicationContext
val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
} else {
Uri.fromFile(file)
}
val safeMime = if (mimeType.isBlank()) "application/octet-stream" else mimeType
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, safeMime)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// Chooser zeigt Android-Auswahl falls mehrere Apps das MIME oeffnen koennen.
val chooser = Intent.createChooser(intent, "Oeffnen mit").apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(chooser)
promise.resolve(true)
} catch (e: Exception) {
promise.reject("OPEN_ERROR", e.message, e)
}
}
}
@@ -21,10 +21,6 @@ class MainApplication : Application(), ReactApplication {
add(ApkInstallerPackage())
add(AudioFocusPackage())
add(PcmStreamPlayerPackage())
add(PcmStreamRecorderPackage())
add(OpenWakeWordPackage())
add(PhoneCallPackage())
add(BackgroundAudioPackage())
}
override fun getJSMainModuleName(): String = "index"
@@ -1,626 +0,0 @@
package com.ariacockpit
import ai.onnxruntime.OnnxTensor
import ai.onnxruntime.OrtEnvironment
import ai.onnxruntime.OrtSession
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioRecordingConfiguration
import android.media.MediaRecorder
import android.media.audiofx.AcousticEchoCanceler
import android.media.audiofx.AutomaticGainControl
import android.media.audiofx.NoiseSuppressor
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.util.Log
import androidx.core.content.ContextCompat
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
import java.nio.FloatBuffer
import java.util.concurrent.atomic.AtomicBoolean
/**
* Wake-Word Erkennung on-device via openWakeWord (https://github.com/dscripka/openWakeWord).
*
* Drei-stufige ONNX Pipeline:
* 1. Audio (16kHz mono int16, 1280-Sample-Chunks) → Melspectrogram → 32-mel Frames
* 2. 76 Mel-Frames Sliding Window (stride 8) → Speech-Embedding → 96-dim Vektor
* 3. Letzte 16 Embeddings (~1.28s Kontext) → Wake-Word-Klassifikator → Sigmoid-Score
*
* Modelle liegen in assets/openwakeword/ (mel + embedding shared, plus pro Keyword
* ein eigenes .onnx). Erkennung feuert nach `patience` aufeinanderfolgenden
* Frames ueber `threshold` und unterdrueckt Wiederholungen fuer `debounceMs`.
*
* Emittiert "WakeWordDetected" als RN-Event wenn ein Trigger erkannt wurde.
*/
class OpenWakeWordModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "OpenWakeWord"
companion object {
private const val TAG = "OpenWakeWord"
private const val SAMPLE_RATE = 16000
private const val CHUNK_SAMPLES = 1280 // 80ms @ 16kHz
private const val MEL_FRAMES_PER_EMBEDDING = 76 // Embedding-Fenster
private const val EMBEDDING_STRIDE = 8 // Slide um 8 Mel-Frames
private const val EMBEDDING_DIM = 96
private const val MEL_BINS = 32
private const val DEFAULT_WW_INPUT_FRAMES = 16 // Fallback wenn Modell-Metadata fehlt
// Nach record.startRecording() erzeugt das Mikro fuer ~1s einen Spin-up-Spike
// (DC-Offset, AGC-Settling) der vom Wake-Word-Klassifikator faelschlich als
// Trigger eingestuft werden kann. Folge: App pausiert beim Oeffnen die Musik,
// weil der False-Positive die AudioFocus-Switch-Logik anwirft (Stefan-Bug 06/2026).
// Loesung: in dieser Phase keine Detections an JS weiterleiten.
private const val STARTUP_SUPPRESSION_MS = 600L
// PCM-Ringpuffer fuer die Wake-Wort-Bestaetigung: letzte 2s roh (16kHz
// mono s16). Bei einer Erkennung wird der Vor-Trigger-Schnipsel an JS
// gereicht und dort von Voxtral verifiziert (gegen Musik-Fehltrigger).
private const val PCM_RING_SAMPLES = 32000 // 2.0s @ 16kHz
private const val PRE_TRIGGER_SAMPLES = 24000 // 1.5s Schnipsel an JS
}
private val env: OrtEnvironment = OrtEnvironment.getEnvironment()
private var melSession: OrtSession? = null
private var embSession: OrtSession? = null
private var wwSession: OrtSession? = null
private var melInputName: String = "input"
private var embInputName: String = "input_1"
private var wwInputName: String = "input"
// Anzahl Embedding-Frames die der Wake-Word-Klassifikator pro Inferenz erwartet —
// hey_jarvis hat 16, andere Community-Modelle koennen abweichen (z.B. 28).
// Wird beim init() aus den Modell-Metadaten gelesen.
private var wwInputFrames: Int = DEFAULT_WW_INPUT_FRAMES
// Konfiguration
private var threshold: Float = 0.5f
private var patience: Int = 2
private var debounceMs: Long = 1500
private var modelName: String = "hey_jarvis"
// Audio-Capture-Thread
private var audioRecord: AudioRecord? = null
private val running = AtomicBoolean(false)
private var captureThread: Thread? = null
// Audio-Effects: Echo-Cancellation (gegen ARIAs eigene TTS-Stimme die sonst
// das Wake-Word triggern wuerde) + Noise-Suppression. Per VOICE_COMMUNICATION
// Audio-Source schon vorhanden, aber explizites Aktivieren ist robuster.
private var aec: AcousticEchoCanceler? = null
private var ns: NoiseSuppressor? = null
private var agc: AutomaticGainControl? = null
// PARTIAL_WAKE_LOCK damit die CPU bei aus-Display nicht in Doze geht und
// die JS-Bridge die WakeWordDetected-Events live verarbeitet (sonst
// queuen sich die Events nur und werden erst beim App-Foreground
// delivered — Stefan-Beobachtung: "Spotify pausiert, aber Gong/Aufnahme
// kommen erst wenn ich die App nach vorne hole").
private var wakeLock: PowerManager.WakeLock? = null
// Inferenz-State
private val melBuffer: ArrayList<FloatArray> = ArrayList(256) // Liste von 32-dim Frames
private var melProcessedIdx: Int = 0
private val embBuffer: ArrayDeque<FloatArray> = ArrayDeque(32) // Ringpuffer letzter Embeddings
private var consecutiveAboveThreshold: Int = 0
private var lastDetectionMs: Long = 0L
// Roh-PCM-Ringpuffer (letzte ~2s) fuer die Wake-Wort-Bestaetigung. Bei einer
// Erkennung wird der Vor-Trigger-Schnipsel base64-kodiert an JS gereicht und
// dort von Voxtral verifiziert ("war das wirklich 'Computer' oder Musik?").
private val pcmRing = ShortArray(PCM_RING_SAMPLES)
private var pcmRingPos = 0
private var pcmRingFilled = false
private val pcmRingLock = Any()
// Zeitpunkt des letzten startRecording — fuer STARTUP_SUPPRESSION_MS-Fenster
private var recordingStartedMs: Long = 0L
// Audio-Sharing mit anderen Apps:
// Wenn z.B. WhatsApp eine Sprachnachricht aufnimmt, dann hält ARIAs
// VOICE_COMMUNICATION-Lock zwar das System nicht offiziell exklusiv,
// aber die Foreground-App bekommt nur Stille — die WhatsApp-Aufnahme
// ist tonlos. Loesung: AudioRecordingCallback hoeren, sobald eine andere
// App das Mic anfordert → unsere AudioRecord freigeben (externallyPaused=true).
// Wenn die andere App fertig ist → reaktivieren. Wakeword pausiert solange.
private var recordingCallback: AudioManager.AudioRecordingCallback? = null
@Volatile private var externallyPaused: Boolean = false
private val mainHandler: Handler by lazy { Handler(Looper.getMainLooper()) }
private val audioManager: AudioManager by lazy {
reactApplicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
}
/**
* Initialisiert die ONNX-Sessions fuer ein bestimmtes Wake-Word.
* modelName: dateiname ohne Suffix (z.B. "hey_jarvis", "alexa", "hey_mycroft", "hey_rhasspy")
*/
@ReactMethod
fun init(modelName: String, threshold: Double, patience: Int, debounceMs: Int, promise: Promise) {
try {
disposeSessions()
this.modelName = modelName
this.threshold = threshold.toFloat()
this.patience = patience.coerceAtLeast(1)
this.debounceMs = debounceMs.toLong()
val ctx = reactApplicationContext
val melBytes = ctx.assets.open("openwakeword/melspectrogram.onnx").use { it.readBytes() }
val embBytes = ctx.assets.open("openwakeword/embedding_model.onnx").use { it.readBytes() }
val wwBytes = ctx.assets.open("openwakeword/$modelName.onnx").use { it.readBytes() }
val opts = OrtSession.SessionOptions()
melSession = env.createSession(melBytes, opts)
embSession = env.createSession(embBytes, opts)
wwSession = env.createSession(wwBytes, opts)
melInputName = melSession!!.inputNames.first()
embInputName = embSession!!.inputNames.first()
wwInputName = wwSession!!.inputNames.first()
// WW-Input-Frame-Count aus dem Modell lesen — variiert pro Keyword.
// Erwartete Form: (1, N, 96), N steht in der Modell-Metadaten.
val wwInputInfo = wwSession!!.inputInfo[wwInputName]
val wwShape = (wwInputInfo?.info as? ai.onnxruntime.TensorInfo)?.shape
wwInputFrames = wwShape?.getOrNull(1)?.toInt()?.takeIf { it > 0 } ?: DEFAULT_WW_INPUT_FRAMES
Log.i(TAG, "Init OK: model=$modelName wwFrames=$wwInputFrames threshold=$threshold patience=$patience " +
"debounce=${debounceMs}ms (inputs: mel=$melInputName emb=$embInputName ww=$wwInputName)")
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "Init fehlgeschlagen: ${e.message}", e)
disposeSessions()
promise.reject("INIT_FAILED", e.message ?: "Unbekannter Fehler", e)
}
}
@ReactMethod
fun start(promise: Promise) {
if (running.get()) {
promise.resolve(true)
return
}
if (melSession == null || embSession == null || wwSession == null) {
promise.reject("NOT_INITIALIZED", "init() muss vor start() aufgerufen werden")
return
}
// Berechtigung pruefen — der App-Code holt die ueblicherweise schon vorher,
// aber wir bestehen hier explizit darauf damit AudioRecord nicht stumm
// failt.
val perm = ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.RECORD_AUDIO)
if (perm != PackageManager.PERMISSION_GRANTED) {
promise.reject("NO_MIC_PERMISSION", "RECORD_AUDIO Permission fehlt")
return
}
try {
acquireAndStartRecording()
// PARTIAL_WAKE_LOCK greifen damit die CPU nicht in Doze geht und
// die JS-Bridge die emit("WakeWordDetected")-Events live verarbeitet.
// 8h Cap als Sicherheit gegen forgotten-release.
try {
val pm = reactApplicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"AriaCockpit:WakeWordRecord").apply {
setReferenceCounted(false)
acquire(8 * 60 * 60 * 1000L)
}
Log.i(TAG, "WakeLock acquired")
} catch (e: Exception) {
Log.w(TAG, "WakeLock acquire fehlgeschlagen: ${e.message}")
}
// AudioRecordingCallback registrieren: andere Apps (WhatsApp-
// Sprachnachricht, Telefonate etc.) wollen das Mic — wir geben
// es vorruebergehend frei statt sie ins Leere recorden zu lassen.
registerRecordingCallback()
Log.i(TAG, "Lauschen gestartet (model=$modelName)")
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "start fehlgeschlagen", e)
running.set(false)
audioRecord?.release()
audioRecord = null
promise.reject("START_FAILED", e.message ?: "Unbekannter Fehler", e)
}
}
/** Reine AudioRecord + Effects + Capture-Thread-Acquisition. Wirft bei
* Fehler — Caller faengt + reportet. Kein WakeLock, keine Callbacks. */
private fun acquireAndStartRecording() {
val minBuf = AudioRecord.getMinBufferSize(
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(CHUNK_SAMPLES * 2 * 4)
// VOICE_COMMUNICATION-Source: aktiviert auf den meisten Android-Geraeten
// automatisch Echo-Cancellation + Noise-Suppression. Wichtig damit
// ARIAs eigene Stimme nicht das Wake-Word triggert wenn parallel
// zur TTS-Wiedergabe gelauscht wird.
val record = AudioRecord(
MediaRecorder.AudioSource.VOICE_COMMUNICATION,
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBuf,
)
if (record.state != AudioRecord.STATE_INITIALIZED) {
record.release()
throw IllegalStateException("AudioRecord nicht initialisiert (Mikro belegt?)")
}
audioRecord = record
// Audio-Effects ZUSAETZLICH explizit aktivieren — manche Geraete
// benoetigen das, obwohl VOICE_COMMUNICATION es eigentlich schon
// mitbringt. Failure ist nicht kritisch (continue ohne Effects).
try {
if (AcousticEchoCanceler.isAvailable()) {
aec = AcousticEchoCanceler.create(record.audioSessionId)?.apply { enabled = true }
Log.i(TAG, "AEC aktiviert (enabled=${aec?.enabled})")
}
} catch (e: Exception) { Log.w(TAG, "AEC failed: ${e.message}") }
try {
if (NoiseSuppressor.isAvailable()) {
ns = NoiseSuppressor.create(record.audioSessionId)?.apply { enabled = true }
}
} catch (e: Exception) { Log.w(TAG, "NS failed: ${e.message}") }
try {
if (AutomaticGainControl.isAvailable()) {
agc = AutomaticGainControl.create(record.audioSessionId)?.apply { enabled = true }
}
} catch (e: Exception) { Log.w(TAG, "AGC failed: ${e.message}") }
resetInferenceState()
running.set(true)
record.startRecording()
recordingStartedMs = System.currentTimeMillis()
captureThread = Thread({ captureLoop() }, "OpenWakeWordCapture").apply {
isDaemon = true
start()
}
}
/** Reine AudioRecord + Effects + Capture-Thread-Release. Sicher (catch all).
* Kein WakeLock-Release, kein Unregistrieren der Callbacks. */
private fun stopAndReleaseRecording() {
running.set(false)
try { captureThread?.join(1500) } catch (_: InterruptedException) {}
captureThread = null
try { audioRecord?.stop() } catch (_: Exception) {}
try { audioRecord?.release() } catch (_: Exception) {}
audioRecord = null
releaseAudioEffects()
}
private fun releaseAudioEffects() {
try { aec?.release() } catch (_: Exception) {}
try { ns?.release() } catch (_: Exception) {}
try { agc?.release() } catch (_: Exception) {}
aec = null; ns = null; agc = null
}
@ReactMethod
fun stop(promise: Promise) {
unregisterRecordingCallback()
externallyPaused = false
stopAndReleaseRecording()
releaseWakeLock()
Log.i(TAG, "Lauschen gestoppt")
promise.resolve(true)
}
@ReactMethod
fun dispose(promise: Promise) {
unregisterRecordingCallback()
externallyPaused = false
stopAndReleaseRecording()
releaseWakeLock()
disposeSessions()
promise.resolve(true)
}
// ── External-Mic-Sharing (AudioRecordingCallback) ──────────────────────
//
// Wenn eine andere App das Mic anfordert (WhatsApp-Voicenote, Telefonie,
// Sprach-Suche im Browser etc.), kriegt die zwar formal Audio — aber
// unsere VOICE_COMMUNICATION-Pipeline blockiert die naively neue Aufnahme
// mit Stille (Android-Audio-Policy). Loesung: AudioRecordingCallback
// beobachten, andere Recorder-Sessions detecten, und unsere Pipeline
// temporaer freigeben. Sobald die andere App fertig ist → reaktivieren.
//
// Effekt: Wake-Word funktioniert solange nicht — fairer Kompromiss.
private fun registerRecordingCallback() {
if (recordingCallback != null) return
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Log.i(TAG, "AudioRecordingCallback nicht verfuegbar (API < 24) — Mic-Sharing inaktiv")
return
}
val cb = object : AudioManager.AudioRecordingCallback() {
override fun onRecordingConfigChanged(configs: MutableList<AudioRecordingConfiguration>?) {
handleRecordingConfigChange(configs)
}
}
try {
audioManager.registerAudioRecordingCallback(cb, mainHandler)
recordingCallback = cb
Log.i(TAG, "AudioRecordingCallback registriert — beobachtet andere Mic-User")
} catch (e: Exception) {
Log.w(TAG, "registerAudioRecordingCallback failed: ${e.message}")
}
}
private fun unregisterRecordingCallback() {
val cb = recordingCallback ?: return
try { audioManager.unregisterAudioRecordingCallback(cb) } catch (_: Exception) {}
recordingCallback = null
}
private fun handleRecordingConfigChange(configs: MutableList<AudioRecordingConfiguration>?) {
if (configs == null) return
// Unsere eigene Session anhand der audioSessionId filtern. Wenn wir
// gerade keinen AudioRecord halten (externallyPaused), ist alles
// andere "extern" — dann zaehlt jeder Eintrag.
val ourSessionId = audioRecord?.audioSessionId
val externalActive = configs.any {
ourSessionId == null || it.clientAudioSessionId != ourSessionId
}
if (running.get() && externalActive) {
Log.i(TAG, "Andere App nutzt Mic — Wake-Word pausiert (configs=${configs.size})")
externallyPaused = true
stopAndReleaseRecording()
return
}
if (externallyPaused && !externalActive) {
Log.i(TAG, "Mic wieder frei — Wake-Word reaktiviert in 300ms")
// Kurze Pause: der "andere" hat eben losgelassen, Audio-Stack braucht
// ein paar ms bis VOICE_COMMUNICATION wieder sauber initialisiert.
mainHandler.postDelayed({
if (!externallyPaused) return@postDelayed // schon resumed
// Sicherheitscheck: wenn inzwischen jemand wieder rein ist
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val cur = audioManager.activeRecordingConfigurations
if (cur != null && cur.isNotEmpty()) {
Log.i(TAG, "Resume verworfen — anderer Mic-User noch da (${cur.size})")
return@postDelayed
}
}
externallyPaused = false
try {
acquireAndStartRecording()
Log.i(TAG, "Wake-Word nach External-Pause reaktiviert")
} catch (e: Exception) {
Log.w(TAG, "Resume nach External-Pause failed: ${e.message}")
// bleiben unten — falls anderer App das Mic doch wieder
// freigibt, feuert der Callback erneut.
externallyPaused = true
}
}, 300L)
}
}
private fun releaseWakeLock() {
try {
wakeLock?.takeIf { it.isHeld }?.release()
if (wakeLock != null) Log.i(TAG, "WakeLock released")
} catch (e: Exception) {
Log.w(TAG, "WakeLock release fehlgeschlagen: ${e.message}")
}
wakeLock = null
}
@ReactMethod
fun isAvailable(promise: Promise) {
// Wake-Word ist immer verfuegbar (kein API-Key, alles on-device)
promise.resolve(true)
}
// RN-Event-Subscriptions — RN-Konvention, sonst Warnung im Debug-Build
@ReactMethod fun addListener(eventName: String) {}
@ReactMethod fun removeListeners(count: Int) {}
private fun disposeSessions() {
try { melSession?.close() } catch (_: Exception) {}
try { embSession?.close() } catch (_: Exception) {}
try { wwSession?.close() } catch (_: Exception) {}
melSession = null
embSession = null
wwSession = null
}
private fun resetInferenceState() {
melBuffer.clear()
melProcessedIdx = 0
embBuffer.clear()
consecutiveAboveThreshold = 0
lastDetectionMs = 0L
// PCM-Ring frisch: sonst koennte Alt-Audio aus dem vorigen Arm-Zyklus
// in den Bestaetigungs-Schnipsel bluten.
synchronized(pcmRingLock) { pcmRingPos = 0; pcmRingFilled = false }
}
/** Letzte ~1.5s Roh-PCM aus dem Ringpuffer als Base64 (s16le, 16kHz mono),
* fuer die Voxtral-Wake-Bestaetigung. null wenn noch zu wenig Audio da ist
* oder das Kodieren scheitert (dann macht JS fail-open weiter wie bisher). */
private fun snapshotPreTrigger(): String? {
val out: ByteArray
synchronized(pcmRingLock) {
val available = if (pcmRingFilled) PCM_RING_SAMPLES else pcmRingPos
val n = if (available < PRE_TRIGGER_SAMPLES) available else PRE_TRIGGER_SAMPLES
if (n <= 0) return null
out = ByteArray(n * 2)
var idx = (pcmRingPos - n + PCM_RING_SAMPLES) % PCM_RING_SAMPLES
for (i in 0 until n) {
val s = pcmRing[idx].toInt()
out[i * 2] = (s and 0xFF).toByte()
out[i * 2 + 1] = ((s shr 8) and 0xFF).toByte()
idx += 1
if (idx >= PCM_RING_SAMPLES) idx = 0
}
}
return try {
android.util.Base64.encodeToString(out, android.util.Base64.NO_WRAP)
} catch (e: Exception) {
Log.w(TAG, "snapshotPreTrigger base64 fehlgeschlagen: ${e.message}")
null
}
}
private fun emitDetected() {
val sinceStart = System.currentTimeMillis() - recordingStartedMs
if (sinceStart in 0 until STARTUP_SUPPRESSION_MS) {
Log.i(TAG, "Wake-Word emit unterdrueckt (sinceStart=${sinceStart}ms < ${STARTUP_SUPPRESSION_MS}ms — Mikro-Spin-up-Spike)")
return
}
val preTriggerB64 = snapshotPreTrigger()
val params = com.facebook.react.bridge.Arguments.createMap().apply {
putString("model", modelName)
if (preTriggerB64 != null) putString("preTriggerPcm", preTriggerB64)
}
try {
reactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("WakeWordDetected", params)
} catch (e: Exception) {
Log.w(TAG, "emit fehlgeschlagen: ${e.message}")
}
}
private fun captureLoop() {
val buf = ShortArray(CHUNK_SAMPLES)
val record = audioRecord ?: return
Log.i(TAG, "Capture-Loop gestartet")
while (running.get()) {
var read = 0
while (read < CHUNK_SAMPLES && running.get()) {
val n = record.read(buf, read, CHUNK_SAMPLES - read)
if (n <= 0) {
Log.w(TAG, "AudioRecord.read returned $n — Loop ende")
running.set(false)
return
}
read += n
}
if (!running.get()) break
// Chunk in den PCM-Ringpuffer schreiben (fuer Wake-Wort-Bestaetigung).
synchronized(pcmRingLock) {
for (i in 0 until CHUNK_SAMPLES) {
pcmRing[pcmRingPos] = buf[i]
pcmRingPos += 1
if (pcmRingPos >= PCM_RING_SAMPLES) { pcmRingPos = 0; pcmRingFilled = true }
}
}
try {
processChunk(buf)
} catch (e: Exception) {
Log.w(TAG, "processChunk: ${e.message}")
}
}
Log.i(TAG, "Capture-Loop beendet")
}
/** Verarbeitet einen 1280-Sample int16 Audio-Chunk. */
private fun processChunk(audio: ShortArray) {
// 1) Audio → mel (output (1, 1, frames, 32))
val floats = FloatArray(audio.size) { audio[it].toFloat() }
val melTensor = OnnxTensor.createTensor(
env,
FloatBuffer.wrap(floats),
longArrayOf(1L, audio.size.toLong()),
)
val melResult = melSession!!.run(mapOf(melInputName to melTensor))
val melOut = melResult.get(0).value
melTensor.close()
@Suppress("UNCHECKED_CAST")
val mel4 = melOut as Array<Array<Array<FloatArray>>>
val frames = mel4[0][0]
// openWakeWord wendet `mel/10 + 2` an, bevor es ans Embedding-Modell geht
for (frame in frames) {
val scaled = FloatArray(frame.size) { frame[it] / 10f + 2f }
melBuffer.add(scaled)
}
melResult.close()
// 2) Sliding window: alle vollstaendigen 76-Frame-Fenster verarbeiten
while (melBuffer.size >= melProcessedIdx + MEL_FRAMES_PER_EMBEDDING) {
val flat = FloatArray(MEL_FRAMES_PER_EMBEDDING * MEL_BINS)
var pos = 0
for (i in 0 until MEL_FRAMES_PER_EMBEDDING) {
val src = melBuffer[melProcessedIdx + i]
System.arraycopy(src, 0, flat, pos, MEL_BINS)
pos += MEL_BINS
}
val embIn = OnnxTensor.createTensor(
env,
FloatBuffer.wrap(flat),
longArrayOf(1L, MEL_FRAMES_PER_EMBEDDING.toLong(), MEL_BINS.toLong(), 1L),
)
val embRes = embSession!!.run(mapOf(embInputName to embIn))
val embOut = embRes.get(0).value
embIn.close()
// Erwartete Output-Form: (1, 1, 1, 96) — rank-4, NICHT (1, 96).
// Die Google-Embedding-Pipeline behaelt extra Dimensionen.
@Suppress("UNCHECKED_CAST")
val embArr = embOut as Array<Array<Array<FloatArray>>>
embBuffer.addLast(embArr[0][0][0].copyOf())
while (embBuffer.size > wwInputFrames) embBuffer.removeFirst()
embRes.close()
melProcessedIdx += EMBEDDING_STRIDE
}
// Mel-Buffer trimmen — verhindert Memory-Wachstum
if (melProcessedIdx > MEL_FRAMES_PER_EMBEDDING) {
val keepFrom = melProcessedIdx - MEL_FRAMES_PER_EMBEDDING
val newList = ArrayList<FloatArray>(melBuffer.size - keepFrom)
for (i in keepFrom until melBuffer.size) newList.add(melBuffer[i])
melBuffer.clear()
melBuffer.addAll(newList)
melProcessedIdx = MEL_FRAMES_PER_EMBEDDING
}
// 3) Klassifikation — sobald wir 16 Embeddings haben
if (embBuffer.size < wwInputFrames) return
val flatEmb = FloatArray(wwInputFrames * EMBEDDING_DIM)
var p = 0
// Letzte wwInputFrames Embeddings nehmen (embBuffer ist auf wwInputFrames begrenzt)
for (e in embBuffer) {
System.arraycopy(e, 0, flatEmb, p, EMBEDDING_DIM)
p += EMBEDDING_DIM
}
val wwIn = OnnxTensor.createTensor(
env,
FloatBuffer.wrap(flatEmb),
longArrayOf(1L, wwInputFrames.toLong(), EMBEDDING_DIM.toLong()),
)
val wwRes = wwSession!!.run(mapOf(wwInputName to wwIn))
val wwOut = wwRes.get(0).value
wwIn.close()
// Erwartete Output-Form: (1, 1) → Array<FloatArray>
@Suppress("UNCHECKED_CAST")
val score = (wwOut as Array<FloatArray>)[0][0]
wwRes.close()
if (score >= threshold) {
consecutiveAboveThreshold++
if (consecutiveAboveThreshold >= patience) {
val now = System.currentTimeMillis()
if (now - lastDetectionMs >= debounceMs) {
lastDetectionMs = now
consecutiveAboveThreshold = 0
Log.i(TAG, "Wake-Word erkannt! score=$score model=$modelName")
emitDetected()
}
}
} else {
consecutiveAboveThreshold = 0
}
}
}
@@ -1,16 +0,0 @@
package com.ariacockpit
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class OpenWakeWordPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(OpenWakeWordModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
@@ -4,15 +4,12 @@ import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Build
import android.util.Base64
import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
import java.util.concurrent.LinkedBlockingQueue
/**
@@ -35,17 +32,11 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
private const val TAG = "PcmStreamPlayer"
// Fallback wenn JS keinen Wert uebergibt.
private const val DEFAULT_PREROLL_SECONDS = 3.5
// 0.0 = sofortige Wiedergabe — play() direkt beim ersten Chunk.
// Macht Sinn fuer F5-TTS weil Render so schnell ist dass ein Puffer
// unnoetig ist und bei kurzen Saetzen sogar stoeren kann.
private const val MIN_PREROLL_SECONDS = 0.0
private const val MIN_PREROLL_SECONDS = 0.5
private const val MAX_PREROLL_SECONDS = 10.0
// Stille am Stream-Anfang, damit AudioTrack sauber anfaehrt und die
// ersten Samples nicht abgeschnitten werden (XTTS-Warmup + play()-Latenz).
private const val LEADING_SILENCE_SECONDS = 0.3
// Stille am Ende — puffert das Hardware-Flushen damit die letzten
// echten Samples garantiert ausgespielt werden bevor stop() kommt.
private const val TRAILING_SILENCE_SECONDS = 0.3
private const val LEADING_SILENCE_SECONDS = 0.2
}
override fun getName() = "PcmStreamPlayer"
@@ -68,23 +59,17 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
// Alte Session beenden falls vorhanden
stopInternal()
// Nur NaN/Inf → Default. 0.0 ist gueltig (= sofortige Wiedergabe).
val prerollSec = if (prerollSeconds.isFinite() && prerollSeconds >= 0.0) {
prerollSeconds.coerceIn(MIN_PREROLL_SECONDS, MAX_PREROLL_SECONDS)
} else {
DEFAULT_PREROLL_SECONDS
}
val prerollSec = prerollSeconds
.coerceIn(MIN_PREROLL_SECONDS, MAX_PREROLL_SECONDS)
.let { if (it.isFinite() && it > 0) it else DEFAULT_PREROLL_SECONDS }
val channelConfig = if (channels == 2) AudioFormat.CHANNEL_OUT_STEREO else AudioFormat.CHANNEL_OUT_MONO
val encoding = AudioFormat.ENCODING_PCM_16BIT
val minBuf = AudioTrack.getMinBufferSize(sampleRate, channelConfig, encoding)
val bytesPerSecond = sampleRate * channels * 2 // 16-bit = 2 bytes
// Buffer muss mindestens PREROLL + etwas Spielraum fassen.
val prerollTarget = (bytesPerSecond * prerollSec).toInt()
// Buffer entkoppelt von Preroll — fester ~4s-Buffer. OnePlus A12
// mit USAGE_ASSISTANT laeuft AudioTrack erst ab ~3s gepufferter
// Daten an. Wir padden Kurztexte vor play() auf 3s (siehe Block
// nach mainLoop), Buffer braucht ~1s Headroom weil write() blockt.
val bufferSize = (bytesPerSecond * 4).coerceAtLeast(minBuf * 8)
val bufferSize = (minBuf * 32).coerceAtLeast(prerollTarget * 2)
prerollBytes = prerollTarget
bytesBuffered = 0
playbackStarted = false
@@ -108,20 +93,7 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
.setTransferMode(AudioTrack.MODE_STREAM)
.build()
// Start-Threshold runterdrehen: Default ist bufferSize/2 (= 2s bei 4s
// Buffer). AudioTrack startet sonst nicht bevor 2s im Puffer sind —
// bei kurzen TTS-Antworten (3 Worte ~ 1.4s) bleibt pos auf 0 stehen.
// 0.1s reicht damit AudioTrack sofort mit dem ersten Chunk anlaeuft.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
try {
val startFrames = (sampleRate / 10).coerceAtLeast(1) // 100ms
newTrack.setStartThresholdInFrames(startFrames)
Log.i(TAG, "Start-Threshold gesetzt: ${startFrames} frames (~100ms)")
} catch (e: Exception) {
Log.w(TAG, "setStartThresholdInFrames failed: ${e.message}")
}
}
// AudioTrack erstellen — play() wird erst aufgerufen wenn Pre-Roll erreicht.
track = newTrack
queue.clear()
writerShouldStop = false
@@ -131,9 +103,9 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
val t = track ?: return@Thread
try {
// Leading-Silence in den Buffer — gibt AudioTrack Zeit anzufahren.
val leadingBytes = ((sampleRate * channels * 2) * LEADING_SILENCE_SECONDS).toInt() and 0x7FFFFFFE
if (leadingBytes > 0) {
val silence = ByteArray(leadingBytes)
val silenceBytes = ((sampleRate * channels * 2) * LEADING_SILENCE_SECONDS).toInt() and 0x7FFFFFFE
if (silenceBytes > 0) {
val silence = ByteArray(silenceBytes)
var silOff = 0
while (silOff < silence.size && !writerShouldStop) {
val w = t.write(silence, silOff, silence.size - silOff)
@@ -142,83 +114,25 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
}
bytesBuffered += silence.size
}
// Bei preroll=0: play() SOFORT nach Leading-Silence aufrufen,
// nicht erst bei Ankunft des ersten echten Chunks. Android's
// AudioTrack haelt den Play-State und wartet auf neue Samples.
// So verschluckt es keine Worte wenn der erste Chunk erst
// nach play()-Startup-Latenz eintrifft.
if (prerollBytes == 0 && !playbackStarted) {
try {
t.play()
playbackStarted = true
Log.i(TAG, "Playback sofort gestartet (preroll=0, ${bytesBuffered}B silence)")
} catch (e: Exception) {
Log.w(TAG, "play() sofort failed: ${e.message}")
}
}
// Idle-Cutoff: wenn endRequested NICHT kam aber lange nichts mehr
// reinkommt, brechen wir ab (Bridge-Crash, verlorener final).
// 120s damit lange F5-TTS-Render-Pausen zwischen Saetzen (z.B. bei
// Modell-Wechsel oder kalter GPU) nicht den Stream abreissen.
var idleMs = 0L
val maxIdleMs = 120_000L
// Zielpufferfuellung — unter diesem Wasserstand fuettern wir
// Stille rein damit AudioTrack nicht underrunt waehrend die
// Bridge den naechsten Satz rendert. Spotify/YouTube reagieren
// sonst mit eigenmaechtiger Wiederaufnahme nach ~10s Stille.
val underrunGuardFrames = sampleRate / 10 // ~100ms
val silenceFillFrames = sampleRate / 20 // ~50ms pro Refill
mainLoop@ while (!writerShouldStop) {
val data = queue.poll(50, java.util.concurrent.TimeUnit.MILLISECONDS)
if (data == null) {
while (!writerShouldStop) {
val data = queue.poll(50, java.util.concurrent.TimeUnit.MILLISECONDS) ?: run {
if (endRequested) {
// Falls play() noch gar nicht lief (Stream ohne data
// ueberhaupt — sehr seltene Edge-Case): jetzt anstossen
// damit das finally{}-Wait nicht endlos blockt.
// Falls wir vor Pre-Roll enden (kurzer Text): trotzdem abspielen
if (!playbackStarted) {
try { t.play(); playbackStarted = true } catch (_: Exception) {}
try { t.play() } catch (_: Exception) {}
playbackStarted = true
}
break@mainLoop
return@Thread
}
// Underrun-Schutz: Stille reinfuettern wenn der AudioTrack-
// Puffer leerzulaufen droht. Spotify resumed sonst nach
// ~10s Pause auf eigene Faust, obwohl wir den Fokus halten.
if (playbackStarted) {
val framesWritten = bytesBuffered / streamBytesPerFrame
val framesPlayed = t.playbackHeadPosition.toLong()
val framesInBuffer = framesWritten - framesPlayed
if (framesInBuffer < underrunGuardFrames) {
val fillBytes = silenceFillFrames * streamBytesPerFrame
val silence = ByteArray(fillBytes)
var silOff = 0
while (silOff < silence.size && !writerShouldStop) {
val w = t.write(silence, silOff, silence.size - silOff)
if (w <= 0) break
silOff += w
}
bytesBuffered += silence.size
}
}
idleMs += 50L
if (idleMs >= maxIdleMs) {
Log.w(TAG, "Idle-Cutoff: ${maxIdleMs}ms keine Daten — Stream wird beendet")
break@mainLoop
}
continue@mainLoop
}
idleMs = 0L
null
} ?: continue
// play() beim ALLERERSTEN data-chunk aufrufen — egal wie wenig
// Daten da sind. Sonst stallt AudioTrack auf OnePlus A12 wenn
// play() erst gerufen wird nachdem der Buffer komplett gefuellt
// ist. Pre-Roll als "Vorrat aufbauen" passiert dann waehrend
// der Track schon spielt — Underrun-Schutz fuettert ggf. Stille.
if (!playbackStarted) {
// Pre-Roll Check: play() erst wenn genug gepuffert
if (!playbackStarted && bytesBuffered + data.size >= prerollBytes) {
try {
t.play()
playbackStarted = true
Log.i(TAG, "Playback gestartet beim 1. Chunk (${bytesBuffered}B leading + ${data.size}B data)")
Log.i(TAG, "Playback gestartet nach Pre-Roll ${bytesBuffered + data.size} Bytes")
} catch (e: Exception) {
Log.w(TAG, "play() failed: ${e.message}")
}
@@ -232,19 +146,6 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
}
bytesBuffered += data.size
}
// Trailing-Silence damit die letzten echten Samples garantiert
// durch das Hardware-Buffering kommen bevor stop() sie abschneidet
val trailingBytes = ((sampleRate * channels * 2) * TRAILING_SILENCE_SECONDS).toInt() and 0x7FFFFFFE
if (trailingBytes > 0 && !writerShouldStop) {
val silence = ByteArray(trailingBytes)
var silOff = 0
while (silOff < silence.size && !writerShouldStop) {
val w = t.write(silence, silOff, silence.size - silOff)
if (w <= 0) break
silOff += w
}
bytesBuffered += silence.size
}
} catch (e: Exception) {
Log.w(TAG, "Writer-Thread Fehler: ${e.message}")
} finally {
@@ -254,21 +155,12 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
val totalFrames = (bytesBuffered / streamBytesPerFrame).toInt()
var lastPos = -1
var stalledCount = 0
var retried = false
while (!writerShouldStop) {
val pos = t.playbackHeadPosition
if (pos >= totalFrames) break
// Safety: wenn Position 2s nicht mehr vorwaerts → AudioTrack hing
if (pos == lastPos) {
stalledCount++
// Nach 500ms Stillstand: AudioTrack-Quirk auf manchen
// Geraeten (OnePlus A12) — play() nochmal anstossen.
if (stalledCount == 10 && pos == 0 && !retried) {
retried = true
Log.w(TAG, "playback nicht angefahren — retry play()")
try { t.play() } catch (e: Exception) {
Log.w(TAG, "retry play() failed: ${e.message}")
}
}
if (stalledCount > 40) {
Log.w(TAG, "playback stalled at $pos/$totalFrames — give up")
break
@@ -283,17 +175,6 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
} catch (_: Exception) {}
try { t.stop() } catch (_: Exception) {}
try { t.release() } catch (_: Exception) {}
// RN-Event: AudioTrack ist wirklich durch (alle Samples gespielt).
// JS released erst JETZT den AudioFocus — sonst spielt Spotify
// beim end()-Cap waehrend ARIA noch redet (15s+ je nach Buffer).
try {
val params = Arguments.createMap()
reactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("PcmPlaybackFinished", params)
} catch (e: Exception) {
Log.w(TAG, "PlaybackFinished emit failed: ${e.message}")
}
}
}, "PcmStreamWriter").apply { start() }
@@ -350,9 +231,6 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
promise.resolve(true)
}
@ReactMethod fun addListener(eventName: String) {}
@ReactMethod fun removeListeners(count: Int) {}
private fun stopInternal() {
writerShouldStop = true
endRequested = true
@@ -361,12 +239,6 @@ class PcmStreamPlayerModule(reactContext: ReactApplicationContext) : ReactContex
writerThread = null
val t = track
if (t != null) {
// pause() + flush() vor stop() — sonst spielt der Hardware-Buffer
// (200-500ms PCM-Samples) noch hörbar weiter, nachdem der User
// den Mute-Button gedrückt hat. Stefan-Bug-Report: "wenn ich auf
// den Mund halten Button klicke während ARIA redet stoppt sie nicht".
try { t.pause() } catch (_: Exception) {}
try { t.flush() } catch (_: Exception) {}
try { t.stop() } catch (_: Exception) {}
try { t.release() } catch (_: Exception) {}
}
@@ -1,246 +0,0 @@
package com.ariacockpit
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.media.audiofx.AcousticEchoCanceler
import android.media.audiofx.AutomaticGainControl
import android.media.audiofx.NoiseSuppressor
import android.os.PowerManager
import android.util.Base64
import android.util.Log
import androidx.core.content.ContextCompat
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
import java.util.concurrent.atomic.AtomicBoolean
/**
* PCM-Streaming-Recorder fuer die Streaming-Whisper-Bridge.
*
* Oeffnet AudioRecord (16 kHz mono s16le, VOICE_COMMUNICATION-Source mit
* automatischer AEC + NS) und feuert ~200ms-Chunks als base64-Event
* "PcmStreamChunk" an die JS-Bridge.
*
* audio.ts schickt die Chunks via RVS direkt an die whisper-bridge die
* dort einen ML-Endpointer laufen laesst — kein dB-VAD-Tuning mehr.
*
* Mic-Ownership: dieser Recorder DARF nicht gleichzeitig mit
* OpenWakeWord laufen — beide wollen AudioRecord vom MIC. Caller
* muss OpenWakeWord.stop() vor start() hier aufrufen und nach stop()
* hier wieder OpenWakeWord.start() — genau wie's audio.ts ohnehin
* macht.
*
* Events:
* "PcmStreamChunk" { pcm: base64-s16le, seq: N, ts: epochMs }
* "PcmStreamError" { error: string }
*/
class PcmStreamRecorderModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
override fun getName() = "PcmStreamRecorder"
companion object {
private const val TAG = "PcmStreamRecorder"
private const val SAMPLE_RATE = 16000
// 200ms-Chunks: gross genug fuer wenig RVS-Overhead, klein genug damit
// der Endpointer im Whisper-Bridge granular sieht. 200ms ist auch das
// Whisper-VAD-Frame-Hop — passt also zu downstream.
private const val CHUNK_SAMPLES = 3200 // 200ms @ 16 kHz
private const val BYTES_PER_SAMPLE = 2 // s16
private const val CHUNK_BYTES = CHUNK_SAMPLES * BYTES_PER_SAMPLE
}
private var audioRecord: AudioRecord? = null
private val running = AtomicBoolean(false)
private var captureThread: Thread? = null
private var aec: AcousticEchoCanceler? = null
private var ns: NoiseSuppressor? = null
private var agc: AutomaticGainControl? = null
// PARTIAL_WAKE_LOCK damit der JS-Bridge-Loop weiterlaeuft auch wenn das
// Display aus ist — sonst sammeln sich zwar Chunks in der nativen Queue
// an, aber emit() landet nicht zeitnah in JS und der Whisper-Bridge
// bekommt die Audio-Chunks erst beim App-Foreground-Resume.
private var wakeLock: PowerManager.WakeLock? = null
private var seq: Long = 0L
@ReactMethod
fun start(promise: Promise) {
if (running.get()) {
promise.resolve(true)
return
}
val perm = ContextCompat.checkSelfPermission(
reactApplicationContext, Manifest.permission.RECORD_AUDIO
)
if (perm != PackageManager.PERMISSION_GRANTED) {
promise.reject("NO_MIC_PERMISSION", "RECORD_AUDIO Permission fehlt")
return
}
try {
val minBuf = AudioRecord.getMinBufferSize(
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
).coerceAtLeast(CHUNK_BYTES * 4) // 4x Chunk-Size als Sicherheit
val record = AudioRecord(
MediaRecorder.AudioSource.VOICE_COMMUNICATION,
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBuf,
)
if (record.state != AudioRecord.STATE_INITIALIZED) {
record.release()
promise.reject("AUDIO_INIT", "AudioRecord nicht initialisiert (Mikro belegt? OpenWakeWord noch aktiv?)")
return
}
audioRecord = record
// AEC/NS/AGC explizit anschalten — manche Geraete liefern's via
// VOICE_COMMUNICATION zwar mit, aber Belt-and-Suspenders.
try {
if (AcousticEchoCanceler.isAvailable()) {
aec = AcousticEchoCanceler.create(record.audioSessionId)?.apply { enabled = true }
}
} catch (e: Exception) { Log.w(TAG, "AEC failed: ${e.message}") }
try {
if (NoiseSuppressor.isAvailable()) {
ns = NoiseSuppressor.create(record.audioSessionId)?.apply { enabled = true }
}
} catch (e: Exception) { Log.w(TAG, "NS failed: ${e.message}") }
try {
if (AutomaticGainControl.isAvailable()) {
agc = AutomaticGainControl.create(record.audioSessionId)?.apply { enabled = true }
}
} catch (e: Exception) { Log.w(TAG, "AGC failed: ${e.message}") }
seq = 0L
running.set(true)
record.startRecording()
try {
val pm = reactApplicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"AriaCockpit:PcmStreamRecord").apply {
setReferenceCounted(false)
acquire(8 * 60 * 60 * 1000L) // 8h Cap
}
} catch (e: Exception) {
Log.w(TAG, "WakeLock acquire fehlgeschlagen: ${e.message}")
}
captureThread = Thread({ captureLoop() }, "PcmStreamRecorderCapture").apply {
isDaemon = true
start()
}
Log.i(TAG, "Recording gestartet (16kHz mono s16le, ${CHUNK_SAMPLES} samples/chunk)")
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "start fehlgeschlagen", e)
running.set(false)
audioRecord?.release()
audioRecord = null
releaseAudioEffects()
releaseWakeLock()
promise.reject("START_FAILED", e.message ?: "Unbekannter Fehler", e)
}
}
@ReactMethod
fun stop(promise: Promise) {
running.set(false)
try {
captureThread?.join(1500)
} catch (_: InterruptedException) {}
captureThread = null
try { audioRecord?.stop() } catch (_: Exception) {}
try { audioRecord?.release() } catch (_: Exception) {}
audioRecord = null
releaseAudioEffects()
releaseWakeLock()
Log.i(TAG, "Recording gestoppt (seq=$seq Chunks gesendet)")
promise.resolve(true)
}
@ReactMethod
fun isRecording(promise: Promise) {
promise.resolve(running.get())
}
private fun captureLoop() {
val buffer = ByteArray(CHUNK_BYTES)
val rec = audioRecord ?: return
try {
while (running.get()) {
var offset = 0
// Solange lesen bis ein voller 200ms-Chunk zusammen ist.
// AudioRecord.read kann weniger als angefordert liefern.
while (offset < CHUNK_BYTES && running.get()) {
val n = rec.read(buffer, offset, CHUNK_BYTES - offset)
if (n <= 0) {
if (!running.get()) break
// Fehlerzustand — kurze Pause, dann weiter probieren
Thread.sleep(5)
continue
}
offset += n
}
if (offset < CHUNK_BYTES) break
val b64 = Base64.encodeToString(buffer, Base64.NO_WRAP)
val ts = System.currentTimeMillis()
val params = Arguments.createMap().apply {
putString("pcm", b64)
// putLong existiert nicht in WritableMap — putDouble fuer ts/seq.
putDouble("seq", seq.toDouble())
putDouble("ts", ts.toDouble())
}
reactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("PcmStreamChunk", params)
seq++
}
} catch (e: Exception) {
Log.e(TAG, "captureLoop crashed", e)
try {
val err = Arguments.createMap().apply {
putString("error", e.message ?: "unknown")
}
reactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("PcmStreamError", err)
} catch (_: Exception) {}
}
}
private fun releaseAudioEffects() {
try { aec?.release() } catch (_: Exception) {}
try { ns?.release() } catch (_: Exception) {}
try { agc?.release() } catch (_: Exception) {}
aec = null; ns = null; agc = null
}
private fun releaseWakeLock() {
try {
if (wakeLock?.isHeld == true) wakeLock?.release()
} catch (_: Exception) {}
wakeLock = null
}
// Damit RCTEventEmitter den Listener-Lifecycle nicht crasht
@ReactMethod fun addListener(eventName: String) {}
@ReactMethod fun removeListeners(count: Int) {}
}
@@ -1,16 +0,0 @@
package com.ariacockpit
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class PcmStreamRecorderPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(PcmStreamRecorderModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
@@ -1,132 +0,0 @@
package com.ariacockpit
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.telephony.PhoneStateListener
import android.telephony.TelephonyCallback
import android.telephony.TelephonyManager
import android.util.Log
import androidx.core.content.ContextCompat
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
import java.util.concurrent.Executors
/**
* Lauscht auf Anruf-Statusaenderungen — wenn das Telefon klingelt oder ein
* Anruf laeuft, sendet das Modul ein "PhoneCallStateChanged"-Event an JS.
*
* JS-Side stoppt dann die TTS-Wiedergabe damit ARIA nicht mitten ins Gespraech
* weiterredet. Ohne READ_PHONE_STATE-Permission failt start() leise — der Rest
* der App funktioniert wie bisher.
*
* State-Strings: "idle" | "ringing" | "offhook"
*/
class PhoneCallModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "PhoneCall"
companion object { private const val TAG = "PhoneCall" }
private var telephonyManager: TelephonyManager? = null
private var legacyListener: PhoneStateListener? = null
private var modernCallback: Any? = null // TelephonyCallback ab API 31
private var lastState: Int = TelephonyManager.CALL_STATE_IDLE
// Eigener Single-Thread-Executor statt mainExecutor — der wird bei
// pausierter Activity verzoegert oder gar nicht abgearbeitet, der eigene
// Thread laeuft unabhaengig solange der App-Prozess lebt (was er ja tut,
// wir haben einen Foreground-Service der das garantiert).
private val callbackExecutor = Executors.newSingleThreadExecutor()
@ReactMethod
fun start(promise: Promise) {
try {
val perm = ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.READ_PHONE_STATE)
if (perm != PackageManager.PERMISSION_GRANTED) {
Log.w(TAG, "READ_PHONE_STATE Permission fehlt — Anruf-Erkennung inaktiv")
promise.resolve(false)
return
}
val tm = reactApplicationContext.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
if (tm == null) {
Log.w(TAG, "TelephonyManager nicht verfuegbar")
promise.resolve(false)
return
}
telephonyManager = tm
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val cb = object : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) {
handleStateChange(state)
}
}
tm.registerTelephonyCallback(callbackExecutor, cb)
modernCallback = cb
} else {
@Suppress("DEPRECATION")
val l = object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String?) {
handleStateChange(state)
}
}
@Suppress("DEPRECATION")
tm.listen(l, PhoneStateListener.LISTEN_CALL_STATE)
legacyListener = l
}
Log.i(TAG, "PhoneCall-Listener aktiv")
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "start fehlgeschlagen", e)
promise.reject("START_FAILED", e.message ?: "Unbekannter Fehler", e)
}
}
@ReactMethod
fun stop(promise: Promise) {
try {
val tm = telephonyManager
if (tm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(modernCallback as? TelephonyCallback)?.let { tm.unregisterTelephonyCallback(it) }
modernCallback = null
} else {
@Suppress("DEPRECATION")
legacyListener?.let { tm.listen(it, PhoneStateListener.LISTEN_NONE) }
legacyListener = null
}
}
telephonyManager = null
lastState = TelephonyManager.CALL_STATE_IDLE
promise.resolve(true)
} catch (e: Exception) {
promise.reject("STOP_FAILED", e.message ?: "")
}
}
private fun handleStateChange(state: Int) {
if (state == lastState) return
lastState = state
val name = when (state) {
TelephonyManager.CALL_STATE_RINGING -> "ringing"
TelephonyManager.CALL_STATE_OFFHOOK -> "offhook"
TelephonyManager.CALL_STATE_IDLE -> "idle"
else -> return
}
Log.i(TAG, "Telefon-State: $name")
val params = Arguments.createMap().apply { putString("state", name) }
try {
reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit("PhoneCallStateChanged", params)
} catch (e: Exception) {
Log.w(TAG, "Event-emit fehlgeschlagen: ${e.message}")
}
}
@ReactMethod fun addListener(eventName: String) {}
@ReactMethod fun removeListeners(count: Int) {}
}
@@ -1,16 +0,0 @@
package com.ariacockpit
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class PhoneCallPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(PhoneCallModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
@@ -1,8 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="cache" path="." />
<files-path name="files" path="." />
<external-path name="external" path="." />
<external-files-path name="external_files" path="." />
<external-cache-path name="external_cache" path="." />
</paths>
-3
View File
@@ -1,6 +1,3 @@
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
// react-native-reanimated/plugin MUSS das LETZTE Plugin sein (Worklet-Transform).
// Nach dem Hinzufuegen einmalig Metro-Cache leeren: `npm start --reset-cache`.
plugins: ['react-native-reanimated/plugin'],
};
+2 -15
View File
@@ -167,23 +167,10 @@ export CI=true
if [ "$MODE" = "debug" ]; then
./gradlew assembleDebug
OUT_DIR="app/build/outputs/apk/debug"
APK_PATH="app/build/outputs/apk/debug/app-debug.apk"
else
./gradlew assembleRelease
OUT_DIR="app/build/outputs/apk/release"
fi
# Mit ABI-Splits heisst die APK z.B. app-arm64-v8a-release.apk statt
# app-release.apk. arm64-v8a-Variante zuerst probieren (das ist unser
# Standard), Universal-APK als Fallback falls Splits deaktiviert sind.
if [ -f "$OUT_DIR/app-arm64-v8a-${MODE}.apk" ]; then
APK_PATH="$OUT_DIR/app-arm64-v8a-${MODE}.apk"
elif [ -f "$OUT_DIR/app-${MODE}.apk" ]; then
APK_PATH="$OUT_DIR/app-${MODE}.apk"
else
echo -e "${RED}Keine passende APK in $OUT_DIR gefunden${NC}"
cd ..
exit 1
APK_PATH="app/build/outputs/apk/release/app-release.apk"
fi
cd ..
-3
View File
@@ -1,6 +1,3 @@
// react-native-gesture-handler MUSS als allererstes importiert werden
// (vor allem anderen), sonst crasht die Gesten-Erkennung auf Android.
import 'react-native-gesture-handler';
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
+19 -21
View File
@@ -1,6 +1,6 @@
{
"name": "aria-cockpit",
"version": "0.2.5.0",
"version": "0.0.5.6",
"private": true,
"scripts": {
"android": "react-native run-android",
@@ -10,35 +10,33 @@
"build:apk": "cd android && ./gradlew assembleRelease"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^1.21.0",
"@react-native-community/geolocation": "^3.2.1",
"@react-navigation/bottom-tabs": "^6.5.11",
"@react-navigation/native": "^6.1.9",
"react": "18.2.0",
"react-native": "0.73.4",
"react-native-audio-recorder-player": "^3.6.7",
"react-native-camera-kit": "^13.0.0",
"@react-navigation/native": "^6.1.9",
"@react-navigation/bottom-tabs": "^6.5.11",
"react-native-screens": "3.27.0",
"react-native-safe-area-context": "^4.8.2",
"react-native-document-picker": "^9.1.1",
"react-native-fs": "^2.20.0",
"react-native-gesture-handler": "2.14.1",
"react-native-sound": "^0.11.2",
"@react-native-community/geolocation": "^3.2.1",
"react-native-image-picker": "^7.1.0",
"react-native-permissions": "^4.1.4",
"react-native-reanimated": "3.6.2",
"react-native-safe-area-context": "^4.8.2",
"react-native-screens": "3.27.0",
"react-native-sound": "^0.11.2",
"react-native-svg": "^14.1.0",
"react-native-webview": "13.6.4"
"react-native-camera-kit": "^13.0.0",
"@react-native-async-storage/async-storage": "^1.21.0",
"react-native-fs": "^2.20.0",
"react-native-audio-recorder-player": "^3.6.7",
"@picovoice/porcupine-react-native": "3.0.5",
"@picovoice/react-native-voice-processor": "1.2.3"
},
"devDependencies": {
"@react-native/eslint-config": "^0.73.2",
"@react-native/metro-config": "^0.73.5",
"@react-native/typescript-config": "^0.73.1",
"@types/jest": "^29.5.11",
"typescript": "^5.3.3",
"@types/react": "^18.2.48",
"@types/react-native": "^0.73.0",
"jest": "^29.7.0",
"@react-native/eslint-config": "^0.73.2",
"@react-native/typescript-config": "^0.73.1",
"@react-native/metro-config": "^0.73.5",
"metro-react-native-babel-preset": "^0.77.0",
"typescript": "^5.3.3"
"jest": "^29.7.0",
"@types/jest": "^29.5.11"
}
}
Binary file not shown.
-89
View File
@@ -1,89 +0,0 @@
/**
* ErrorBoundary — fängt React-Render-Fehler und zeigt eine Error-Box
* statt White-Screen-of-Death. Plus: Crash wird zum logger geschickt,
* der das ueber RVS an die Bridge weiterleitet.
*
* Einsatz: kritische Komponenten/Modals damit ein Bug nicht die ganze
* App killt.
*/
import React from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { reportAppError } from '../services/logger';
interface Props {
children: React.ReactNode;
/** Optional: Bezeichnung der eingegrenzten Section fuer's Log. */
scope?: string;
/** Optional: Reset-Callback (z.B. Modal schliessen) — Button ist dann sichtbar. */
onReset?: () => void;
}
interface State {
err: Error | null;
info: string;
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { err: null, info: '' };
}
static getDerivedStateFromError(err: Error): Partial<State> {
return { err };
}
componentDidCatch(err: Error, info: any) {
const stack = info?.componentStack || '';
this.setState({ info: stack });
reportAppError({
scope: this.props.scope || 'ErrorBoundary',
message: err?.message || String(err),
stack: (err?.stack || '') + '\n--- componentStack ---\n' + stack,
});
}
render() {
if (this.state.err) {
return (
<View style={s.box}>
<Text style={s.title}> Etwas ist schiefgegangen</Text>
<Text style={s.scope}>{this.props.scope || 'unbekannte Komponente'}</Text>
<ScrollView style={s.scroll}>
<Text style={s.msg}>{this.state.err.message || String(this.state.err)}</Text>
{this.state.info ? <Text style={s.stack}>{this.state.info}</Text> : null}
</ScrollView>
{this.props.onReset ? (
<TouchableOpacity style={s.btn} onPress={() => { this.setState({err:null,info:''}); this.props.onReset?.(); }}>
<Text style={s.btnText}>Schliessen + zurueck</Text>
</TouchableOpacity>
) : (
<TouchableOpacity style={s.btn} onPress={() => this.setState({err:null,info:''})}>
<Text style={s.btnText}>Erneut versuchen</Text>
</TouchableOpacity>
)}
<Text style={s.hint}>
Crash wurde an die Bridge gemeldet sichtbar in der Diagnostic-Web-UI unter /api/app-log
</Text>
</View>
);
}
return this.props.children;
}
}
const s = StyleSheet.create({
box: { flex:1, padding:16, backgroundColor:'#1A0A0A' },
title: { color:'#FF6B6B', fontWeight:'bold', fontSize:16, marginBottom:6 },
scope: { color:'#FF9500', fontSize:12, marginBottom:10 },
scroll: { flex:1, backgroundColor:'#0D0D1A', borderRadius:6, padding:10, marginBottom:10 },
msg: { color:'#FF6B6B', fontSize:13, marginBottom:8 },
stack: { color:'#8888AA', fontSize:11, fontFamily:'monospace' },
btn: { backgroundColor:'#0096FF', paddingVertical:10, borderRadius:6, alignItems:'center' },
btnText: { color:'#fff', fontWeight:'600' },
hint: { color:'#555570', fontSize:10, marginTop:8, textAlign:'center' },
});
export default ErrorBoundary;
+8 -5
View File
@@ -34,10 +34,13 @@ interface FileUploadProps {
onCancel: () => void;
}
// Alle Dateitypen zulassen — Stefan will ueber die Bueroklammer jede Datei
// hochladen koennen, nicht nur Bilder/Dokumente. Die Komponente verarbeitet
// beliebige Typen ohnehin (Base64 + application/octet-stream als Fallback).
const SUPPORTED_TYPES = [DocumentPicker.types.allFiles];
// Unterstuetzte Dateitypen
const SUPPORTED_TYPES = [
DocumentPicker.types.images,
DocumentPicker.types.pdf,
DocumentPicker.types.docx,
DocumentPicker.types.plainText,
];
// --- Komponente ---
@@ -109,7 +112,7 @@ const FileUpload: React.FC<FileUploadProps> = ({ onFileSelected, onCancel }) =>
<TouchableOpacity style={styles.pickButton} onPress={pickFile} activeOpacity={0.7}>
<Text style={styles.pickIcon}>{'\uD83D\uDCC1'}</Text>
<Text style={styles.pickText}>Datei ausw\u00E4hlen</Text>
<Text style={styles.pickHint}>Alle Dateitypen</Text>
<Text style={styles.pickHint}>JPG, PNG, PDF, DOCX, TXT</Text>
</TouchableOpacity>
) : (
// Vorschau und Senden
-272
View File
@@ -1,272 +0,0 @@
/**
* Memory-Browser — Liste mit Suche + Filter, Tap oeffnet MemoryDetailModal.
*
* Eingesetzt von:
* - SettingsScreen → Sektion "Gedächtnis" (kompletter Editor)
* - Inbox-Modal (Notizen-Button neben Lupe) — kann aber auch Bubbles
* aus dem Chat als zusaetzlichen Filter zeigen
*/
import React, { useEffect, useState, useCallback } from 'react';
import {
ActivityIndicator,
FlatList,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
Alert,
Modal,
} from 'react-native';
import brainApi, { Memory } from '../services/brainApi';
import MemoryDetailModal from './MemoryDetailModal';
const TYPE_LABELS: Record<string, string> = {
identity: 'Identität', rule: 'Regeln', preference: 'Präferenzen',
tool: 'Tools', skill: 'Skills', fact: 'Fakten',
conversation: 'Konversation', reminder: 'Reminder',
};
const TYPE_OPTIONS = ['', 'identity', 'rule', 'preference', 'tool', 'skill', 'fact', 'conversation', 'reminder'];
interface Props {
/** Wenn gesetzt: nur diese IDs anzeigen (z.B. Inbox-Modal mit Chat-Bubbles-Filter). */
restrictToIds?: string[];
/** Headline ueber der Liste. */
title?: string;
/** Style-Erweiterung fuer den Container. */
flatStyle?: boolean;
/** Wenn gesetzt: kein eigenes DetailModal mounten — Parent kuemmert sich. */
onOpenMemory?: (id: string) => void;
}
export const MemoryBrowser: React.FC<Props> = ({ restrictToIds, title, flatStyle, onOpenMemory }) => {
const [items, setItems] = useState<Memory[]>([]);
const [filtered, setFiltered] = useState<Memory[]>([]);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [q, setQ] = useState('');
const [typeFilter, setTypeFilter] = useState('');
const [pinnedFilter, setPinnedFilter] = useState<'all' | 'pinned' | 'cold'>('all');
const [showTypeMenu, setShowTypeMenu] = useState(false);
const [openId, setOpenId] = useState<string | null>(null);
const load = useCallback(() => {
setLoading(true); setErr(null);
brainApi.listMemories({ limit: 500 })
.then(setItems)
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, []);
useEffect(() => { load(); }, [load]);
// Filter clientseitig — bei kleiner DB (<1000) easy
useEffect(() => {
let out = items;
if (restrictToIds && restrictToIds.length) {
const set = new Set(restrictToIds);
out = out.filter(m => set.has(m.id));
}
if (typeFilter) out = out.filter(m => m.type === typeFilter);
if (pinnedFilter === 'pinned') out = out.filter(m => m.pinned);
else if (pinnedFilter === 'cold') out = out.filter(m => !m.pinned);
if (q.trim()) {
const needle = q.toLowerCase();
out = out.filter(m =>
(m.title || '').toLowerCase().includes(needle) ||
(m.content || '').toLowerCase().includes(needle) ||
(m.category || '').toLowerCase().includes(needle) ||
(m.tags || []).some(t => t.toLowerCase().includes(needle))
);
}
setFiltered(out);
}, [items, q, typeFilter, pinnedFilter, restrictToIds]);
const [showNewMemoryDialog, setShowNewMemoryDialog] = useState(false);
const [newMemoryTitle, setNewMemoryTitle] = useState('');
const onAddNew = () => {
setNewMemoryTitle('');
setShowNewMemoryDialog(true);
};
const confirmAddNew = async () => {
const t = newMemoryTitle.trim();
if (!t) { setShowNewMemoryDialog(false); return; }
setShowNewMemoryDialog(false);
try {
const m = await brainApi.saveMemory({
type: 'fact', title: t,
content: '(noch leer — bitte editieren)',
});
load();
if (onOpenMemory) onOpenMemory(m.id);
else setOpenId(m.id);
} catch (e: any) {
Alert.alert('Fehler', String(e?.message || e));
}
};
const renderItem = ({ item }: { item: Memory }) => {
const attCount = (item.attachments || []).length;
return (
<TouchableOpacity style={s.row} onPress={() => onOpenMemory ? onOpenMemory(item.id) : setOpenId(item.id)}>
<View style={{flex:1}}>
<Text style={s.rowTitle} numberOfLines={1}>
{item.pinned ? '📌 ' : ''}{item.title || '(ohne Titel)'}
{attCount > 0 ? <Text style={s.attBadge}>{` 📎${attCount}`}</Text> : null}
</Text>
<Text style={s.rowMeta} numberOfLines={1}>
{TYPE_LABELS[item.type] || item.type}
{item.category ? ` · [${item.category}]` : ''}
</Text>
<Text style={s.rowPreview} numberOfLines={2}>{item.content}</Text>
</View>
</TouchableOpacity>
);
};
return (
<View style={[s.container, flatStyle && {padding:0,backgroundColor:'transparent'}]}>
{title ? <Text style={s.heading}>{title}</Text> : null}
<View style={s.searchRow}>
<TextInput
style={s.search}
value={q}
onChangeText={setQ}
placeholder="Suche in Titel, Inhalt, Tags…"
placeholderTextColor="#555570"
/>
<TouchableOpacity style={s.iconBtn} onPress={load}>
<Text style={{color:'#0096FF'}}></Text>
</TouchableOpacity>
</View>
<View style={s.filterRow}>
<TouchableOpacity style={s.filterBtn} onPress={() => setShowTypeMenu(true)}>
<Text style={s.filterText}>{typeFilter ? (TYPE_LABELS[typeFilter] || typeFilter) : 'Alle Typen'} </Text>
</TouchableOpacity>
<TouchableOpacity style={s.filterBtn} onPress={() => {
setPinnedFilter(pinnedFilter === 'all' ? 'pinned' : pinnedFilter === 'pinned' ? 'cold' : 'all');
}}>
<Text style={s.filterText}>
{pinnedFilter === 'pinned' ? '📌 Nur Pinned' : pinnedFilter === 'cold' ? 'Nur Cold' : 'Alle'}
</Text>
</TouchableOpacity>
<TouchableOpacity style={[s.filterBtn,{backgroundColor:'#0096FF'}]} onPress={onAddNew}>
<Text style={[s.filterText,{color:'#fff'}]}>+ Neu</Text>
</TouchableOpacity>
</View>
{err ? <Text style={s.err}>{err}</Text> : null}
{loading && items.length === 0 ? (
<ActivityIndicator color="#0096FF" style={{marginTop:20}} />
) : (
<FlatList
data={filtered}
keyExtractor={m => m.id}
renderItem={renderItem}
// nestedScrollEnabled: notwendig damit die FlatList auf Android
// scrollt wenn sie in einer aeusseren ScrollView haengt (Settings-
// Screen ist ScrollView). Ohne das frisst der aeussere ScrollView
// alle Gesten und die innere Liste ist tot.
nestedScrollEnabled={true}
keyboardShouldPersistTaps="handled"
ListEmptyComponent={
<Text style={{color:'#555570',textAlign:'center',padding:20,fontStyle:'italic'}}>
{items.length === 0 ? '(keine Memories in der DB)' : '(keine Treffer für diese Filter)'}
</Text>
}
contentContainerStyle={{paddingBottom:20}}
/>
)}
<Text style={s.footer}>
{filtered.length}/{items.length} Memories
</Text>
{/* Type-Filter-Auswahl */}
<Modal visible={showTypeMenu} transparent animationType="fade" onRequestClose={() => setShowTypeMenu(false)}>
<TouchableOpacity style={s.menuBack} activeOpacity={1} onPress={() => setShowTypeMenu(false)}>
<View style={s.menuBox}>
{TYPE_OPTIONS.map(t => (
<TouchableOpacity
key={t || 'all'}
style={s.menuItem}
onPress={() => { setTypeFilter(t); setShowTypeMenu(false); }}
>
<Text style={s.menuItemText}>
{t ? (TYPE_LABELS[t] || t) : 'Alle Typen'}
</Text>
</TouchableOpacity>
))}
</View>
</TouchableOpacity>
</Modal>
{/* Eigenes DetailModal nur wenn der Parent kein Callback uebergibt
(vermeidet Modal-in-Modal-Stacking auf Android). */}
{!onOpenMemory && (
<MemoryDetailModal
memoryId={openId}
visible={!!openId}
onClose={() => { setOpenId(null); load(); }}
onDeleted={() => { setOpenId(null); load(); }}
/>
)}
{/* "Neue Memory"-Dialog (Alert.prompt ist iOS-only, daher eigenes Modal) */}
<Modal visible={showNewMemoryDialog} transparent animationType="fade" onRequestClose={() => setShowNewMemoryDialog(false)}>
<View style={s.menuBack}>
<View style={[s.menuBox, {padding:16, minWidth:280}]}>
<Text style={{color:'#FFD60A', fontWeight:'bold', fontSize:14, marginBottom:10}}>Neue Memory anlegen</Text>
<Text style={{color:'#8888AA', fontSize:11, marginBottom:6}}>Titel:</Text>
<TextInput
value={newMemoryTitle}
onChangeText={setNewMemoryTitle}
autoFocus
placeholder="z.B. Stefans Auto"
placeholderTextColor="#555570"
style={{backgroundColor:'#1E1E2E', color:'#E0E0F0', padding:8, borderRadius:4, fontSize:13, marginBottom:12}}
/>
<View style={{flexDirection:'row', gap:8, justifyContent:'flex-end'}}>
<TouchableOpacity onPress={() => setShowNewMemoryDialog(false)} style={{padding:8}}>
<Text style={{color:'#8888AA'}}>Abbrechen</Text>
</TouchableOpacity>
<TouchableOpacity onPress={confirmAddNew} style={{backgroundColor:'#0096FF', paddingHorizontal:14, paddingVertical:8, borderRadius:4}}>
<Text style={{color:'#fff', fontWeight:'600'}}>Anlegen</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</View>
);
};
const s = StyleSheet.create({
container: { flex:1, padding:8, backgroundColor:'#0D0D1A' },
heading: { color:'#0096FF', fontWeight:'bold', fontSize:14, marginBottom:8 },
searchRow: { flexDirection:'row', gap:6, marginBottom:6 },
search: { flex:1, backgroundColor:'#1E1E2E', color:'#E0E0F0', padding:8, borderRadius:6, fontSize:13 },
iconBtn: { paddingHorizontal:12, justifyContent:'center', backgroundColor:'#1E1E2E', borderRadius:6 },
filterRow: { flexDirection:'row', gap:6, marginBottom:8 },
filterBtn: { backgroundColor:'#1E1E2E', paddingHorizontal:10, paddingVertical:6, borderRadius:6 },
filterText: { color:'#E0E0F0', fontSize:12 },
err: { color:'#FF6B6B', fontSize:12, marginVertical:6 },
row: { backgroundColor:'#1E1E2E', padding:10, borderRadius:6, marginBottom:6 },
rowTitle: { color:'#E0E0F0', fontWeight:'600', fontSize:13 },
attBadge: { color:'#34C759', fontWeight:'normal', fontSize:11 },
rowMeta: { color:'#8888AA', fontSize:11, marginTop:2 },
rowPreview: { color:'#666680', fontSize:11, marginTop:4 },
footer: { color:'#555570', fontSize:10, textAlign:'center', paddingVertical:6 },
menuBack: { flex:1, backgroundColor:'rgba(0,0,0,0.7)', justifyContent:'center', alignItems:'center' },
menuBox: { backgroundColor:'#0D0D1A', borderRadius:8, paddingVertical:4, minWidth:200 },
menuItem: { paddingVertical:10, paddingHorizontal:14 },
menuItemText: { color:'#E0E0F0', fontSize:13 },
});
export default MemoryBrowser;
@@ -1,364 +0,0 @@
/**
* Memory-Detail-Modal — Anzeige + Edit eines einzelnen Memory-Eintrags.
*
* Zwei Modi:
* - read-only: zeigt alle Felder + Anhang-Vorschau (Klick auf Bild = Vollbild)
* - edit: Form mit Save/Delete/Anhang-hochladen
*
* Memory-Daten werden beim Oeffnen aus dem Brain (via brainApi → RVS) frisch
* gezogen. Optimistic Updates sind explizit nicht da — der DB-Stand ist die
* Truth.
*/
import React, { useEffect, useState } from 'react';
import {
ActivityIndicator,
Alert,
Image,
Modal,
ScrollView,
StyleSheet,
Switch,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import DocumentPicker, { DocumentPickerResponse } from 'react-native-document-picker';
import RNFS from 'react-native-fs';
import brainApi, { Memory, MemoryAttachment } from '../services/brainApi';
interface Props {
memoryId: string | null;
visible: boolean;
onClose: () => void;
onDeleted?: (id: string) => void;
}
const TYPE_OPTIONS = [
{ value: 'identity', label: 'identity (FEST)' },
{ value: 'rule', label: 'rule (FEST)' },
{ value: 'preference', label: 'preference (FEST)' },
{ value: 'tool', label: 'tool (FEST)' },
{ value: 'skill', label: 'skill (FEST)' },
{ value: 'fact', label: 'fact (Cold)' },
{ value: 'conversation', label: 'conversation (Cold)' },
{ value: 'reminder', label: 'reminder (Cold)' },
];
export const MemoryDetailModal: React.FC<Props> = ({ memoryId, visible, onClose, onDeleted }) => {
const [memory, setMemory] = useState<Memory | null>(null);
const [loading, setLoading] = useState(false);
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
// Edit-Felder
const [eTitle, setETitle] = useState('');
const [eContent, setEContent] = useState('');
const [eCategory, setECategory] = useState('');
const [eTags, setETags] = useState('');
const [ePinned, setEPinned] = useState(false);
// Bild-Vollbild
const [fullscreen, setFullscreen] = useState<string | null>(null);
// Memory laden beim Oeffnen
useEffect(() => {
if (!visible || !memoryId) {
setMemory(null); setEditing(false); setErr(null); return;
}
setLoading(true); setErr(null);
brainApi.getMemory(memoryId)
.then(m => {
setMemory(m);
setETitle(m.title || '');
setEContent(m.content || '');
setECategory(m.category || '');
setETags((m.tags || []).join(', '));
setEPinned(!!m.pinned);
})
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, [visible, memoryId]);
const reload = () => {
if (!memoryId) return;
setLoading(true);
brainApi.getMemory(memoryId)
.then(m => setMemory(m))
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
};
const onSave = async () => {
if (!memoryId) return;
setSaving(true); setErr(null);
try {
const tags = eTags.split(',').map(t => t.trim()).filter(Boolean);
const m = await brainApi.updateMemory(memoryId, {
title: eTitle.trim(),
content: eContent.trim(),
category: eCategory.trim(),
tags,
pinned: ePinned,
});
setMemory(m);
setEditing(false);
} catch (e: any) {
setErr(String(e?.message || e));
} finally {
setSaving(false);
}
};
const onDelete = () => {
if (!memoryId || !memory) return;
Alert.alert(
'Memory loeschen?',
`"${memory.title}"\n\nWird permanent aus der DB entfernt, inkl. aller Anhaenge.`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Loeschen',
style: 'destructive',
onPress: async () => {
try {
await brainApi.deleteMemory(memoryId);
if (onDeleted) onDeleted(memoryId);
onClose();
} catch (e: any) {
Alert.alert('Fehler', String(e?.message || e));
}
},
},
],
);
};
const onPickAndUpload = async () => {
if (!memoryId) return;
try {
const picked: DocumentPickerResponse[] = await DocumentPicker.pick({
type: [DocumentPicker.types.images, DocumentPicker.types.pdf, DocumentPicker.types.allFiles],
copyTo: 'cachesDirectory',
});
for (const f of picked) {
setBusy(`Lade ${f.name}`);
// RNFS lesen → base64 → API
const localPath = (f.fileCopyUri || f.uri).replace(/^file:\/\//, '');
const b64 = await RNFS.readFile(localPath, 'base64');
await brainApi.uploadAttachment(memoryId, f.name || 'datei', b64);
}
setBusy(null);
reload();
} catch (e: any) {
setBusy(null);
if (DocumentPicker.isCancel(e)) return;
Alert.alert('Upload-Fehler', String(e?.message || e));
}
};
const onDeleteAttachment = (att: MemoryAttachment) => {
if (!memoryId) return;
Alert.alert(
'Anhang loeschen?',
`"${att.name}"`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Loeschen',
style: 'destructive',
onPress: async () => {
try {
const m = await brainApi.deleteAttachment(memoryId, att.name);
setMemory(m);
} catch (e: any) {
Alert.alert('Fehler', String(e?.message || e));
}
},
},
],
);
};
const onTapAttachment = async (att: MemoryAttachment) => {
if (!memoryId) return;
if ((att.mime || '').startsWith('image/')) {
try {
setBusy('Lade Bild…');
const data = await brainApi.getAttachmentBytes(memoryId, att.name);
// Temp-File schreiben damit <Image source={uri: file://...}> es zeigen kann
const safe = att.name.replace(/[^A-Za-z0-9._-]/g, '_');
const localPath = `${RNFS.CachesDirectoryPath}/memory_${memoryId}_${safe}`;
await RNFS.writeFile(localPath, data.base64, 'base64');
setBusy(null);
setFullscreen('file://' + localPath);
} catch (e: any) {
setBusy(null);
Alert.alert('Fehler', String(e?.message || e));
}
} else {
Alert.alert('Anhang', `${att.name}\n${att.mime}\n${att.size} Byte\n\nPfad: ${att.path}`);
}
};
return (
<Modal visible={visible} animationType="slide" transparent onRequestClose={onClose}>
<View style={s.backdrop}>
<View style={s.box}>
<View style={s.header}>
<Text style={s.title}>{editing ? 'Memory bearbeiten' : 'Memory-Detail'}</Text>
<TouchableOpacity onPress={onClose} hitSlop={{top:8,bottom:8,left:8,right:8}}>
<Text style={s.closeX}>×</Text>
</TouchableOpacity>
</View>
<ScrollView style={s.body} contentContainerStyle={{paddingBottom:20}}>
{loading ? (
<ActivityIndicator color="#0096FF" style={{marginTop:30}} />
) : err && !memory ? (
<Text style={s.err}>{err}</Text>
) : memory ? (
editing ? (
<View>
<Text style={s.label}>Typ</Text>
<Text style={{color:'#888',fontSize:12,marginBottom:8}}>{memory.type} (kann hier nicht geaendert werden)</Text>
<Text style={s.label}>Titel</Text>
<TextInput style={s.input} value={eTitle} onChangeText={setETitle} />
<Text style={s.label}>Inhalt</Text>
<TextInput
style={[s.input, {minHeight:120, textAlignVertical:'top'}]}
value={eContent}
onChangeText={setEContent}
multiline
/>
<Text style={s.label}>Kategorie</Text>
<TextInput style={s.input} value={eCategory} onChangeText={setECategory} />
<Text style={s.label}>Tags (komma-getrennt)</Text>
<TextInput style={s.input} value={eTags} onChangeText={setETags} />
<View style={{flexDirection:'row',alignItems:'center',marginTop:10,gap:8}}>
<Switch value={ePinned} onValueChange={setEPinned} />
<Text style={{color:'#E0E0F0'}}>📌 Pinned (immer im System-Prompt)</Text>
</View>
{err ? <Text style={s.err}>{err}</Text> : null}
<View style={{flexDirection:'row',gap:8,marginTop:14}}>
<TouchableOpacity style={[s.btn,s.btnSecondary]} onPress={() => setEditing(false)} disabled={saving}>
<Text style={s.btnText}>Abbrechen</Text>
</TouchableOpacity>
<TouchableOpacity style={[s.btn,s.btnPrimary,{flex:1}]} onPress={onSave} disabled={saving}>
<Text style={s.btnText}>{saving ? 'Speichere…' : 'Speichern'}</Text>
</TouchableOpacity>
</View>
</View>
) : (
<View>
<View style={{flexDirection:'row',alignItems:'flex-start',justifyContent:'space-between'}}>
<Text style={s.bigTitle}>{memory.pinned ? '📌 ' : ''}{memory.title}</Text>
<TouchableOpacity onPress={() => setEditing(true)} style={s.iconBtn}>
<Text style={s.iconBtnText}></Text>
</TouchableOpacity>
</View>
<Text style={s.meta}>
{memory.type}{memory.category ? ` · [${memory.category}]` : ''}
</Text>
{(memory.tags || []).length > 0 ? (
<View style={s.tagsRow}>
{memory.tags.map(t => <Text key={t} style={s.tag}>{t}</Text>)}
</View>
) : null}
<Text style={s.contentBlock}>{memory.content}</Text>
<Text style={s.sectionHead}>📎 Anhaenge</Text>
{(memory.attachments || []).length === 0 ? (
<Text style={{color:'#555570',fontStyle:'italic',fontSize:12}}>(keine)</Text>
) : (
(memory.attachments || []).map((a) => {
const isImage = (a.mime || '').startsWith('image/');
return (
<View key={a.name} style={s.attRow}>
<TouchableOpacity style={{flexDirection:'row',alignItems:'center',gap:8,flex:1}} onPress={() => onTapAttachment(a)}>
<Text style={{fontSize:18}}>{isImage ? '🖼️' : '📄'}</Text>
<View style={{flex:1}}>
<Text style={{color:'#E0E0F0',fontSize:12}} numberOfLines={1}>{a.name}</Text>
<Text style={{color:'#555570',fontSize:10}}>{a.mime} · {Math.round(a.size/1024)} KB</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => onDeleteAttachment(a)} style={s.attDelete}>
<Text style={{color:'#FF6B6B',fontSize:12}}>🗑</Text>
</TouchableOpacity>
</View>
);
})
)}
<TouchableOpacity style={[s.btn,s.btnSecondary,{marginTop:8}]} onPress={onPickAndUpload}>
<Text style={s.btnText}> Datei anhaengen</Text>
</TouchableOpacity>
{busy ? <Text style={{color:'#8888AA',fontSize:11,marginTop:4}}>{busy}</Text> : null}
<Text style={s.timestamps}>
angelegt: {(memory.created_at || '').slice(0,16).replace('T',' ')}{'\n'}
geaendert: {(memory.updated_at || '').slice(0,16).replace('T',' ')}{'\n'}
id: {memory.id}
</Text>
<TouchableOpacity style={[s.btn,s.btnDanger,{marginTop:14}]} onPress={onDelete}>
<Text style={s.btnText}>🗑 Memory komplett loeschen</Text>
</TouchableOpacity>
</View>
)
) : null}
</ScrollView>
</View>
</View>
<Modal visible={!!fullscreen} transparent onRequestClose={() => setFullscreen(null)}>
<TouchableOpacity style={s.fsBack} onPress={() => setFullscreen(null)}>
{fullscreen ? <Image source={{uri:fullscreen}} style={s.fsImg} resizeMode="contain" /> : null}
</TouchableOpacity>
</Modal>
</Modal>
);
};
const s = StyleSheet.create({
backdrop: { flex:1, backgroundColor:'rgba(0,0,0,0.75)', justifyContent:'flex-end' },
box: { backgroundColor:'#0D0D1A', borderTopLeftRadius:12, borderTopRightRadius:12, maxHeight:'92%' },
header: { flexDirection:'row', justifyContent:'space-between', alignItems:'center', padding:14, borderBottomColor:'#1E1E2E', borderBottomWidth:1 },
title: { color:'#FFD60A', fontWeight:'bold', fontSize:15 },
closeX: { color:'#8888AA', fontSize:24, paddingHorizontal:6 },
body: { padding:14 },
err: { color:'#FF6B6B', fontSize:12, marginTop:8 },
label: { color:'#8888AA', fontSize:11, marginBottom:3, marginTop:8 },
input: { backgroundColor:'#080810', borderColor:'#1E1E2E', borderWidth:1, borderRadius:4, padding:8, color:'#E0E0F0', fontSize:13 },
bigTitle: { color:'#E0E0F0', fontWeight:'bold', fontSize:16, flex:1, marginRight:6 },
iconBtn: { padding:6, backgroundColor:'#1E1E2E', borderRadius:6 },
iconBtnText: { color:'#0096FF', fontSize:14 },
meta: { color:'#8888AA', fontSize:11, marginTop:4 },
tagsRow: { flexDirection:'row', flexWrap:'wrap', gap:4, marginTop:6 },
tag: { backgroundColor:'#1E1E2E', color:'#8888AA', fontSize:10, paddingHorizontal:6, paddingVertical:2, borderRadius:8 },
contentBlock: { color:'#E0E0F0', fontSize:13, marginTop:12, lineHeight:18 },
sectionHead: { color:'#0096FF', fontSize:11, marginTop:14, marginBottom:6, textTransform:'uppercase', letterSpacing:0.5 },
attRow: { flexDirection:'row', alignItems:'center', backgroundColor:'#080810', padding:8, borderRadius:6, marginBottom:4, gap:6 },
attDelete: { padding:4 },
timestamps: { color:'#555570', fontSize:10, marginTop:12, fontFamily:'monospace' },
btn: { paddingVertical:10, paddingHorizontal:14, borderRadius:6, alignItems:'center' },
btnPrimary: { backgroundColor:'#0096FF' },
btnSecondary: { backgroundColor:'#1E1E2E' },
btnDanger: { backgroundColor:'#3B1010', borderWidth:1, borderColor:'#FF6B6B' },
btnText: { color:'#fff', fontSize:13, fontWeight:'600' },
fsBack: { flex:1, backgroundColor:'rgba(0,0,0,0.95)', justifyContent:'center', alignItems:'center' },
fsImg: { width:'95%', height:'85%' },
});
export default MemoryDetailModal;
-88
View File
@@ -1,88 +0,0 @@
/**
* MessageText — selektierbarer Chat-Text mit Android-Auto-Linkifizierung,
* plus Inline-Image-Rendering wenn der Text Bild-URLs enthaelt.
*
* - Markdown-Syntax `![alt](url)` und plain `https://...image.png` werden
* erkannt — die URL bleibt im Text sichtbar (klickbar via Linkify),
* zusaetzlich wird das Bild als <Image> oder <SvgUri> drunter gerendert.
* - Wir nutzen Androids dataDetectorType="all" (System macht Phone/URL/Email
* automatisch klickbar) und ein einzelnes <Text selectable> ohne nested
* <Text> mit eigenem onPress — Nested Text mit onPress fing die Long-Press-
* Geste ab, damit war Markieren+Kopieren defekt.
*/
import React, { useEffect, useState } from 'react';
import { View, Text, Image, TextStyle, StyleProp } from 'react-native';
import { SvgUri } from 'react-native-svg';
interface Props {
text: string;
style?: StyleProp<TextStyle>;
}
// Bild-URL-Pattern: http(s)://... endend auf gaengige Bild-Endungen.
const IMG_URL_RE = /https?:\/\/[^\s)<"']+\.(?:jpe?g|png|gif|webp|bmp|ico|svg)(?:\?[^\s)<"']*)?/gi;
function extractImageUrls(text: string): string[] {
const urls = new Set<string>();
const matches = text.match(IMG_URL_RE);
if (matches) matches.forEach(u => urls.add(u));
return Array.from(urls);
}
const SVG_RE = /\.svg(?:\?|$)/i;
/** Image mit dynamischer Aspect-Ratio aus echten Bilddimensionen.
* SVGs werden ueber react-native-svg gerendert (kein Image.getSize). */
const InlineImage: React.FC<{ uri: string }> = ({ uri }) => {
const isSvg = SVG_RE.test(uri);
const [aspectRatio, setAspectRatio] = useState<number>(1);
const [failed, setFailed] = useState(false);
useEffect(() => {
if (isSvg) return; // Image.getSize geht fuer SVG nicht
let cancelled = false;
Image.getSize(
uri,
(w, h) => { if (!cancelled && w > 0 && h > 0) setAspectRatio(Math.max(0.5, Math.min(2.5, w / h))); },
() => { if (!cancelled) setFailed(true); },
);
return () => { cancelled = true; };
}, [uri, isSvg]);
if (failed) return null;
if (isSvg) {
return (
<View style={{ marginTop: 8, width: 260, height: 260, backgroundColor: '#0D0D1A', borderRadius: 8, alignItems: 'center', justifyContent: 'center' }}>
<SvgUri uri={uri} width="100%" height="100%" onError={() => setFailed(true)} />
</View>
);
}
return (
<Image
source={{ uri }}
style={{ width: 260, aspectRatio, borderRadius: 8, marginTop: 8, backgroundColor: '#0D0D1A' }}
resizeMode="cover"
onError={() => setFailed(true)}
/>
);
};
const MessageText: React.FC<Props> = ({ text, style }) => {
const imageUrls = extractImageUrls(text || '');
if (imageUrls.length === 0) {
return (
<Text style={style} selectable dataDetectorType="all">
{text}
</Text>
);
}
return (
<View>
<Text style={style} selectable dataDetectorType="all">
{text}
</Text>
{imageUrls.map(u => <InlineImage key={u} uri={u} />)}
</View>
);
};
export default MessageText;
-614
View File
@@ -1,614 +0,0 @@
/**
* OAuth-Browser — Verwaltung der OAuth-Provider (Spotify + Custom) und ihrer
* Credentials. Eingesetzt von SettingsScreen → Sektion "OAuth-Apps".
*
* Pro Service:
* - Status (verbunden / konfiguriert / leer)
* - client_id + client_secret (Passwort-Toggle)
* - Bei Custom-Services: auch auth_url + token_url + scopes editierbar
* - "Autorisieren ↗" oeffnet die Provider-Auth-Seite im System-Browser
* - "Abmelden" + (bei Custom) "🗑 Service entfernen"
*
* Plus: "+ Custom-Service" oeffnet ein Modal fuer name/auth_url/token_url/scopes.
*
* Hinweis zu Credentials: client_id/client_secret laufen ueber HTTP zur
* Bridge, von dort zum Brain. Wenn die App via RVS verbunden ist, geht alles
* ueber TLS (wss://) — der Wert ist nie im Klartext im Netz unterwegs.
*/
import React, { useCallback, useEffect, useState } from 'react';
import {
ActivityIndicator,
Alert,
FlatList,
Linking,
Modal,
ScrollView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import brainApi, { OAuthServiceStatus, OAuthAppConfig } from '../services/brainApi';
const COL_OK = '#34C759';
const COL_PENDING = '#FFD60A';
const COL_OFF = '#666680';
const COL_ERR = '#FF6B6B';
function fmtExpiry(secs: number | null | undefined): string {
if (secs == null) return '';
if (secs <= 0) return 'abgelaufen';
if (secs < 60) return `${secs}s`;
if (secs < 3600) return `${Math.round(secs / 60)} min`;
if (secs < 86400) return `${Math.round(secs / 3600)} h`;
return `${Math.round(secs / 86400)} Tage`;
}
interface MergedService extends OAuthServiceStatus {
app?: OAuthAppConfig;
isDefault: boolean;
}
export const OAuthBrowser: React.FC = () => {
const [services, setServices] = useState<MergedService[]>([]);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [editService, setEditService] = useState<MergedService | null>(null);
const [showNew, setShowNew] = useState(false);
const load = useCallback(() => {
setLoading(true); setErr(null);
Promise.all([brainApi.listOAuthServices(), brainApi.getOAuthApps()])
.then(([statusRes, appsRes]) => {
const apps = appsRes.apps || {};
const defaults = new Set(appsRes.defaults || []);
const items: MergedService[] = (statusRes.services || []).map(s => ({
...s,
app: apps[s.service],
isDefault: defaults.has(s.service),
}));
items.sort((a, b) => {
if (a.authenticated !== b.authenticated) return a.authenticated ? -1 : 1;
if (a.configured !== b.configured) return a.configured ? -1 : 1;
return a.service.localeCompare(b.service);
});
setServices(items);
})
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, []);
useEffect(() => { load(); }, [load]);
const renderItem = ({ item }: { item: MergedService }) => {
let statusColor: string = COL_OFF;
let statusIcon = '⚫';
let statusText = 'nicht konfiguriert';
if (item.authenticated) {
statusColor = COL_OK; statusIcon = '✅';
statusText = `verbunden${item.expiresInSec != null ? ' · noch ' + fmtExpiry(item.expiresInSec) : ''}`;
} else if (item.configured) {
statusColor = COL_PENDING; statusIcon = '🟡';
statusText = 'konfiguriert, nicht autorisiert';
}
return (
<TouchableOpacity style={s.row} onPress={() => setEditService(item)}>
<View style={{flex: 1, marginRight: 8}}>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 6, marginBottom: 2}}>
<Text style={{color: '#E0E0F0', fontWeight: '600', fontSize: 14, textTransform: 'capitalize'}}>{item.service}</Text>
{!item.isDefault ? (
<Text style={{color: '#8888AA', fontSize: 10}}>(custom)</Text>
) : null}
</View>
<Text style={{color: statusColor, fontSize: 12}}>{statusIcon} {statusText}</Text>
</View>
</TouchableOpacity>
);
};
return (
<View style={{flex: 1}}>
<View style={s.toolbar}>
<Text style={{color: '#8888AA', fontSize: 11, flex: 1}}>
Verbinde ARIA mit externen Services (Spotify u.a.).
</Text>
<TouchableOpacity onPress={load} style={s.iconBtn}>
<Text style={{fontSize: 16}}>{'↻'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setShowNew(true)} style={[s.iconBtn, {backgroundColor: '#0096FF'}]}>
<Text style={{fontSize: 13, color: '#fff', fontWeight: '700'}}>+ Custom</Text>
</TouchableOpacity>
</View>
{err ? <Text style={s.err}>{err}</Text> : null}
{loading && services.length === 0 ? (
<ActivityIndicator color="#0096FF" style={{marginTop: 20}} />
) : (
<FlatList
data={services}
keyExtractor={s => s.service}
renderItem={renderItem}
nestedScrollEnabled={true}
ListEmptyComponent={
<Text style={{color: '#555570', textAlign: 'center', padding: 20, fontStyle: 'italic'}}>
(keine OAuth-Services frag ARIA: "verbinde mich mit X")
</Text>
}
contentContainerStyle={{paddingBottom: 20}}
/>
)}
{editService ? (
<OAuthEditModal
service={editService}
onClose={() => setEditService(null)}
onReload={() => { setEditService(null); load(); }}
/>
) : null}
{showNew ? (
<OAuthCustomNewModal
onClose={() => setShowNew(false)}
onCreated={() => { setShowNew(false); load(); }}
/>
) : null}
</View>
);
};
// ── Edit-Modal (Credentials + Authorize + Revoke + Delete) ──────────
interface EditProps {
service: MergedService;
onClose: () => void;
onReload: () => void;
}
const OAuthEditModal: React.FC<EditProps> = ({ service: svc, onClose, onReload }) => {
const [clientId, setClientId] = useState(svc.app?.client_id || '');
const [clientSecret, setClientSecret] = useState('');
const [showSecret, setShowSecret] = useState(false);
const [authUrl, setAuthUrl] = useState(svc.app?.auth_url || '');
const [tokenUrl, setTokenUrl] = useState(svc.app?.token_url || '');
const [scopes, setScopes] = useState((svc.app?.scopes || []).join(' '));
const [saving, setSaving] = useState(false);
const [showAdvanced, setShowAdvanced] = useState(false);
const save = async () => {
if (!clientId.trim()) {
Alert.alert('Fehler', 'client_id darf nicht leer sein.');
return;
}
setSaving(true);
const body: any = {
service: svc.service,
client_id: clientId.trim(),
};
if (clientSecret) body.client_secret = clientSecret;
if (authUrl.trim()) body.auth_url = authUrl.trim();
if (tokenUrl.trim()) body.token_url = tokenUrl.trim();
if (scopes.trim()) body.scopes = scopes.trim().split(/\s+/).filter(Boolean);
try {
await brainApi.saveOAuthApp(body);
onReload();
} catch (e: any) {
Alert.alert('Speichern fehlgeschlagen', String(e?.message || e));
} finally {
setSaving(false);
}
};
const authorize = async () => {
if (!svc.configured) {
Alert.alert('Erst Credentials eintragen', 'client_id und client_secret muessen vor dem Autorisieren gespeichert sein.');
return;
}
try {
const r = await brainApi.authorizeOAuth(svc.service);
// Im System-Browser oeffnen — InAppBrowser wuerde z.T. von Providern blockiert
const ok = await Linking.canOpenURL(r.url);
if (!ok) {
Alert.alert('Browser nicht verfuegbar', 'Konnte die Auth-URL nicht oeffnen.');
return;
}
Linking.openURL(r.url);
Alert.alert(
'Im Browser anmelden',
`Bitte stimme bei ${svc.service} zu. Nach dem Redirect zur Callback-Seite kannst du den Tab schliessen — ARIA bekommt das Token automatisch.\n\nDie Status-Anzeige in der App aktualisiert sich nach Refresh.`,
[{ text: 'OK', onPress: () => setTimeout(onReload, 8000) }],
);
} catch (e: any) {
Alert.alert('Authorize fehlgeschlagen', String(e?.message || e));
}
};
const revoke = () => {
Alert.alert(
'Abmelden?',
`Token fuer ${svc.service} entfernen. Du musst danach neu autorisieren.`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Abmelden',
style: 'destructive',
onPress: async () => {
try { await brainApi.revokeOAuth(svc.service); onReload(); }
catch (e: any) { Alert.alert('Fehler', String(e?.message || e)); }
},
},
],
);
};
const removeService = () => {
Alert.alert(
'Service komplett entfernen?',
`"${svc.service}" wird inkl. client_id/secret und Token geloescht.`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Loeschen',
style: 'destructive',
onPress: async () => {
try { await brainApi.deleteOAuthApp(svc.service); onReload(); }
catch (e: any) { Alert.alert('Fehler', String(e?.message || e)); }
},
},
],
);
};
return (
<Modal visible animationType="slide" onRequestClose={onClose} transparent={false}>
<View style={s.modal}>
<View style={s.modalHeader}>
<Text style={s.modalTitle} numberOfLines={1}>{svc.service}</Text>
<TouchableOpacity onPress={onClose} hitSlop={{top:8,bottom:8,left:8,right:8}}>
<Text style={{color: '#8888AA', fontSize: 18}}>{'✕'}</Text>
</TouchableOpacity>
</View>
<ScrollView style={{flex: 1}} contentContainerStyle={{padding: 16}}>
{svc.authenticated ? (
<View style={[s.metaBox, {borderLeftWidth: 3, borderLeftColor: COL_OK, marginBottom: 12}]}>
<Text style={[s.meta, {color: COL_OK, fontWeight: '700'}]}>
verbunden{svc.expiresInSec != null ? ` · Token noch ${fmtExpiry(svc.expiresInSec)}` : ''}
</Text>
{svc.hasRefresh ? <Text style={s.meta}>refresh_token vorhanden auto-renew aktiv</Text>
: <Text style={[s.meta, {color: COL_ERR}]}>KEIN refresh_token Token verfaellt komplett</Text>}
{svc.scope ? <Text style={s.meta}>scopes: {svc.scope}</Text> : null}
</View>
) : null}
<Text style={s.label}>client_id</Text>
<TextInput
style={s.input}
value={clientId}
onChangeText={setClientId}
placeholder="aus dem Provider-Developer-Dashboard"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={s.label}>
client_secret {svc.app?.has_client_secret ? '— gespeichert (leer = behalten)' : '— fehlt'}
</Text>
<View style={{flexDirection: 'row', gap: 6}}>
<TextInput
style={[s.input, {flex: 1}]}
value={clientSecret}
onChangeText={setClientSecret}
placeholder={svc.app?.has_client_secret ? '(neuen eintragen oder leer lassen)' : 'aus dem Dashboard'}
placeholderTextColor="#444460"
secureTextEntry={!showSecret}
autoCapitalize="none"
autoCorrect={false}
/>
<TouchableOpacity
style={[s.btn, {backgroundColor: '#1A1A2E', justifyContent: 'center'}]}
onPress={() => setShowSecret(v => !v)}
>
<Text style={{color: '#8888AA', fontSize: 14}}>{showSecret ? '🙈' : '👁'}</Text>
</TouchableOpacity>
</View>
{/* URLs/Scopes: bei Defaults hinter "advanced" versteckt damit Stefan
nicht ausversehen die Spotify-URLs ueberschreibt. */}
{svc.isDefault ? (
<TouchableOpacity onPress={() => setShowAdvanced(v => !v)} style={{marginTop: 12}}>
<Text style={{color: '#666680', fontSize: 11, fontStyle: 'italic'}}>
{showAdvanced ? '▼' : '▶'} Default-URLs ueberschreiben (advanced)
</Text>
</TouchableOpacity>
) : null}
{(!svc.isDefault || showAdvanced) ? (
<View style={{marginTop: 8}}>
<Text style={s.label}>auth_url</Text>
<TextInput
style={s.input}
value={authUrl}
onChangeText={setAuthUrl}
placeholder="https://provider.com/oauth/authorize"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={s.label}>token_url</Text>
<TextInput
style={s.input}
value={tokenUrl}
onChangeText={setTokenUrl}
placeholder="https://provider.com/oauth/token"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={s.label}>scopes (space-separated)</Text>
<TextInput
style={s.input}
value={scopes}
onChangeText={setScopes}
placeholder="read write user.email"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
</View>
) : null}
<View style={{flexDirection: 'row', gap: 8, marginTop: 16}}>
<TouchableOpacity
style={[s.btn, {backgroundColor: '#0096FF', flex: 1}]}
onPress={save}
disabled={saving}
>
<Text style={{color: '#fff', textAlign: 'center', fontWeight: '700'}}>
{saving ? 'speichert...' : 'Speichern'}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[s.btn, {backgroundColor: svc.configured ? '#34C759' : '#1E1E2E', flex: 1}]}
onPress={authorize}
disabled={!svc.configured}
>
<Text style={{color: svc.configured ? '#fff' : '#555570', textAlign: 'center', fontWeight: '700'}}>
Autorisieren
</Text>
</TouchableOpacity>
</View>
{svc.authenticated ? (
<TouchableOpacity
style={[s.btn, {backgroundColor: '#3A1F1F', borderColor: COL_ERR, marginTop: 12}]}
onPress={revoke}
>
<Text style={{color: COL_ERR, textAlign: 'center', fontWeight: '700'}}>Abmelden (Token loeschen)</Text>
</TouchableOpacity>
) : null}
{!svc.isDefault ? (
<TouchableOpacity
style={[s.btn, {backgroundColor: '#3A1F1F', borderColor: COL_ERR, marginTop: 8}]}
onPress={removeService}
>
<Text style={{color: COL_ERR, textAlign: 'center', fontWeight: '700'}}>🗑 Service komplett entfernen</Text>
</TouchableOpacity>
) : null}
<View style={{height: 30}} />
</ScrollView>
</View>
</Modal>
);
};
// ── Neuer Custom-Provider ──────────────────────────────────────────
interface NewProps {
onClose: () => void;
onCreated: () => void;
}
const OAuthCustomNewModal: React.FC<NewProps> = ({ onClose, onCreated }) => {
const [name, setName] = useState('');
const [authUrl, setAuthUrl] = useState('https://');
const [tokenUrl, setTokenUrl] = useState('https://');
const [scopes, setScopes] = useState('');
const [creating, setCreating] = useState(false);
const create = async () => {
const svc = name.trim().toLowerCase();
if (!/^[a-z0-9_-]+$/.test(svc)) {
Alert.alert('Ungueltiger Name', 'Erlaubt: a-z 0-9 _ -');
return;
}
if (!authUrl.startsWith('http') || !tokenUrl.startsWith('http')) {
Alert.alert('Ungueltige URLs', 'auth_url und token_url muessen http(s):// sein.');
return;
}
setCreating(true);
try {
const body: any = { service: svc, auth_url: authUrl.trim(), token_url: tokenUrl.trim() };
if (scopes.trim()) body.scopes = scopes.trim().split(/\s+/).filter(Boolean);
await brainApi.saveOAuthApp(body);
onCreated();
} catch (e: any) {
Alert.alert('Anlegen fehlgeschlagen', String(e?.message || e));
} finally {
setCreating(false);
}
};
return (
<Modal visible animationType="slide" onRequestClose={onClose} transparent={false}>
<View style={s.modal}>
<View style={s.modalHeader}>
<Text style={s.modalTitle}>Custom OAuth-Provider</Text>
<TouchableOpacity onPress={onClose} hitSlop={{top:8,bottom:8,left:8,right:8}}>
<Text style={{color: '#8888AA', fontSize: 18}}>{'✕'}</Text>
</TouchableOpacity>
</View>
<ScrollView style={{flex: 1}} contentContainerStyle={{padding: 16}}>
<Text style={{color: '#8888AA', fontSize: 12, marginBottom: 12}}>
Trag die OAuth2-Endpunkte des Anbieters ein. client_id + client_secret
kommen anschliessend ins Edit-Formular. Die Callback-URL die du beim
Anbieter eintragen musst, zeigt dir der OAuth-Block im Brain-System-Prompt.
</Text>
<Text style={s.label}>Service-Name (z.B. dropbox, discord)</Text>
<TextInput
style={s.input}
value={name}
onChangeText={setName}
placeholder="kurz, a-z 0-9 _ -"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={s.label}>auth_url</Text>
<TextInput
style={s.input}
value={authUrl}
onChangeText={setAuthUrl}
placeholder="https://provider.com/oauth/authorize"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={s.label}>token_url</Text>
<TextInput
style={s.input}
value={tokenUrl}
onChangeText={setTokenUrl}
placeholder="https://provider.com/oauth/token"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={s.label}>scopes (space-separated, optional)</Text>
<TextInput
style={s.input}
value={scopes}
onChangeText={setScopes}
placeholder="read write user.email"
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
<View style={{flexDirection: 'row', gap: 8, marginTop: 20}}>
<TouchableOpacity style={[s.btn, {backgroundColor: '#1A1A2E', flex: 1}]} onPress={onClose}>
<Text style={{color: '#8888AA', textAlign: 'center'}}>Abbrechen</Text>
</TouchableOpacity>
<TouchableOpacity style={[s.btn, {backgroundColor: '#0096FF', flex: 1}]} onPress={create} disabled={creating}>
<Text style={{color: '#fff', textAlign: 'center', fontWeight: '700'}}>
{creating ? '...' : 'Anlegen'}
</Text>
</TouchableOpacity>
</View>
</ScrollView>
</View>
</Modal>
);
};
// ── Styles ─────────────────────────────────────────────────────────
const s = StyleSheet.create({
toolbar: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
paddingHorizontal: 10,
paddingVertical: 8,
backgroundColor: '#0D0D1A',
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
iconBtn: {
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 6,
backgroundColor: '#1A1A2E',
},
row: {
paddingVertical: 12,
paddingHorizontal: 14,
backgroundColor: '#0D0D1A',
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
err: {
color: '#FF6B6B',
padding: 12,
fontSize: 12,
},
modal: {
flex: 1,
backgroundColor: '#0D0D1A',
},
modalHeader: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
modalTitle: {
color: '#E0E0F0',
fontSize: 16,
fontWeight: '700',
flex: 1,
marginRight: 12,
textTransform: 'capitalize',
},
label: {
color: '#8888AA',
fontSize: 11,
fontWeight: '700',
textTransform: 'uppercase',
letterSpacing: 0.5,
marginTop: 12,
marginBottom: 4,
},
input: {
backgroundColor: '#1A1A2E',
borderWidth: 1,
borderColor: '#1E1E2E',
borderRadius: 6,
color: '#E0E0F0',
padding: 10,
fontSize: 14,
fontFamily: 'monospace',
},
metaBox: {
backgroundColor: '#1A1A2E',
borderRadius: 6,
padding: 10,
gap: 4,
},
meta: {
color: '#8888AA',
fontSize: 12,
},
btn: {
paddingHorizontal: 14,
paddingVertical: 10,
borderRadius: 6,
borderWidth: 1,
borderColor: 'transparent',
},
});
export default OAuthBrowser;
-504
View File
@@ -1,504 +0,0 @@
/**
* Projekt-Übersicht + Switcher.
*
* Modal-Komponente die:
* - Den aktuellen Projekt-Status zeigt (Hauptchat oder konkretes Projekt)
* - Die Projekt-Liste rendert (sortiert nach letzter Aktivität)
* - Per Tap zwischen Projekten wechseln lässt
* - Neue Projekte anlegen kann
* - Bestehende editieren/beenden/archivieren
*
* Eingesetzt von ChatScreen (über den Projekt-Indicator) und von
* SettingsScreen.tsx in der Section 'projects'.
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
ActivityIndicator,
Alert,
FlatList,
Modal,
ScrollView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import brainApi, { Project } from '../services/brainApi';
import rvs from '../services/rvs';
import projectFocus from '../services/projectFocus';
interface Props {
/** Optional — wenn als Modal genutzt, sonst inline */
visible?: boolean;
onClose?: () => void;
/** Wird gerufen wenn Stefan ein anderes Projekt fokussiert (App-lokale
* UI-Entscheidung, wechselt den Chat-Focus). */
onActiveChanged?: (project: Project | null) => void;
/** Der aktuell in der App fokussierte Kontext (App-lokale Source-of-Truth).
* Leer = Hauptchat. Steuert das ✓-FOCUS-Highlight. WICHTIG: der Drawer darf
* den Focus NICHT aus dem Brain-Status ableiten — im Multi-Threading gibt es
* kein globales active_project mehr (status.active ist null), das wuerde den
* Focus bei jedem Drawer-Oeffnen auf Hauptchat zuruecksetzen. */
currentFocusId?: string;
/** 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 {
if (!unixSec) return '?';
const diff = (Date.now() / 1000) - unixSec;
if (diff < 60) return 'gerade eben';
if (diff < 3600) return `vor ${Math.floor(diff / 60)} Min`;
if (diff < 86400) return `vor ${Math.floor(diff / 3600)} Std`;
if (diff < 86400 * 14) return `vor ${Math.floor(diff / 86400)} Tagen`;
return new Date(unixSec * 1000).toLocaleDateString('de-DE');
}
export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onActiveChanged, currentFocusId, 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);
const [err, setErr] = useState<string | null>(null);
const [newOpen, setNewOpen] = useState(false);
const [newName, setNewName] = useState('');
const [newDesc, setNewDesc] = useState('');
const [editing, setEditing] = useState<Project | null>(null);
const [editName, setEditName] = useState('');
const [editDesc, setEditDesc] = useState('');
const [editKind, setEditKind] = useState<'code' | 'chat'>('chat');
// Versteckte Projekte standardmaessig ausblenden; Toggle blendet sie
// temporaer (gedimmt) ein — zum Ansehen/Auswaehlen oder Wieder-Sichtbarmachen.
const [showHidden, setShowHidden] = useState(false);
// Refs damit useCallback NICHT bei jeder Re-Render des Parents neu erzeugt
// wird (parent uebergibt oft inline-arrow-Callbacks, neue Identity jedes
// Render → useCallback re-runs → useEffect refeuert → infinite spinner).
const onActiveChangedRef = useRef(onActiveChanged);
useEffect(() => { onActiveChangedRef.current = onActiveChanged; }, [onActiveChanged]);
const load = useCallback(() => {
setLoading(true); setErr(null);
brainApi.getProjectStatus()
.then(status => {
// NUR die Projektliste + Queue uebernehmen. NICHT status.active in den
// App-Focus pushen — im Multi-Threading ist das Brain-active_project
// bedeutungslos (null), das wuerde den Focus bei jedem Drawer-Oeffnen
// auf Hauptchat zuruecksetzen und alle Nachrichten dort landen lassen.
setProjects(status.projects || []);
})
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, []);
useEffect(() => { if (visible) load(); }, [visible, load]);
// Highlight („✓ FOCUS") folgt dem App-Focus (Source-of-Truth), nicht dem
// Brain. switchTo setzt activeId zusaetzlich sofort fuer Instant-Feedback.
useEffect(() => { setActiveId(currentFocusId || ''); }, [currentFocusId]);
// Reload bei RVS-Reconnect — sonst zeigt die Liste den Fast-Fail ewig
useEffect(() => {
if (!visible) return;
const unsub = rvs.onStateChange((state) => { if (state === 'connected') load(); });
return () => unsub();
}, [visible, load]);
// Live-Sync: ein anderer Client (Diagnostic / andere App) hat ein Projekt
// geaendert (verstecken/anlegen/beenden/…) → project_changed ueber RVS →
// Liste neu laden, ohne dass Stefan manuell refreshen muss.
useEffect(() => {
if (!visible) return;
const unsub = rvs.onMessage((msg: any) => {
if (msg?.type === 'project_changed') load();
});
return () => unsub();
}, [visible, load]);
const switchTo = useCallback((id: string) => {
// 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();
if (!name) return;
brainApi.createProject({ name, description: newDesc.trim() })
.then(() => {
setNewName(''); setNewDesc(''); setNewOpen(false);
load();
})
.catch(e => Alert.alert('Anlegen fehlgeschlagen', String(e?.message || e)));
}, [newName, newDesc, load]);
const openEdit = useCallback((p: Project) => {
setEditing(p);
setEditName(p.name);
setEditDesc(p.description || '');
setEditKind(p.kind === 'code' ? 'code' : 'chat');
}, []);
const saveEdit = useCallback(() => {
if (!editing) return;
const patch: Partial<Pick<Project, 'name' | 'description' | 'kind'>> = {};
if (editName.trim() && editName.trim() !== editing.name) patch.name = editName.trim();
if (editDesc.trim() !== (editing.description || '')) patch.description = editDesc.trim();
const curKind = editing.kind === 'code' ? 'code' : 'chat';
if (editKind !== curKind) patch.kind = editKind;
if (Object.keys(patch).length === 0) { setEditing(null); return; }
brainApi.updateProject(editing.id, patch)
.then(() => {
// Kind sofort in den Workspace spiegeln (Editor/Desktop-Panels).
if (patch.kind) projectFocus.setKind(editing.id, patch.kind);
setEditing(null); load();
})
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
}, [editing, editName, editDesc, editKind, load]);
const endProject = useCallback((p: Project) => {
Alert.alert(`"${p.name}" beenden?`,
'Bleibt sichtbar, kann nicht mehr aktiv sein außer mit explizitem Wiedereintritt.',
[
{ text: 'Abbrechen', style: 'cancel' },
{ text: 'Beenden', onPress: () => {
brainApi.endProject(p.id).then(() => load()).catch(e => Alert.alert('Fehler', String(e?.message || e)));
}},
]);
}, [load]);
// Nach einer Projekt-Mutation die anderen Clients (Diagnostic, weitere
// App-Instanzen) live aktualisieren — via RVS project_changed. RVS echot
// NICHT an den Sender zurueck, darum laden wir lokal zusaetzlich selbst.
const broadcastProjectsChanged = useCallback(() => {
try { rvs.send('project_changed' as any, { reason: 'app' }); } catch {}
}, []);
const toggleHidden = useCallback((p: Project) => {
brainApi.setProjectHidden(p.id, !p.hidden)
.then(() => { broadcastProjectsChanged(); load(); })
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
}, [load, broadcastProjectsChanged]);
const archiveProject = useCallback((p: Project) => {
Alert.alert(`"${p.name}" archivieren?`,
'Verschwindet aus der Standardliste. Über "archivierte zeigen" erreichbar.',
[
{ text: 'Abbrechen', style: 'cancel' },
{ text: 'Archivieren', style: 'destructive', onPress: () => {
brainApi.archiveProject(p.id)
.then(() => { setEditing(null); load(); })
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
}},
]);
}, [load]);
// ── Render ────────────────────────────────────────────────
const renderItem = ({ item }: { item: Project }) => {
const isActive = item.id === activeId;
const dot = _statusDot(item.id);
const hidden = !!item.hidden;
return (
<TouchableOpacity
onPress={() => switchTo(item.id)}
onLongPress={() => openEdit(item)}
style={[s.row, isActive && s.rowActive, hidden && s.rowHidden]}
>
<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.has_files && (
<Text style={{ fontSize: 12 }} accessibilityLabel="hat Dateien">📄{item.file_count ? ` ${item.file_count}` : ''}</Text>
)}
{hidden && <Text style={s.hiddenBadge}>versteckt</Text>}
{item.status === 'ended' && <Text style={s.statusBadge}>beendet</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>
{/* Auge: verstecken (🙈) / wieder sichtbar (👁). Eigener Touch, damit
der Tap NICHT das Projekt wechselt. */}
<TouchableOpacity
onPress={() => toggleHidden(item)}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
style={s.eyeBtn}
>
<Text style={s.eyeIcon}>{hidden ? '👁' : '🙈'}</Text>
</TouchableOpacity>
</TouchableOpacity>
);
};
const hiddenCount = projects.filter(p => p.hidden).length;
const visibleProjects = showHidden ? projects : projects.filter(p => !p.hidden);
const body = (
<View style={{ flex: 1, backgroundColor: '#0A0A14' }}>
{/* Header */}
<View style={s.header}>
{onClose && (
<TouchableOpacity onPress={onClose} style={s.headerBtn}>
<Text style={s.headerBtnText}></Text>
</TouchableOpacity>
)}
<Text style={s.headerTitle}>Projekte</Text>
<TouchableOpacity onPress={() => setNewOpen(true)} style={s.headerBtn}>
<Text style={[s.headerBtnText, { color: '#34C759' }]}>+ Neu</Text>
</TouchableOpacity>
</View>
{/* Hauptchat-Eintrag (immer oben) */}
{(() => {
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>
);
})()}
{/* Versteckte-Toggle — nur wenn es welche gibt (oder gerade eingeblendet) */}
{(hiddenCount > 0 || showHidden) && (
<TouchableOpacity onPress={() => setShowHidden(v => !v)} style={s.hiddenToggle}>
<Text style={s.hiddenToggleText}>
{showHidden
? `🙈 Versteckte ausblenden${hiddenCount ? ` (${hiddenCount})` : ''}`
: `👁 Versteckte anzeigen${hiddenCount ? ` (${hiddenCount})` : ''}`}
</Text>
</TouchableOpacity>
)}
{loading ? (
<View style={{ padding: 24, alignItems: 'center' }}>
<ActivityIndicator color="#0096FF" />
</View>
) : err ? (
<Text style={s.errorText}> {err}</Text>
) : (
<FlatList
data={visibleProjects}
keyExtractor={p => p.id}
renderItem={renderItem}
ListEmptyComponent={
projects.length > 0 ? (
<Text style={s.emptyText}>
Alle {hiddenCount} Projekte sind versteckt.{'\n'}
Tipp 👁 Versteckte anzeigen".
</Text>
) : (
<Text style={s.emptyText}>
Noch keine Projekte. Tipp + Neu oder sag zu ARIA:{'\n'}
„Lass uns ein Projekt 'XY' anlegen".
</Text>
)
}
/>
)}
{/* Neu-Anlegen Modal */}
<Modal visible={newOpen} animationType="slide" transparent onRequestClose={() => setNewOpen(false)}>
<View style={s.modalOverlay}>
<View style={s.modalCard}>
<Text style={s.modalTitle}>Neues Projekt</Text>
<TextInput
value={newName}
onChangeText={setNewName}
placeholder="Name (z.B. 'Frankreich-Urlaub')"
placeholderTextColor="#555570"
style={s.input}
autoFocus
/>
<TextInput
value={newDesc}
onChangeText={setNewDesc}
placeholder="Beschreibung — kurz, hilft beim Wiederfinden"
placeholderTextColor="#555570"
style={[s.input, { height: 70 }]}
multiline
/>
<View style={{ flexDirection: 'row', gap: 8, marginTop: 12 }}>
<TouchableOpacity onPress={() => setNewOpen(false)} style={[s.modalBtn, { backgroundColor: '#2A2A3E' }]}>
<Text style={s.modalBtnText}>Abbrechen</Text>
</TouchableOpacity>
<TouchableOpacity onPress={createProject} style={[s.modalBtn, { backgroundColor: '#34C759' }]}>
<Text style={s.modalBtnText}>Anlegen + aktivieren</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
{/* Edit Modal */}
<Modal visible={!!editing} animationType="slide" transparent onRequestClose={() => setEditing(null)}>
<View style={s.modalOverlay}>
<View style={s.modalCard}>
<Text style={s.modalTitle}>Projekt bearbeiten</Text>
<TextInput
value={editName}
onChangeText={setEditName}
placeholder="Name"
placeholderTextColor="#555570"
style={s.input}
/>
<TextInput
value={editDesc}
onChangeText={setEditDesc}
placeholder="Beschreibung"
placeholderTextColor="#555570"
style={[s.input, { height: 70 }]}
multiline
/>
<TouchableOpacity
onPress={() => setEditKind(k => (k === 'code' ? 'chat' : 'code'))}
style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 8 }}
>
<Text style={{ color: '#E0E0F0', fontSize: 14 }}>💻 Code-Projekt{'\n'}
<Text style={{ color: '#8888AA', fontSize: 11 }}>zeigt Editor + Desktop im Cockpit</Text>
</Text>
<View style={{
width: 46, height: 26, borderRadius: 13, padding: 3,
backgroundColor: editKind === 'code' ? '#0096FF' : '#2A2A3E',
alignItems: editKind === 'code' ? 'flex-end' : 'flex-start',
}}>
<View style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: '#FFFFFF' }} />
</View>
</TouchableOpacity>
<View style={{ flexDirection: 'row', gap: 8, marginTop: 12 }}>
<TouchableOpacity onPress={() => setEditing(null)} style={[s.modalBtn, { backgroundColor: '#2A2A3E' }]}>
<Text style={s.modalBtnText}>Abbrechen</Text>
</TouchableOpacity>
<TouchableOpacity onPress={saveEdit} style={[s.modalBtn, { backgroundColor: '#34C759' }]}>
<Text style={s.modalBtnText}>Speichern</Text>
</TouchableOpacity>
</View>
{editing && editing.status !== 'ended' && (
<TouchableOpacity onPress={() => endProject(editing)} style={s.tertiaryBtn}>
<Text style={s.tertiaryBtnText}> Projekt beenden</Text>
</TouchableOpacity>
)}
{editing && (
<TouchableOpacity onPress={() => archiveProject(editing)} style={s.tertiaryBtn}>
<Text style={[s.tertiaryBtnText, { color: '#E55C5C' }]}>🗑 Archivieren</Text>
</TouchableOpacity>
)}
</View>
</View>
</Modal>
</View>
);
// Wenn als Modal genutzt
if (onClose) {
return (
<Modal visible={visible} animationType="slide" onRequestClose={onClose}>
{body}
</Modal>
);
}
return body;
};
const s = StyleSheet.create({
header: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 12,
paddingVertical: 14,
borderBottomWidth: 1,
borderColor: '#1E1E2E',
backgroundColor: '#080810',
},
headerBtn: { padding: 8, minWidth: 60 },
headerBtnText: { color: '#0096FF', fontSize: 18, fontWeight: '600' },
headerTitle: { flex: 1, textAlign: 'center', color: '#E0E0F0', fontSize: 18, fontWeight: '700' },
row: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 16,
paddingVertical: 12,
borderBottomWidth: 1,
borderColor: '#1E1E2E',
},
rowActive: {
backgroundColor: 'rgba(52,199,89,0.08)',
borderLeftWidth: 3,
borderLeftColor: '#34C759',
},
rowHidden: { opacity: 0.55 },
eyeBtn: { paddingHorizontal: 8, paddingVertical: 6, marginLeft: 6 },
eyeIcon: { fontSize: 18 },
hiddenBadge: { color: '#B392F0', fontSize: 10, fontWeight: '700',
backgroundColor: 'rgba(179,146,240,0.15)', paddingHorizontal: 6,
paddingVertical: 2, borderRadius: 4 },
hiddenToggle: {
paddingHorizontal: 16, paddingVertical: 10,
borderBottomWidth: 1, borderColor: '#1E1E2E',
backgroundColor: '#0D0D18',
},
hiddenToggleText: { color: '#B392F0', fontSize: 12, fontWeight: '600' },
rowName: { color: '#E0E0F0', fontSize: 16, fontWeight: '600' },
rowDesc: { color: '#8888AA', fontSize: 13, marginTop: 4 },
rowMeta: { color: '#555570', fontSize: 11, marginTop: 4 },
activeBadge: { color: '#34C759', fontSize: 10, fontWeight: '800' },
statusBadge: { color: '#FFD60A', fontSize: 10, fontWeight: '700',
backgroundColor: 'rgba(255,214,10,0.15)', paddingHorizontal: 6,
paddingVertical: 2, borderRadius: 4 },
errorText: { color: '#FF6E6E', padding: 16, textAlign: 'center', fontSize: 13 },
emptyText: { color: '#555570', padding: 24, textAlign: 'center', fontSize: 13, lineHeight: 19 },
modalOverlay: {
flex: 1, backgroundColor: 'rgba(0,0,0,0.6)',
justifyContent: 'center', paddingHorizontal: 20,
},
modalCard: { backgroundColor: '#15151E', borderRadius: 12, padding: 18 },
modalTitle: { color: '#E0E0F0', fontSize: 18, fontWeight: '700', marginBottom: 14 },
input: {
backgroundColor: '#0A0A14', borderRadius: 6, color: '#E0E0F0',
paddingHorizontal: 12, paddingVertical: 10, fontSize: 14, marginBottom: 8,
borderWidth: 1, borderColor: '#2A2A3E',
},
modalBtn: { flex: 1, alignItems: 'center', paddingVertical: 11, borderRadius: 6 },
modalBtnText: { color: '#fff', fontSize: 14, fontWeight: '700' },
tertiaryBtn: { alignItems: 'center', paddingVertical: 10, marginTop: 8 },
tertiaryBtnText: { color: '#FFD60A', fontSize: 13, fontWeight: '600' },
});
export default ProjectsBrowser;
+6 -13
View File
@@ -121,20 +121,13 @@ const QRScanner: React.FC<QRScannerProps> = ({ visible, onScan, onClose }) => {
<View style={styles.container}>
{hasPermission ? (
<>
{/* react-native-camera-kit v13: die .d.ts markiert viele OPTIONALE
CameraScreen-Props faelschlich als required (defaultProps fuellen
sie zur Laufzeit) und kennt colorForScannerFrame nicht — der war
ein No-Op und ist raus. scanBarcode/onReadCode ist die korrekte
v13-Barcode-API. Props als any spreaden, um die kaputten Lib-Typen
zu umgehen, ohne echten Code zu veraendern. */}
<CameraScreen
{...({
scanBarcode: true,
onReadCode: handleBarcodeScan,
showFrame: true,
frameColor: '#0096FF',
laserColor: '#0096FF',
} as any)}
scanBarcode={true}
onReadCode={handleBarcodeScan}
showFrame={true}
frameColor="#0096FF"
laserColor="#0096FF"
colorForScannerFrame="#0096FF"
/>
{/* Overlay oben */}
-657
View File
@@ -1,657 +0,0 @@
/**
* Skill-Browser — Liste aller Skills mit Toggle, Tap-zum-Details, Run,
* Logs und Loeschen.
*
* Eingesetzt von SettingsScreen → Sektion "Skills".
*
* Brain-API ueber brainApi (RVS-Brain-Proxy). Code-Edits laufen NICHT
* ueber diese UI — Skill-Code-Aenderungen sind ARIAs Domaene
* (skill_update Brain-Tool). Hier nur Manifest-Felder + Run + Cleanup.
*/
import React, { useCallback, useEffect, useState } from 'react';
import {
ActivityIndicator,
Alert,
FlatList,
Modal,
ScrollView,
StyleSheet,
Switch,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import brainApi, { Skill, SkillConfigField, SkillVersion } from '../services/brainApi';
const COL_ACTIVE = '#34C759';
const COL_INACTIVE = '#555570';
const COL_ARIA = '#FFD60A';
const COL_STEFAN = '#0096FF';
function relTime(iso: string | null | undefined): string {
if (!iso) return '—';
const t = new Date(iso).getTime();
if (!t) return '—';
const diffSec = Math.floor((Date.now() - t) / 1000);
if (diffSec < 60) return `vor ${diffSec}s`;
if (diffSec < 3600) return `vor ${Math.floor(diffSec / 60)}min`;
if (diffSec < 86400) return `vor ${Math.floor(diffSec / 3600)}h`;
return `vor ${Math.floor(diffSec / 86400)}d`;
}
export const SkillBrowser: React.FC = () => {
const [items, setItems] = useState<Skill[]>([]);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [filter, setFilter] = useState<'all' | 'active' | 'inactive'>('all');
const [detail, setDetail] = useState<Skill | null>(null);
const load = useCallback(() => {
setLoading(true); setErr(null);
brainApi.listSkills()
.then(s => {
s.sort((a, b) => {
if (a.active !== b.active) return a.active ? -1 : 1;
return (a.name || '').localeCompare(b.name || '');
});
setItems(s);
})
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, []);
useEffect(() => { load(); }, [load]);
const visible = items.filter(s => {
if (filter === 'active') return s.active;
if (filter === 'inactive') return !s.active;
return true;
});
const toggleActive = (s: Skill) => {
brainApi.updateSkill(s.name, { active: !s.active })
.then(() => load())
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
};
const renderItem = ({ item }: { item: Skill }) => {
const isAria = (item.author || '').toLowerCase() === 'aria';
const authorColor = isAria ? COL_ARIA : COL_STEFAN;
const authorLabel = isAria ? '🤖 von ARIA' : '👤 von Stefan';
return (
<TouchableOpacity style={s.row} onPress={() => setDetail(item)}>
<View style={{flex: 1, marginRight: 8}}>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 6, marginBottom: 4}}>
<Text style={{color: authorColor, fontSize: 10, fontWeight: '700'}}>{authorLabel}</Text>
<Text style={{color: '#E0E0F0', fontWeight: '600', flex: 1}} numberOfLines={1}>{item.name}</Text>
</View>
<Text style={{color: '#8888AA', fontSize: 12}} numberOfLines={2}>{item.description}</Text>
{item.setup_error ? (
<Text style={{color: '#FF6B6B', fontSize: 11, marginTop: 4}} numberOfLines={2}>
Setup-Fehler: {item.setup_error}
</Text>
) : null}
<Text style={{color: '#444460', fontSize: 10, marginTop: 4}}>
{item.execution} · {item.use_count || 0}× ausgefuehrt · zuletzt: {relTime(item.last_used)}
</Text>
</View>
<Switch
value={item.active}
onValueChange={() => toggleActive(item)}
trackColor={{ false: '#1E1E2E', true: COL_ACTIVE }}
thumbColor="#E0E0F0"
/>
</TouchableOpacity>
);
};
return (
<View style={{flex: 1}}>
<View style={s.toolbar}>
{(['all', 'active', 'inactive'] as const).map(f => (
<TouchableOpacity
key={f}
style={[s.chip, filter === f && s.chipActive]}
onPress={() => setFilter(f)}
>
<Text style={{color: filter === f ? '#0D0D1A' : '#8888AA', fontSize: 12, fontWeight: '600'}}>
{f === 'all' ? 'Alle' : f === 'active' ? 'Aktive' : 'Inaktive'}
</Text>
</TouchableOpacity>
))}
<View style={{flex: 1}} />
<TouchableOpacity onPress={load} style={s.iconBtn}>
<Text style={{fontSize: 16}}>{'↻'}</Text>
</TouchableOpacity>
</View>
{err ? <Text style={s.err}>{err}</Text> : null}
{loading && items.length === 0 ? (
<ActivityIndicator color="#0096FF" style={{marginTop: 20}} />
) : (
<FlatList
data={visible}
keyExtractor={s => s.name}
renderItem={renderItem}
nestedScrollEnabled={true}
ListEmptyComponent={
<Text style={{color: '#555570', textAlign: 'center', padding: 20, fontStyle: 'italic'}}>
{items.length === 0
? '(noch keine Skills — frag ARIA: "bau mir einen Skill der ...")'
: '(keine Treffer für diesen Filter)'}
</Text>
}
contentContainerStyle={{paddingBottom: 20}}
/>
)}
{detail ? (
<SkillDetailModal
skill={detail}
onClose={() => setDetail(null)}
onReload={() => { load(); brainApi.getSkill(detail.name).then(setDetail).catch(() => {}); }}
/>
) : null}
</View>
);
};
// ── Detail-Modal mit Run + Logs + Delete ─────────────────────────────
interface DetailProps {
skill: Skill;
onClose: () => void;
onReload: () => void;
}
const SkillDetailModal: React.FC<DetailProps> = ({ skill, onClose, onReload }) => {
const [argValues, setArgValues] = useState<Record<string, string>>({});
const [running, setRunning] = useState(false);
const [runResult, setRunResult] = useState<{
ok: boolean; exit_code: number; stdout: string; stderr: string; duration_sec: number;
} | null>(null);
const [logs, setLogs] = useState<any[] | null>(null);
const [loadingLogs, setLoadingLogs] = useState(false);
// P3: Skill-Config (statische Werte je Skill, z.B. API-Keys)
const [cfgSchema, setCfgSchema] = useState<SkillConfigField[]>([]);
const [cfgValues, setCfgValues] = useState<Record<string, any>>({});
const [cfgDraft, setCfgDraft] = useState<Record<string, string>>({});
const [cfgSaving, setCfgSaving] = useState(false);
// P4: Versionen + Rollback
const [versions, setVersions] = useState<SkillVersion[]>([]);
const [versionsLoading, setVersionsLoading] = useState(false);
const args = Array.isArray(skill.args) ? skill.args : [];
// Config + Versionen beim Mount laden
useEffect(() => {
brainApi.getSkillConfig(skill.name)
.then(r => { setCfgSchema(r.schema || []); setCfgValues(r.values || {}); })
.catch(() => {});
setVersionsLoading(true);
brainApi.listSkillVersions(skill.name)
.then(setVersions)
.catch(() => setVersions([]))
.finally(() => setVersionsLoading(false));
}, [skill.name]);
const setArg = (name: string, value: string) =>
setArgValues(prev => ({ ...prev, [name]: value }));
const run = () => {
setRunning(true); setRunResult(null);
const argsObj: Record<string, any> = {};
for (const a of args) {
if (a?.name && argValues[a.name] !== undefined && argValues[a.name] !== '') {
argsObj[a.name] = argValues[a.name];
}
}
brainApi.runSkill(skill.name, argsObj)
.then(r => setRunResult(r))
.catch(e => setRunResult({
ok: false, exit_code: -1, stdout: '', stderr: String(e?.message || e), duration_sec: 0,
}))
.finally(() => setRunning(false));
};
const loadLogs = () => {
setLoadingLogs(true);
brainApi.getSkillLogs(skill.name, 20)
.then(setLogs)
.catch(e => Alert.alert('Logs-Fehler', String(e?.message || e)))
.finally(() => setLoadingLogs(false));
};
const remove = () => {
Alert.alert(
'Skill loeschen?',
`"${skill.name}" wird komplett entfernt (venv, logs, manifest). Nicht rueckholbar.`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Loeschen',
style: 'destructive',
onPress: () => {
brainApi.deleteSkill(skill.name)
.then(() => { onReload(); onClose(); })
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
},
},
],
);
};
const saveConfig = () => {
// secret-Felder die als '***SET***' angezeigt sind und vom User NICHT
// angefasst wurden, bleiben auf dem alten Wert. cfgDraft enthaelt nur
// explizit getippte Werte; alles andere uebernehmen wir aus cfgValues.
const next: Record<string, any> = { ...cfgValues };
for (const f of cfgSchema) {
const draft = cfgDraft[f.name];
const isSecret = f.secret || f.type === 'password';
if (draft === undefined) continue;
if (isSecret && draft === '') continue; // leer = unveraendert
if (draft === '') { delete next[f.name]; continue; }
if (f.type === 'number') {
const n = Number(draft); next[f.name] = isNaN(n) ? draft : n;
} else if (f.type === 'boolean') {
next[f.name] = draft === 'true' || draft === '1';
} else {
next[f.name] = draft;
}
}
// Maskierte Werte (***SET***) niemals zurueckschreiben
for (const k of Object.keys(next)) if (next[k] === '***SET***') delete next[k];
setCfgSaving(true);
brainApi.setSkillConfig(skill.name, next)
.then(() => {
// frisch laden um neuen masked-State zu zeigen
return brainApi.getSkillConfig(skill.name);
})
.then(r => { setCfgSchema(r.schema || []); setCfgValues(r.values || {}); setCfgDraft({}); })
.catch(e => Alert.alert('Speichern fehlgeschlagen', String(e?.message || e)))
.finally(() => setCfgSaving(false));
};
const reloadVersions = () => {
setVersionsLoading(true);
brainApi.listSkillVersions(skill.name)
.then(setVersions)
.catch(() => {})
.finally(() => setVersionsLoading(false));
};
const doRollback = (versionId: string) => {
Alert.alert(
'Rollback?',
`Skill "${skill.name}" auf ${versionId} zuruecksetzen?\n\nDer aktuelle Stand wird vorher automatisch gesichert (safety-snapshot).`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Rollback', style: 'destructive',
onPress: () => {
brainApi.rollbackSkill(skill.name, versionId)
.then(r => {
Alert.alert('Rollback OK', `Safety-Snapshot: ${r.safety_snapshot}`);
reloadVersions(); onReload();
})
.catch(e => Alert.alert('Rollback fehlgeschlagen', String(e?.message || e)));
},
},
],
);
};
const removeVersion = (versionId: string) => {
Alert.alert(
'Version loeschen?',
`${versionId} dauerhaft entfernen?`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Loeschen', style: 'destructive',
onPress: () => {
brainApi.deleteSkillVersion(skill.name, versionId)
.then(reloadVersions)
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
},
},
],
);
};
return (
<Modal visible animationType="slide" onRequestClose={onClose} transparent={false}>
<View style={s.modal}>
<View style={s.modalHeader}>
<Text style={s.modalTitle} numberOfLines={1}>{skill.name}</Text>
<TouchableOpacity onPress={onClose} hitSlop={{top:8,bottom:8,left:8,right:8}}>
<Text style={{color: '#8888AA', fontSize: 18}}>{'✕'}</Text>
</TouchableOpacity>
</View>
<ScrollView style={{flex: 1}} contentContainerStyle={{padding: 16}}>
<Text style={s.label}>Beschreibung</Text>
<Text style={{color: '#E0E0F0', marginBottom: 12}}>{skill.description}</Text>
<View style={s.metaBox}>
<Text style={s.meta}>execution: {skill.execution} · entry: {skill.entry}</Text>
<Text style={s.meta}>author: {skill.author || '?'} · version: {skill.version || '?'}</Text>
<Text style={s.meta}>{skill.use_count || 0}× ausgefuehrt · zuletzt: {relTime(skill.last_used)}</Text>
{skill.setup_error ? (
<Text style={[s.meta, {color: '#FF6B6B'}]}>setup_error: {skill.setup_error}</Text>
) : null}
{Array.isArray(skill.requires?.pip) && skill.requires!.pip!.length > 0 ? (
<Text style={s.meta}>pip: {skill.requires!.pip!.join(', ')}</Text>
) : null}
</View>
{/* Args-Inputs */}
{args.length > 0 ? (
<>
<Text style={[s.label, {marginTop: 18}]}>Argumente</Text>
{args.map((a: any) => (
<View key={a.name} style={{marginBottom: 10}}>
<Text style={{color: '#8888AA', fontSize: 12, marginBottom: 4}}>
{a.name}{a.required ? ' *' : ''} {a.description ? `${a.description}` : ''}
</Text>
<TextInput
style={s.input}
value={argValues[a.name] || ''}
onChangeText={(v) => setArg(a.name, v)}
placeholder={a.type || 'string'}
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
/>
</View>
))}
</>
) : null}
{/* Config-Schema-Form (P3) */}
{cfgSchema.length > 0 ? (
<>
<Text style={[s.label, {marginTop: 18}]}> Konfiguration</Text>
{cfgSchema.map((f) => {
const isSecret = f.secret || f.type === 'password';
const cur = cfgValues[f.name];
const isSet = isSecret && cur === '***SET***';
const placeholder = isSet ? '••• gesetzt — leer lassen = unverändert'
: (f.default !== undefined && f.default !== null ? `Default: ${String(f.default)}` : (f.type || 'string'));
const valStr = cfgDraft[f.name] !== undefined
? cfgDraft[f.name]
: (isSecret ? '' : (cur !== undefined && cur !== null && cur !== '***SET***' ? String(cur) : ''));
if (f.type === 'boolean') {
const bv = cfgDraft[f.name] !== undefined
? (cfgDraft[f.name] === 'true')
: (cur === true || cur === 'true');
return (
<View key={f.name} style={{marginBottom: 10, flexDirection: 'row', alignItems: 'center', gap: 10}}>
<Switch value={bv} onValueChange={(v) => setCfgDraft(p => ({...p, [f.name]: v ? 'true' : 'false'}))}
trackColor={{false: '#1E1E2E', true: '#0096FF'}} thumbColor="#fff" />
<View style={{flex: 1}}>
<Text style={{color: '#E0E0F0', fontSize: 13}}>{f.label || f.name}</Text>
{f.description ? <Text style={{color: '#555570', fontSize: 11}}>{f.description}</Text> : null}
</View>
</View>
);
}
return (
<View key={f.name} style={{marginBottom: 10}}>
<Text style={{color: '#8888AA', fontSize: 12, marginBottom: 4}}>
{f.label || f.name}{isSecret ? ' 🔒' : ''}
{f.description ? <Text style={{color: '#555570'}}> {f.description}</Text> : null}
</Text>
<TextInput
style={s.input}
value={valStr}
onChangeText={(v) => setCfgDraft(p => ({...p, [f.name]: v}))}
placeholder={placeholder}
placeholderTextColor="#444460"
autoCapitalize="none"
autoCorrect={false}
secureTextEntry={isSecret}
keyboardType={f.type === 'number' ? 'numeric' : 'default'}
/>
</View>
);
})}
<TouchableOpacity
style={[s.btn, {backgroundColor: '#1A1A2E', borderColor: COL_ACTIVE, marginTop: 4}]}
onPress={saveConfig}
disabled={cfgSaving}
>
<Text style={{color: COL_ACTIVE, textAlign: 'center', fontWeight: '700'}}>
{cfgSaving ? 'Speichere...' : '💾 Konfiguration speichern'}
</Text>
</TouchableOpacity>
</>
) : null}
{/* Versionen (P4) */}
{versions.length > 0 ? (
<>
<Text style={[s.label, {marginTop: 18}]}>📦 Versionen ({versions.length})</Text>
{versions.map(v => (
<View key={v.version_id} style={[s.metaBox, {marginTop: 6, flexDirection: 'row', alignItems: 'center', gap: 6}]}>
<View style={{flex: 1}}>
<Text style={[s.meta, {fontFamily: 'monospace', color: '#E0E0F0'}]}>{v.version_id}</Text>
<Text style={s.meta}>{v.archived_at ? new Date(v.archived_at).toLocaleString('de-DE') : '—'}</Text>
{v.summary ? <Text style={[s.meta, {fontStyle: 'italic'}]} numberOfLines={2}>{v.summary}</Text> : null}
</View>
<TouchableOpacity onPress={() => doRollback(v.version_id)}
style={[s.btn, {paddingHorizontal: 10, paddingVertical: 6, borderColor: COL_ARIA, backgroundColor: '#1A1A2E'}]}>
<Text style={{color: COL_ARIA, fontSize: 12}}></Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => removeVersion(v.version_id)}
style={[s.btn, {paddingHorizontal: 10, paddingVertical: 6, borderColor: '#FF6B6B', backgroundColor: '#1A1A2E'}]}>
<Text style={{color: '#FF6B6B', fontSize: 12}}>🗑</Text>
</TouchableOpacity>
</View>
))}
</>
) : versionsLoading ? (
<ActivityIndicator color="#0096FF" style={{marginTop: 14}} />
) : null}
<View style={{flexDirection: 'row', gap: 8, marginTop: 14}}>
<TouchableOpacity
style={[s.btn, {backgroundColor: skill.active ? '#0096FF' : '#1E1E2E', flex: 1}]}
onPress={run}
disabled={!skill.active || running}
>
<Text style={{color: skill.active ? '#fff' : '#555570', fontWeight: '700', textAlign: 'center'}}>
{running ? 'läuft...' : '▶ Ausführen'}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[s.btn, {backgroundColor: '#1A1A2E', flex: 1}]}
onPress={loadLogs}
>
<Text style={{color: '#8888AA', textAlign: 'center'}}>📜 Logs</Text>
</TouchableOpacity>
</View>
{!skill.active ? (
<Text style={{color: '#FFD60A', fontSize: 12, marginTop: 6, fontStyle: 'italic'}}>
Skill ist deaktiviert toggle in der Liste zum Aktivieren.
</Text>
) : null}
{/* Run-Result */}
{runResult ? (
<View style={[s.metaBox, {marginTop: 14, borderLeftWidth: 3, borderLeftColor: runResult.ok ? COL_ACTIVE : '#FF6B6B'}]}>
<Text style={[s.meta, {color: runResult.ok ? COL_ACTIVE : '#FF6B6B', fontWeight: '700'}]}>
{runResult.ok ? '✓ OK' : `✗ FEHLER (exit ${runResult.exit_code})`} · {runResult.duration_sec}s
</Text>
{runResult.stdout ? (
<>
<Text style={[s.meta, {marginTop: 6, color: '#8888AA', fontWeight: '600'}]}>stdout:</Text>
<Text style={[s.meta, {fontFamily: 'monospace', color: '#C0C0D0'}]}>{runResult.stdout}</Text>
</>
) : null}
{runResult.stderr ? (
<>
<Text style={[s.meta, {marginTop: 6, color: '#FF6B6B', fontWeight: '600'}]}>stderr:</Text>
<Text style={[s.meta, {fontFamily: 'monospace', color: '#FF9999'}]}>{runResult.stderr}</Text>
</>
) : null}
</View>
) : null}
{/* Logs */}
{loadingLogs ? (
<ActivityIndicator color="#0096FF" style={{marginTop: 14}} />
) : logs ? (
<View style={{marginTop: 14}}>
<Text style={[s.label, {marginTop: 0}]}>Letzte Runs (Top 20)</Text>
{logs.length === 0 ? (
<Text style={{color: '#555570', fontStyle: 'italic'}}>(keine Logs)</Text>
) : logs.map((log, idx) => (
<View key={idx} style={[s.metaBox, {marginTop: 6, borderLeftWidth: 2, borderLeftColor: log.ok ? COL_ACTIVE : '#FF6B6B'}]}>
<Text style={[s.meta, {color: log.ok ? COL_ACTIVE : '#FF6B6B'}]}>
{log.ok ? '✓' : '✗'} {log.ts ? new Date(log.ts).toLocaleString('de-DE') : '?'} · {log.duration_sec || 0}s
</Text>
{log.stdout ? (
<Text style={[s.meta, {fontFamily: 'monospace', color: '#C0C0D0'}]} numberOfLines={3}>
{String(log.stdout).slice(0, 300)}
</Text>
) : null}
</View>
))}
</View>
) : null}
<View style={{height: 30}} />
</ScrollView>
<View style={s.modalFooter}>
<TouchableOpacity style={[s.btn, {backgroundColor: '#3A1F1F', borderColor: '#FF6B6B'}]} onPress={remove}>
<Text style={{color: '#FF6B6B', fontWeight: '700'}}>🗑 Loeschen</Text>
</TouchableOpacity>
<View style={{flex: 1}} />
<TouchableOpacity style={[s.btn, {backgroundColor: '#1A1A2E'}]} onPress={onClose}>
<Text style={{color: '#8888AA'}}>Schliessen</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
);
};
// ── Styles ───────────────────────────────────────────────────────────
const s = StyleSheet.create({
toolbar: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
paddingHorizontal: 10,
paddingVertical: 8,
backgroundColor: '#0D0D1A',
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
chip: {
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 12,
backgroundColor: '#1A1A2E',
},
chipActive: {
backgroundColor: '#FFD60A',
},
iconBtn: {
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 6,
backgroundColor: '#1A1A2E',
},
row: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 12,
paddingHorizontal: 14,
backgroundColor: '#0D0D1A',
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
err: {
color: '#FF6B6B',
padding: 12,
fontSize: 12,
},
modal: {
flex: 1,
backgroundColor: '#0D0D1A',
},
modalHeader: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
modalTitle: {
color: '#E0E0F0',
fontSize: 16,
fontWeight: '700',
flex: 1,
marginRight: 12,
},
modalFooter: {
flexDirection: 'row',
alignItems: 'center',
padding: 12,
borderTopWidth: 1,
borderTopColor: '#1E1E2E',
gap: 8,
},
label: {
color: '#8888AA',
fontSize: 11,
fontWeight: '700',
textTransform: 'uppercase',
letterSpacing: 0.5,
marginTop: 8,
marginBottom: 4,
},
input: {
backgroundColor: '#1A1A2E',
borderWidth: 1,
borderColor: '#1E1E2E',
borderRadius: 6,
color: '#E0E0F0',
padding: 10,
fontSize: 14,
},
metaBox: {
backgroundColor: '#1A1A2E',
borderRadius: 6,
padding: 10,
marginTop: 6,
gap: 4,
},
meta: {
color: '#8888AA',
fontSize: 12,
},
btn: {
paddingHorizontal: 14,
paddingVertical: 10,
borderRadius: 6,
borderWidth: 1,
borderColor: 'transparent',
},
});
export default SkillBrowser;
-595
View File
@@ -1,595 +0,0 @@
/**
* Trigger-Browser — Liste aller Trigger (timer + watcher) mit Toggle,
* Tap-zum-Bearbeiten und "+ Neu"-Knopf.
*
* Eingesetzt von SettingsScreen → Sektion "Trigger".
*
* Brain-API ueber brainApi (RVS-Brain-Proxy).
*/
import React, { useCallback, useEffect, useState } from 'react';
import {
ActivityIndicator,
Alert,
FlatList,
Modal,
ScrollView,
StyleSheet,
Switch,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import brainApi, { Trigger } from '../services/brainApi';
import rvs from '../services/rvs';
const COL_ACTIVE = '#34C759';
const COL_INACTIVE = '#555570';
const COL_TIMER = '#0096FF';
const COL_WATCHER = '#FFD60A';
function relTime(iso: string | null | undefined): string {
if (!iso) return '—';
const t = new Date(iso).getTime();
if (!t) return '—';
const diffSec = Math.floor((Date.now() - t) / 1000);
if (diffSec < 60) return `vor ${diffSec}s`;
if (diffSec < 3600) return `vor ${Math.floor(diffSec / 60)}min`;
if (diffSec < 86400) return `vor ${Math.floor(diffSec / 3600)}h`;
return `vor ${Math.floor(diffSec / 86400)}d`;
}
export const TriggerBrowser: React.FC = () => {
const [items, setItems] = useState<Trigger[]>([]);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [filter, setFilter] = useState<'all' | 'active' | 'inactive'>('all');
const [editTrigger, setEditTrigger] = useState<Trigger | null>(null);
const [showNew, setShowNew] = useState(false);
const load = useCallback(() => {
setLoading(true); setErr(null);
brainApi.listTriggers()
.then(t => {
// Sortierung: aktive zuerst, dann nach Name
t.sort((a, b) => {
if (a.active !== b.active) return a.active ? -1 : 1;
return (a.name || '').localeCompare(b.name || '');
});
setItems(t);
})
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, []);
useEffect(() => { load(); }, [load]);
// Auto-Reload bei RVS-Reconnect — sonst zeigt die Liste den Fast-Fail-
// Fehler aus brainApi ewig an obwohl die Verbindung schon wieder da ist.
useEffect(() => {
const unsub = rvs.onStateChange((state) => {
if (state === 'connected') {
load();
}
});
return () => unsub();
}, [load]);
const visible = items.filter(t => {
if (filter === 'active') return t.active;
if (filter === 'inactive') return !t.active;
return true;
});
const toggleActive = (t: Trigger) => {
brainApi.updateTrigger(t.name, { active: !t.active })
.then(() => load())
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
};
const deleteTrigger = (t: Trigger) => {
Alert.alert(
'Trigger löschen?',
`"${t.name}" — diese Aktion ist nicht rückgängig zu machen.`,
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Löschen',
style: 'destructive',
onPress: () => {
brainApi.deleteTrigger(t.name)
.then(() => { setEditTrigger(null); load(); })
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
},
},
],
);
};
const renderItem = ({ item }: { item: Trigger }) => {
const typeColor = item.type === 'timer' ? COL_TIMER : COL_WATCHER;
const typeLabel = item.type === 'timer' ? '⏰ Timer' : '👁 Watcher';
return (
<TouchableOpacity style={s.row} onPress={() => setEditTrigger(item)}>
<View style={{flex: 1, marginRight: 8}}>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 6, marginBottom: 4}}>
<Text style={{color: typeColor, fontSize: 11, fontWeight: '700'}}>{typeLabel}</Text>
<Text style={{color: '#E0E0F0', fontWeight: '600', flex: 1}} numberOfLines={1}>{item.name}</Text>
</View>
<Text style={{color: '#8888AA', fontSize: 12}} numberOfLines={2}>{item.message}</Text>
{item.type === 'watcher' && item.condition ? (
<Text style={{color: '#555570', fontSize: 11, marginTop: 4, fontFamily: 'monospace'}} numberOfLines={1}>
{item.condition}
</Text>
) : null}
{item.type === 'timer' && item.fires_at ? (
<Text style={{color: '#555570', fontSize: 11, marginTop: 4}}>
feuert: {new Date(item.fires_at).toLocaleString('de-DE')}
</Text>
) : null}
<Text style={{color: '#444460', fontSize: 10, marginTop: 4}}>
{item.fire_count || 0}× gefeuert · zuletzt: {relTime(item.last_fired_at)}
</Text>
</View>
<Switch
value={item.active}
onValueChange={() => toggleActive(item)}
trackColor={{ false: '#1E1E2E', true: COL_ACTIVE }}
thumbColor="#E0E0F0"
/>
</TouchableOpacity>
);
};
return (
<View style={{flex: 1}}>
{/* Filter-Leiste + Reload + Neu */}
<View style={s.toolbar}>
{(['all', 'active', 'inactive'] as const).map(f => (
<TouchableOpacity
key={f}
style={[s.chip, filter === f && s.chipActive]}
onPress={() => setFilter(f)}
>
<Text style={{color: filter === f ? '#0D0D1A' : '#8888AA', fontSize: 12, fontWeight: '600'}}>
{f === 'all' ? 'Alle' : f === 'active' ? 'Aktive' : 'Inaktive'}
</Text>
</TouchableOpacity>
))}
<View style={{flex: 1}} />
<TouchableOpacity onPress={load} style={s.iconBtn}>
<Text style={{fontSize: 16}}>{'↻'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setShowNew(true)} style={[s.iconBtn, {backgroundColor: '#0096FF'}]}>
<Text style={{fontSize: 14, color: '#fff', fontWeight: '700'}}>+ Neu</Text>
</TouchableOpacity>
</View>
{err ? <Text style={s.err}>{err}</Text> : null}
{loading && items.length === 0 ? (
<ActivityIndicator color="#0096FF" style={{marginTop: 20}} />
) : (
<FlatList
data={visible}
keyExtractor={t => t.name}
renderItem={renderItem}
nestedScrollEnabled={true}
ListEmptyComponent={
<Text style={{color: '#555570', textAlign: 'center', padding: 20, fontStyle: 'italic'}}>
{items.length === 0 ? '(keine Trigger angelegt)' : '(keine Treffer für diesen Filter)'}
</Text>
}
contentContainerStyle={{paddingBottom: 20}}
/>
)}
{editTrigger ? (
<TriggerEditModal
trigger={editTrigger}
onClose={() => setEditTrigger(null)}
onSaved={() => { setEditTrigger(null); load(); }}
onDelete={() => deleteTrigger(editTrigger)}
/>
) : null}
{showNew ? (
<TriggerNewModal
onClose={() => setShowNew(false)}
onCreated={() => { setShowNew(false); load(); }}
/>
) : null}
</View>
);
};
// ── Edit-Modal ─────────────────────────────────────────────────────────
interface EditProps {
trigger: Trigger;
onClose: () => void;
onSaved: () => void;
onDelete: () => void;
}
const TriggerEditModal: React.FC<EditProps> = ({ trigger, onClose, onSaved, onDelete }) => {
const [message, setMessage] = useState(trigger.message || '');
const [condition, setCondition] = useState(trigger.condition || '');
const [firesAt, setFiresAt] = useState(trigger.fires_at || '');
const [checkInterval, setCheckInterval] = useState(String(trigger.check_interval_sec || 300));
const [throttle, setThrottle] = useState(String(trigger.throttle_sec || 3600));
const [saving, setSaving] = useState(false);
const save = () => {
setSaving(true);
const patch: any = { message };
if (trigger.type === 'watcher') {
patch.condition = condition;
patch.check_interval_sec = parseInt(checkInterval, 10) || 300;
patch.throttle_sec = parseInt(throttle, 10) || 3600;
} else if (trigger.type === 'timer') {
patch.fires_at = firesAt;
}
brainApi.updateTrigger(trigger.name, patch)
.then(onSaved)
.catch(e => Alert.alert('Fehler beim Speichern', String(e?.message || e)))
.finally(() => setSaving(false));
};
return (
<Modal visible animationType="slide" onRequestClose={onClose} transparent>
<View style={s.modalBg}>
<View style={s.modal}>
<View style={s.modalHeader}>
<Text style={{color: trigger.type === 'timer' ? COL_TIMER : COL_WATCHER, fontWeight: '700', fontSize: 16, flex: 1}}>
{trigger.type === 'timer' ? '⏰' : '👁'} {trigger.name}
</Text>
<TouchableOpacity onPress={onClose}>
<Text style={{color: '#8888AA', fontSize: 24}}>×</Text>
</TouchableOpacity>
</View>
<ScrollView style={{padding: 14}} nestedScrollEnabled>
<Text style={s.label}>Nachricht</Text>
<TextInput
style={s.input}
value={message}
onChangeText={setMessage}
multiline
placeholder="Was soll ARIA sagen wenn der Trigger feuert?"
placeholderTextColor="#555570"
/>
{trigger.type === 'watcher' ? (
<>
<Text style={s.label}>Condition</Text>
<TextInput
style={[s.input, {fontFamily: 'monospace', fontSize: 12}]}
value={condition}
onChangeText={setCondition}
placeholder="z.B. near(53.0, 8.5, 300)"
placeholderTextColor="#555570"
autoCapitalize="none"
/>
<View style={{flexDirection: 'row', gap: 8}}>
<View style={{flex: 1}}>
<Text style={s.label}>Check-Intervall (s)</Text>
<TextInput
style={s.input}
value={checkInterval}
onChangeText={setCheckInterval}
keyboardType="number-pad"
/>
</View>
<View style={{flex: 1}}>
<Text style={s.label}>Throttle (s)</Text>
<TextInput
style={s.input}
value={throttle}
onChangeText={setThrottle}
keyboardType="number-pad"
/>
</View>
</View>
</>
) : (
<>
<Text style={s.label}>Feuert am (ISO, UTC)</Text>
<TextInput
style={[s.input, {fontFamily: 'monospace', fontSize: 12}]}
value={firesAt}
onChangeText={setFiresAt}
placeholder="2026-05-15T20:00:00+00:00"
placeholderTextColor="#555570"
autoCapitalize="none"
/>
</>
)}
<View style={s.metaBox}>
<Text style={s.meta}>Status: {trigger.active ? '🟢 aktiv' : '⚪ inaktiv'}</Text>
<Text style={s.meta}>Gefeuert: {trigger.fire_count || 0}×</Text>
<Text style={s.meta}>Zuletzt gefeuert: {relTime(trigger.last_fired_at)}</Text>
<Text style={s.meta}>Zuletzt geprüft: {relTime(trigger.last_checked_at)}</Text>
{trigger.author ? <Text style={s.meta}>Angelegt von: {trigger.author}</Text> : null}
</View>
</ScrollView>
<View style={s.modalFooter}>
<TouchableOpacity onPress={onDelete} style={[s.btn, {backgroundColor: '#3A1F1F', borderColor: '#FF3B30'}]}>
<Text style={{color: '#FF3B30', fontWeight: '700'}}>🗑 Löschen</Text>
</TouchableOpacity>
<View style={{flex: 1}} />
<TouchableOpacity onPress={save} disabled={saving} style={[s.btn, {backgroundColor: '#0096FF', opacity: saving ? 0.5 : 1}]}>
<Text style={{color: '#fff', fontWeight: '700'}}>{saving ? 'Speichert...' : 'Speichern'}</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
);
};
// ── Neu-Modal ──────────────────────────────────────────────────────────
interface NewProps {
onClose: () => void;
onCreated: () => void;
}
const TriggerNewModal: React.FC<NewProps> = ({ onClose, onCreated }) => {
const [ttype, setTtype] = useState<'timer' | 'watcher'>('watcher');
const [name, setName] = useState('');
const [message, setMessage] = useState('');
const [condition, setCondition] = useState('');
const [firesAt, setFiresAt] = useState('');
const [checkInterval, setCheckInterval] = useState('300');
const [throttle, setThrottle] = useState('3600');
const [saving, setSaving] = useState(false);
const create = () => {
if (!name.trim() || !message.trim()) {
Alert.alert('Name und Nachricht erforderlich');
return;
}
setSaving(true);
const promise = ttype === 'timer'
? brainApi.createTimer({
name: name.trim(),
fires_at: firesAt.trim(),
message: message.trim(),
})
: brainApi.createWatcher({
name: name.trim(),
condition: condition.trim(),
message: message.trim(),
check_interval_sec: parseInt(checkInterval, 10) || 300,
throttle_sec: parseInt(throttle, 10) || 3600,
});
promise
.then(onCreated)
.catch(e => Alert.alert('Fehler beim Anlegen', String(e?.message || e)))
.finally(() => setSaving(false));
};
return (
<Modal visible animationType="slide" onRequestClose={onClose} transparent>
<View style={s.modalBg}>
<View style={s.modal}>
<View style={s.modalHeader}>
<Text style={{color: '#FFD60A', fontWeight: '700', fontSize: 16, flex: 1}}>+ Neuer Trigger</Text>
<TouchableOpacity onPress={onClose}>
<Text style={{color: '#8888AA', fontSize: 24}}>×</Text>
</TouchableOpacity>
</View>
<ScrollView style={{padding: 14}} nestedScrollEnabled>
<Text style={s.label}>Typ</Text>
<View style={{flexDirection: 'row', gap: 8, marginBottom: 12}}>
{(['watcher', 'timer'] as const).map(t => (
<TouchableOpacity
key={t}
onPress={() => setTtype(t)}
style={[s.chip, ttype === t && s.chipActive, {flex: 1, paddingVertical: 10}]}
>
<Text style={{color: ttype === t ? '#0D0D1A' : '#8888AA', fontWeight: '700', textAlign: 'center'}}>
{t === 'watcher' ? '👁 Watcher' : '⏰ Timer'}
</Text>
</TouchableOpacity>
))}
</View>
<Text style={s.label}>Name (kebab-case)</Text>
<TextInput
style={s.input}
value={name}
onChangeText={setName}
placeholder="z.B. drk-kreyenbrueck-warnung"
placeholderTextColor="#555570"
autoCapitalize="none"
/>
<Text style={s.label}>Nachricht</Text>
<TextInput
style={s.input}
value={message}
onChangeText={setMessage}
multiline
placeholder="Was soll ARIA sagen?"
placeholderTextColor="#555570"
/>
{ttype === 'watcher' ? (
<>
<Text style={s.label}>Condition</Text>
<TextInput
style={[s.input, {fontFamily: 'monospace', fontSize: 12}]}
value={condition}
onChangeText={setCondition}
placeholder="z.B. entered_near(53.0, 8.5, 300)"
placeholderTextColor="#555570"
autoCapitalize="none"
/>
<Text style={s.hint}>
Funktionen: near() / entered_near() / left_near() · Variablen: disk_free_gb, hour_of_day, current_lat, current_lon, last_user_message_ago_sec
</Text>
<View style={{flexDirection: 'row', gap: 8}}>
<View style={{flex: 1}}>
<Text style={s.label}>Check-Intervall (s)</Text>
<TextInput
style={s.input}
value={checkInterval}
onChangeText={setCheckInterval}
keyboardType="number-pad"
/>
</View>
<View style={{flex: 1}}>
<Text style={s.label}>Throttle (s)</Text>
<TextInput
style={s.input}
value={throttle}
onChangeText={setThrottle}
keyboardType="number-pad"
/>
</View>
</View>
</>
) : (
<>
<Text style={s.label}>Feuert am (ISO, UTC)</Text>
<TextInput
style={[s.input, {fontFamily: 'monospace', fontSize: 12}]}
value={firesAt}
onChangeText={setFiresAt}
placeholder="2026-05-15T20:00:00+00:00"
placeholderTextColor="#555570"
autoCapitalize="none"
/>
<Text style={s.hint}>Beispiel oben: heute 20:00 UTC = 22:00 CEST</Text>
</>
)}
</ScrollView>
<View style={s.modalFooter}>
<View style={{flex: 1}} />
<TouchableOpacity onPress={create} disabled={saving} style={[s.btn, {backgroundColor: '#0096FF', opacity: saving ? 0.5 : 1}]}>
<Text style={{color: '#fff', fontWeight: '700'}}>{saving ? 'Legt an...' : 'Anlegen'}</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
);
};
const s = StyleSheet.create({
toolbar: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
marginBottom: 8,
},
chip: {
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 14,
backgroundColor: '#1E1E2E',
},
chipActive: {
backgroundColor: '#FFD60A',
},
iconBtn: {
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 14,
backgroundColor: '#1E1E2E',
},
err: {
color: '#FF3B30',
padding: 12,
fontSize: 12,
},
row: {
flexDirection: 'row',
alignItems: 'center',
padding: 12,
backgroundColor: '#1A1A2E',
borderRadius: 8,
marginBottom: 6,
},
modalBg: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.6)',
justifyContent: 'center',
alignItems: 'center',
padding: 16,
},
modal: {
backgroundColor: '#0D0D1A',
borderRadius: 12,
width: '100%',
maxWidth: 600,
maxHeight: '90%',
borderWidth: 1,
borderColor: '#1E1E2E',
},
modalHeader: {
flexDirection: 'row',
alignItems: 'center',
padding: 14,
borderBottomWidth: 1,
borderBottomColor: '#1E1E2E',
},
modalFooter: {
flexDirection: 'row',
alignItems: 'center',
padding: 12,
borderTopWidth: 1,
borderTopColor: '#1E1E2E',
gap: 8,
},
label: {
color: '#8888AA',
fontSize: 11,
fontWeight: '700',
textTransform: 'uppercase',
letterSpacing: 0.5,
marginTop: 8,
marginBottom: 4,
},
input: {
backgroundColor: '#1A1A2E',
borderWidth: 1,
borderColor: '#1E1E2E',
borderRadius: 6,
color: '#E0E0F0',
padding: 10,
fontSize: 14,
marginBottom: 8,
},
hint: {
color: '#555570',
fontSize: 11,
fontStyle: 'italic',
marginTop: -4,
marginBottom: 10,
},
metaBox: {
backgroundColor: '#1A1A2E',
borderRadius: 6,
padding: 10,
marginTop: 10,
gap: 4,
},
meta: {
color: '#8888AA',
fontSize: 12,
},
btn: {
paddingHorizontal: 14,
paddingVertical: 10,
borderRadius: 6,
borderWidth: 1,
borderColor: 'transparent',
},
});
export default TriggerBrowser;
-47
View File
@@ -1,47 +0,0 @@
/**
* ViewModeToggle — kleiner Header-Button zum Umschalten zwischen Kompakt-
* Ansicht (klassischer Chat) und Cockpit (Kachel-Desktop).
*
* Sitzt rechts im Navigations-Header ("ARIA Cockpit"), kollidiert also mit
* nichts in der Chat-Ansicht. Zeigt das Ziel des naechsten Taps.
*/
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, TouchableOpacity } from 'react-native';
import viewMode, { ViewModeValue } from '../services/viewMode';
const ViewModeToggle: React.FC = () => {
const [mode, setMode] = useState<ViewModeValue>(viewMode.get());
useEffect(() => viewMode.subscribe(setMode), []);
const isCockpit = mode === 'cockpit';
return (
<TouchableOpacity
onPress={() => viewMode.toggle()}
style={[styles.pill, isCockpit && styles.pillActive]}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
activeOpacity={0.75}
>
<Text style={[styles.text, isCockpit && styles.textActive]}>
{isCockpit ? '⧉ Cockpit' : '⧉ Kompakt'}
</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
pill: {
marginRight: 12,
paddingHorizontal: 12,
paddingVertical: 6,
borderRadius: 16,
borderWidth: 1,
borderColor: '#1E1E2E',
backgroundColor: '#12122A',
},
pillActive: { borderColor: '#0096FF', backgroundColor: '#0A1F33' },
text: { color: '#9090B0', fontSize: 13, fontWeight: '700' },
textActive: { color: '#0096FF' },
});
export default ViewModeToggle;
+90 -60
View File
@@ -1,19 +1,12 @@
/**
* VoiceButton — Tap-to-Talk-Aufnahmeknopf (Streaming-Variante).
* VoiceButton - Push-to-Talk + Auto-Stop Aufnahmeknopf
*
* Push-to-Talk gibt's nicht mehr. Tap startet Streaming-Aufnahme an die
* Whisper-Bridge. Tap nochmal sendet stt_stream_end → Whisper liefert den
* finalen Text → aria-bridge forwardet direkt an Brain. Keine dB/VAD-
* Stille-Erkennung mehr — Whisper hoert auf semantische Stille (kein
* neuer Text mehr).
* Zwei Modi:
* 1. Push-to-Talk: gedrueckt halten zum Aufnehmen, loslassen zum Senden
* 2. Tap-to-Talk: einmal tippen startet Aufnahme, VAD stoppt automatisch bei Stille
* (auch genutzt fuer Wake-Word-getriggerte Aufnahme)
*
* Diese Komponente ist absichtlich "dumm": sie kapselt nur den
* Tap-Lifecycle + die Animation. Recording-Optionen (voice/speed/
* location/interrupted) baut ChatScreen, die User-Bubble ebenfalls.
*
* Visuelles Feedback: pulsierende Animation + Dauer + dB-Pegel via
* audioService.onMeterUpdate (das macht audio.ts noch fuer alte Records;
* neu kommt der Pegel via NativeEventEmitter (PcmStreamMeter) — folgt).
* Visuelles Feedback durch pulsierende Animation waehrend der Aufnahme.
*/
import React, { useState, useRef, useEffect, useCallback } from 'react';
@@ -24,28 +17,25 @@ import {
StyleSheet,
Easing,
TouchableOpacity,
Pressable,
} from 'react-native';
import audioService, { RecordingState } from '../services/audio';
import audioService, { RecordingResult } from '../services/audio';
// --- Typen ---
interface VoiceButtonProps {
/** User hat getippt — ChatScreen soll Bubble bauen + startStreamingRecording.
* Returns true wenn die Aufnahme tatsaechlich gestartet ist. */
onTapStart: () => Promise<boolean>;
/** User hat nochmal getippt — ChatScreen soll stopStreamingRecording rufen. */
onTapStop: () => Promise<void>;
/** Wird aufgerufen wenn die Aufnahme fertig ist */
onRecordingComplete: (result: RecordingResult) => void;
/** Button deaktivieren */
disabled?: boolean;
/** Wake-Word-Modus aktiv (zeigt gruenen Indikator-Dot) */
/** Wake-Word-Modus aktiv (zeigt Indikator) */
wakeWordActive?: boolean;
}
// --- Komponente ---
const VoiceButton: React.FC<VoiceButtonProps> = ({
onTapStart,
onTapStop,
onRecordingComplete,
disabled = false,
wakeWordActive = false,
}) => {
@@ -54,21 +44,7 @@ const VoiceButton: React.FC<VoiceButtonProps> = ({
const [meterDb, setMeterDb] = useState(-160);
const pulseAnim = useRef(new Animated.Value(1)).current;
const durationTimer = useRef<ReturnType<typeof setInterval> | null>(null);
// State via audioService.onStateChange spiegeln — der Service ist die
// Quelle der Wahrheit (Streaming-Session, Wake-Word-Multi-Turn, etc.
// koennen den Recording-State von extern aendern). isStreamingRecording
// ist auch true wenn die Wake-Word-Konversation gerade aufzeichnet —
// dann zeigt der Button "stop"-Symbol, und Tap stoppt die laufende
// Aufnahme (egal ob via Wake-Word oder Knopf gestartet).
useEffect(() => {
const unsub = audioService.onStateChange((next: RecordingState) => {
setIsRecording(next === 'recording');
});
// Initial-State synchronisieren
setIsRecording(audioService.getRecordingState() === 'recording');
return unsub;
}, []);
const isLongPress = useRef(false);
// Puls-Animation starten/stoppen
useEffect(() => {
@@ -96,13 +72,14 @@ const VoiceButton: React.FC<VoiceButtonProps> = ({
}
}, [isRecording, pulseAnim]);
// Aufnahmedauer zaehlen + Metering (Pegel-Bar)
// Aufnahmedauer zaehlen + Metering
useEffect(() => {
if (isRecording) {
setDurationMs(0);
durationTimer.current = setInterval(() => {
setDurationMs(prev => prev + 100);
}, 100);
const unsubMeter = audioService.onMeterUpdate(setMeterDb);
return () => {
unsubMeter();
@@ -113,28 +90,78 @@ const VoiceButton: React.FC<VoiceButtonProps> = ({
clearInterval(durationTimer.current);
durationTimer.current = null;
}
setMeterDb(-160);
}
}, [isRecording]);
// Tap-Handler. Guard gegen Doppel-Tap waehrend asyncer Start/Stop.
const tapBusy = useRef(false);
const handleTap = useCallback(async () => {
if (disabled || tapBusy.current) return;
tapBusy.current = true;
try {
// Service-State fragen statt React-State (Closure koennte stale sein)
const svcState = audioService.getRecordingState();
if (svcState === 'recording') {
await onTapStop();
} else if (svcState === 'idle') {
await onTapStart();
// VAD Silence Callback — Auto-Stop
useEffect(() => {
const unsubSilence = audioService.onSilenceDetected(async () => {
if (!isRecording) return;
setIsRecording(false);
const result = await audioService.stopRecording();
if (result && result.durationMs > 500) {
onRecordingComplete(result);
}
// 'processing': Stop laeuft gerade — nichts tun, User muss nochmal tippen
} finally {
tapBusy.current = false;
});
return unsubSilence;
}, [isRecording, onRecordingComplete]);
// Auto-Start fuer Wake Word (extern getriggert)
const startAutoRecording = useCallback(async () => {
if (disabled || isRecording) return;
const started = await audioService.startRecording(true); // autoStop = true
if (started) {
isLongPress.current = false;
setIsRecording(true);
}
}, [disabled, onTapStart, onTapStop]);
}, [disabled, isRecording]);
// Push-to-Talk: Lang druecken
const handlePressIn = async () => {
if (disabled || isRecording) return;
isLongPress.current = true;
const started = await audioService.startRecording(false); // kein autoStop
if (started) {
setIsRecording(true);
}
};
const handlePressOut = async () => {
if (!isRecording || !isLongPress.current) return;
isLongPress.current = false;
setIsRecording(false);
const result = await audioService.stopRecording();
if (result && result.durationMs > 300) {
onRecordingComplete(result);
}
};
// Tap-to-Talk: Einmal tippen startet mit Auto-Stop
const handleTap = async () => {
if (disabled) return;
if (isRecording) {
// Aufnahme manuell stoppen
setIsRecording(false);
const result = await audioService.stopRecording();
if (result && result.durationMs > 300) {
onRecordingComplete(result);
}
} else {
// Aufnahme mit Auto-Stop starten
const started = await audioService.startRecording(true);
if (started) {
isLongPress.current = false;
setIsRecording(true);
}
}
};
// Expose startAutoRecording via ref fuer Wake Word
React.useImperativeHandle(
React.createRef(),
() => ({ startAutoRecording }),
[startAutoRecording],
);
const formatDuration = (ms: number): string => {
const seconds = Math.floor(ms / 1000);
@@ -142,11 +169,7 @@ const VoiceButton: React.FC<VoiceButtonProps> = ({
return `${seconds}.${tenths}s`;
};
// Meter-Visualisierung (-60..0 dB → 0..1). Bei Streaming-Mode liefert
// audio.ts (noch) keinen Pegel, also bleibt der Balken leer — wird in
// einem Folge-Commit nachgerueckt (PcmStreamRecorder-Module muss dafuer
// einen RMS-Wert mit-emitten). Tut der Streaming-Funktion keinen Abbruch,
// ist reines UI-Beiwerk.
// Meter-Visualisierung (0-1 Skala)
const meterLevel = Math.max(0, Math.min(1, (meterDb + 60) / 60));
return (
@@ -160,6 +183,10 @@ const VoiceButton: React.FC<VoiceButtonProps> = ({
isRecording && styles.buttonOuterRecording,
{ transform: [{ scale: pulseAnim }] },
]}
onStartShouldSetResponder={() => true}
onResponderGrant={handlePressIn}
onResponderRelease={handlePressOut}
onResponderTerminate={handlePressOut}
>
<TouchableOpacity
activeOpacity={0.8}
@@ -180,6 +207,9 @@ const VoiceButton: React.FC<VoiceButtonProps> = ({
);
};
// Expose startAutoRecording fuer externe Aufrufe (Wake Word)
export type VoiceButtonHandle = { startAutoRecording: () => Promise<void> };
// --- Styles ---
const styles = StyleSheet.create({
@@ -1,426 +0,0 @@
/**
* Voice-ID Enrollment + Status — App-seitig.
*
* User nimmt 5-7 Samples (je 4s) seiner Stimme auf, App schickt sie an
* die whisper-bridge via RVS (voice_id_enroll_request). Bridge berechnet
* SpeechBrain-ECAPA-Embeddings, mittelt sie zu einem Fingerprint, speichert
* /voice-id/fingerprint.json.
*
* Verwendung: in SettingsScreen für Section 'voice_id' eingebunden.
* Holt Status bei Mount + nach jedem Enroll/Delete neu ab.
*/
import React, { useCallback, useEffect, useState } from 'react';
import {
ActivityIndicator,
Alert,
ScrollView,
StyleSheet,
Text,
ToastAndroid,
TouchableOpacity,
View,
} from 'react-native';
import audioService from '../services/audio';
import rvs from '../services/rvs';
const SAMPLE_DURATION_MS = 4000; // Pro Sample 4s aufnehmen
const SAMPLES_REQUIRED = 5; // Mindest-Sampleanzahl fuer Save
type Sample = {
base64: string;
durationMs: number;
};
type Status =
| { state: 'loading' }
| { state: 'unenrolled' }
| { state: 'enrolled'; sampleCount: number; durations: number[]; updatedAt: number; dim: number }
| { state: 'error'; message: string };
function _newReqId(prefix: string): string {
return `${prefix}_${Date.now().toString(36)}_${Math.floor(Math.random() * 1e6).toString(36)}`;
}
export const VoiceIdEnrollment: React.FC = () => {
const [status, setStatus] = useState<Status>({ state: 'loading' });
const [samples, setSamples] = useState<Sample[]>([]);
const [recording, setRecording] = useState(false);
const [recordCountdown, setRecordCountdown] = useState(0);
const [enrollPending, setEnrollPending] = useState(false);
const [pendingReqId, setPendingReqId] = useState<string | null>(null);
// Status laden
const refreshStatus = useCallback(() => {
setStatus({ state: 'loading' });
const reqId = _newReqId('vid');
setPendingReqId(reqId);
rvs.send('voice_id_status_request' as any, { requestId: reqId });
}, []);
useEffect(() => {
refreshStatus();
}, [refreshStatus]);
// RVS-Antworten verarbeiten
useEffect(() => {
const unsub = rvs.onMessage((msg: any) => {
if (!msg) return;
const p = msg.payload || {};
if (msg.type === 'voice_id_status_response') {
if (p.ok === false) {
setStatus({ state: 'error', message: p.error || 'Whisper-Bridge nicht erreichbar' });
return;
}
if (p.enrolled) {
setStatus({
state: 'enrolled',
sampleCount: p.sample_count || 0,
durations: p.sample_durations_s || [],
updatedAt: p.updated_at || 0,
dim: p.embedding_dim || 0,
});
} else {
setStatus({ state: 'unenrolled' });
}
} else if (msg.type === 'voice_id_enroll_response') {
setEnrollPending(false);
if (p.ok === false) {
Alert.alert('Enrollment fehlgeschlagen', p.error || 'Unbekannter Fehler');
return;
}
const rejected = (p.rejected || []).length;
ToastAndroid.show(
`✓ Stimme gespeichert (${p.sample_count} Samples${rejected ? `, ${rejected} verworfen` : ''})`,
ToastAndroid.LONG,
);
setSamples([]);
refreshStatus();
} else if (msg.type === 'voice_id_delete_response') {
ToastAndroid.show(p.removed ? '✓ Stimme gelöscht' : 'Es war keine gespeichert', ToastAndroid.SHORT);
refreshStatus();
}
});
return () => unsub();
}, [refreshStatus]);
// Ein Sample aufnehmen — fest 4s, dann auto-stop
const recordSample = useCallback(async () => {
if (recording || enrollPending) return;
setRecording(true);
setRecordCountdown(SAMPLE_DURATION_MS / 1000);
try {
const ok = await audioService.startRecording(false);
if (!ok) {
ToastAndroid.show('Aufnahme konnte nicht gestartet werden', ToastAndroid.LONG);
setRecording(false);
setRecordCountdown(0);
return;
}
// Countdown-Timer (rein UI)
const tickInterval = setInterval(() => {
setRecordCountdown(c => Math.max(0, c - 1));
}, 1000);
// Auto-Stop nach festen 4s
await new Promise(r => setTimeout(r, SAMPLE_DURATION_MS));
clearInterval(tickInterval);
const result = await audioService.stopRecording();
setRecordCountdown(0);
setRecording(false);
if (!result || !result.base64) {
ToastAndroid.show('Aufnahme leer — nochmal probieren', ToastAndroid.LONG);
return;
}
setSamples(prev => [...prev, { base64: result.base64, durationMs: result.durationMs }]);
} catch (err: any) {
console.warn('[VoiceId] recordSample:', err);
try { await audioService.cancelRecording(); } catch {}
setRecording(false);
setRecordCountdown(0);
ToastAndroid.show('Aufnahmefehler: ' + (err?.message || err), ToastAndroid.LONG);
}
}, [recording, enrollPending]);
const removeSample = useCallback((idx: number) => {
setSamples(prev => prev.filter((_, i) => i !== idx));
}, []);
const sendEnrollment = useCallback(() => {
if (samples.length < SAMPLES_REQUIRED) {
Alert.alert('Noch nicht genug',
`Bitte mindestens ${SAMPLES_REQUIRED} Samples aufnehmen — aktuell ${samples.length}.`);
return;
}
if (enrollPending) return;
setEnrollPending(true);
const reqId = _newReqId('videnroll');
rvs.send('voice_id_enroll_request' as any, {
requestId: reqId,
samples: samples.map(s => s.base64),
});
// Sicherheits-Timeout: wenn nach 60s nichts kommt, freigeben
setTimeout(() => {
setEnrollPending(prev => {
if (prev) {
ToastAndroid.show('Enrollment-Timeout — bitte erneut versuchen', ToastAndroid.LONG);
}
return false;
});
}, 60_000);
}, [samples, enrollPending]);
const deleteFingerprint = useCallback(() => {
Alert.alert(
'Stimme löschen?',
'Danach muss ARIA neu enrolled werden, sonst greift Speaker-ID-Filter nicht.',
[
{ text: 'Abbrechen', style: 'cancel' },
{
text: 'Löschen', style: 'destructive', onPress: () => {
const reqId = _newReqId('viddel');
rvs.send('voice_id_delete_request' as any, { requestId: reqId });
},
},
],
);
}, []);
// ── Render ──────────────────────────────────────────────
return (
<ScrollView contentContainerStyle={{ paddingBottom: 30 }}>
<Text style={s.intro}>
ARIA erkennt deine Stimme an einem Fingerprint (SpeechBrain ECAPA-TDNN, 192 Dimensionen).
Andere Sprecher (TV, Hintergrund, andere Personen) werden gefiltert keine Brain-Calls,
keine Tokens. {'\n\n'}
Sprich {SAMPLES_REQUIRED} Mal je {SAMPLE_DURATION_MS / 1000}s ganz normal verschiedene
Sätze, ruhige Umgebung empfohlen.
</Text>
{/* Status-Karte */}
<View style={s.card}>
<Text style={s.cardLabel}>Status</Text>
{status.state === 'loading' && (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<ActivityIndicator color="#0096FF" />
<Text style={s.statusText}>Wird abgefragt...</Text>
</View>
)}
{status.state === 'unenrolled' && (
<Text style={[s.statusText, { color: '#FFD60A' }]}> Nicht enrolled Stimme einrichten </Text>
)}
{status.state === 'enrolled' && (
<>
<Text style={[s.statusText, { color: '#34C759' }]}>
Enrolled {status.sampleCount} Samples
({status.durations.reduce((a, b) => a + b, 0).toFixed(1)}s gesamt)
</Text>
<Text style={s.statusSub}>
Aktualisiert {new Date(status.updatedAt * 1000).toLocaleString('de-DE')} · dim={status.dim}
</Text>
</>
)}
{status.state === 'error' && (
<Text style={[s.statusText, { color: '#FF6E6E' }]}> {status.message}</Text>
)}
</View>
{/* Aufnahme-Bereich */}
<View style={s.card}>
<Text style={s.cardLabel}>Samples ({samples.length}/{SAMPLES_REQUIRED})</Text>
{samples.length === 0 && !recording && (
<Text style={s.hint}>Tipp: sprich klare normale Sätze, je 3-4 Sekunden Audio.</Text>
)}
{samples.map((sample, idx) => (
<View key={idx} style={s.sampleRow}>
<Text style={s.sampleText}>
Sample {idx + 1} · {(sample.durationMs / 1000).toFixed(1)}s
</Text>
<TouchableOpacity onPress={() => removeSample(idx)} disabled={enrollPending}>
<Text style={{ color: '#FF6E6E', fontSize: 18 }}></Text>
</TouchableOpacity>
</View>
))}
<TouchableOpacity
onPress={recordSample}
disabled={recording || enrollPending}
style={[s.recordBtn, (recording || enrollPending) && { opacity: 0.5 }]}
>
{recording ? (
<>
<ActivityIndicator color="#fff" />
<Text style={s.recordBtnText}>Aufnahme läuft {recordCountdown}s</Text>
</>
) : (
<Text style={s.recordBtnText}> Sample {samples.length + 1} aufnehmen</Text>
)}
</TouchableOpacity>
{samples.length > 0 && !recording && (
<TouchableOpacity
onPress={() => setSamples([])}
disabled={enrollPending}
style={s.resetBtn}
>
<Text style={s.resetBtnText}>Alle verwerfen</Text>
</TouchableOpacity>
)}
</View>
{/* Aktionen */}
<View style={{ flexDirection: 'row', gap: 8, marginTop: 8 }}>
<TouchableOpacity
onPress={sendEnrollment}
disabled={samples.length < SAMPLES_REQUIRED || enrollPending}
style={[
s.primaryBtn,
(samples.length < SAMPLES_REQUIRED || enrollPending) && { opacity: 0.4 },
]}
>
{enrollPending ? (
<>
<ActivityIndicator color="#fff" />
<Text style={s.primaryBtnText}>Wird verarbeitet</Text>
</>
) : (
<Text style={s.primaryBtnText}>
Speichern ({samples.length}/{SAMPLES_REQUIRED})
</Text>
)}
</TouchableOpacity>
</View>
{/* Verwaltung */}
{status.state === 'enrolled' && (
<View style={[s.card, { marginTop: 20 }]}>
<Text style={s.cardLabel}>Verwaltung</Text>
<TouchableOpacity onPress={refreshStatus} style={s.secondaryBtn}>
<Text style={s.secondaryBtnText}>🔄 Status aktualisieren</Text>
</TouchableOpacity>
<TouchableOpacity onPress={deleteFingerprint} style={s.dangerBtn}>
<Text style={s.dangerBtnText}>🗑 Fingerprint löschen (Re-Enrollment nötig)</Text>
</TouchableOpacity>
</View>
)}
</ScrollView>
);
};
const s = StyleSheet.create({
intro: {
color: '#8888AA',
fontSize: 13,
lineHeight: 19,
marginBottom: 16,
paddingHorizontal: 4,
},
card: {
backgroundColor: 'rgba(30,30,46,0.6)',
borderRadius: 8,
padding: 14,
marginBottom: 10,
},
cardLabel: {
color: '#8888AA',
fontSize: 11,
fontWeight: '700',
textTransform: 'uppercase',
letterSpacing: 0.5,
marginBottom: 8,
},
statusText: {
color: '#E0E0F0',
fontSize: 14,
fontWeight: '600',
},
statusSub: {
color: '#555570',
fontSize: 11,
marginTop: 4,
},
hint: {
color: '#555570',
fontSize: 12,
fontStyle: 'italic',
marginBottom: 8,
},
sampleRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 6,
borderBottomWidth: 1,
borderColor: '#2A2A3E',
},
sampleText: {
color: '#E0E0F0',
fontSize: 13,
},
recordBtn: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
backgroundColor: '#E55C5C',
borderRadius: 8,
paddingVertical: 14,
marginTop: 12,
},
recordBtnText: {
color: '#fff',
fontSize: 15,
fontWeight: '700',
},
resetBtn: {
alignItems: 'center',
paddingVertical: 8,
marginTop: 6,
},
resetBtnText: {
color: '#FFD60A',
fontSize: 12,
},
primaryBtn: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
backgroundColor: '#34C759',
borderRadius: 8,
paddingVertical: 14,
},
primaryBtnText: {
color: '#fff',
fontSize: 15,
fontWeight: '700',
},
secondaryBtn: {
backgroundColor: 'rgba(0,150,255,0.15)',
borderRadius: 6,
paddingVertical: 10,
alignItems: 'center',
marginTop: 6,
},
secondaryBtnText: {
color: '#0096FF',
fontSize: 13,
fontWeight: '600',
},
dangerBtn: {
backgroundColor: 'rgba(229,92,92,0.15)',
borderRadius: 6,
paddingVertical: 10,
alignItems: 'center',
marginTop: 6,
},
dangerBtnText: {
color: '#E55C5C',
fontSize: 13,
fontWeight: '600',
},
});
export default VoiceIdEnrollment;
-224
View File
@@ -1,224 +0,0 @@
/**
* ZoomableImage — Pinch-to-Zoom + Pan fuers Vollbild-Modal.
*
* Reine RN-Implementation, ohne react-native-gesture-handler.
*
* - 2 Finger: Pinch (Zoom 1x..5x) + simultaner Pan via Focal-Punkt
* - 1 Finger: Pan wenn schon gezoomt (>1.02x)
* - Doppel-Tap (<300ms zw. zwei Single-Taps): Toggle 1x ↔ 2.5x
*
* Implementierungs-Hinweise zur alten Version (warum's nicht ging):
* - `gestureState.numberActiveTouches` ist nicht zuverlaessig direkt
* nach onPanResponderGrant. Wir lesen Finger-Anzahl jetzt
* ausschliesslich aus `e.nativeEvent.touches.length`.
* - Beim Wechsel von 2 → 1 Fingern bleib die Pinch-Referenz haengen.
* Jetzt: bei jedem Finger-Wechsel re-snapshotten wir die Geste.
* - Animated.Image bekommt jetzt pointerEvents="none" damit der View
* GARANTIERT die Touches abbekommt.
* - useNativeDriver ist bewusst AUS — sonst koennen wir setValue()
* nicht synchron mit dem Pan-Responder zusammen nutzen.
*/
import React, { useMemo, useRef } from 'react';
import {
Animated,
PanResponder,
GestureResponderEvent,
ImageStyle,
StyleProp,
StyleSheet,
View,
} from 'react-native';
interface Props {
uri: string;
containerWidth: number;
containerHeight: number;
style?: StyleProp<ImageStyle>;
}
const MIN_SCALE = 1;
const MAX_SCALE = 5;
const DOUBLE_TAP_MS = 300;
const DOUBLE_TAP_DIST = 30; // Bewegung max. damit ein Tap als Tap gilt
const PAN_SLOP_AT_SCALE_1 = 4; // Mikro-Movement nicht als Pan werten
const ZoomableImage: React.FC<Props> = ({ uri, containerWidth, containerHeight, style }) => {
// Animated-Werte fuer die Render-Transformation
const scale = useRef(new Animated.Value(1)).current;
const tx = useRef(new Animated.Value(0)).current;
const ty = useRef(new Animated.Value(0)).current;
// Logische Zustaende — wir lesen Animated.Value nicht zurueck (waere async)
const view = useRef({ scale: 1, x: 0, y: 0 }).current;
// Geste-Snapshot: was war zu Beginn dieser Geste-Phase
const gesture = useRef({
fingers: 0, // aktuelle Finger-Anzahl
startScale: 1,
startX: 0,
startY: 0,
startDist: 0, // Pinch-Referenz-Distanz
startFocalX: 0,
startFocalY: 0,
movedSinceTouch: 0, // fuer Tap-Erkennung
touchStartedAt: 0,
touchStartX: 0,
touchStartY: 0,
}).current;
// Doppel-Tap
const lastTap = useRef({ at: 0, x: 0, y: 0 });
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
const applyClamped = (s: number, x: number, y: number) => {
const ns = clamp(s, MIN_SCALE, MAX_SCALE);
// Translation auf das verfuegbare Volumen begrenzen
const maxX = Math.max(0, (containerWidth * ns - containerWidth) / 2);
const maxY = Math.max(0, (containerHeight * ns - containerHeight) / 2);
const nx = clamp(x, -maxX, maxX);
const ny = clamp(y, -maxY, maxY);
view.scale = ns;
view.x = nx;
view.y = ny;
scale.setValue(ns);
tx.setValue(nx);
ty.setValue(ny);
};
const distance = (touches: any[]) =>
Math.hypot(touches[0].pageX - touches[1].pageX, touches[0].pageY - touches[1].pageY);
const focal = (touches: any[]) => ({
x: (touches[0].pageX + touches[1].pageX) / 2,
y: (touches[0].pageY + touches[1].pageY) / 2,
});
// Snapshot vor jedem Phasenwechsel (1↔2 Finger) — verhindert Spruenge
const snapshot = (touches: any[]) => {
gesture.startScale = view.scale;
gesture.startX = view.x;
gesture.startY = view.y;
if (touches.length >= 2) {
gesture.startDist = distance(touches);
const f = focal(touches);
gesture.startFocalX = f.x;
gesture.startFocalY = f.y;
} else if (touches.length === 1) {
gesture.startDist = 0;
gesture.startFocalX = touches[0].pageX;
gesture.startFocalY = touches[0].pageY;
}
};
const responder = useMemo(
() =>
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e: GestureResponderEvent) => {
const touches = e.nativeEvent.touches as any[];
gesture.fingers = touches.length;
gesture.movedSinceTouch = 0;
gesture.touchStartedAt = Date.now();
gesture.touchStartX = touches[0]?.pageX ?? 0;
gesture.touchStartY = touches[0]?.pageY ?? 0;
snapshot(touches);
},
onPanResponderMove: (e: GestureResponderEvent, _gs) => {
const touches = e.nativeEvent.touches as any[];
// Phasenwechsel? → Re-Snapshot, damit nicht gesprungen wird
if (touches.length !== gesture.fingers) {
gesture.fingers = touches.length;
snapshot(touches);
return;
}
gesture.movedSinceTouch += 1;
if (touches.length >= 2) {
// Pinch + Pan via Focal
const d = distance(touches);
if (gesture.startDist === 0) {
// Sicherheitsnetz falls Snapshot gemissed wurde
snapshot(touches);
return;
}
const factor = d / gesture.startDist;
const f = focal(touches);
const newScale = clamp(gesture.startScale * factor, MIN_SCALE, MAX_SCALE);
// Focal-basierter Pan: zoomt um den Mittelpunkt der zwei Finger
const newX = gesture.startX + (f.x - gesture.startFocalX);
const newY = gesture.startY + (f.y - gesture.startFocalY);
applyClamped(newScale, newX, newY);
} else if (touches.length === 1 && view.scale > 1.02) {
const dx = touches[0].pageX - gesture.startFocalX;
const dy = touches[0].pageY - gesture.startFocalY;
if (Math.abs(dx) < PAN_SLOP_AT_SCALE_1 && Math.abs(dy) < PAN_SLOP_AT_SCALE_1) return;
applyClamped(view.scale, gesture.startX + dx, gesture.startY + dy);
}
},
onPanResponderRelease: (e: GestureResponderEvent) => {
const elapsed = Date.now() - gesture.touchStartedAt;
const dx = (e.nativeEvent.changedTouches?.[0]?.pageX ?? gesture.touchStartX) - gesture.touchStartX;
const dy = (e.nativeEvent.changedTouches?.[0]?.pageY ?? gesture.touchStartY) - gesture.touchStartY;
const wasTap =
elapsed < 280 &&
Math.abs(dx) < DOUBLE_TAP_DIST &&
Math.abs(dy) < DOUBLE_TAP_DIST;
if (wasTap) {
const now = Date.now();
if (now - lastTap.current.at < DOUBLE_TAP_MS) {
// Doppel-Tap → Zoom-Toggle
if (view.scale > 1.1) {
applyClamped(1, 0, 0);
} else {
applyClamped(2.5, 0, 0);
}
lastTap.current = { at: 0, x: 0, y: 0 };
} else {
lastTap.current = { at: now, x: gesture.touchStartX, y: gesture.touchStartY };
}
}
gesture.fingers = 0;
gesture.startDist = 0;
},
onPanResponderTerminate: () => {
gesture.fingers = 0;
gesture.startDist = 0;
},
}),
[],
);
return (
<View
style={StyleSheet.absoluteFill}
collapsable={false}
{...responder.panHandlers}
>
<Animated.View pointerEvents="none" style={StyleSheet.absoluteFill}>
<Animated.Image
source={{ uri }}
style={[
style,
{
transform: [{ translateX: tx }, { translateY: ty }, { scale }],
},
]}
resizeMode="contain"
/>
</Animated.View>
</View>
);
};
export default ZoomableImage;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-104
View File
@@ -1,104 +0,0 @@
/**
* ariaView — Empfaenger der von ARIA komponierten RAEUMLICHEN Ansichten (M1).
*
* Fluss: ARIA ruft im Brain `present_view` → Brain-Event `aria_view` → Bridge →
* RVS `aria_view` → hier gepuffert → WorkspaceCanvas rendert Orb + Karten, die
* auf der Flaeche materialisieren.
*
* Der Service haelt pro Projekt die AKTUELLE View-Spec, damit eine spaet
* gemountete Canvas-Kachel sofort den Ist-Stand bekommt. Muster wie
* services/codeFile.ts (Singleton, rvs.onMessage).
*
* Die Karten-Typen sind bewusst offen (string), damit spaetere Renderer (vnc,
* chart, file …) ohne Service-Aenderung dazukommen. Der jeweilige Client-Renderer
* entscheidet, was er mit einem unbekannten Typ macht (i.d.R. ignorieren).
*/
import rvs, { RVSMessage } from './rvs';
export type OrbState = 'idle' | 'listening' | 'thinking' | 'speaking' | 'working';
export interface ViewMarker {
lat: number;
lon: number;
label?: string;
}
export interface ViewCard {
type: 'text' | 'image' | 'map' | 'code' | 'list' | string;
title?: string;
md?: string; // text/list
src?: string; // image
markers?: ViewMarker[]; // map
path?: string; // code
lang?: string; // code
// Zukuenftige Kartenfelder ohne Service-Aenderung:
[k: string]: any;
}
export interface ViewSpec {
cards: ViewCard[];
orb?: OrbState;
title?: string;
}
export interface AriaView {
projectId: string;
view: ViewSpec;
clientMsgId?: string;
ts: number;
}
type ViewSub = (v: AriaView) => void;
class AriaViewService {
private views = new Map<string, AriaView>();
private subs: ViewSub[] = [];
constructor() {
rvs.onMessage((m) => this.onMessage(m));
}
private onMessage(m: RVSMessage): void {
if (m.type !== 'aria_view') return;
const p = (m.payload || {}) as any;
const raw = (p.view || {}) as any;
const cards: ViewCard[] = Array.isArray(raw.cards) ? raw.cards : [];
if (cards.length === 0) return; // leere Ansicht ignorieren
const view: ViewSpec = {
cards,
orb: raw.orb || 'speaking',
title: raw.title || '',
};
const projectId: string = p.projectId || '';
const entry: AriaView = {
projectId,
view,
clientMsgId: p.clientMsgId || '',
ts: Date.now(),
};
this.views.set(projectId, entry);
this.subs.forEach((cb) => {
try { cb(entry); } catch {}
});
}
/** Aktuelle Ansicht eines Projekts (leer = Hauptchat). */
getView(projectId: string): AriaView | undefined {
return this.views.get(projectId || '');
}
/** Registriert einen Listener fuer neue Ansichten. */
subscribe(cb: ViewSub): () => void {
this.subs.push(cb);
return () => { this.subs = this.subs.filter((s) => s !== cb); };
}
/** Ansicht eines Projekts verwerfen (z.B. wenn der User sie wegwischt). */
clear(projectId: string): void {
this.views.delete(projectId || '');
}
}
const ariaView = new AriaViewService();
export default ariaView;
File diff suppressed because it is too large Load Diff
-85
View File
@@ -1,85 +0,0 @@
/**
* Background-Audio + Hintergrund-Persistenz: ARIAs TTS, Mic-Aufnahme,
* Wake-Word-Lauschen UND der allgemeine Hintergrund-Modus laufen
* weiter wenn die App minimiert ist. Wir starten dafuer einen Foreground-
* Service mit foregroundServiceType=mediaPlayback|microphone, der eine
* persistente Notification zeigt solange irgendein Slot aktiv ist.
*
* Mehrere Komponenten koennen den Service unabhaengig "halten":
* - 'tts' : ARIA spricht
* - 'rec' : Aufnahme laeuft
* - 'wake' : Wake-Word lauscht passiv (Ohr aktiv)
* - 'location' : Background-GPS-Tracking (opt-in in Settings)
* - 'background' : Persistenter Hintergrund-Modus (Settings-Toggle).
* Haelt JS-Engine + WebSocket auch ohne Audio am Leben
* Trigger-Replies, Reconnects, Push-Reaktionen.
*
* Solange mindestens ein Slot aktiv ist, laeuft der Service. Wenn alle
* Slots leer sind, wird er gestoppt. Der Notification-Text passt sich an
* den hoechstprioren Slot an (tts > rec > wake > location > background).
*/
import { NativeModules } from 'react-native';
interface BackgroundAudioNative {
start(reason: string): Promise<boolean>;
stop(): Promise<boolean>;
}
const { BackgroundAudio } = NativeModules as { BackgroundAudio?: BackgroundAudioNative };
type Slot = 'tts' | 'rec' | 'wake' | 'location' | 'background';
const slots = new Set<Slot>();
// Prioritaet fuer den Notification-Text — hoechste zuerst. 'background'
// ist die fallback-Anzeige wenn nichts anderes laeuft.
const PRIORITY: Slot[] = ['tts', 'rec', 'wake', 'location', 'background'];
function topReason(): string {
for (const s of PRIORITY) {
if (slots.has(s)) return s;
}
return '';
}
async function applyState(): Promise<void> {
if (!BackgroundAudio) return;
if (slots.size === 0) {
try { await BackgroundAudio.stop(); } catch {}
console.log('[BackgroundAudio] Service gestoppt (keine Slots)');
import('./logger').then(m => m.reportAppDebug('bg.stop', 'service stopped')).catch(()=>{});
return;
}
const reason = topReason();
try {
await BackgroundAudio.start(reason);
console.log('[BackgroundAudio] Service aktiv (slot=%s, slots=%s)',
reason, [...slots].join('+'));
import('./logger').then(m => m.reportAppDebug('bg.start', `slot=${reason} all=[${[...slots].join(',')}]`)).catch(()=>{});
} catch (err: any) {
console.warn('[BackgroundAudio] start fehlgeschlagen:', err?.message || err);
import('./logger').then(m => m.reportAppDebug('bg.start.fail', err?.message || String(err))).catch(()=>{});
}
}
export async function acquireBackgroundAudio(slot: Slot): Promise<void> {
if (slots.has(slot)) return;
slots.add(slot);
await applyState();
}
export async function releaseBackgroundAudio(slot: Slot): Promise<void> {
if (!slots.has(slot)) return;
slots.delete(slot);
await applyState();
}
export function backgroundAudioActive(): boolean {
return slots.size > 0;
}
// --- Legacy API (nur tts-Slot) — fuer Aufruf-Sites die noch nichts vom Slot-
// system wissen. Mappt auf den 'tts'-Slot. ---
export const startBackgroundAudio = () => acquireBackgroundAudio('tts');
export const stopBackgroundAudio = () => releaseBackgroundAudio('tts');
-687
View File
@@ -1,687 +0,0 @@
/**
* Brain-API-Client fuer die App.
*
* Die App hat keinen direkten HTTP-Zugriff aufs Brain (nur via RVS). Wir
* tunneln alle Memory-Operationen ueber den generischen brain_request /
* brain_response RVS-Channel den die Bridge implementiert.
*
* Pattern: pro Call eine eindeutige requestId, Listener wartet auf passende
* brain_response, Promise loest auf / wird abgelehnt bei status>=400.
*/
import rvs from './rvs';
type AnyJson = any;
interface PendingRequest {
resolve: (data: AnyJson) => void;
reject: (err: Error) => void;
timer: ReturnType<typeof setTimeout>;
expectBinary?: boolean;
}
const pending = new Map<string, PendingRequest>();
let installed = false;
function _ensureListener() {
if (installed) return;
installed = true;
rvs.onMessage((msg: any) => {
if (!msg || msg.type !== 'brain_response') return;
const p = msg.payload || {};
const reqId: string = p.requestId || '';
const handler = pending.get(reqId);
if (!handler) return;
pending.delete(reqId);
clearTimeout(handler.timer);
const status: number = Number(p.status || 0);
if (status >= 200 && status < 300) {
if (handler.expectBinary) {
handler.resolve({ base64: p.base64 || '', contentType: p.contentType || '' });
} else {
handler.resolve(p.json !== undefined ? p.json : (p.text !== undefined ? p.text : null));
}
} else {
const detail = (p.json && p.json.detail) || p.text || `HTTP ${status}`;
handler.reject(new Error(`Brain ${status}: ${detail}`));
}
});
}
let _nextId = 0;
function _newRequestId(): string {
_nextId += 1;
return `brain_${Date.now().toString(36)}_${_nextId}`;
}
/** Mini-Query-String-Builder ohne URLSearchParams (Hermes-Polyfill kennt
* kein URLSearchParams.set, crasht). Akzeptiert object mit string/number/
* bool-Values; undefined/null/leere Strings werden ausgelassen. */
function _qs(params: Record<string, unknown>): string {
const parts: string[] = [];
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === null || v === '') continue;
parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
}
return parts.length ? `?${parts.join('&')}` : '';
}
interface SendOpts {
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
body?: AnyJson;
bodyBase64?: string;
contentType?: string;
expectBinary?: boolean;
timeoutMs?: number;
}
function _send(path: string, opts: SendOpts = {}): Promise<AnyJson> {
_ensureListener();
// Fast-Fail wenn RVS nicht verbunden — sonst tickt der Timeout 30s und
// der TriggerBrowser / Dateimanager zeigt ne ewig drehende Spinner.
// Stefan-Bug 06/2026: "Connection refused, App haengt 30 Sekunden".
const rvsState = rvs.getState();
if (rvsState !== 'connected') {
return Promise.reject(new Error(
`Keine Verbindung zum Brain (RVS: ${rvsState}). Warte auf Reconnect...`,
));
}
return new Promise((resolve, reject) => {
const requestId = _newRequestId();
const timer = setTimeout(() => {
if (pending.delete(requestId)) {
reject(new Error(`Brain-Timeout fuer ${path}`));
}
}, opts.timeoutMs || 30000);
pending.set(requestId, { resolve, reject, timer, expectBinary: opts.expectBinary });
rvs.send('brain_request' as any, {
requestId,
method: opts.method || 'GET',
path,
...(opts.body !== undefined ? { body: opts.body } : {}),
...(opts.bodyBase64 ? { bodyBase64: opts.bodyBase64 } : {}),
...(opts.contentType ? { contentType: opts.contentType } : {}),
});
});
}
// ── Typen ────────────────────────────────────────────────────────────
export interface MemoryAttachment {
name: string;
mime: string;
size: number;
path: string;
}
export interface Memory {
id: string;
type: string;
title: string;
content: string;
pinned: boolean;
category: string;
source: string;
tags: string[];
created_at: string;
updated_at: string;
conversation_id?: string | null;
score?: number | null;
attachments?: MemoryAttachment[];
}
/** OAuth-Service-Status wie aus Brain `/oauth/services` zurueckkommt. */
export interface OAuthServiceStatus {
service: string;
configured: boolean;
authenticated: boolean;
expiresAt?: number | null;
expiresInSec?: number | null;
hasRefresh: boolean;
scope?: string;
isDefault: boolean;
}
/** OAuth-App-Config (client_id/scopes/URLs) — client_secret kommt NIE rausgegeben. */
export interface OAuthAppConfig {
client_id: string;
has_client_secret: boolean;
scopes?: string[] | null;
auth_url?: string | null;
token_url?: string | null;
}
/** Projekt — Stefans Threading-Konzept im Hauptchat. */
export interface Project {
id: string;
name: string;
description: string;
status: 'active' | 'ended' | 'archived';
hidden?: boolean; // aus Listen ausgeblendet (bleibt nutzbar)
created_at: number;
updated_at: number;
last_activity_at: number;
turn_count: number;
// Workspace: 'code' blendet Editor-/VNC-Kacheln ein. ARIA setzt das selbst
// via set_project_kind; fehlt/undefined = 'chat' (nur Chat-Kachel).
kind?: 'code' | 'chat';
// Optionale absolute noVNC-URL (falls der Desktop direkt erreichbar ist,
// sonst laeuft der VNC-Stream als RFB-Bytes durch RVS).
desktop_url?: string;
// Automatisch: hat das Projekt Dateien in /shared/projects/<id>/? → Datei-Symbol.
has_files?: boolean;
file_count?: number;
}
export interface ProjectStatus {
active_id: string;
active: Project | null;
projects: Project[];
}
/** QEMU-VM eines Projekts (Registry + Live-Status). */
export interface ProjectVm {
name: string;
arch: string;
iso?: string;
vnc_display: number;
mem: number;
running?: boolean;
vnc_port?: number;
boot_cmd?: string;
created_at?: number;
}
/** 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;
description: string;
execution: string; // local-venv | local-bin | bash
entry: string; // run.py | run.sh
args?: any[]; // [{name, type, required, description}]
requires?: { pip?: string[]; binaries?: string[] };
active: boolean;
created_at?: string;
updated_at?: string;
last_used?: string | null;
use_count?: number;
version?: string;
author?: string; // "aria" | "stefan"
setup_error?: string;
// P3: konfigurierbare Werte (API-Keys, IDs etc.) — Stefan setzt sie hier,
// Skill bekommt sie als CFG_<NAME> ENV. Werte selbst kommen via /config.
config_schema?: SkillConfigField[];
// P4: Versions-Historie. Detail-Liste kommt via /versions.
version_history?: { version_id: string; archived_at?: string; summary?: string }[];
}
export interface SkillConfigField {
name: string;
type: 'string' | 'number' | 'boolean' | 'password';
label?: string;
secret?: boolean;
description?: string;
default?: any;
}
export interface SkillVersion {
version_id: string;
archived_at?: string;
summary?: string;
}
/** Trigger-Manifest wie aus Brain `/triggers/list` zurueckkommt. */
export interface Trigger {
name: string;
type: 'timer' | 'watcher' | string;
active: boolean;
author?: string;
message: string;
fires_at?: string; // ISO, nur timer
condition?: string; // nur watcher
check_interval_sec?: number; // nur watcher
throttle_sec?: number; // nur watcher
fire_count?: number;
last_fired_at?: string | null;
last_checked_at?: string | null;
created_at?: string;
updated_at?: string;
}
// ── Memory CRUD ──────────────────────────────────────────────────────
export const brainApi = {
/** Einzelne Memory holen (mit allen Feldern inkl. Anhaenge) */
getMemory(id: string): Promise<Memory> {
return _send(`/memory/get/${encodeURIComponent(id)}`);
},
/** Liste aller Memories, optional nach Type gefiltert. */
listMemories(opts: { type?: string; limit?: number } = {}): Promise<Memory[]> {
const qs = _qs({ type: opts.type, limit: opts.limit || 500 });
return _send(`/memory/list${qs}`);
},
/** Volltext-Substring-Suche. */
searchText(q: string, opts: { type?: string; includePinned?: boolean; k?: number } = {}): Promise<Memory[]> {
const qs = _qs({
q,
type: opts.type,
include_pinned: opts.includePinned !== false,
k: opts.k || 50,
});
return _send(`/memory/search-text${qs}`);
},
/** Semantische Suche (Embedder). */
searchSemantic(q: string, opts: { type?: string; includePinned?: boolean; k?: number; threshold?: number } = {}): Promise<Memory[]> {
const qs = _qs({
q,
type: opts.type,
include_pinned: opts.includePinned !== false,
k: opts.k || 10,
score_threshold: opts.threshold ?? 0.30,
});
return _send(`/memory/search${qs}`);
},
/** Memory anlegen. */
saveMemory(body: {
type: string;
title: string;
content: string;
pinned?: boolean;
category?: string;
tags?: string[];
}): Promise<Memory> {
return _send('/memory/save', {
method: 'POST',
body: { source: 'app', ...body },
});
},
/** Memory aktualisieren (Patch — nur uebergebene Felder werden geaendert). */
updateMemory(id: string, body: Partial<Pick<Memory, 'title' | 'content' | 'pinned' | 'category' | 'tags'>>): Promise<Memory> {
return _send(`/memory/update/${encodeURIComponent(id)}`, {
method: 'PATCH',
body,
});
},
/** Memory loeschen. */
deleteMemory(id: string): Promise<{ deleted: string }> {
return _send(`/memory/delete/${encodeURIComponent(id)}`, {
method: 'DELETE',
timeoutMs: 15000,
});
},
// ── Anhaenge ────────────────────────────────────────────────────────
/** Datei als Anhang an die Memory haengen (Base64-Upload). */
uploadAttachment(memoryId: string, name: string, base64: string): Promise<Memory> {
return _send(`/memory/${encodeURIComponent(memoryId)}/attachments`, {
method: 'POST',
body: { name, data_base64: base64 },
timeoutMs: 120000,
});
},
/** Anhang loeschen. */
deleteAttachment(memoryId: string, filename: string): Promise<Memory> {
return _send(
`/memory/${encodeURIComponent(memoryId)}/attachments/${encodeURIComponent(filename)}`,
{ method: 'DELETE' },
);
},
/** Anhang-Bytes holen (fuer Vorschau / Download). Liefert Base64. */
getAttachmentBytes(memoryId: string, filename: string): Promise<{ base64: string; contentType: string }> {
return _send(
`/memory/${encodeURIComponent(memoryId)}/attachments/${encodeURIComponent(filename)}`,
{ expectBinary: true, timeoutMs: 60000 },
);
},
// ── Triggers ────────────────────────────────────────────────────────
/** Liste aller Trigger (aktive + inaktive).
* Brain returnt {triggers: [...]} wir unwrappen damit der Caller einfach
* t.sort/filter/map nutzen kann. Ohne das Unwrap warf t.sort() eine
* TypeError-Exception und der TriggerBrowser blieb leer. */
listTriggers(): Promise<Trigger[]> {
return _send('/triggers/list').then((r: any) => Array.isArray(r) ? r : (r?.triggers || []));
},
/** Einzelnen Trigger holen (inkl. fire_count, last_fired_at, ...). */
getTrigger(name: string): Promise<Trigger> {
return _send(`/triggers/${encodeURIComponent(name)}`);
},
/** Verfuegbare Condition-Variablen + Funktionen (fuer Watcher-Editor). */
getTriggerConditions(): Promise<{ variables: any[]; functions: any[] }> {
return _send('/triggers/conditions');
},
/** Trigger-Logs (last N Feuerungen). */
getTriggerLogs(name: string, limit: number = 50): Promise<any[]> {
return _send(`/triggers/${encodeURIComponent(name)}/logs?limit=${limit}`);
},
/** Timer anlegen. fires_at = ISO timestamp (UTC). */
createTimer(body: { name: string; fires_at: string; message: string; author?: string }): Promise<Trigger> {
return _send('/triggers/timer', {
method: 'POST',
body: { author: 'app', ...body },
});
},
/** Watcher anlegen. */
createWatcher(body: {
name: string;
condition: string;
message: string;
check_interval_sec?: number;
throttle_sec?: number;
author?: string;
}): Promise<Trigger> {
return _send('/triggers/watcher', {
method: 'POST',
body: { author: 'app', ...body },
});
},
/** Trigger patchen (active/message/condition/throttle/interval/fires_at). */
updateTrigger(name: string, body: Partial<{
active: boolean;
message: string;
condition: string;
throttle_sec: number;
check_interval_sec: number;
fires_at: string;
}>): Promise<Trigger> {
return _send(`/triggers/${encodeURIComponent(name)}`, {
method: 'PATCH',
body,
});
},
/** Trigger loeschen. */
deleteTrigger(name: string): Promise<{ deleted: string }> {
return _send(`/triggers/${encodeURIComponent(name)}`, {
method: 'DELETE',
timeoutMs: 15000,
});
},
// ── Skills ────────────────────────────────────────────────────────
/** Liste aller Skills (aktive + inaktive). Brain returnt {skills: [...]}. */
listSkills(): Promise<Skill[]> {
return _send('/skills/list').then((r: any) => Array.isArray(r) ? r : (r?.skills || []));
},
/** Einzelnen Skill holen (inkl. setup_error, last_used, use_count). */
getSkill(name: string): Promise<Skill> {
return _send(`/skills/${encodeURIComponent(name)}`);
},
/** Skill ausfuehren (mit args als ENV ARG_XXX). Skill-Run kann lange dauern,
* 5 min Default-Timeout. */
runSkill(name: string, args: Record<string, any> = {}): Promise<{
ok: boolean; exit_code: number; stdout: string; stderr: string;
duration_sec: number; log_path?: string;
}> {
return _send('/skills/run', {
method: 'POST',
body: { name, args, timeout_sec: 300 },
timeoutMs: 320000,
});
},
/** Skill-Manifest aendern (description, active, args...). Code-Aenderungen
* gehen ueber ARIAs eigene skill_update-Tool die App-UI sollte sie
* NICHT direkt anbieten (zu fehleranfaellig). */
updateSkill(name: string, body: Partial<{
description: string;
active: boolean;
args: any[];
version: string;
}>): Promise<Skill> {
return _send(`/skills/${encodeURIComponent(name)}`, {
method: 'PATCH',
body,
timeoutMs: 15000,
});
},
/** Skill loeschen (samt venv + logs). */
deleteSkill(name: string): Promise<{ deleted: string }> {
return _send(`/skills/${encodeURIComponent(name)}`, {
method: 'DELETE',
timeoutMs: 15000,
});
},
/** Letzte Run-Logs eines Skills. */
getSkillLogs(name: string, limit: number = 20): Promise<any[]> {
return _send(`/skills/${encodeURIComponent(name)}/logs?limit=${limit}`)
.then((r: any) => Array.isArray(r) ? r : (r?.logs || []));
},
/** P3: Config-Schema + aktuelle Werte (secret-Felder gemaskt mit '***SET***'). */
getSkillConfig(name: string): Promise<{ schema: SkillConfigField[]; values: Record<string, any> }> {
return _send(`/skills/${encodeURIComponent(name)}/config`)
.then((r: any) => ({ schema: r?.schema || [], values: r?.values || {} }));
},
/** P3: Config-Werte komplett ueberschreiben. Werte greifen ab dem naechsten Run. */
setSkillConfig(name: string, values: Record<string, any>): Promise<{ ok: boolean; values: Record<string, any> }> {
return _send(`/skills/${encodeURIComponent(name)}/config`, {
method: 'POST',
body: { values },
timeoutMs: 10000,
});
},
/** P4: Liste archivierter Versionen, neueste zuerst. */
listSkillVersions(name: string): Promise<SkillVersion[]> {
return _send(`/skills/${encodeURIComponent(name)}/versions`)
.then((r: any) => r?.versions || []);
},
/** P4: Rollback auf eine fruehere Version. Aktueller Stand wird automatisch gesichert. */
rollbackSkill(name: string, versionId: string): Promise<{ ok: boolean; rolled_back_to: string; safety_snapshot: string }> {
return _send(`/skills/${encodeURIComponent(name)}/rollback`, {
method: 'POST',
body: { version_id: versionId },
timeoutMs: 60000, // venv-Rebuild kann dauern
});
},
/** P4: Einzelne Version dauerhaft loeschen. */
deleteSkillVersion(name: string, versionId: string): Promise<{ ok: boolean; deleted: string }> {
return _send(`/skills/${encodeURIComponent(name)}/versions/${encodeURIComponent(versionId)}`, {
method: 'DELETE',
timeoutMs: 10000,
});
},
// ── OAuth ────────────────────────────────────────────────────────
/** Liste aller Services mit Auth-Status (configured/authenticated/expires). */
listOAuthServices(): Promise<{ services: OAuthServiceStatus[] }> {
return _send('/oauth/services');
},
/** Persistierte Provider-Configs (URLs/scopes/client_id, KEIN client_secret). */
getOAuthApps(): Promise<{ apps: Record<string, OAuthAppConfig>; defaults: string[] }> {
return _send('/oauth/apps');
},
/** Provider-Config setzen/aktualisieren. Leerer client_secret laesst
* den bestehenden Wert stehen. */
saveOAuthApp(body: {
service: string;
client_id?: string;
client_secret?: string;
scopes?: string[];
auth_url?: string;
token_url?: string;
}): Promise<{ ok: boolean; service: string }> {
return _send('/oauth/apps', {
method: 'POST',
body,
timeoutMs: 15000,
});
},
/** Service-Eintrag komplett entfernen (incl. Token). */
deleteOAuthApp(service: string): Promise<{ ok: boolean }> {
return _send(`/oauth/apps/${encodeURIComponent(service)}`, {
method: 'DELETE',
timeoutMs: 15000,
});
},
/** Authorize-URL bauen (Brain speichert state, gibt url + redirect_uri zurueck). */
authorizeOAuth(service: string, scopes?: string[]): Promise<{
url: string; state: string; redirect_uri: string; service: string;
}> {
return _send('/oauth/authorize', {
method: 'POST',
body: { service, scopes },
timeoutMs: 15000,
});
},
/** Token loeschen (lokal — kein Provider-Revoke). */
revokeOAuth(service: string): Promise<{ ok: boolean }> {
return _send(`/oauth/${encodeURIComponent(service)}/revoke`, {
method: 'POST',
timeoutMs: 15000,
});
},
// ── Projekte ───────────────────────────────────────────────────
/** Kompletter Status: aktives Projekt + Liste. */
getProjectStatus(): Promise<ProjectStatus> {
return _send('/projects/status');
},
/** Nur die Liste — fuer Sidebar/Drawer. */
listProjects(includeArchived: boolean = false): Promise<Project[]> {
return _send(`/projects/list${includeArchived ? '?include_archived=true' : ''}`)
.then((r: any) => r?.projects || []);
},
/** Neues Projekt anlegen — wird automatisch aktiviert. */
createProject(body: { name: string; description?: string }): Promise<Project> {
return _send('/projects/create', {
method: 'POST',
body: { description: '', ...body },
});
},
/** Aktives Projekt wechseln. Leerer projectId = Hauptthread. */
switchProject(projectId: string): Promise<ProjectStatus> {
return _send('/projects/switch', {
method: 'POST',
body: { project_id: projectId },
});
},
/** Projekt als beendet markieren (bleibt sichtbar, aktiv ist dann der Hauptthread). */
endProject(projectId: string): Promise<Project> {
return _send(`/projects/${encodeURIComponent(projectId)}/end`, {
method: 'POST',
});
},
/** Projekt archivieren (verschwindet aus der Default-Liste). */
archiveProject(projectId: string): Promise<{ id: string; status: string }> {
return _send(`/projects/${encodeURIComponent(projectId)}/archive`, {
method: 'POST',
});
},
/** Projekt-Metadaten patchen (name / description / hidden / kind). */
updateProject(projectId: string, patch: Partial<Pick<Project, 'name' | 'description' | 'hidden' | 'kind'>>): Promise<Project> {
return _send(`/projects/${encodeURIComponent(projectId)}`, {
method: 'PATCH',
body: patch,
});
},
/** Projekt manuell als Code-Projekt / normalen Chat markieren. */
setProjectKind(projectId: string, kind: 'code' | 'chat'): Promise<Project> {
return _send(`/projects/${encodeURIComponent(projectId)}`, {
method: 'PATCH',
body: { kind },
});
},
/** Vorhandene Code-Dateien eines Projekts auflisten (/shared/projects/<id>/). */
listProjectFiles(projectId: string): Promise<{ projectId: string; files: { path: string; size: number }[] }> {
return _send(`/projects/${encodeURIComponent(projectId)}/files`);
},
/** Inhalt einer Projekt-Datei laden (Text). */
readProjectFile(projectId: string, path: string): Promise<{ projectId: string; path: string; content: string }> {
return _send(`/projects/${encodeURIComponent(projectId)}/file?path=${encodeURIComponent(path)}`);
},
/** Binaere Projekt-Datei (z.B. Bild) als Base64 + MIME laden. */
readProjectFileBinary(projectId: string, path: string): Promise<{ path: string; mime: string; base64: string }> {
return _send(`/projects/${encodeURIComponent(projectId)}/file?binary=1&path=${encodeURIComponent(path)}`, { timeoutMs: 30000 });
},
// ── QEMU-VMs pro Projekt ─────────────────────────────────────────
listProjectVms(projectId: string): Promise<{ projectId: string; vms: ProjectVm[] }> {
return _send(`/projects/${encodeURIComponent(projectId)}/vms`, { timeoutMs: 20000 });
},
addProjectVm(projectId: string, body: { name: string; arch?: string; iso?: string; vnc_display?: number; mem?: number; create_disk?: boolean; size?: string }): Promise<ProjectVm> {
return _send(`/projects/${encodeURIComponent(projectId)}/vms`, { method: 'POST', body, timeoutMs: 30000 });
},
removeProjectVm(projectId: string, name: string, purge = false): Promise<{ ok: boolean }> {
return _send(`/projects/${encodeURIComponent(projectId)}/vms/${encodeURIComponent(name)}?purge=${purge ? 'true' : 'false'}`, { method: 'DELETE' });
},
bootProjectVm(projectId: string, name: string): Promise<{ ok: boolean; vnc_port: number; output: string }> {
return _send(`/projects/${encodeURIComponent(projectId)}/vms/${encodeURIComponent(name)}/boot`, { method: 'POST', timeoutMs: 45000 });
},
stopProjectVm(projectId: string, name: string): Promise<{ ok: boolean; output: string }> {
return _send(`/projects/${encodeURIComponent(projectId)}/vms/${encodeURIComponent(name)}/stop`, { method: 'POST', timeoutMs: 30000 });
},
/** Screenshot der laufenden VM (Base64-PNG) — VM-Bildschirm ohne Live-VNC. */
screenshotProjectVm(projectId: string, name: string): Promise<{ ok: boolean; filename: string; base64: string }> {
return _send(`/projects/${encodeURIComponent(projectId)}/vms/${encodeURIComponent(name)}/screenshot`, { method: 'POST', timeoutMs: 30000 });
},
/** Projekt verstecken / wieder sichtbar machen (bleibt voll nutzbar). */
setProjectHidden(projectId: string, hidden: boolean): Promise<Project> {
return _send(`/projects/${encodeURIComponent(projectId)}`, {
method: 'PATCH',
body: { hidden },
});
},
/** 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;
Binary file not shown.
-102
View File
@@ -1,102 +0,0 @@
/**
* desktop Desktop-/VNC-Anbindung fuer Code-Projekte.
*
* Zwei Aufgaben:
* 1. Verfuegbarkeit: `check_desktop` triggert die Bridge, `desktop_status`
* meldet zurueck ob eine QEMU-VNC laeuft (und ggf. eine direkte URL).
* 2. VNC-Tunnel: der noVNC-Client in der App-WebView spricht kein eigenes
* WebSocket, sondern schickt RFB-Bytes als `vnc_input` (Base64) ueber RVS;
* die Bridge oeffnet die TCP-Verbindung zu QEMU (host:5901) und streamt die
* Antwort als `vnc_data` zurueck. Base64-in-JSON wie audio_pcm.
*
* Eine Session = ein Desktop; wir nutzen die Projekt-ID als Session-Key (leer =
* 'main'). Muster wie services/rvs.ts (Singleton mit Listener-Listen).
*/
import rvs, { RVSMessage } from './rvs';
export interface DesktopStatus {
available: boolean;
session: string;
/** optionale direkte noVNC-URL (falls Host direkt erreichbar) */
url?: string;
message?: string;
}
type StatusSub = (s: DesktopStatus) => void;
type VncDataSub = (b64: string) => void;
const DEFAULT_VNC_PORT = 5901;
const sessionOf = (projectId: string) => projectId || 'main';
class DesktopService {
private status: DesktopStatus = { available: false, session: '' };
private statusSubs: StatusSub[] = [];
private vncDataSubs: VncDataSub[] = [];
private currentSession = '';
constructor() {
rvs.onMessage((m) => this.onMessage(m));
}
private onMessage(m: RVSMessage): void {
const p = (m.payload || {}) as any;
if (m.type === 'desktop_status') {
this.status = {
available: !!p.available,
session: p.session || '',
url: typeof p.url === 'string' ? p.url : undefined,
message: p.message,
};
const s = this.status;
this.statusSubs.forEach((cb) => cb(s));
} else if (m.type === 'vnc_data') {
if (this.currentSession && p.session && p.session !== this.currentSession) return;
const b64 = typeof p.b64 === 'string' ? p.b64 : '';
if (b64) this.vncDataSubs.forEach((cb) => cb(b64));
}
}
getStatus(): DesktopStatus {
return this.status;
}
subscribeStatus(cb: StatusSub): () => void {
this.statusSubs.push(cb);
cb(this.status);
return () => { this.statusSubs = this.statusSubs.filter((s) => s !== cb); };
}
/** Bridge fragen, ob fuer dieses Projekt ein QEMU-Desktop laeuft. */
requestCheck(projectId: string, port: number = DEFAULT_VNC_PORT): void {
rvs.send('check_desktop', { projectId: projectId || '', session: sessionOf(projectId), port });
}
/** VNC-Tunnel oeffnen — Bridge verbindet TCP zu QEMU. */
openVnc(projectId: string, port: number = DEFAULT_VNC_PORT): string {
const session = sessionOf(projectId);
this.currentSession = session;
rvs.send('vnc_open', { session, port });
return session;
}
closeVnc(): void {
if (this.currentSession) rvs.send('vnc_close', { session: this.currentSession });
this.currentSession = '';
}
/** RFB-Bytes (Base64) aus der noVNC-WebView an die Bridge weiterreichen. */
sendInput(b64: string): void {
if (!this.currentSession) return;
rvs.send('vnc_input', { session: this.currentSession, b64 });
}
/** Listener fuer eingehende RFB-Bytes (Base64) — die noVNC-WebView. */
onVncData(cb: VncDataSub): () => void {
this.vncDataSubs.push(cb);
return () => { this.vncDataSubs = this.vncDataSubs.filter((s) => s !== cb); };
}
}
const desktop = new DesktopService();
export default desktop;
-236
View File
@@ -1,236 +0,0 @@
/**
* GPS-Tracking-Service.
*
* Wenn aktiv: pushed alle paar Sekunden die aktuelle Position als
* `location_update {lat, lon}` an den RVS-Server, damit Brain-Watcher
* mit `near()`-Conditions etwas zum Vergleichen haben.
*
* Default: AUS. Wird entweder vom User manuell in Settings angeschaltet
* oder von ARIA via location_tracking-RVS-Message (Brain-Tool
* `request_location_tracking`).
*
* Energie-Schutz: distanceFilter 30m, interval 15s. Echte Fahrt-Updates
* (Geschwindigkeit) kommen sauber durch, stationaer wird kaum gesendet.
*/
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Linking, PermissionsAndroid, Platform, ToastAndroid } from 'react-native';
import Geolocation from '@react-native-community/geolocation';
import rvs from './rvs';
import { acquireBackgroundAudio, releaseBackgroundAudio } from './backgroundAudio';
// Opt-in Background-GPS — Settings-Toggle "GPS auch im Hintergrund".
// Default AUS. Wenn AN: ACCESS_BACKGROUND_LOCATION-Permission noetig
// (kann nicht ueber Standard-Dialog angefordert werden, User muss in
// Android-Settings auf "Immer erlauben" gehen) + ForegroundService mit
// foregroundServiceType=location wird hochgezogen.
export const BG_GPS_STORAGE_KEY = 'aria_gps_background_enabled';
export async function isBackgroundGpsEnabled(): Promise<boolean> {
try {
const v = await AsyncStorage.getItem(BG_GPS_STORAGE_KEY);
return v === 'true';
} catch {
return false;
}
}
export async function setBackgroundGpsEnabled(enabled: boolean): Promise<void> {
try {
await AsyncStorage.setItem(BG_GPS_STORAGE_KEY, String(enabled));
} catch {}
}
/** Prueft ob ACCESS_BACKGROUND_LOCATION gewaehrt ist und oeffnet sonst die
* Android-App-Settings damit der User "Immer erlauben" auswaehlen kann.
* Returns true wenn permission ok, false wenn User Settings oeffnen muss. */
export async function ensureBackgroundLocationPermission(): Promise<boolean> {
if (Platform.OS !== 'android') return true;
try {
const granted = await PermissionsAndroid.check(
'android.permission.ACCESS_BACKGROUND_LOCATION' as any,
);
if (granted) return true;
// Erst FINE_LOCATION anfordern falls noch nicht da
const fine = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (fine !== PermissionsAndroid.RESULTS.GRANTED) return false;
// Ab Android 10+ kann BACKGROUND_LOCATION NICHT ueber den normalen
// PermissionsAndroid.request abgefragt werden — User muss in Settings
// auf "Immer erlauben" wechseln. Wir oeffnen die App-Settings-Seite.
ToastAndroid.show(
'Bitte in Android-Einstellungen unter Standort "Immer erlauben" auswaehlen',
ToastAndroid.LONG,
);
Linking.openSettings();
return false;
} catch (e) {
console.warn('[gps-track] BG-Permission-Check fehlgeschlagen:', e);
return false;
}
}
type Listener = (active: boolean) => void;
class GpsTrackingService {
private watchId: number | null = null;
private active = false;
private listeners: Set<Listener> = new Set();
// Defensive: nicht zu schnell oeffentlich togglen
private lastChangeAt = 0;
// Letzte bekannte Position — wird vom Heartbeat-Timer alle 60s erneut
// an die Bridge gesendet, sonst veraltet near() im Brain (NEAR_MAX_AGE_SEC
// = 5 min) wenn der User stationaer ist und distanceFilter keine Updates
// mehr triggert.
private lastLat: number | null = null;
private lastLon: number | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
isActive(): boolean {
return this.active;
}
onChange(cb: Listener): () => void {
this.listeners.add(cb);
return () => { this.listeners.delete(cb); };
}
private notify() {
for (const cb of this.listeners) {
try { cb(this.active); } catch {}
}
}
/** Beim App-Start: gespeicherten Zustand wiederherstellen (Default off). */
async restoreFromStorage(): Promise<void> {
try {
const v = await AsyncStorage.getItem('aria_gps_tracking');
if (v === 'true') {
console.log('[gps-track] Restore: war an, starte wieder');
this.start('Beim Start wiederhergestellt');
}
} catch {}
}
private async ensurePermission(): Promise<boolean> {
if (Platform.OS !== 'android') return true;
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'GPS-Tracking',
message: 'ARIA braucht laufende Standort-Updates damit GPS-Watcher (Blitzer-Warner, near()) funktionieren.',
buttonPositive: 'Erlauben',
buttonNegative: 'Abbrechen',
},
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (e) {
console.warn('[gps-track] Permission-Fehler:', e);
return false;
}
}
async start(reason: string = ''): Promise<boolean> {
if (this.active) return true;
const ok = await this.ensurePermission();
if (!ok) {
ToastAndroid.show('GPS-Tracking: Berechtigung abgelehnt', ToastAndroid.LONG);
return false;
}
// Background-GPS opt-in: wenn aktiv, ForegroundService mit type=location
// hochziehen. Brauche ACCESS_BACKGROUND_LOCATION (User muss in Android-
// Settings 'Immer erlauben' aktivieren). Wenn die fehlt, watchPosition
// liefert im Hintergrund keine Updates (nur Heartbeat sendet alte Werte).
const bgEnabled = await isBackgroundGpsEnabled();
if (bgEnabled) {
// Ohne ACCESS_BACKGROUND_LOCATION liefert watchPosition im Hintergrund
// NICHTS (Android 10+) → der Foreground-Service allein bringt nichts, und
// genau der Fall "Ankunft waehrend der Fahrt, Screen aus" faellt durch.
// Deshalb erst die Permission sicherstellen (oeffnet ggf. die Android-
// Settings fuer "Immer erlauben"), DANN den Location-Foreground-Service
// hochziehen — der haelt den Prozess wach, sodass watchPosition + der
// 60s-Heartbeat auch unter Doze weiterlaufen.
const bgOk = await ensureBackgroundLocationPermission();
if (!bgOk) {
console.warn('[gps-track] Background-Permission fehlt — Tracking nur im Vordergrund zuverlaessig');
}
try { await acquireBackgroundAudio('location'); } catch {}
}
try {
this.watchId = Geolocation.watchPosition(
(pos) => {
const lat = pos.coords.latitude;
const lon = pos.coords.longitude;
this.lastLat = lat;
this.lastLon = lon;
rvs.send('location_update' as any, { lat, lon });
},
(err) => {
console.warn('[gps-track] watchPosition error:', err?.code, err?.message);
},
{
enableHighAccuracy: true,
distanceFilter: 30, // erst senden wenn 30m gewandert
interval: 15000, // (Android) gewuenschte Frequenz
fastestInterval: 10000, // (Android) max Frequenz
} as any,
);
// Heartbeat: alle 60s die letzte bekannte Position erneut senden.
// Sonst bleibt der Brain-State stale wenn der User stationaer ist
// (distanceFilter blockt watchPosition-Updates) → near()-Watcher
// verwerfen die Position als veraltet (NEAR_MAX_AGE_SEC = 300s).
// Kein neuer GPS-Wakeup, nur Re-Send der letzten Werte → akkufreundlich.
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
this.heartbeatTimer = setInterval(() => {
if (this.lastLat != null && this.lastLon != null) {
rvs.send('location_update' as any, { lat: this.lastLat, lon: this.lastLon });
}
}, 60_000);
this.active = true;
this.lastChangeAt = Date.now();
this.notify();
AsyncStorage.setItem('aria_gps_tracking', 'true').catch(() => {});
ToastAndroid.show(
reason ? `GPS-Tracking aktiv (${reason})` : 'GPS-Tracking aktiv',
ToastAndroid.SHORT,
);
console.log('[gps-track] gestartet', reason ? `(${reason})` : '');
return true;
} catch (e: any) {
console.warn('[gps-track] start fehlgeschlagen:', e?.message);
return false;
}
}
stop(reason: string = ''): void {
if (!this.active) return;
if (this.watchId !== null) {
try { Geolocation.clearWatch(this.watchId); } catch {}
this.watchId = null;
}
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
// Location-Foreground-Service-Slot freigeben (falls vorher acquired)
try { releaseBackgroundAudio('location'); } catch {}
this.active = false;
this.lastChangeAt = Date.now();
this.notify();
AsyncStorage.setItem('aria_gps_tracking', 'false').catch(() => {});
ToastAndroid.show(
reason ? `GPS-Tracking aus (${reason})` : 'GPS-Tracking aus',
ToastAndroid.SHORT,
);
console.log('[gps-track] gestoppt', reason ? `(${reason})` : '');
}
async toggle(reason: string = ''): Promise<void> {
if (this.active) this.stop(reason);
else await this.start(reason);
}
}
export default new GpsTrackingService();
-248
View File
@@ -1,248 +0,0 @@
/**
* Verbose-Logging-Toggle: console.log laesst sich global stummschalten.
* console.warn/console.error bleiben immer an Fehler will man immer sehen.
*
* Default: an (true). Toggle ueber Settings Protokoll Verbose Logging.
* Beim Start wird der gespeicherte Wert geladen, vorher loggen wir normal.
*/
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform, DeviceEventEmitter, AppState } from 'react-native';
import rvs from './rvs';
// Lokales Event damit die SettingsScreen Live Logs / Events Tabs
// auch das sehen was die App SELBST loggt (reportAppDebug/Error).
// Bisher gingen die nur via RVS an die Bridge. Lokal sichtbar = Mama-
// tauglich Debug ohne curl.
export const APP_LOG_EVENT = 'AriaLocalAppLog';
interface LocalLogEntry {
ts: number;
level: 'info' | 'warn' | 'error';
scope: string;
message: string;
}
export const VERBOSE_LOGGING_KEY = 'aria_verbose_logging';
// Eigener Toggle fuer Debug-Logs die ueber RVS an die Bridge gehen
// (/shared/logs/app.log → Diagnostic /api/app-log). Damit der Default-User
// nicht stuendlich Traffic + Disk-Schreiben hat, dieser ist DEFAULT AUS.
// Stefan schaltet's nur ein wenn er ein konkretes Problem debuggen muss.
export const DEBUG_LOGS_TO_BRIDGE_KEY = 'aria_debug_logs_to_bridge';
// Original-console.log retten, damit wir die Wrapper jederzeit wieder
// "scharf" stellen koennen (sonst waere ein Toggle-an nach -aus tot).
const originalLog = console.log.bind(console);
const noop = () => {};
let _verbose = true;
let _debugLogsToBridge = false;
// ─── Crash-Kontext ohne adb ─────────────────────────────────────────
// Ein RUN_MARKER bleibt gesetzt, solange die App AKTIV laeuft; bei sauberem
// Wechsel in den Hintergrund wird er geloescht. Ist er beim naechsten Start
// noch da, ist der vorige Lauf unsauber gestorben (nativer Crash/OOM — der
// schreibt KEINEN JS-Fehler, taucht also sonst nirgends auf). Wir melden das
// dann via RVS mit dem letzten Breadcrumb (was die App zuletzt tat).
const RUN_MARKER_KEY = 'aria_run_marker';
const BREADCRUMB_KEY = 'aria_last_breadcrumb';
let _breadcrumb: { ts: number; scope: string; message: string } = { ts: 0, scope: '', message: '' };
let _breadcrumbDirty = false;
/** Letzte App-Aktivitaet merken — Crash-Kontext fuer den naechsten Boot. */
export function noteBreadcrumb(scope: string, message: string): void {
_breadcrumb = { ts: Date.now(), scope: scope || '', message: String(message || '').slice(0, 120) };
_breadcrumbDirty = true;
}
function applyState(): void {
console.log = _verbose ? originalLog : noop;
}
/** Wert aus AsyncStorage laden und anwenden. Beim App-Start aufrufen. */
export async function initLogger(): Promise<void> {
try {
const v = await AsyncStorage.getItem(VERBOSE_LOGGING_KEY);
_verbose = v !== 'false'; // default: true
} catch {}
try {
const d = await AsyncStorage.getItem(DEBUG_LOGS_TO_BRIDGE_KEY);
_debugLogsToBridge = d === 'true'; // default: false
} catch {}
applyState();
await _initCrashDetection();
}
// Native-Crash-Erkennung (ohne adb) — siehe RUN_MARKER-Kommentar oben.
async function _initCrashDetection(): Promise<void> {
try {
const marker = await AsyncStorage.getItem(RUN_MARKER_KEY);
if (marker) {
let bc: any = {};
try { bc = JSON.parse((await AsyncStorage.getItem(BREADCRUMB_KEY)) || '{}'); } catch {}
const gap = bc && bc.ts ? Math.round((Date.now() - bc.ts) / 1000) : -1;
// Verzoegert melden — RVS ist beim Boot oft noch nicht verbunden.
setTimeout(() => {
reportAppError({
scope: 'app.crash-detected',
level: 'warn',
message: `Voriger Lauf ohne sauberes Shutdown beendet (nativer Crash/OOM?). `
+ `Letzte Aktivitaet: [${(bc && bc.scope) || '?'}] ${(bc && bc.message) || '?'}`
+ (gap >= 0 ? ` (vor ~${gap}s)` : ''),
});
}, 6000);
}
await AsyncStorage.setItem(RUN_MARKER_KEY, String(Date.now()));
} catch {}
// Breadcrumb throttled persistieren (alle 5s, nur wenn geaendert).
setInterval(() => {
if (_breadcrumbDirty) {
_breadcrumbDirty = false;
AsyncStorage.setItem(BREADCRUMB_KEY, JSON.stringify(_breadcrumb)).catch(() => {});
}
}, 5000);
// Sauberer Hintergrund-Wechsel → Marker weg (kein Crash). Rueckkehr → wieder
// scharf. So melden nur echte Aktiv-Crashes, kein normales Backgrounden.
try {
AppState.addEventListener('change', (s) => {
if (s === 'background') AsyncStorage.removeItem(RUN_MARKER_KEY).catch(() => {});
else if (s === 'active') AsyncStorage.setItem(RUN_MARKER_KEY, String(Date.now())).catch(() => {});
});
} catch {}
}
export function isVerboseLogging(): boolean {
return _verbose;
}
export function setVerboseLogging(verbose: boolean): void {
_verbose = verbose;
applyState();
AsyncStorage.setItem(VERBOSE_LOGGING_KEY, String(verbose)).catch(() => {});
}
export function isDebugLogsToBridge(): boolean {
return _debugLogsToBridge;
}
export function setDebugLogsToBridge(enabled: boolean): void {
_debugLogsToBridge = enabled;
AsyncStorage.setItem(DEBUG_LOGS_TO_BRIDGE_KEY, String(enabled)).catch(() => {});
}
// ─── App-Crash-Reporting via RVS ────────────────────────────────────
//
// Wenn die App crasht — egal ob React-Render-Fehler (ErrorBoundary) oder
// ungefangener JS-Error (ErrorUtils-Handler) — schicken wir den Crash
// als RVS-Message vom Typ "app_log" an die Bridge. Die schreibt in
// /shared/logs/app.log, sodass wir/Diagnostic die Crashes mitlesen
// koennen ohne ADB.
interface AppErrorEvent {
scope: string;
message: string;
stack?: string;
level?: 'error' | 'warn' | 'info';
}
let _reportingInstalled = false;
/** Schickt einen App-Fehler via RVS an die Bridge. */
export function reportAppError(ev: AppErrorEvent): void {
const ts = Date.now();
noteBreadcrumb(ev.scope, ev.message);
try {
rvs.send('app_log' as any, {
ts,
platform: Platform.OS,
level: ev.level || 'error',
scope: ev.scope,
message: ev.message,
stack: (ev.stack || '').slice(0, 8000),
});
} catch {
// RVS noch nicht connected — Fehler geht im console weiter.
}
// Lokal in den App-Logs-Tab emitten — Errors gehen IMMER durch
// (unabhaengig vom Debug-Toggle).
try {
const entry: LocalLogEntry = {
ts, level: ev.level || 'error', scope: ev.scope, message: ev.message,
};
DeviceEventEmitter.emit(APP_LOG_EVENT, entry);
} catch {}
// Plus lokal: console.error, damit Stefan's adb (wenn doch mal verfuegbar)
// den Crash sieht.
console.error(`[app-error scope=${ev.scope}]`, ev.message, '\n', ev.stack || '');
}
/** Schickt eine Debug-/Info-Message via RVS an die Bridge. Landet ebenfalls
* in /shared/logs/app.log abrufbar via `curl /api/app-log?lines=N`.
* Im Gegensatz zu reportAppError: keine Stacktrace, level=info, kein
* console.error. Fuer Live-Diagnose im Hintergrund wenn ADB nicht da ist.
*
* Nur aktiv wenn Settings Protokoll Debug-Logs an Bridge AN ist.
* Default aus damit Mama-Modus keine Disk-Schreiblast hat. Error-Reports
* (reportAppError) gehen weiterhin IMMER durch. */
export function reportAppDebug(scope: string, message: string): void {
// Breadcrumb IMMER aktualisieren (auch wenn Debug-Logs-an-Bridge aus ist) —
// fuer den Crash-Kontext beim naechsten Boot.
noteBreadcrumb(scope, message);
if (!_debugLogsToBridge) return;
const ts = Date.now();
const trimmed = String(message).slice(0, 2000);
try {
rvs.send('app_log' as any, {
ts,
platform: Platform.OS,
level: 'info',
scope,
message: trimmed,
});
} catch {}
// Plus lokal in den App-Logs-Tab emitten — damit Stefan in der App
// selbst (Settings → Protokoll → Live Logs) sieht was passiert,
// ohne curl gegen Bridge.
try {
const entry: LocalLogEntry = { ts, level: 'info', scope, message: trimmed };
DeviceEventEmitter.emit(APP_LOG_EVENT, entry);
} catch {}
}
/** Installiert einen globalen JS-Error-Handler der ungefangene Errors via
* RVS an die Bridge schickt. Beim App-Start aufrufen. */
export function installGlobalCrashReporter(): void {
if (_reportingInstalled) return;
_reportingInstalled = true;
try {
const g: any = global as any;
const prev = g.ErrorUtils?.getGlobalHandler?.();
g.ErrorUtils?.setGlobalHandler?.((err: any, isFatal: boolean) => {
reportAppError({
scope: isFatal ? 'global-fatal' : 'global-nonfatal',
message: (err && err.message) || String(err),
stack: err && err.stack,
});
// Original-Handler weiterhin aufrufen damit React-Native das System-
// Crash-Overlay zeigt (im Dev-Build) bzw. in Production sauber stirbt.
if (typeof prev === 'function') {
try { prev(err, isFatal); } catch {}
}
});
// unhandled Promise-Rejections — manche RN-Versionen haben das nicht
// automatisch im ErrorUtils.
g.HermesInternal?.enablePromiseRejectionTracker?.({
allRejections: true,
onUnhandled: (id: number, err: any) => {
reportAppError({
scope: 'promise-unhandled',
level: 'warn',
message: (err && err.message) || String(err),
stack: err && err.stack,
});
},
});
} catch {
// ErrorUtils nicht da → nix machen
}
}
-262
View File
@@ -1,262 +0,0 @@
/**
* PhoneCall-Service pausiert ARIA bei Telefonaten:
*
* 1. Klassischer Mobilfunk-Anruf via TelephonyManager (PhoneCallModule.kt)
* Status: idle / ringing / offhook
*
* 2. VoIP-Anrufe (WhatsApp, Signal, Discord, Telegram, Teams, ...) via
* AudioFocus-Loss-Event (AudioFocusModule.kt). Diese Apps requestn
* AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE wenn ein Anruf reinkommt wir
* bekommen ein "loss" Event und reagieren genauso wie auf RINGING.
*
* In beiden Faellen wird audioService.haltAllPlayback() + wakeWordService.
* pauseForCall() gerufen. Bei call-end (idle / focus-gain) resumeFromCall.
*
* Permission READ_PHONE_STATE ist nur fuer Pfad 1 noetig Pfad 2 braucht
* keine extra Berechtigung weil unser eigener AudioFocus-Listener feuert.
*/
import {
NativeEventEmitter,
NativeModules,
PermissionsAndroid,
Platform,
ToastAndroid,
} from 'react-native';
import audioService from './audio';
import wakeWordService from './wakeword';
interface PhoneCallNative {
start(): Promise<boolean>;
stop(): Promise<boolean>;
}
const { PhoneCall } = NativeModules as { PhoneCall?: PhoneCallNative };
type PhoneState = 'idle' | 'ringing' | 'offhook';
class PhoneCallService {
private started: boolean = false;
private subscription: { remove: () => void } | null = null;
private focusSubscription: { remove: () => void } | null = null;
private lastState: PhoneState = 'idle';
/** Damit Resume nach VoIP-Loss nicht doppelt feuert wenn auch
* TelephonyManager-IDLE-Event kommt. */
private interruptedByFocus: boolean = false;
/** True wenn der TelephonyManager-Listener (Pfad 1) wirklich registriert
* ist. False wenn READ_PHONE_STATE abgelehnt wurde oder Native nicht ging. */
private telephonyAttached: boolean = false;
/** Status fuer Diagnose: laeuft die Anruf-Erkennung tatsaechlich? */
status(): { focusAttached: boolean; telephonyAttached: boolean } {
return {
focusAttached: this.focusSubscription !== null,
telephonyAttached: this.telephonyAttached,
};
}
/** Nach App-Resume: pruefen ob die Listener noch leben. Wenn der
* TelephonyManager-Listener verloren ging (kann passieren wenn der
* React-Bridge-Context recreated wurde), neu attachen. */
async refresh(): Promise<void> {
if (!this.started) return;
if (this.telephonyAttached) return; // alles ok
if (!PhoneCall) return;
try {
const ok = await PhoneCall.start();
if (ok) {
if (!this.subscription) {
const emitter = new NativeEventEmitter(NativeModules.PhoneCall as any);
this.subscription = emitter.addListener(
'PhoneCallStateChanged',
(e: { state: PhoneState }) => this._onStateChanged(e.state),
);
}
this.telephonyAttached = true;
console.log('[PhoneCall] refresh: TelephonyManager-Listener re-attached');
}
} catch (err: any) {
console.warn('[PhoneCall] refresh fehlgeschlagen:', err?.message || err);
}
}
async start(): Promise<boolean> {
if (this.started || Platform.OS !== 'android') return false;
// 1. AudioFocus-Listener IMMER registrieren — fangs VoIP-Calls (WhatsApp,
// Signal, Discord etc.) abdecken, brauchen keine Permission.
try {
const focusEmitter = new NativeEventEmitter(NativeModules.AudioFocus as any);
this.focusSubscription = focusEmitter.addListener(
'AudioFocusChanged',
(e: { type: 'loss' | 'loss_transient' | 'gain' }) => this._onFocusChanged(e.type),
);
console.log('[PhoneCall] AudioFocus-Listener aktiv (fuer VoIP-Calls)');
} catch (err: any) {
console.warn('[PhoneCall] AudioFocus-Subscription gescheitert', err?.message || err);
}
// 2. TelephonyManager-Listener — fuer klassische Mobilfunk-Anrufe
if (PhoneCall) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE,
{
title: 'ARIA Cockpit — Anruf-Erkennung',
message: 'Damit ARIA bei einem eingehenden Anruf nicht weiterredet, '
+ 'darf die App den Anruf-Status sehen (Klingeln/Aktiv/Aufgelegt). '
+ 'Es werden keine Anrufdaten gelesen oder gespeichert.',
buttonPositive: 'Erlauben',
buttonNegative: 'Spaeter',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
const ok = await PhoneCall.start();
if (ok) {
const emitter = new NativeEventEmitter(NativeModules.PhoneCall as any);
this.subscription = emitter.addListener(
'PhoneCallStateChanged',
(e: { state: PhoneState }) => this._onStateChanged(e.state),
);
this.telephonyAttached = true;
console.log('[PhoneCall] TelephonyManager-Listener aktiv');
} else {
console.warn('[PhoneCall] PhoneCall.start() lieferte false — Native-Listener nicht aktiv');
}
} else {
console.warn('[PhoneCall] READ_PHONE_STATE abgelehnt — VoIP-Calls werden trotzdem ueber AudioFocus erkannt');
}
} catch (err: any) {
console.warn('[PhoneCall] TelephonyManager-Setup gescheitert:', err?.message || err);
}
}
this.started = true;
return true;
}
async stop(): Promise<void> {
if (!this.started) return;
try { this.subscription?.remove(); } catch {}
try { this.focusSubscription?.remove(); } catch {}
this.subscription = null;
this.focusSubscription = null;
if (PhoneCall) {
try { await PhoneCall.stop(); } catch {}
}
this.started = false;
this.lastState = 'idle';
this.interruptedByFocus = false;
this.telephonyAttached = false;
}
private _onStateChanged(state: PhoneState): void {
if (state === this.lastState) return;
const prev = this.lastState;
console.log('[PhoneCall] State: %s → %s', prev, state);
this.lastState = state;
if (state === 'ringing' || state === 'offhook') {
this._haltForCall(state === 'ringing' ? 'Anruf — ARIA pausiert' : 'Im Gespraech — ARIA pausiert');
} else if (state === 'idle' && prev !== 'idle') {
// Wenn schon durch AudioFocus-Loss pausiert wurde, NICHT doppelt resumen.
// Der Focus-Gain-Event triggert das Resume.
if (!this.interruptedByFocus) {
this._resumeAfterCall('Anruf beendet — ARIA wieder aktiv');
}
}
}
/** AudioFocus-Loss = irgendeine andere App hat den Focus uebernommen.
* Das passiert bei VoIP-Anrufen (was wir wollen) ABER auch bei normalen
* Audio-Playern (anderer Player startet, Notification-Sound, sogar
* unsere eigenen Sound-Calls beim Play-Button). Daher checken wir den
* AudioMode nur IN_CALL (2) oder IN_COMMUNICATION (3) zaehlt als Anruf. */
private async _onFocusChanged(type: 'loss' | 'loss_transient' | 'gain'): Promise<void> {
if (type === 'loss' || type === 'loss_transient') {
// Schon durch klassischen TelephonyManager pausiert? Dann nichts doppeln.
if (this.lastState === 'ringing' || this.lastState === 'offhook') return;
// Mode pruefen — nur echte Anrufe behandeln.
let mode = -1;
try { mode = await (NativeModules.AudioFocus as any)?.getMode?.(); } catch {}
if (mode !== 2 && mode !== 3) {
// NORMAL-Mode → kein Anruf (Stefan hat z.B. Play-Button gedrueckt
// oder Spotify hat sich neu reingedraengelt). Keine Toasts.
console.log('[PhoneCall] FOCUS_LOSS ignoriert (AudioMode=%d, kein Call)', mode);
return;
}
this.interruptedByFocus = true;
this._haltForCall('Anruf erkannt (VoIP) — ARIA pausiert');
// Pollen, weil GAIN nicht zuverlaessig kommt (wir releasen den Focus
// selbst beim halt → kein automatischer GAIN). AudioMode != IN_COMMUNICATION
// = Call vorbei.
this._startVoipResumePoll();
} else if (type === 'gain') {
if (this.interruptedByFocus) {
this.interruptedByFocus = false;
this._stopVoipResumePoll();
this._resumeAfterCall('Audio frei — ARIA wieder aktiv');
}
}
}
/** Polling-Fallback: alle 3s checken ob AudioMode wieder NORMAL ist. */
private voipPollTimer: ReturnType<typeof setInterval> | null = null;
private _startVoipResumePoll(): void {
if (this.voipPollTimer) return;
this.voipPollTimer = setInterval(async () => {
if (!this.interruptedByFocus) {
this._stopVoipResumePoll();
return;
}
try {
const mode = await (NativeModules.AudioFocus as any)?.getMode?.();
// 0 = MODE_NORMAL — Call ist vorbei
if (typeof mode === 'number' && mode === 0) {
this.interruptedByFocus = false;
this._stopVoipResumePoll();
this._resumeAfterCall('Anruf beendet — ARIA wieder aktiv');
}
} catch {}
}, 3000);
}
private _stopVoipResumePoll(): void {
if (this.voipPollTimer) {
clearInterval(this.voipPollTimer);
this.voipPollTimer = null;
}
}
private _haltForCall(toast: string): void {
// Position merken bevor wir den Stream killen — fuer Auto-Resume.
audioService.captureInterruption();
// pauseForCall (statt haltAllPlayback): pcmBuffer + messageId bleiben,
// weitere Chunks werden weiter gesammelt damit isFinal die WAV schreibt.
audioService.pauseForCall(toast);
wakeWordService.pauseForCall().catch(() => {});
ToastAndroid.show(toast, ToastAndroid.SHORT);
}
private _resumeAfterCall(toast: string): void {
// Anruf-Pause aufheben — neue Chunks duerfen wieder direkt abgespielt
// werden (falls die Bridge mid-Anruf isFinal noch nicht geschickt hat).
audioService.endCallPause();
wakeWordService.resumeFromCall().catch(() => {});
ToastAndroid.show(toast, ToastAndroid.SHORT);
// 800ms warten bevor Auto-Resume — sonst kollidiert ARIA's neuer Focus-
// Request mit Spotify's Auto-Resume nach Anruf-Ende. System haengt nach
// dem Auflegen noch im IN_CALL-Mode-Uebergang, Spotify schaut auf Focus-
// Gain und wuerde sofort wieder LOSS sehen → bleibt pausiert.
// Mit Delay: Spotify resumed kurz, dann pausiert ARIA wieder ordnungs-
// gemaess. Wenn ARIA nichts pending hat, bleibt Spotify einfach an.
setTimeout(() => {
audioService.resumeFromInterruption(30000).then(ok => {
if (ok) {
console.log('[PhoneCall] Auto-Resume von gemerkter Position gestartet');
}
}).catch(() => {});
}, 800);
}
}
const phoneCallService = new PhoneCallService();
export default phoneCallService;
-105
View File
@@ -1,105 +0,0 @@
/**
* projectFocus leichter Publish/Subscribe-Spiegel des aktuell fokussierten
* Projekt-Kontexts.
*
* ChatScreen bleibt die Quelle der Wahrheit fuer sein eigenes Rendering und
* publiziert hier bei jedem Focus-/Namens-/Kind-Wechsel EINWEG hinein. Der
* Workspace-Canvas liest/abonniert das Singleton, um zu wissen welches Projekt
* gerade aktiv ist und ob es ein Code-Projekt ist ohne dass ChatScreen den
* Workspace kennen oder umgebaut werden muss.
*
* Muster wie services/rvs.ts (Singleton mit Listener-Liste + Unsubscribe).
*/
export type ProjectKind = 'code' | 'chat';
export interface FocusSnapshot {
/** '' = Hauptchat, sonst Projekt-ID */
focusedProjectId: string;
projectNameById: Record<string, string>;
projectKindById: Record<string, ProjectKind>;
}
type Sub = (snap: FocusSnapshot) => void;
class ProjectFocus {
private snap: FocusSnapshot = {
focusedProjectId: '',
projectNameById: {},
projectKindById: {},
};
private subs: Sub[] = [];
// --- Getter (synchron, fuer Nicht-Reaktive Leser) ---
get(): FocusSnapshot {
return this.snap;
}
getFocusedProjectId(): string {
return this.snap.focusedProjectId;
}
getProjectName(id: string): string {
return this.snap.projectNameById[id] || id;
}
/** Default 'chat' ein Projekt ist erst 'code' wenn es explizit so
* markiert wurde (set_project_kind) oder ein Code-/Desktop-Signal kam. */
getProjectKind(id: string): ProjectKind {
return this.snap.projectKindById[id] || 'chat';
}
// --- Publisher (von ChatScreen aufgerufen) ---
setFocus(id: string): void {
if (this.snap.focusedProjectId === id) return;
this.snap = { ...this.snap, focusedProjectId: id };
this.emit();
}
setNames(map: Record<string, string>): void {
// Flacher Merge — behaelt bereits bekannte Namen, ueberschreibt neue.
this.snap = {
...this.snap,
projectNameById: { ...this.snap.projectNameById, ...map },
};
this.emit();
}
setKind(id: string, kind: ProjectKind): void {
if (this.snap.projectKindById[id] === kind) return;
this.snap = {
...this.snap,
projectKindById: { ...this.snap.projectKindById, [id]: kind },
};
this.emit();
}
setKinds(map: Record<string, ProjectKind>): void {
this.snap = {
...this.snap,
projectKindById: { ...this.snap.projectKindById, ...map },
};
this.emit();
}
// --- Abo ---
/** Registriert einen Listener und liefert sofort den aktuellen Snapshot. */
subscribe(cb: Sub): () => void {
this.subs.push(cb);
cb(this.snap);
return () => {
this.subs = this.subs.filter(s => s !== cb);
};
}
private emit(): void {
const s = this.snap;
this.subs.forEach(cb => cb(s));
}
}
const projectFocus = new ProjectFocus();
export default projectFocus;
+3 -31
View File
@@ -83,39 +83,21 @@ class RVSConnection {
// --- Verbindung ---
/** Verbindung zum RVS aufbauen. force=true: bestehende Connection hart
* schliessen + neu verbinden (auch wenn JS denkt readyState=OPEN kann
* nach Hintergrund-Pause ein Zombie-WS sein wo TCP tot ist aber JS-State
* noch OPEN zeigt; in dem Fall war "Bereits verbunden" ein No-Op und
* Stefan musste manuell zigmal klicken). */
connect(force: boolean = false): void {
/** Verbindung zum RVS aufbauen */
connect(): void {
if (!this.config) {
this.log('warn', 'Keine Verbindungskonfiguration vorhanden');
return;
}
if (!force && this.ws?.readyState === WebSocket.OPEN) {
if (this.ws?.readyState === WebSocket.OPEN) {
this.log('info', 'Bereits verbunden');
return;
}
// Wenn ein WS-Objekt da ist (Zombie oder lebend), sauber abreissen
// bevor wir einen neuen aufbauen — sonst gibt's zwei parallele
// Verbindungen + doppelte Events.
if (this.ws) {
this.log('info', 'Bestehende WS-Verbindung wird geschlossen vor Neu-Connect');
try {
this.ws.onclose = null; // verhindert dass scheduleReconnect doppelt feuert
this.ws.onerror = null;
this.ws.close();
} catch (_) {}
this.ws = null;
}
this.shouldReconnect = true;
this.reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
this.usingTLSFallback = false;
this.clearTimers();
this.log('info', `Verbindungsaufbau zu ${this.config.host}:${this.config.port} (TLS: ${this.config.useTLS ? 'ja' : 'nein'})`);
this.establishConnection();
}
@@ -230,16 +212,6 @@ class RVSConnection {
this.ws = null;
this.setState('disconnected');
// Sticky-Fallback-Reset: beim naechsten Reconnect wieder primary
// (wss://) versuchen statt fuer immer auf ws:// zu kleben. War
// der Hauptgrund warum die App nach Hintergrund-Rueckkehr nicht
// mehr verband — TLS-Handshake-Timeout in einem Reconnect → Fallback
// auf ws:// → Caddy refused → endlos im Fallback haengen.
if (this.usingTLSFallback) {
this.log('info', 'Reset TLS-Fallback fuer naechsten Reconnect (zurueck zu wss://)');
this.usingTLSFallback = false;
}
if (this.shouldReconnect) {
this.scheduleReconnect();
}
+1 -75
View File
@@ -29,11 +29,6 @@ class UpdateService {
private downloading = false;
constructor() {
// Beim Start alte APK-Reste aus dem Cache wegraeumen — wenn diese App
// laeuft, sind frueher heruntergeladene APKs entweder schon installiert
// oder unvollstaendig gewesen. Spart sonst pro Update 20-30MB auf dem Handy.
this.cleanupOldApks().catch(() => {});
// Auf update_available Nachrichten lauschen
rvs.onMessage((msg: RVSMessage) => {
if (msg.type === 'update_available' as any) {
@@ -50,71 +45,6 @@ class UpdateService {
});
}
/** Sucht ueberall wo .apk-Dateien herumliegen koennten. */
private async _apkSearchDirs(): Promise<string[]> {
const dirs = [RNFS.CachesDirectoryPath, RNFS.DocumentDirectoryPath];
if ((RNFS as any).ExternalCachesDirectoryPath) {
dirs.push((RNFS as any).ExternalCachesDirectoryPath);
}
if (RNFS.ExternalDirectoryPath) {
dirs.push(RNFS.ExternalDirectoryPath);
}
return dirs;
}
/** Raeumt alte heruntergeladene APK-Dateien aus den App-Verzeichnissen auf.
* Public damit Settings den Button "Update-Cache leeren" benutzen kann. */
async cleanupOldApks(keepCurrentName?: string): Promise<{ removed: number; freedMB: number }> {
const dirs = await this._apkSearchDirs();
let removed = 0;
let freed = 0;
for (const dir of dirs) {
try {
if (!(await RNFS.exists(dir))) continue;
const files = await RNFS.readDir(dir);
const apks = files.filter(f => /\.apk$/i.test(f.name));
for (const f of apks) {
if (keepCurrentName && f.name === keepCurrentName) continue;
try {
const size = parseInt(f.size as any, 10) || 0;
await RNFS.unlink(f.path);
removed += 1;
freed += size;
console.log(`[Update] APK geloescht: ${f.path} (${(size / 1024 / 1024).toFixed(1)}MB)`);
} catch (err: any) {
console.warn(`[Update] APK-Loeschen fehlgeschlagen: ${f.path} (${err?.message || err})`);
}
}
} catch (err: any) {
console.warn(`[Update] Cleanup-Fehler in ${dir}: ${err?.message || err}`);
}
}
const freedMB = freed / 1024 / 1024;
if (removed > 0) {
console.log(`[Update] Cleanup fertig: ${removed} APK${removed === 1 ? '' : 's'} entfernt, ${freedMB.toFixed(1)}MB freigegeben`);
}
return { removed, freedMB };
}
/** Aktuelle Groesse aller APK-Dateien in den App-Verzeichnissen (in MB). */
async getApkCacheSize(): Promise<{ count: number; totalMB: number }> {
const dirs = await this._apkSearchDirs();
let count = 0;
let total = 0;
for (const dir of dirs) {
try {
if (!(await RNFS.exists(dir))) continue;
const files = await RNFS.readDir(dir);
for (const f of files) {
if (!f.isFile() || !/\.apk$/i.test(f.name)) continue;
count += 1;
total += parseInt(f.size as any, 10) || 0;
}
} catch {}
}
return { count, totalMB: total / 1024 / 1024 };
}
/** Bei App-Start Update pruefen */
checkForUpdate(): void {
if (this.checking) return;
@@ -181,15 +111,11 @@ class UpdateService {
});
});
// Vor dem Schreiben alte APKs im Cache wegraeumen — falls mehrere
// Updates in einer Session gezogen werden
await this.cleanupOldApks();
// Base64 als APK-Datei speichern
const destPath = `${RNFS.CachesDirectoryPath}/${apkData.fileName}`;
await RNFS.writeFile(destPath, apkData.base64, 'base64');
const fileSize = await RNFS.stat(destPath);
console.log(`[Update] APK gespeichert: ${destPath} (${(Number(fileSize.size) / 1024 / 1024).toFixed(1)}MB)`);
console.log(`[Update] APK gespeichert: ${destPath} (${(parseInt(fileSize.size) / 1024 / 1024).toFixed(1)}MB)`);
// APK installieren via natives ApkInstaller Module (FileProvider + Intent)
if (Platform.OS === 'android') {
-57
View File
@@ -1,57 +0,0 @@
/**
* viewMode App-Ansicht: 'compact' (klassischer Vollbild-Chat wie vor 0.2.2.0)
* oder 'cockpit' (zoombarer Kachel-Desktop).
*
* Default 'compact' fuer normale Nutzung aendert sich nichts (Mama-tauglich).
* Umschaltbar ueber den Header-Button; persistiert in AsyncStorage. Muster wie
* services/rvs.ts (Singleton mit Listener-Liste).
*/
import AsyncStorage from '@react-native-async-storage/async-storage';
export type ViewModeValue = 'compact' | 'cockpit';
const KEY = 'aria_view_mode';
type Sub = (mode: ViewModeValue) => void;
class ViewMode {
private mode: ViewModeValue = 'compact';
private subs: Sub[] = [];
private loaded = false;
constructor() {
AsyncStorage.getItem(KEY).then((v) => {
if (v === 'cockpit' || v === 'compact') this.mode = v;
this.loaded = true;
this.emit();
}).catch(() => { this.loaded = true; });
}
get(): ViewModeValue { return this.mode; }
isLoaded(): boolean { return this.loaded; }
set(mode: ViewModeValue): void {
if (this.mode === mode) return;
this.mode = mode;
AsyncStorage.setItem(KEY, mode).catch(() => {});
this.emit();
}
toggle(): void {
this.set(this.mode === 'compact' ? 'cockpit' : 'compact');
}
subscribe(cb: Sub): () => void {
this.subs.push(cb);
cb(this.mode);
return () => { this.subs = this.subs.filter((s) => s !== cb); };
}
private emit(): void {
const m = this.mode;
this.subs.forEach((cb) => cb(m));
}
}
const viewMode = new ViewMode();
export default viewMode;
-71
View File
@@ -1,71 +0,0 @@
/**
* Spielt einen kurzen "Bereit"-Sound (Airplane Ding-Dong) wenn das Mikrofon
* nach Wake-Word-Erkennung wirklich offen ist. Datei liegt in
* android/app/src/main/res/raw/wake_ready_sound.mp3 wird ueber Android's
* Resource-System per react-native-sound abgespielt.
*
* Toggle: AsyncStorage-Key 'aria_wake_ready_sound_enabled' (default true).
*/
import Sound from 'react-native-sound';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const WAKE_READY_SOUND_STORAGE_KEY = 'aria_wake_ready_sound_enabled';
Sound.setCategory('Playback', false);
let cachedSound: Sound | null = null;
let cachedFailed = false;
function getSound(): Promise<Sound | null> {
if (cachedFailed) return Promise.resolve(null);
if (cachedSound) return Promise.resolve(cachedSound);
return new Promise(resolve => {
const s = new Sound('wake_ready_sound', Sound.MAIN_BUNDLE, (err) => {
if (err) {
console.warn('[WakeReadySound] Konnte nicht geladen werden:', err);
cachedFailed = true;
resolve(null);
return;
}
cachedSound = s;
resolve(s);
});
});
}
/** True wenn der User den "Bereit"-Sound aktiviert hat. Default: true. */
export async function isWakeReadySoundEnabled(): Promise<boolean> {
try {
const raw = await AsyncStorage.getItem(WAKE_READY_SOUND_STORAGE_KEY);
if (raw === null) return true; // Default an
return raw === 'true';
} catch {
return true;
}
}
export async function setWakeReadySoundEnabled(enabled: boolean): Promise<void> {
try {
await AsyncStorage.setItem(WAKE_READY_SOUND_STORAGE_KEY, String(enabled));
} catch {}
}
/** Spielt den Bereit-Sound einmal ab non-blocking. Wenn der User ihn
* in den Settings deaktiviert hat oder die Datei nicht ladbar ist,
* passiert einfach nichts. */
export async function playWakeReadySound(): Promise<void> {
if (!(await isWakeReadySoundEnabled())) return;
const s = await getSound();
if (!s) return;
try {
s.stop(() => {
s.setCurrentTime(0);
s.play((success) => {
if (!success) console.warn('[WakeReadySound] Wiedergabe fehlgeschlagen');
});
});
} catch (e) {
console.warn('[WakeReadySound] play() Exception:', e);
}
}
+99 -689
View File
@@ -1,291 +1,107 @@
/**
* Gespraechsmodus / Wake Word Service
*
* Wake-Word-Engine: openWakeWord (https://github.com/dscripka/openWakeWord),
* komplett on-device via ONNX Runtime in Native-Kotlin (siehe
* OpenWakeWordModule.kt + assets/openwakeword/). Kein API-Key, kein Cloud-
* Roundtrip, kein Cent Lizenzgebuehren.
*
* Drei Zustaende:
* off Ohr aus, nichts laeuft
* armed Ohr aktiv, openWakeWord hoert passiv auf das Wake-Word.
* Das Mikro ist von OpenWakeWord belegt; AudioRecorder ist aus.
* conversing Wake-Word getriggert (oder Ohr-Tap manuell):
* aktive Konversation. OpenWakeWord pausiert (gibt Mikro frei),
* armed Ohr aktiv, Porcupine hoert passiv auf das Wake-Word.
* Das Mikro ist von Porcupine belegt; AudioRecorder ist aus.
* conversing Wake-Word getriggert (oder Ohr-Tap ohne Wake-Word):
* aktive Konversation. Porcupine pausiert (gibt Mikro frei),
* AudioRecorder uebernimmt fuer die Aufnahme.
* Nach jeder ARIA-Antwort oeffnet das Mikro fuer X Sekunden
* (Conversation-Window). Stille im Fenster zurueck zu armed.
*
* Faellt das Native-Modul aus (alte App-Version, ONNX-Init-Fehler), geht
* 'start' direkt in 'conversing' (klassischer Direkt-Aufnahme-Modus).
* Wake-Word fallback: ist kein Picovoice-Access-Key gesetzt, geht 'start'
* direkt in 'conversing' (klassischer Gespraechsmodus). 'endConversation'
* geht dann nach 'off' statt 'armed'.
*/
import { NativeEventEmitter, NativeModules, ToastAndroid } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { acquireBackgroundAudio } from './backgroundAudio';
type WakeWordCallback = () => void;
type StateCallback = (state: WakeWordState) => void;
type PassiveListenCallback = () => void;
export type WakeWordState = 'off' | 'armed' | 'conversing' | 'listening';
/** Reine HANG-Notbremse fuer den Passive-Listen-Modus. Das echte Ende regelt IMMER
* die passive Aufnahme selbst: Stille-Toleranz (User pausiert), No-Speech (User
* sagt gar nichts) oder Hard-Cap (max. Aufnahmedauer, ~5min) ChatScreen ruft
* dann exitPassiveListening. Dieser Timer darf aktives Reden NIE abschneiden
* deshalb LÄNGER als der Hard-Cap (nur falls ein Endpoint-Event mal verloren geht
* und der State sonst ewig 'listening' bliebe). Das alte 30s-Fenster, das lange
* Antworten mitten im Satz kappte, ist damit raus. */
const PASSIVE_BACKSTOP_MS = 10 * 60_000;
export type WakeWordState = 'off' | 'armed' | 'conversing';
export const WAKE_ACCESS_KEY_STORAGE = 'aria_wake_access_key';
export const WAKE_KEYWORD_STORAGE = 'aria_wake_keyword';
// Wake-Word-Empfindlichkeit (openWakeWord-Threshold). Hoeher = strenger =
// weniger Fehlauslösung, aber man muss deutlicher/lauter sprechen (fuehlt sich
// "traege" an). Fehlausloeser werden ueber Speaker-ID (E3) ohnehin verworfen,
// deshalb darf der Default empfindlicher sein. 0.45 (war 0.6/0.5). 0..1.
export const WAKE_THRESHOLD_DEFAULT = 0.45;
export const WAKE_THRESHOLD_MIN = 0.3;
export const WAKE_THRESHOLD_MAX = 0.9;
export const WAKE_THRESHOLD_STORAGE_KEY = 'aria_wake_threshold';
export async function loadWakeThreshold(): Promise<number> {
try {
const raw = await AsyncStorage.getItem(WAKE_THRESHOLD_STORAGE_KEY);
if (raw != null) {
const n = parseFloat(raw);
if (isFinite(n) && n >= WAKE_THRESHOLD_MIN && n <= WAKE_THRESHOLD_MAX) return n;
}
} catch {}
return WAKE_THRESHOLD_DEFAULT;
}
export async function saveWakeThreshold(v: number): Promise<void> {
await AsyncStorage.setItem(WAKE_THRESHOLD_STORAGE_KEY, String(v));
}
// Hintergrund-Wake: darf das Wake-Wort auch triggern, wenn die App im
// Hintergrund / der Bildschirm gesperrt ist? Default AUS — im Hintergrund
// sind die meisten „Trigger" Fehlalarme (TV, Husten, AudioFocus-Spikes).
// AN = auch bei gesperrtem Bildschirm zuhoeren. Die native Erkennung laeuft
// ohnehin durch (Foreground-Service + Wake-Locks) — dieser Schalter oeffnet
// nur das JS-Gate in onWakeDetected.
export const BG_WAKE_STORAGE_KEY = 'aria_bg_wake_enabled';
export async function loadBgWakeEnabled(): Promise<boolean> {
try {
return (await AsyncStorage.getItem(BG_WAKE_STORAGE_KEY)) === 'true';
} catch {
return false;
}
}
export async function saveBgWakeEnabled(enabled: boolean): Promise<void> {
try {
await AsyncStorage.setItem(BG_WAKE_STORAGE_KEY, String(enabled));
} catch {}
}
// Wake-Wort-Bestaetigung: nach einem openWakeWord-Trigger den Vor-Trigger-Audio
// von Voxtral gegenpruefen lassen ("war das wirklich 'Computer' oder Musik?").
// Killt Musik-Fehltrigger (z.B. Pet Shop Boys), kostet ~0.5-1s Extra-Latenz pro
// Wake. Default AUS (opt-in), fail-open. Braucht das native preTriggerPcm im
// Event (neueres APK) — ohne das macht die App normal weiter.
export const WAKE_CONFIRM_STORAGE_KEY = 'aria_wake_confirm_enabled';
export async function loadWakeConfirmEnabled(): Promise<boolean> {
try {
return (await AsyncStorage.getItem(WAKE_CONFIRM_STORAGE_KEY)) === 'true';
} catch {
return false;
}
}
export async function saveWakeConfirmEnabled(enabled: boolean): Promise<void> {
try {
await AsyncStorage.setItem(WAKE_CONFIRM_STORAGE_KEY, String(enabled));
} catch {}
}
/** Verfuegbare Wake-Words entsprechen den .onnx Dateien in
* android/app/src/main/assets/openwakeword/. Custom-Keywords (eigenes
* Training via openwakeword Notebook) muessen aktuell als Asset eingebaut
* werden Diagnostic-Upload ist Phase 2. */
export const WAKE_KEYWORDS = [
'hey_jarvis',
/** Built-In Keywords von Picovoice pre-trained, sofort einsetzbar.
* Custom Keywords (z.B. "ARIA") brauchen ein .ppn File aus der Picovoice
* Console wird spaeter ueber Diagnostic uploadbar. */
export const BUILTIN_KEYWORDS = [
'jarvis',
'computer',
'picovoice',
'porcupine',
'bumblebee',
'terminator',
'alexa',
'hey_mycroft',
'hey_rhasspy',
'hey google',
'ok google',
'hey siri',
] as const;
export type WakeKeyword = typeof WAKE_KEYWORDS[number];
export const DEFAULT_KEYWORD: WakeKeyword = 'hey_jarvis';
/** Hilfs-Mapping fuer die Anzeige im UI. */
export const KEYWORD_LABELS: Record<WakeKeyword, string> = {
hey_jarvis: 'Hey Jarvis',
computer: 'Computer',
alexa: 'Alexa',
hey_mycroft: 'Hey Mycroft',
hey_rhasspy: 'Hey Rhasspy',
};
// Detection-Tuning. Threshold ist ueber die Settings konfigurierbar
// (loadWakeThreshold) — der Wert hier ist nur der Fallback.
const DEFAULT_THRESHOLD = WAKE_THRESHOLD_DEFAULT;
// patience=1 statt 2: nur EIN Frame ueber Threshold noetig → deutlich schneller.
// Speaker-ID filtert Fehlausloeser, also ist das vertretbar.
const DEFAULT_PATIENCE = 1;
const DEFAULT_DEBOUNCE_MS = 1500;
interface OpenWakeWordModule {
init(modelName: string, threshold: number, patience: number, debounceMs: number): Promise<boolean>;
start(): Promise<boolean>;
stop(): Promise<boolean>;
dispose(): Promise<boolean>;
isAvailable(): Promise<boolean>;
}
const { OpenWakeWord } = NativeModules as { OpenWakeWord?: OpenWakeWordModule };
export type BuiltinKeyword = typeof BUILTIN_KEYWORDS[number];
export const DEFAULT_KEYWORD: BuiltinKeyword = 'jarvis';
class WakeWordService {
private state: WakeWordState = 'off';
private wakeCallbacks: WakeWordCallback[] = [];
private stateCallbacks: StateCallback[] = [];
/** Barge-In-Callbacks: feuern wenn Wake-Word WAEHREND ARIA spricht erkannt
* wird. ChatScreen reagiert mit TTS-stop + neuer Aufnahme. */
private bargeCallbacks: WakeWordCallback[] = [];
/** True solange Wake-Word parallel zu TTS aktiv ist. */
private bargeListening: boolean = false;
/** Anruf-Pause: state wird gemerkt damit nach Auflegen wiederhergestellt wird. */
private callPaused: boolean = false;
private preCallState: WakeWordState = 'off';
/** Cooldown nach App-Resume: kurze Phase in der Wake-Word-Detections
* ignoriert werden. Beim Wechsel von Background nach Vordergrund gibt's
* oft einen Audio-Pegel-Spike (AudioFocus-Switch, AudioTrack re-route),
* der openWakeWord faelschlich triggern kann. */
private cooldownUntilMs: number = 0;
/** Zeitpunkt des letzten echten Wake-Word-Triggers gebraucht damit
* ChatScreen entscheiden kann ob ein 'conversing'-State bei App-Resume
* ein false-positive war (Wake-Word im Hintergrund getriggert waehrend
* Stefan gar nicht in der App war). */
private lastTriggerAt: number = 0;
/** App liegt im Hintergrund alle Detections sperren. Wird vom
* AppState-Listener im ChatScreen via setBackground/setForeground gesetzt.
* Hintergrund-Detections sind quasi immer false-positives (TV, Husten,
* AudioFocus-Switch beim Wechsel zu Musik etc.). */
private inBackground: boolean = false;
/** Wenn true: Wake-Wort triggert auch im Hintergrund / bei gesperrtem
* Bildschirm. Default false. Wird beim Arm aus AsyncStorage geladen und
* bei Aenderung in den Einstellungen via setBgWakeEnabled() aktualisiert. */
private bgWakeEnabled: boolean = false;
/** Wake-Wort per Voxtral bestaetigen (gegen Musik-Fehltrigger)? Default false.
* Wird beim Arm geladen + per setWakeConfirmEnabled aus den Einstellungen. */
private wakeConfirmEnabled: boolean = false;
/** Re-Entry-Guard fuer onWakeDetected: native kann mehrere
* WakeWordDetected-Events emitten BEVOR OpenWakeWord.stop() in JS
* resolved (Bridge-Queue + Doze-Backlog). Mit dem Flag wird das zweite
* Event sofort verworfen. Reset beim Verlassen von 'conversing'.
* Ausnahme: bargeListening Barge-In ist ein legitimer neuer Trigger
* waehrend ARIA noch redet, NICHT vom Guard blockieren. */
private detectionInProgress: boolean = false;
/** Passive-Listen-Backstop-Timer: Notbremse (PASSIVE_BACKSTOP_MS). Normal endet
* das Fenster ueber die Stille-Toleranz der Aufnahme; feuert dieser Timer
* trotzdem, zurueck zu armed. */
private passiveListenTimer: ReturnType<typeof setTimeout> | null = null;
/** Callbacks fuer den Eintritt in Passive-Listen ChatScreen startet
* hier eine streaming-Aufnahme OHNE User-Bubble (passiv lauschen). */
private passiveListenCallbacks: PassiveListenCallback[] = [];
/** Hook, der das Mikro freigibt (laufende Streaming-Aufnahme canceln) BEVOR
* wir OpenWakeWord.start() rufen. Ohne das haelt die passive/conversing
* Aufnahme das Mikro noch, start() schlaegt fehl Ohr bleibt ausgegraut
* (state=off). ChatScreen registriert den Hook mit audioService.cancel. */
private micReleaseHook: (() => Promise<void>) | null = null;
private keyword: WakeKeyword = DEFAULT_KEYWORD;
private nativeReady: boolean = false;
// Picovoice Manager (lazy, da Native Module nicht in jedem Build verfuegbar ist)
private porcupine: any = null;
private accessKey: string = '';
private keyword: string = DEFAULT_KEYWORD;
private initInProgress: Promise<boolean> | null = null;
private eventSub: { remove: () => void } | null = null;
/** Beim App-Start aufrufen — laedt Settings, baut Native-Modul. */
/** Beim App-Start aufrufen — laedt Settings, baut Porcupine wenn Key da ist. */
async loadFromStorage(): Promise<void> {
try {
const k = await AsyncStorage.getItem(WAKE_ACCESS_KEY_STORAGE);
const w = await AsyncStorage.getItem(WAKE_KEYWORD_STORAGE);
const wt = (w || DEFAULT_KEYWORD).trim() as WakeKeyword;
this.keyword = (WAKE_KEYWORDS as readonly string[]).includes(wt) ? wt : DEFAULT_KEYWORD;
await this.initNative();
this.accessKey = (k || '').trim();
this.keyword = (w || DEFAULT_KEYWORD).trim();
if (this.accessKey) {
// Vorinitialisieren — wirft sich nicht durch wenn etwas fehlt
await this.initPorcupine();
}
} catch (err) {
console.warn('[WakeWord] loadFromStorage', err);
}
}
/** ChatScreen registriert hier einen Hook, der eine laufende Streaming-
* Aufnahme cancelt (Mikro freigeben) wird vor jedem Re-Arm gerufen. */
setMicReleaseHook(fn: (() => Promise<void>) | null): void {
this.micReleaseHook = fn;
/** Settings-Wechsel — neuer Key oder Keyword. Re-Init Porcupine. */
async configure(accessKey: string, keyword: string): Promise<boolean> {
this.accessKey = (accessKey || '').trim();
this.keyword = (keyword || DEFAULT_KEYWORD).trim();
await AsyncStorage.setItem(WAKE_ACCESS_KEY_STORAGE, this.accessKey);
await AsyncStorage.setItem(WAKE_KEYWORD_STORAGE, this.keyword);
// Laufende Instanz stoppen
await this.disposePorcupine();
if (!this.accessKey) return false;
// Neu initialisieren
return this.initPorcupine();
}
private async _freeMic(): Promise<void> {
if (!this.micReleaseHook) return;
try { await this.micReleaseHook(); } catch (e) {
console.warn('[WakeWord] micReleaseHook err:', e);
}
}
/** Settings-Wechsel: anderes Wake-Word. Re-Init des Native-Moduls. */
async configure(keyword: string): Promise<boolean> {
const next: WakeKeyword = (WAKE_KEYWORDS as readonly string[]).includes(keyword)
? (keyword as WakeKeyword)
: DEFAULT_KEYWORD;
this.keyword = next;
await AsyncStorage.setItem(WAKE_KEYWORD_STORAGE, next);
// Laufende Instanz stoppen + neu initialisieren
await this.disposeNative();
const ok = await this.initNative();
if (!ok) {
ToastAndroid.show(
`Wake-Word "${KEYWORD_LABELS[next]}" konnte nicht initialisiert werden — Logs pruefen`,
ToastAndroid.LONG,
);
}
return ok;
}
private async initNative(): Promise<boolean> {
if (!OpenWakeWord) {
console.warn('[WakeWord] OpenWakeWord Native-Modul nicht verfuegbar — Direkt-Aufnahme-Fallback aktiv');
this.nativeReady = false;
return false;
}
private async initPorcupine(): Promise<boolean> {
if (this.initInProgress) return this.initInProgress;
this.initInProgress = (async () => {
try {
const threshold = await loadWakeThreshold();
this.bgWakeEnabled = await loadBgWakeEnabled();
this.wakeConfirmEnabled = await loadWakeConfirmEnabled();
console.log('[WakeWord] init mit threshold=%s, bgWake=%s, confirm=%s',
threshold, this.bgWakeEnabled, this.wakeConfirmEnabled);
await OpenWakeWord.init(this.keyword, threshold, DEFAULT_PATIENCE, DEFAULT_DEBOUNCE_MS);
// Subscribe nur einmal
if (!this.eventSub) {
const emitter = new NativeEventEmitter(NativeModules.OpenWakeWord);
this.eventSub = emitter.addListener('WakeWordDetected', (payload: any) => {
console.log('[WakeWord] Native Detection-Event empfangen');
// payload.preTriggerPcm (base64 s16le 16kHz) fuer die Bestaetigung —
// nur in neueren APKs vorhanden; ohne = fail-open (kein Verify).
this.onWakeDetected(payload && payload.preTriggerPcm ? String(payload.preTriggerPcm) : null)
.catch(err => console.warn('[WakeWord] onWakeDetected crashed:', err));
});
}
this.nativeReady = true;
console.log('[WakeWord] Init OK (model=%s)', this.keyword);
const { PorcupineManager } = require('@picovoice/porcupine-react-native');
// Built-In Keyword-Identifier sind lower-case strings im SDK
this.porcupine = await PorcupineManager.fromBuiltInKeywords(
this.accessKey,
[this.keyword],
(_keywordIndex: number) => this.onWakeDetected(),
);
console.log('[WakeWord] Porcupine init OK (keyword=%s)', this.keyword);
return true;
} catch (err: any) {
console.warn('[WakeWord] Init fehlgeschlagen:', err?.message || err);
this.nativeReady = false;
} catch (err) {
console.warn('[WakeWord] Porcupine init fehlgeschlagen:', err);
this.porcupine = null;
return false;
} finally {
this.initInProgress = null;
@@ -294,45 +110,30 @@ class WakeWordService {
return this.initInProgress;
}
private async disposeNative(): Promise<void> {
if (!OpenWakeWord) return;
try { await OpenWakeWord.dispose(); } catch {}
this.nativeReady = false;
private async disposePorcupine() {
if (this.porcupine) {
try { await this.porcupine.stop(); } catch {}
try { await this.porcupine.delete(); } catch {}
this.porcupine = null;
}
}
/** Ohr-Button gedrueckt — startet passives Lauschen oder direkt Konversation. */
async start(): Promise<boolean> {
if (this.state !== 'off') return true;
// Foreground-Service VOR dem Mic-Zugriff hochziehen damit Background-
// Lauschen funktioniert (Android braucht foregroundServiceType=microphone
// aktiv zum Zeitpunkt des AudioRecord.startRecording).
await acquireBackgroundAudio('wake');
if (this.nativeReady && OpenWakeWord) {
if (this.porcupine) {
// Passives Lauschen via Porcupine
try {
await OpenWakeWord.start();
console.log('[WakeWord] armed — warte auf "%s"', this.keyword);
// Debug-Log via RVS damit wir auch ohne ADB sehen wann es greift
import('./logger').then(m => m.reportAppDebug('wake.start', `armed, keyword=${this.keyword}`)).catch(()=>{});
ToastAndroid.show(`Lausche auf "${KEYWORD_LABELS[this.keyword]}"`, ToastAndroid.SHORT);
await this.porcupine.start();
console.log('[WakeWord] armed — warte auf Wake Word "%s"', this.keyword);
this.setState('armed');
return true;
} catch (err: any) {
console.warn('[WakeWord] start fehlgeschlagen — Fallback Direkt-Aufnahme:',
err?.message || err);
ToastAndroid.show(
`Wake-Word-Start failed: ${err?.message || err}`,
ToastAndroid.LONG,
);
} catch (err) {
console.warn('[WakeWord] Porcupine start fehlgeschlagen — Fallback Direkt-Konversation:', err);
}
} else {
console.warn('[WakeWord] Native-Modul nicht bereit — Direkt-Aufnahme-Fallback');
ToastAndroid.show(
'Wake-Word nicht aktiv — direkte Aufnahme startet (Mikro hoert mit)',
ToastAndroid.LONG,
);
}
// Fallback: direkt in Konversation
console.log('[WakeWord] Direkt-Aufnahme startet (kein Wake-Word)');
// Fallback: direkt in die Konversation
console.log('[WakeWord] Konversation startet sofort (kein Wake-Word)');
this.setState('conversing');
setTimeout(() => {
if (this.state === 'conversing') {
@@ -345,429 +146,56 @@ class WakeWordService {
/** Komplett ausschalten (Ohr abschalten) */
async stop(): Promise<void> {
console.log('[WakeWord] Ohr deaktiviert');
this.cancelPassiveListenTimer();
if (this.nativeReady && OpenWakeWord) {
try { await OpenWakeWord.stop(); } catch {}
if (this.porcupine) {
try { await this.porcupine.stop(); } catch {}
}
this.bargeListening = false;
this.setState('off');
}
/** Cooldown setzen alle Wake-Word-Detections in den naechsten ms ignorieren.
* Wird beim App-Resume gerufen weil AppState-Wechsel Audio-Spikes erzeugen
* die openWakeWord faelschlich als Trigger interpretiert. */
setResumeCooldown(ms: number = 500): void {
this.cooldownUntilMs = Date.now() + ms;
console.log('[WakeWord] Cooldown aktiv fuer %dms', ms);
}
/** App in den Hintergrund: alle Wake-Word-Detections sperren.
* Im Hintergrund will Stefan praktisch nie einen neuen Dialog starten
* was als Wake-Word" reinkommt ist Husten/TV/AudioFocus-Switch. */
setBackground(): void {
this.inBackground = true;
console.log('[WakeWord] App im Hintergrund — Detections %s',
this.bgWakeEnabled ? 'AKTIV (Hintergrund-Wake an)' : 'gesperrt');
}
/** Hintergrund-Wake ein/aus schalten (aus den Einstellungen). */
setBgWakeEnabled(enabled: boolean): void {
this.bgWakeEnabled = enabled;
console.log('[WakeWord] Hintergrund-Wake = %s', enabled);
}
/** Wake-Wort-Bestaetigung (Voxtral) ein/aus (aus den Einstellungen). */
setWakeConfirmEnabled(enabled: boolean): void {
this.wakeConfirmEnabled = enabled;
console.log('[WakeWord] Wake-Bestaetigung = %s', enabled);
}
/** Ist Hintergrund-Wake an? Steuert u.a. ob der Konversationsmodus auch im
* Hintergrund weiterlaeuft (sonst: im Hintergrund direkt zurueck aufs Wake-Word). */
isBgWakeEnabled(): boolean {
return this.bgWakeEnabled;
}
/** App im Vordergrund: Detections wieder freigeben, plus kurzer Cooldown
* als Schutz gegen den AudioFocus-/AudioTrack-Spike direkt nach dem Resume.
* 1s statt 3s 3s hat sich "traege" angefuehlt (Trigger direkt nach dem
* App-Oeffnen wurden verschluckt). */
setForeground(): void {
this.inBackground = false;
this.cooldownUntilMs = Date.now() + 1000;
console.log('[WakeWord] App im Vordergrund — Cooldown 1s aktiv');
}
/** Wake-Word getriggert: Native-Modul pausieren, Konversation starten.
* preTriggerPcm: base64 s16le 16kHz Vor-Trigger-Audio fuer die Bestaetigung
* (null = nicht verfuegbar keine Bestaetigung, normal weiter). */
private async onWakeDetected(preTriggerPcm: string | null = null): Promise<void> {
if (this.inBackground && !this.bgWakeEnabled) {
console.log('[WakeWord] Trigger ignoriert (App im Hintergrund, Hintergrund-Wake aus)');
import('./logger').then(m => m.reportAppDebug('wake.detect', 'ignored: app in background (bg-wake off)')).catch(()=>{});
return;
}
// Re-Entry-Guard: blocken wenn ein Detection-Zyklus schon laeuft.
// Ausnahme: Barge-In waehrend ARIA-TTS ist ein legitimer neuer Trigger.
if (this.detectionInProgress && !this.bargeListening) {
console.log('[WakeWord] Trigger ignoriert (Detection-Zyklus laeuft schon — Native-Doppel-Event-Race)');
import('./logger').then(m => m.reportAppDebug('wake.detect', 'ignored: detectionInProgress')).catch(()=>{});
return;
}
const now = Date.now();
if (now < this.cooldownUntilMs) {
const left = this.cooldownUntilMs - now;
console.log('[WakeWord] Trigger ignoriert (Cooldown noch %dms aktiv — wahrscheinlich App-Resume-Spike)', left);
return;
}
this.detectionInProgress = true;
console.log('[WakeWord] Wake-Word "%s" erkannt! (state=%s, barge=%s)',
this.keyword, this.state, this.bargeListening);
import('./logger').then(m => m.reportAppDebug('wake.detect',
`keyword=${this.keyword} state=${this.state} barge=${this.bargeListening}`)).catch(()=>{});
this.lastTriggerAt = now;
if (this.nativeReady && OpenWakeWord) {
try {
await OpenWakeWord.stop();
import('./logger').then(m => m.reportAppDebug('wake.detect', 'native stop ok')).catch(()=>{});
} catch (e: any) {
import('./logger').then(m => m.reportAppDebug('wake.detect', `native stop FAIL ${e?.message}`)).catch(()=>{});
}
}
this.bargeListening = false;
// Wenn wir bereits in 'conversing' sind und der Trigger waehrend ARIAs TTS
// kam (Barge-In via Wake-Word), feuern wir einen separaten Callback damit
// ChatScreen das TTS abbrechen + neue Aufnahme starten kann. Sonst normal.
if (this.state === 'conversing') {
import('./logger').then(m => m.reportAppDebug('wake.detect',
`barge path: cbs=${this.bargeCallbacks.length}`)).catch(()=>{});
this.bargeCallbacks.forEach(cb => {
try { cb(); } catch (e) { console.warn('[WakeWord] barge cb err:', e); }
});
// Kein erneutes setState — wir bleiben in 'conversing'.
return;
}
// Wake-Wort-Bestaetigung (gegen Musik-Fehltrigger): den Vor-Trigger-Schnipsel
// von Voxtral gegenpruefen. Bestaetigt → weiter (Gong + Mikro). Verworfen
// (Musik/Rauschen, kein "Computer") → kein Dialog, kein Gong, re-arm. Fail-
// open: ohne PCM / bei Timeout/Fehler laeuft es normal durch.
if (this.wakeConfirmEnabled && preTriggerPcm) {
const confirmed = await this.confirmWake(preTriggerPcm);
if (!confirmed) {
this.detectionInProgress = false;
if (this.nativeReady && OpenWakeWord) {
try { await OpenWakeWord.start(); } catch (e) {
console.warn('[WakeWord] re-arm nach verworfener Bestaetigung failed:', e);
}
}
return;
}
/** Wake-Word getriggert: Porcupine pausieren, Konversation starten. */
private async onWakeDetected(): Promise<void> {
console.log('[WakeWord] Wake-Word "%s" erkannt!', this.keyword);
if (this.porcupine) {
try { await this.porcupine.stop(); } catch {}
}
this.setState('conversing');
// Direkt feuern — KEIN setTimeout. Im Hintergrund (Display aus) parkt
// Android den JS-Thread; ein setTimeout(200ms) kann dann Minuten lang
// nicht zuendekommen, weil Hermes auf einen Native-Wake-Event wartet.
// OpenWakeWord.stop() oben ist awaited → Mikro ist schon frei, kein
// 200ms-Sicherheitsabstand noetig.
import('./logger').then(m => m.reportAppDebug('wake.detect',
`state→conversing, firing ${this.wakeCallbacks.length} callback(s) directly`)).catch(()=>{});
this.wakeCallbacks.forEach(cb => {
try { cb(); } catch (e) { console.warn('[WakeWord] wake cb err:', e); }
});
}
/** Voxtral-Bestaetigung des Vor-Trigger-Schnipsels. true = Wake-Wort erkannt
* (oder fail-open bei Timeout/Fehler), false = Musik/Rauschen verwerfen. */
private async confirmWake(pcm: string): Promise<boolean> {
try {
const audio = await import('./audio');
const text = await audio.transcribeBlob(pcm);
if (text === null) {
console.log('[WakeWord] Bestaetigung: Timeout/Fehler → fail-open (durchlassen)');
return true;
// kurz warten damit Mikrofon frei ist
setTimeout(() => {
if (this.state === 'conversing') {
this.wakeCallbacks.forEach(cb => cb());
}
const norm = text.toLowerCase();
// Distinktive Wake-Wort-Bestandteile (>= 4 Zeichen; 'hey' o.ae. rausfiltern,
// taucht sonst in Song-Texten auf und wuerde faelschlich bestaetigen).
const kwWords = this.keyword.toLowerCase().replace(/_/g, ' ')
.split(/\s+/).filter(w => w.length >= 4);
if (kwWords.length === 0) return true; // zu kurzes Keyword → nicht pruefbar
const ok = kwWords.some(w => norm.includes(w));
console.log('[WakeWord] Bestaetigung: text=%o kw=%o → %s',
text, kwWords, ok ? 'BESTAETIGT' : 'verworfen (Musik-FP?)');
import('./logger').then(m => m.reportAppDebug('wake.confirm',
`text="${text.slice(0, 40)}" kw=${kwWords.join('|')}${ok ? 'ok' : 'reject'}`)).catch(() => {});
return ok;
} catch (e) {
console.warn('[WakeWord] confirmWake err → fail-open:', e);
return true;
}
}
/** Wake-Word PARALLEL zur TTS-Wiedergabe lauschen lassen User kann
* "Computer" sagen waehrend ARIA noch redet, AcousticEchoCanceler im
* Native-Modul verhindert dass ARIAs eigene Stimme triggert.
* Voraussetzung: AudioRecorder muss frei sein (Recording aus). Wenn der
* AudioRecorder gerade laeuft, hat der Vorrang Wake-Word geht nicht. */
async startBargeListening(): Promise<void> {
if (!this.nativeReady || !OpenWakeWord) return;
if (this.state !== 'conversing') return;
if (this.bargeListening) return;
try {
await OpenWakeWord.start();
this.bargeListening = true;
console.log('[WakeWord] Barge-Listening aktiv (parallel zu TTS)');
} catch (err) {
console.warn('[WakeWord] Barge-Listening start fehlgeschlagen:', err);
}
}
/** Barge-Listening wieder aus z.B. wenn der AudioRecorder fuer die
* naechste Aufnahme das Mikro braucht. */
async stopBargeListening(): Promise<void> {
if (!this.bargeListening) return;
if (this.nativeReady && OpenWakeWord) {
try { await OpenWakeWord.stop(); } catch {}
}
this.bargeListening = false;
console.log('[WakeWord] Barge-Listening aus');
}
/** Bei eingehendem Anruf: Wake-Word + Aufnahme stoppen, Pre-Call-State
* merken. Telefonie-App belegt das Mikro waehrend des Anrufs, plus ARIA
* soll nicht in laufende Telefonate reinhoeren. */
async pauseForCall(): Promise<void> {
if (this.callPaused) return;
this.preCallState = this.state;
if (this.state === 'off') {
this.callPaused = true; // merken dass wir pausiert wurden
return;
}
this.callPaused = true;
if (this.nativeReady && OpenWakeWord) {
try { await OpenWakeWord.stop(); } catch {}
}
this.bargeListening = false;
console.log('[WakeWord] Anruf — Wake-Word pausiert (war: %s)', this.preCallState);
}
/** Nach Auflegen: Pre-Call-State wiederherstellen. Aktive Konversation
* geht zu armed zurueck (User soll nicht in einen halben Dialog springen). */
async resumeFromCall(): Promise<void> {
if (!this.callPaused) return;
const restoreTo = this.preCallState;
this.callPaused = false;
this.preCallState = 'off';
console.log('[WakeWord] Anruf zu Ende — restore state=%s', restoreTo);
if (restoreTo === 'off') return;
// Aktive Konversation war wahrscheinlich durch haltAllPlayback eh abgebrochen,
// sicher zu armed degraden.
if (restoreTo === 'conversing') this.setState('armed');
if (this.nativeReady && OpenWakeWord) {
try { await OpenWakeWord.start(); } catch (err) {
console.warn('[WakeWord] Restore-Start fehlgeschlagen:', err);
}
}
}, 200);
}
/** Konversation beenden User hat im Window nichts gesagt.
* Mit Wake-Word: zurueck zu 'armed' (Listener wieder an).
* Mit Wake-Word: zurueck zu 'armed' (Porcupine wieder an).
* Ohne: zurueck zu 'off'.
*
* WICHTIG: setzt bargeListening=false BEVOR OpenWakeWord.start() laeuft.
* Grund: wenn endConversation aus dem onPlaybackFinished-Handler kommt,
* feuert direkt danach ein zweiter Listener (stopBargeListening) der
* wuerde sonst OpenWakeWord.stop() rufen weil bargeListening noch true
* ist, und unseren frisch re-armierten Listener killen.
*/
/** @param skipPassive true = KEIN passives Lauschen, direkt zurueck aufs
* Wake-Word (armed). Fuer klare Steuerbefehle (Fast-Path) nach
* "nächster Titel" will Stefan kein 30s-Fenster, sondern Stop. */
async endConversation(skipPassive: boolean = false): Promise<void> {
if (this.state !== 'conversing') {
import('./logger').then(m => m.reportAppDebug('wake.end',
`endConversation called but state=${this.state} → noop`)).catch(()=>{});
return;
}
const wasBarge = this.bargeListening;
// Flag NULLEN bevor wir die Listener triggern. Sonst killt der parallele
// stopBargeListening-Listener (TTS-end) gleich danach unseren Native-
// OpenWakeWord, weil er bargeListening=true sieht und annimmt er muss
// den Listener stoppen.
this.bargeListening = false;
import('./logger').then(m => m.reportAppDebug('wake.end',
`endConversation called, wasBarge=${wasBarge}, nativeReady=${this.nativeReady}`)).catch(()=>{});
// Kein skipPassive? Dann EIN Stille-Fenster zum Weiterreden (kein Wake-Word
// noetig). Das echte Ende regelt die Stille-Toleranz der passiven Aufnahme;
// der Backstop-Timer ist nur die Notbremse. Der User kann ohne erneute
// Anrede weitersprechen; sagt er nichts → zurueck aufs Wake-Word.
if (!skipPassive && this.nativeReady) {
this.enterPassiveListening(PASSIVE_BACKSTOP_MS);
return;
}
if (this.nativeReady && OpenWakeWord) {
// Wenn wakeword schon laeuft (war Barge-Listener waehrend TTS):
// OpenWakeWord.start() ist idempotent (Kotlin checkt running.get()
// und resolved sofort). Wir koennen es trotzdem rufen — billiger
// als state extra zu fragen, garantiert dass nach diesem Pfad
// Native auch wirklich an ist falls es out-of-band gestoppt wurde.
async endConversation(): Promise<void> {
if (this.state !== 'conversing') return;
if (this.porcupine && this.accessKey) {
try {
await this._freeMic(); // Streaming-Aufnahme canceln → Mikro frei
await OpenWakeWord.start();
console.log('[WakeWord] Konversation zu Ende — zurueck zu armed (wasBarge=%s)', wasBarge);
import('./logger').then(m => m.reportAppDebug('wake.end',
`OpenWakeWord.start() OK → state=armed, wasBarge=${wasBarge}`)).catch(()=>{});
ToastAndroid.show(`Lausche wieder auf "${KEYWORD_LABELS[this.keyword]}"`, ToastAndroid.SHORT);
await this.porcupine.start();
console.log('[WakeWord] Konversation zu Ende — zurueck zu armed');
this.setState('armed');
return;
} catch (err: any) {
} catch (err) {
console.warn('[WakeWord] re-arm fehlgeschlagen:', err);
import('./logger').then(m => m.reportAppDebug('wake.end',
`OpenWakeWord.start() FAIL: ${err?.message || err} → state=off`,
)).catch(()=>{});
}
}
console.log('[WakeWord] Konversation zu Ende — Ohr aus');
import('./logger').then(m => m.reportAppDebug('wake.end',
`fallback: nativeReady=${this.nativeReady} → state=off`)).catch(()=>{});
ToastAndroid.show('Mikro aus', ToastAndroid.SHORT);
this.setState('off');
}
/** Eintritt in den Passive-Listen-Modus: state='listening', Timer fuer
* Auto-Ende setzen, Callbacks feuern damit ChatScreen die passive
* Streaming-Aufnahme startet. OpenWakeWord bleibt AUS (Mic-Exklusivitaet
* audioService braucht das Mikro fuer die passive Aufnahme).
* Speaker-ID-Gating (Phase 3) filtert fremde Stimmen auf der Bridge. */
private enterPassiveListening(durationMs: number): void {
this.cancelPassiveListenTimer();
this.setState('listening');
const seconds = Math.round(durationMs / 1000);
console.log('[WakeWord] Passive-Listen aktiv (Backstop %ds) — Speaker-ID gefiltert', seconds);
import('./logger').then(m => m.reportAppDebug('wake.passive',
`entered listening (backstop ${seconds}s), cb-count=${this.passiveListenCallbacks.length}`)).catch(()=>{});
ToastAndroid.show('🎧 sprich einfach weiter', ToastAndroid.SHORT);
this.passiveListenTimer = setTimeout(() => {
this.passiveListenTimer = null;
this.exitPassiveListening('timeout').catch(() => {});
}, durationMs);
this.passiveListenCallbacks.forEach(cb => {
try { cb(); } catch (e) { console.warn('[WakeWord] passive cb err:', e); }
});
}
/** Verlassen des Passive-Listen-Modus.
* reason='speech' User hat was gesagt (STT-Endpoint mit text) uebergang
* in 'conversing' (Brain antwortet, TTS spielt, dann resume endConversation
* wieder passive listening, repeat).
* reason='timeout' 30s nichts gehoert zurueck zu armed (Wake-Word wieder an).
* reason='manual' User hat App geschlossen / stopped zurueck zu armed. */
async exitPassiveListening(reason: 'timeout' | 'speech' | 'manual'): Promise<void> {
if (this.state !== 'listening') return;
this.cancelPassiveListenTimer();
console.log('[WakeWord] Passive-Listen Ende (reason=%s)', reason);
import('./logger').then(m => m.reportAppDebug('wake.passive',
`exit reason=${reason}`)).catch(()=>{});
if (reason === 'speech') {
// Wechsel zu 'conversing' damit das Standard-Conversation-Flow greift
// (Brain-Response, TTS, resume etc.). Wake-Word bleibt aus (Mic belegt).
this.setState('conversing');
return;
}
// timeout oder manual → Wake-Word reaktivieren, armed-State.
if (this.nativeReady && OpenWakeWord) {
try {
await this._freeMic(); // passive Streaming-Aufnahme canceln → Mikro frei
await OpenWakeWord.start();
console.log('[WakeWord] zurueck zu armed nach passive-listen');
ToastAndroid.show(`Lausche wieder auf "${KEYWORD_LABELS[this.keyword]}"`, ToastAndroid.SHORT);
this.setState('armed');
return;
} catch (err) {
console.warn('[WakeWord] re-arm nach passive-listen failed:', err);
}
}
this.setState('off');
}
private cancelPassiveListenTimer(): void {
if (this.passiveListenTimer) {
clearTimeout(this.passiveListenTimer);
this.passiveListenTimer = null;
}
}
/** Subscribe auf Passive-Listen-Events: feuert wenn der Service in den
* passiven Modus eintritt. ChatScreen startet hier eine streaming-
* Aufnahme OHNE User-Bubble (passiv lauschen). */
onPassiveListen(callback: PassiveListenCallback): () => void {
this.passiveListenCallbacks.push(callback);
return () => {
this.passiveListenCallbacks = this.passiveListenCallbacks.filter(c => c !== callback);
};
}
/** Wenn ein conversing-State auf einem Wake-Word-Trigger juenger als
* maxAgeMs basiert: false-positive verwerfen, zurueck zu armed.
* Wird vom ChatScreen aufgerufen wenn die App aus laengerem Hintergrund
* zurueck kommt dann ist ein gerade getriggertes" Wake-Word sehr
* wahrscheinlich ein TV-Spike, Husten, ARIAs eigene TTS-Aufnahme etc.
* Returnt true wenn verworfen wurde. */
async discardIfFreshlyTriggered(maxAgeMs: number = 10_000): Promise<boolean> {
if (this.state !== 'conversing') return false;
if (this.lastTriggerAt === 0) return false;
const age = Date.now() - this.lastTriggerAt;
if (age > maxAgeMs) return false;
console.log('[WakeWord] Resume: verwerfe verdaechtiges conversing (age=%dms)', age);
this.lastTriggerAt = 0;
if (this.nativeReady && OpenWakeWord) {
try {
await this._freeMic(); // ggf. laufende Aufnahme canceln → Mikro frei
await OpenWakeWord.start();
ToastAndroid.show('Hintergrund-Trigger verworfen — lausche wieder', ToastAndroid.SHORT);
this.setState('armed');
return true;
} catch (err) {
console.warn('[WakeWord] re-arm nach discard fehlgeschlagen:', err);
}
}
this.setState('off');
return true;
}
/** Nach ARIA-Antwort (TTS fertig): naechste Aufnahme im Conversation-Window starten.
*
* WICHTIG: setTimeout(800ms) kann im Hintergrund (Display aus) verspaetet
* feuern JS-Thread ist geparkt. Wenn der Timer >2s ueberfaellig ist,
* hat der User offensichtlich die App verlassen und kommt erst spaeter
* wieder wir oeffnen das Mikro dann NICHT, sondern beenden die
* Konversation. Sonst sieht der User nach dem App-Resume "Mikro plus-
* aufnahme laeuft" obwohl er gar nichts gesagt hat wirkt wie Phantom-
* Wake-Word. Klassische Doze-Throttling-Falle wie bei wake.detect frueher. */
/** Nach ARIA-Antwort (TTS fertig): naechste Aufnahme im Conversation-Window starten */
async resume(): Promise<void> {
if (this.state !== 'conversing') return;
const scheduledAt = Date.now();
// Kurze Pause damit TTS-Audio nicht ins Mikrofon geht
await new Promise(resolve => setTimeout(resolve, 800));
if (this.state !== 'conversing') return;
const delay = Date.now() - scheduledAt;
if (delay > 2800) {
// Timer war stark verspaetet — JS-Thread war im Hintergrund geparkt.
// Conversation als beendet behandeln statt das Mikro zu oeffnen.
console.log('[WakeWord] resume(): %dms statt ~800ms — App war im Background. endConversation statt mic-open', delay);
import('./logger').then(m => m.reportAppDebug('wake.resume',
`delayed ${delay}ms (>2800) — endConversation statt mic-open`)).catch(()=>{});
// Asynchroner Aufruf — endConversation ist async, kein await damit wir
// hier nicht in einem Promise-Chain haengen.
this.endConversation().catch(() => {});
return;
if (this.state === 'conversing') {
console.log('[WakeWord] TTS fertig — naechste Aufnahme im Conversation-Window');
this.wakeCallbacks.forEach(cb => cb());
}
console.log('[WakeWord] TTS fertig — naechste Aufnahme im Conversation-Window (delay=%dms)', delay);
this.wakeCallbacks.forEach(cb => cb());
}
/** True solange das Ohr aktiv ist (armed ODER conversing). */
@@ -780,10 +208,10 @@ class WakeWordService {
}
hasWakeWord(): boolean {
return this.nativeReady;
return !!this.porcupine;
}
getKeyword(): WakeKeyword {
getKeyword(): string {
return this.keyword;
}
@@ -796,19 +224,6 @@ class WakeWordService {
};
}
/** Subscribe auf Barge-In-Events: Wake-Word erkannt waehrend ARIA noch
* spricht. ChatScreen sollte dann TTS abbrechen + neue Aufnahme starten. */
onBargeIn(callback: WakeWordCallback): () => void {
this.bargeCallbacks.push(callback);
return () => {
this.bargeCallbacks = this.bargeCallbacks.filter(cb => cb !== callback);
};
}
isBargeListening(): boolean {
return this.bargeListening;
}
onStateChange(callback: StateCallback): () => void {
this.stateCallbacks.push(callback);
return () => {
@@ -822,12 +237,7 @@ class WakeWordService {
private setState(state: WakeWordState): void {
if (this.state !== state) {
const wasConversing = this.state === 'conversing';
this.state = state;
// Re-Entry-Guard freigeben sobald wir 'conversing' verlassen — Zyklus ist durch
if (wasConversing && state !== 'conversing') {
this.detectionInProgress = false;
}
this.stateCallbacks.forEach(cb => cb(state));
}
}
-175
View File
@@ -1,175 +0,0 @@
/**
* AriaViewCanvas die pannbare Flaeche, auf der ARIAs komponierte Ansicht
* (aria_view) MATERIALISIERT: Orb oben, darunter die Karten. Erscheint als
* Overlay ueber dem Chat, sobald ARIA present_view aufruft ("sag was Orb denkt
* Karte fliegt rein"). Der erste, greifbare Vorgeschmack aufs generative
* Cockpit (M1).
*
* Bedienung (NoMachine-Prinzip): 2-Finger halten + schieben bewegt die Welt,
* Pinch zoomt. Ein-Finger-Touch geht an die Karten durch (Scrollen). Die Welt
* traegt gerenderte/gestreamte Inhalte interaktive native Panels rasten
* spaeter bei Scale 1 ein (Chat bleibt separat darunter).
*
* Geraete-agnostisch gehalten: liest nur die ViewSpec, damit ein spaeterer Web-/
* AR-Renderer dieselbe Spec konsumieren kann.
*/
import React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Animated, {
FadeInDown,
useAnimatedStyle,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { ViewSpec } from '../services/ariaView';
import Orb from './Orb';
import CardView from './CardView';
const MIN_SCALE = 0.5;
const MAX_SCALE = 3;
interface Props {
view: ViewSpec;
onClose: () => void;
}
const AriaViewCanvas: React.FC<Props> = ({ view, onClose }) => {
const tx = useSharedValue(0);
const ty = useSharedValue(0);
const scale = useSharedValue(1);
const savedTx = useSharedValue(0);
const savedTy = useSharedValue(0);
const savedScale = useSharedValue(1);
const pan = Gesture.Pan()
.minPointers(2)
.maxPointers(2)
.onUpdate((e) => {
tx.value = savedTx.value + e.translationX;
ty.value = savedTy.value + e.translationY;
})
.onEnd(() => {
savedTx.value = tx.value;
savedTy.value = ty.value;
});
const pinch = Gesture.Pinch()
.onUpdate((e) => {
const next = savedScale.value * e.scale;
scale.value = Math.max(MIN_SCALE, Math.min(MAX_SCALE, next));
})
.onEnd(() => {
savedScale.value = scale.value;
});
const composed = Gesture.Simultaneous(pan, pinch);
const worldStyle = useAnimatedStyle(() => ({
transform: [
{ translateX: tx.value },
{ translateY: ty.value },
{ scale: scale.value },
],
}));
const resetCamera = () => {
tx.value = withTiming(0);
ty.value = withTiming(0);
scale.value = withTiming(1);
savedTx.value = 0;
savedTy.value = 0;
savedScale.value = 1;
};
const cards = Array.isArray(view.cards) ? view.cards : [];
return (
<View style={styles.overlay}>
<GestureDetector gesture={composed}>
<Animated.View style={[styles.world, worldStyle]}>
<View style={styles.orbWrap}>
<Orb state={view.orb} size={110} />
</View>
{!!view.title && <Text style={styles.worldTitle}>{view.title}</Text>}
<View style={styles.cards}>
{cards.map((c, i) => (
<Animated.View
key={i}
entering={FadeInDown.duration(420).delay(120 + i * 90)}
>
<CardView card={c} />
</Animated.View>
))}
</View>
</Animated.View>
</GestureDetector>
{/* Steuerung — ausserhalb des Transforms, immer bei Scale 1 bedienbar */}
<View style={styles.topBar} pointerEvents="box-none">
<TouchableOpacity style={styles.iconBtn} onPress={resetCamera}>
<Text style={styles.icon}></Text>
</TouchableOpacity>
<TouchableOpacity style={styles.iconBtn} onPress={onClose}>
<Text style={styles.icon}></Text>
</TouchableOpacity>
</View>
<View style={styles.hintWrap} pointerEvents="none">
<Text style={styles.hint}>2 Finger: schieben · Pinch: zoomen</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
overlay: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'rgba(6,6,16,0.94)',
zIndex: 50,
},
world: {
...StyleSheet.absoluteFillObject,
alignItems: 'center',
paddingTop: 48,
paddingHorizontal: 18,
},
orbWrap: { marginTop: 8, marginBottom: 6 },
worldTitle: {
color: '#C9C9FF',
fontSize: 18,
fontWeight: '700',
marginBottom: 4,
textAlign: 'center',
},
cards: { width: '100%', maxWidth: 560 },
topBar: {
position: 'absolute',
top: 10,
right: 12,
flexDirection: 'row',
},
iconBtn: {
width: 40,
height: 40,
borderRadius: 20,
marginLeft: 10,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(30,30,60,0.9)',
borderWidth: 1,
borderColor: 'rgba(123,92,255,0.4)',
},
icon: { color: '#C9C9FF', fontSize: 18 },
hintWrap: {
position: 'absolute',
bottom: 14,
alignSelf: 'center',
},
hint: {
color: '#6A6A90',
fontSize: 12,
},
});
export default AriaViewCanvas;
-114
View File
@@ -1,114 +0,0 @@
/**
* CardView rendert EINE Karte einer aria_view-Spec (M1). Schaltet nach
* card.type auf den passenden Renderer. Unbekannte Typen werden als Text-
* Fallback gezeigt (nie crashen).
*
* Bewusst dependency-leicht (v1): Markdown wird als Klartext dargestellt, Map
* als Marker-Liste (kein Karten-Lib), Code als Monospace-Block. Spaeter koennen
* einzelne Renderer aufgebohrt werden, ohne die Spec/den Fluss zu aendern.
*/
import React from 'react';
import { Image, ScrollView, StyleSheet, Text, View } from 'react-native';
import { ViewCard, ViewMarker } from '../services/ariaView';
const ImageBody: React.FC<{ src?: string }> = ({ src }) => {
const isUrl = !!src && /^https?:\/\//i.test(src);
if (isUrl) {
return <Image source={{ uri: src }} style={styles.image} resizeMode="contain" />;
}
return <Text style={styles.muted}>🖼 {src || '(kein Bild)'}</Text>;
};
const ListBody: React.FC<{ md?: string }> = ({ md }) => {
const lines = (md || '')
.split('\n')
.map((l) => l.replace(/^\s*[-*•]\s?/, '').trim())
.filter(Boolean);
if (lines.length === 0) return <Text style={styles.muted}>(leer)</Text>;
return (
<View>
{lines.map((l, i) => (
<View key={i} style={styles.listRow}>
<Text style={styles.bullet}></Text>
<Text style={styles.text}>{l}</Text>
</View>
))}
</View>
);
};
const MapBody: React.FC<{ markers?: ViewMarker[] }> = ({ markers }) => {
const ms = Array.isArray(markers) ? markers : [];
return (
<View style={styles.map}>
<Text style={styles.mapHint}>🗺 Karte ({ms.length} Orte)</Text>
{ms.map((m, i) => (
<Text key={i} style={styles.text}>
📍 {m.label || `${m.lat?.toFixed?.(4)}, ${m.lon?.toFixed?.(4)}`}
</Text>
))}
</View>
);
};
const CodeBody: React.FC<{ md?: string; path?: string; lang?: string }> = ({ md, path, lang }) => (
<View>
{(path || lang) && (
<Text style={styles.codeCaption}>
{path || ''}{lang ? ` · ${lang}` : ''}
</Text>
)}
<ScrollView horizontal style={styles.codeScroll}>
<Text style={styles.code}>{md || ''}</Text>
</ScrollView>
</View>
);
const CardView: React.FC<{ card: ViewCard }> = ({ card }) => {
return (
<View style={styles.card}>
{!!card.title && <Text style={styles.cardTitle}>{card.title}</Text>}
{card.type === 'image' ? (
<ImageBody src={card.src} />
) : card.type === 'list' ? (
<ListBody md={card.md} />
) : card.type === 'map' ? (
<MapBody markers={card.markers} />
) : card.type === 'code' ? (
<CodeBody md={card.md} path={card.path} lang={card.lang} />
) : (
<Text style={styles.text}>{card.md || ''}</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
card: {
backgroundColor: 'rgba(18,18,42,0.92)',
borderColor: 'rgba(123,92,255,0.35)',
borderWidth: 1,
borderRadius: 14,
padding: 14,
marginVertical: 8,
shadowColor: '#7B5CFF',
shadowOpacity: 0.25,
shadowRadius: 12,
shadowOffset: { width: 0, height: 2 },
elevation: 6,
},
cardTitle: { color: '#C9C9FF', fontSize: 15, fontWeight: '700', marginBottom: 8 },
text: { color: '#E6E6F0', fontSize: 14, lineHeight: 20, flexShrink: 1 },
muted: { color: '#8A8AB0', fontSize: 13, fontStyle: 'italic' },
image: { width: '100%', height: 200, borderRadius: 8, backgroundColor: '#0D0D1A' },
listRow: { flexDirection: 'row', alignItems: 'flex-start', marginVertical: 2 },
bullet: { color: '#7B5CFF', marginRight: 8, fontSize: 14, lineHeight: 20 },
map: { backgroundColor: '#0D0D1A', borderRadius: 8, padding: 10 },
mapHint: { color: '#00B4D8', fontSize: 13, fontWeight: '600', marginBottom: 6 },
codeCaption: { color: '#8A8AB0', fontSize: 12, marginBottom: 6 },
codeScroll: { backgroundColor: '#0A0A14', borderRadius: 8, padding: 10 },
code: { color: '#B9F5C9', fontFamily: 'monospace', fontSize: 12.5, lineHeight: 18 },
});
export default React.memo(CardView);
-106
View File
@@ -1,106 +0,0 @@
/**
* Orb ARIAs Praesenz-Avatar (M1). Zeigt ihren Zustand (idle/listening/
* thinking/speaking/working) als pulsierender Leucht-Kern und ist das
* verbindende Element ueber alle Oberflaechen (App/Web/spaeter Brille).
*
* Reine Optik, keine Logik der Zustand kommt von aussen (aria_view.orb bzw.
* spaeter direkt von Audio/Wake-Word-Signalen). Dependency-leicht: nur
* reanimated (schon installiert), kein SVG/Gradient noetig.
*/
import React, { useEffect } from 'react';
import { StyleSheet, View } from 'react-native';
import Animated, {
Easing,
cancelAnimation,
useAnimatedStyle,
useSharedValue,
withRepeat,
withTiming,
} from 'react-native-reanimated';
import { OrbState } from '../services/ariaView';
const COLORS: Record<OrbState, string> = {
idle: '#3A6EA5',
listening: '#00B4D8',
thinking: '#7B5CFF',
speaking: '#34C759',
working: '#FF9500',
};
interface Props {
state?: OrbState;
size?: number;
}
const Orb: React.FC<Props> = ({ state = 'idle', size = 120 }) => {
const pulse = useSharedValue(1);
useEffect(() => {
const fast = state === 'thinking' || state === 'working';
cancelAnimation(pulse);
pulse.value = 1;
pulse.value = withRepeat(
withTiming(fast ? 1.14 : 1.07, {
duration: fast ? 620 : 1500,
easing: Easing.inOut(Easing.ease),
}),
-1,
true,
);
return () => cancelAnimation(pulse);
}, [state, pulse]);
const animStyle = useAnimatedStyle(() => ({ transform: [{ scale: pulse.value }] }));
const color = COLORS[state] || COLORS.idle;
return (
<View style={[styles.wrap, { width: size, height: size }]}>
<Animated.View
style={[
styles.glow,
{ width: size, height: size, borderRadius: size / 2, backgroundColor: color },
animStyle,
]}
/>
<Animated.View
style={[
styles.ring,
{
width: size * 0.72,
height: size * 0.72,
borderRadius: size * 0.36,
borderColor: color,
},
animStyle,
]}
/>
<View
style={[
styles.core,
{
width: size * 0.44,
height: size * 0.44,
borderRadius: size * 0.22,
backgroundColor: color,
shadowColor: color,
},
]}
/>
</View>
);
};
const styles = StyleSheet.create({
wrap: { alignItems: 'center', justifyContent: 'center' },
glow: { position: 'absolute', opacity: 0.22 },
ring: { position: 'absolute', borderWidth: 2, opacity: 0.55 },
core: {
shadowOpacity: 0.9,
shadowRadius: 16,
shadowOffset: { width: 0, height: 0 },
elevation: 12,
},
});
export default React.memo(Orb);
-92
View File
@@ -1,92 +0,0 @@
/**
* WorkspaceDeck die Workbench: Vollbild-Panels + Taskleisten-Dock unten.
*
* Statt einer Zoom-Landkarte: jedes Panel ist bildschirmfuellend und Handy-
* optimiert, das Dock wechselt per Daumen-Tap sofort. Alle Panels sind IMMER
* gemountet (nur das aktive ist via display sichtbar) kein Remount, Chat
* behaelt RVS/Audio/Queue, WebViews behalten ihren Zustand.
*
* Bei offener Tastatur blendet das Dock aus (mehr Platz zum Tippen).
*/
import React, { useEffect, useState } from 'react';
import { Keyboard, StyleSheet, View } from 'react-native';
import { TileId } from './layout';
import { useWorkspaceLayout } from './useWorkspaceLayout';
import WorkspaceDock from './WorkspaceDock';
import ChatTile from './tiles/ChatTile';
import FilesTile from './tiles/FilesTile';
import CodeEditorTile from './tiles/CodeEditorTile';
import DesktopTile from './tiles/DesktopTile';
interface Props {
projectId: string;
panels: TileId[];
badges?: Partial<Record<TileId, string>>;
}
const WorkspaceDeck: React.FC<Props> = ({ projectId, panels, badges }) => {
const [active, setActive] = useState<TileId>('chat');
const [kbVisible, setKbVisible] = useState(false);
const { loaded, getFocus, saveFocus } = useWorkspaceLayout(projectId);
// Aktives Panel pro Projekt wiederherstellen.
useEffect(() => {
if (!loaded) return;
const stored = getFocus();
if (stored && panels.includes(stored)) setActive(stored);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId, loaded]);
// Falls das aktive Panel wegfaellt → erstes nehmen.
useEffect(() => {
if (!panels.includes(active)) setActive(panels[0] || 'chat');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [panels.join(',')]);
useEffect(() => {
if (loaded) saveFocus(active);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active, loaded]);
useEffect(() => {
const s1 = Keyboard.addListener('keyboardDidShow', () => setKbVisible(true));
const s2 = Keyboard.addListener('keyboardDidHide', () => setKbVisible(false));
return () => { s1.remove(); s2.remove(); };
}, []);
const render = (id: TileId) => {
switch (id) {
case 'chat': return <ChatTile />;
case 'files': return <FilesTile projectId={projectId} focused={active === 'files'} />;
case 'editor': return <CodeEditorTile projectId={projectId} />;
case 'vnc': return <DesktopTile projectId={projectId} focused={active === 'vnc'} />;
default: return null;
}
};
return (
<View style={styles.root}>
<View style={styles.stack}>
{panels.map((id) => (
<View
key={id}
style={[StyleSheet.absoluteFill, { display: active === id ? 'flex' : 'none' }]}
>
{render(id)}
</View>
))}
</View>
{!kbVisible && (
<WorkspaceDock panels={panels} active={active} badges={badges} onSelect={setActive} />
)}
</View>
);
};
const styles = StyleSheet.create({
root: { flex: 1, backgroundColor: '#0D0D1A' },
stack: { flex: 1, position: 'relative' },
});
export default WorkspaceDeck;
-108
View File
@@ -1,108 +0,0 @@
/**
* WorkspaceDock die Taskleiste unten (Daumenzone). Ein Tap wechselt sofort
* das Panel; ein animierter Indikator gleitet unter das aktive Icon. Kleine
* Aktivitaets-Punkte (Badges) zeigen z.B. Desktop verbunden" / „Code da".
*
* Das ist der Kern des Workbench-Gefuehls: Desktop-Umfang, aber Handy-schnell
* per Daumen erreichbar statt einer Zoom-Landkarte.
*/
import React, { useState } from 'react';
import { LayoutChangeEvent, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { TileId, TILE_META } from './layout';
interface Props {
panels: TileId[];
active: TileId;
badges?: Partial<Record<TileId, string>>; // TileId → Punkt-Farbe (undefined = kein Punkt)
onSelect: (id: TileId) => void;
}
const WorkspaceDock: React.FC<Props> = ({ panels, active, badges, onSelect }) => {
const insets = useSafeAreaInsets();
const [rowW, setRowW] = useState(0);
const n = Math.max(1, panels.length);
const idx = Math.max(0, panels.indexOf(active));
const slot = rowW / n;
const onLayout = (e: LayoutChangeEvent) => setRowW(e.nativeEvent.layout.width);
const indicatorStyle = useAnimatedStyle(() => ({
width: slot,
transform: [{ translateX: withTiming(slot * idx, { duration: 200 }) }],
}));
return (
<View style={[styles.dock, { paddingBottom: Math.max(insets.bottom, 6) }]}>
<View style={styles.row} onLayout={onLayout}>
{rowW > 0 && <Animated.View style={[styles.indicator, indicatorStyle]} pointerEvents="none" />}
{panels.map((id) => {
const meta = TILE_META[id];
const isActive = id === active;
const badge = badges?.[id];
return (
<TouchableOpacity
key={id}
style={styles.item}
onPress={() => onSelect(id)}
activeOpacity={0.7}
>
<View>
<Text style={[styles.icon, isActive && styles.iconActive]}>{meta.icon}</Text>
{!!badge && <View style={[styles.badge, { backgroundColor: badge }]} />}
</View>
<Text style={[styles.label, isActive && styles.labelActive]} numberOfLines={1}>
{meta.title}
</Text>
</TouchableOpacity>
);
})}
</View>
</View>
);
};
const styles = StyleSheet.create({
dock: {
backgroundColor: '#0B0B18',
borderTopWidth: 1,
borderTopColor: '#1E1E2E',
},
row: {
flexDirection: 'row',
height: 58,
position: 'relative',
},
indicator: {
position: 'absolute',
top: 0,
height: 3,
backgroundColor: '#0096FF',
borderBottomLeftRadius: 3,
borderBottomRightRadius: 3,
},
item: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
gap: 2,
},
icon: { fontSize: 22, opacity: 0.55 },
iconActive: { opacity: 1 },
label: { color: '#6A6A85', fontSize: 10, fontWeight: '600' },
labelActive: { color: '#0096FF' },
badge: {
position: 'absolute',
top: -2,
right: -6,
width: 8,
height: 8,
borderRadius: 4,
borderWidth: 1,
borderColor: '#0B0B18',
},
});
export default WorkspaceDock;
-102
View File
@@ -1,102 +0,0 @@
/**
* WorkspaceScreen Screen-Wrapper fuer die Workbench.
*
* Kompakt-Modus klassischer Vollbild-Chat (wie vor dem Umbau).
* Cockpit-Modus Workbench mit Taskleisten-Dock: Chat · Code · Desktop.
*
* Aktivitaets-Badges am Dock: Editor blau, wenn schon Code-Dateien da sind;
* Desktop gruen NUR, wenn im aktiven Projekt eine VM laeuft.
*/
import React, { useEffect, useMemo, useState } from 'react';
import { View } from 'react-native';
import projectFocus, { FocusSnapshot } from '../services/projectFocus';
import codeFile from '../services/codeFile';
import brainApi from '../services/brainApi';
import viewMode, { ViewModeValue } from '../services/viewMode';
import ChatScreen from '../screens/ChatScreen';
import { TileId } from './layout';
import WorkspaceDeck from './WorkspaceDeck';
import ariaView, { AriaView } from '../services/ariaView';
import AriaViewCanvas from './AriaViewCanvas';
const COCKPIT_PANELS: TileId[] = ['chat', 'files', 'editor', 'vnc'];
const WorkspaceScreen: React.FC = () => {
const [mode, setMode] = useState<ViewModeValue>(viewMode.get());
const [focus, setFocus] = useState<FocusSnapshot>(projectFocus.get());
const [hasCode, setHasCode] = useState(false);
const [hasDesktop, setHasDesktop] = useState(false);
const [view, setView] = useState<AriaView | undefined>(undefined);
useEffect(() => viewMode.subscribe(setMode), []);
useEffect(() => projectFocus.subscribe(setFocus), []);
const pid = focus.focusedProjectId;
// aria_view: ARIAs komponierte Ansicht fuers fokussierte Projekt spiegeln.
useEffect(() => {
setView(ariaView.getView(pid));
return ariaView.subscribe((v) => {
if ((v.projectId || '') === (pid || '')) setView(v);
});
}, [pid]);
// Code-Signal: hat der Spiegel schon Dateien fuer dieses Projekt?
useEffect(() => {
setHasCode(codeFile.getFiles(pid).length > 0);
return codeFile.subscribe((u) => {
if ((u.projectId || '') === (pid || '')) setHasCode(true);
});
}, [pid]);
// Desktop-Signal: gruener Punkt NUR, wenn im AKTIVEN Projekt wirklich eine VM
// laeuft (nicht generell irgendwo). Quelle ist die projektbezogene VM-Liste;
// leichtes Nachfassen, damit Start/Stop sich zeitnah zeigt.
useEffect(() => {
if (!pid) { setHasDesktop(false); return; }
let alive = true;
const check = () => {
brainApi.listProjectVms(pid)
.then(r => { if (alive) setHasDesktop((r.vms || []).some(v => v.running)); })
.catch(() => { if (alive) setHasDesktop(false); });
};
check();
const t = setInterval(check, 6000);
return () => { alive = false; clearInterval(t); };
}, [pid]);
const badges = useMemo(() => ({
editor: hasCode ? '#0096FF' : undefined,
vnc: hasDesktop ? '#34C759' : undefined,
} as Partial<Record<TileId, string>>), [hasCode, hasDesktop]);
// Kompakt-Ansicht: klassischer Vollbild-Chat; Cockpit: Workbench mit Dock.
const content =
mode === 'compact' ? (
<ChatScreen />
) : (
<WorkspaceDeck projectId={pid} panels={COCKPIT_PANELS} badges={badges} />
);
// Generative Flaeche als Overlay, sobald ARIA fuer dieses Projekt eine Ansicht
// komponiert hat (present_view → aria_view). Chat/Cockpit bleiben darunter.
const showView = !!view && (view.projectId || '') === (pid || '');
return (
<View style={{ flex: 1 }}>
{content}
{showView && view && (
<AriaViewCanvas
view={view.view}
onClose={() => {
ariaView.clear(pid);
setView(undefined);
}}
/>
)}
</View>
);
};
export default WorkspaceScreen;
-167
View File
@@ -1,167 +0,0 @@
/**
* editorHtml selbstenthaltener Live-Code-Editor fuer die WebView (offline,
* kein CDN/Bundler). Eine transparente <textarea> ueber einer <pre>-Highlight-
* Ebene: man sieht Syntax-Highlighting UND kann tippen. Bewusst leichtgewichtig
* (Regex-Highlighter fuer C-artige/JS/Python/Shell), damit es ohne Build-Schritt
* inline passt.
*
* Bridge-Protokoll:
* RN -> WebView window.ariaBridge.onMessage(jsonString):
* {cmd:'setContent', content, language, version}
* {cmd:'applyPatch', from, to, insert, version}
* {cmd:'setLanguage', language}
* {cmd:'setReadOnly', value}
* WebView -> RN window.ReactNativeWebView.postMessage(jsonString):
* {event:'ready'}
* {event:'onEditFromUser', from, to, insert, fullText, version}
*/
export const EDITOR_HTML = `<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; background: #0D0D1A; }
#wrap { position: relative; height: 100%; width: 100%; }
#hl, #ed {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
margin: 0; border: 0; padding: 10px 12px;
font-family: 'Courier New', monospace; font-size: 13px; line-height: 1.45;
white-space: pre; word-wrap: normal; overflow: auto; tab-size: 2;
}
#hl { color: #C8C8E0; z-index: 1; pointer-events: none; }
#ed {
z-index: 2; color: transparent; background: transparent; caret-color: #0096FF;
resize: none; outline: none;
-webkit-text-fill-color: transparent;
}
#ed::selection { background: rgba(0,150,255,0.3); }
.tok-cmt { color: #6A7A6A; font-style: italic; }
.tok-str { color: #C6A972; }
.tok-num { color: #B58BE0; }
.tok-kw { color: #4F9CE8; font-weight: bold; }
</style></head><body>
<div id="wrap">
<pre id="hl"></pre>
<textarea id="ed" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
</div>
<script>
(function(){
var ed = document.getElementById('ed');
var hl = document.getElementById('hl');
var lang = 'text';
var version = 0;
var lastValue = '';
var applyingProgrammatic = false;
var KW = {
common: ['if','else','for','while','do','return','break','continue','switch','case','default','function','var','let','const','class','new','this','import','from','export','try','catch','finally','throw','typeof','instanceof','void','delete','in','of','yield','async','await','def','elif','end','then','fi','esac','local','echo','extends','implements','interface','public','private','protected','static','struct','enum','include','define','null','true','false','undefined','None','True','False','print','with','as','pass','lambda','not','and','or','is']
};
function esc(s){ return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function highlight(code){
// Token-Scan: Kommentare, Strings, Zahlen, Keywords. Bewusst simpel.
var out = '';
var i = 0, n = code.length;
var kwRe = /[A-Za-z_][A-Za-z0-9_]*/;
while(i < n){
var c = code[i];
var two = code.substr(i,2);
// Zeilenkommentar // oder #
if(two === '//' || (c === '#')){
var j = code.indexOf('\\n', i); if(j<0) j=n;
out += '<span class="tok-cmt">'+esc(code.slice(i,j))+'</span>'; i=j; continue;
}
// Blockkommentar
if(two === '/*'){
var k = code.indexOf('*/', i+2); k = (k<0)? n : k+2;
out += '<span class="tok-cmt">'+esc(code.slice(i,k))+'</span>'; i=k; continue;
}
// Strings
if(c === '"' || c === "'" || c === '\`'){
var q=c, m=i+1;
while(m<n){ if(code[m]==='\\\\'){m+=2;continue;} if(code[m]===q){m++;break;} m++; }
out += '<span class="tok-str">'+esc(code.slice(i,m))+'</span>'; i=m; continue;
}
// Zahl
if(c>='0' && c<='9'){
var p=i+1; while(p<n && /[0-9a-fA-F.xX_]/.test(code[p])) p++;
out += '<span class="tok-num">'+esc(code.slice(i,p))+'</span>'; i=p; continue;
}
// Wort / Keyword
if(/[A-Za-z_]/.test(c)){
var rest = code.slice(i);
var mm = rest.match(kwRe);
var w = mm[0];
if(KW.common.indexOf(w) >= 0){ out += '<span class="tok-kw">'+esc(w)+'</span>'; }
else { out += esc(w); }
i += w.length; continue;
}
out += esc(c); i++;
}
return out;
}
function render(){
hl.innerHTML = highlight(ed.value) + '\\n';
hl.scrollTop = ed.scrollTop; hl.scrollLeft = ed.scrollLeft;
}
function post(obj){ if(window.ReactNativeWebView) window.ReactNativeWebView.postMessage(JSON.stringify(obj)); }
// Minimalen Diff (gemeinsamer Prefix/Suffix) zwischen alt und neu.
function diff(a, b){
var s = 0; var maxS = Math.min(a.length, b.length);
while(s < maxS && a[s] === b[s]) s++;
var e = 0;
while(e < (maxS - s) && a[a.length-1-e] === b[b.length-1-e]) e++;
return { from: s, to: a.length - e, insert: b.slice(s, b.length - e) };
}
var editTimer = null;
ed.addEventListener('input', function(){
render();
if(applyingProgrammatic) return;
if(editTimer) clearTimeout(editTimer);
editTimer = setTimeout(function(){
var nv = ed.value;
var d = diff(lastValue, nv);
lastValue = nv; version++;
post({ event:'onEditFromUser', from:d.from, to:d.to, insert:d.insert, fullText:nv, version:version });
}, 160);
});
ed.addEventListener('scroll', function(){ hl.scrollTop=ed.scrollTop; hl.scrollLeft=ed.scrollLeft; });
window.ariaBridge = {
onMessage: function(json){
var m; try { m = JSON.parse(json); } catch(e){ return; }
if(m.cmd === 'setContent'){
applyingProgrammatic = true;
ed.value = m.content || '';
lastValue = ed.value;
if(typeof m.version === 'number') version = m.version;
if(m.language) lang = m.language;
render();
applyingProgrammatic = false;
} else if(m.cmd === 'applyPatch'){
applyingProgrammatic = true;
var v = ed.value;
var from = Math.max(0, Math.min(m.from, v.length));
var to = Math.max(from, Math.min(m.to, v.length));
ed.value = v.slice(0, from) + (m.insert||'') + v.slice(to);
lastValue = ed.value;
if(typeof m.version === 'number') version = m.version;
render();
applyingProgrammatic = false;
} else if(m.cmd === 'setLanguage'){
lang = m.language || 'text'; render();
} else if(m.cmd === 'setReadOnly'){
ed.readOnly = !!m.value;
}
}
};
render();
post({ event:'ready' });
})();
</script></body></html>`;
-134
View File
@@ -1,134 +0,0 @@
/**
* novncHtml noVNC-Client fuer die WebView, dessen WebSocket durch den
* RVS-Tunnel gebrueckt wird.
*
* Trick: window.WebSocket wird VOR dem Laden von noVNC durch einen Shim
* ersetzt. noVNC (RFB) glaubt, ein echtes WebSocket zu benutzen; tatsaechlich
* gehen die RFB-Bytes als Base64 per postMessage an RN RVS Bridge QEMU
* (und zurueck). Da RFB "server-speaks-first" ist, ist die Reihenfolge robust.
*
* noVNC wird vom CDN geladen (das Telefon hat Internet, da es ohnehin am RVS
* haengt). Voll-offline-Bundling waere ein spaeterer Schritt.
*
* Protokoll:
* RN -> WebView window.ariaVnc.onData(b64) RFB-Bytes vom Server
* WebView -> RN {event:'ready'} RFB initialisiert Tunnel oeffnen
* {event:'vnc_send', b64} RFB-Bytes an den Server
* {event:'vnc_close'} RFB hat geschlossen
* {event:'vnc_state', state} connected|disconnected
*/
export const NOVNC_HTML = `<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
* { margin:0; padding:0; }
html, body { height:100%; background:#000; overflow:hidden; }
#screen { width:100%; height:100%; }
#msg { position:absolute; top:8px; left:0; right:0; text-align:center;
color:#9090B0; font-family:sans-serif; font-size:12px; pointer-events:none; }
</style></head><body>
<div id="screen"></div>
<div id="msg">Verbinde mit Desktop </div>
<script>
(function(){
function post(o){ if(window.ReactNativeWebView) window.ReactNativeWebView.postMessage(JSON.stringify(o)); }
function b64FromBytes(bytes){
var CHUNK=0x8000, parts=[];
for(var i=0;i<bytes.length;i+=CHUNK){ parts.push(String.fromCharCode.apply(null, bytes.subarray(i,i+CHUNK))); }
return btoa(parts.join(''));
}
function bytesFromB64(b64){
var s=atob(b64), a=new Uint8Array(s.length);
for(var i=0;i<s.length;i++) a[i]=s.charCodeAt(i);
return a;
}
// --- WebSocket-Shim ---
function BridgeSocket(url, protocols){
this.url=url; this.protocol=''; this.readyState=0; this.binaryType='arraybuffer';
this.onopen=null; this.onclose=null; this.onerror=null; this.onmessage=null;
var self=this; window.__vncSocket=self;
setTimeout(function(){ self.readyState=1; if(self.onopen) self.onopen({type:'open'}); }, 0);
}
BridgeSocket.CONNECTING=0; BridgeSocket.OPEN=1; BridgeSocket.CLOSING=2; BridgeSocket.CLOSED=3;
BridgeSocket.prototype.send=function(data){
var bytes;
if(data instanceof ArrayBuffer) bytes=new Uint8Array(data);
else if(ArrayBuffer.isView(data)) bytes=new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
else bytes=new Uint8Array(0);
post({event:'vnc_send', b64:b64FromBytes(bytes)});
};
BridgeSocket.prototype.close=function(){
if(this.readyState===3) return;
this.readyState=3; if(this.onclose) this.onclose({type:'close'}); post({event:'vnc_close'});
};
BridgeSocket.prototype.addEventListener=function(t,fn){ this['on'+t]=fn; };
BridgeSocket.prototype.removeEventListener=function(t){ this['on'+t]=null; };
window.WebSocket = BridgeSocket;
// Eingehende Server-Bytes → in den Shim einspeisen.
window.ariaVnc = {
onData:function(b64){
var sock=window.__vncSocket;
if(!sock || !sock.onmessage) return;
sock.onmessage({ type:'message', data: bytesFromB64(b64).buffer });
}
};
var msg=document.getElementById('msg');
// Tastatur laeuft NICHT mehr ueber ein verstecktes WebView-Feld (Android
// oeffnet die Software-Tastatur dafuer unzuverlaessig). Stattdessen haelt die
// App ein echtes RN-<TextInput> und ruft window.ariaVncKey.* per
// injectJavaScript auf → wird unten (nach RFB-Init) definiert.
// cp<0x100 → Keysym == Codepoint (Latin-1)
// sonst → X11-Unicode-Keysym 0x01000000+cp
function cpToKeysym(cp){ return cp < 0x100 ? cp : 0x01000000 + cp; }
import('https://cdn.jsdelivr.net/npm/@novnc/novnc@1.4.0/core/rfb.js').then(function(mod){
var RFB = mod.default;
var rfb = new RFB(document.getElementById('screen'), 'ws://aria-vnc/', {});
var fit=true;
rfb.scaleViewport = true;
rfb.clipViewport = false;
rfb.addEventListener('connect', function(){ msg.style.display='none'; post({event:'vnc_state', state:'connected'}); });
rfb.addEventListener('disconnect', function(e){
msg.style.display='block'; msg.textContent='Desktop getrennt';
post({event:'vnc_state', state:'disconnected'});
});
window.__rfb = rfb;
// Down+Up einer Taste an die VM schicken.
function tap(keysym, code){ try{ rfb.sendKey(keysym, code||null, true); rfb.sendKey(keysym, code||null, false); }catch(_){} }
// Empfaenger-API: die App (RN-<TextInput> + Sondertasten-Leiste) ruft das
// per injectJavaScript.
// char(cp) druckbares Zeichen (Codepoint)
// keysym(ks) Sondertaste als fertiges X11-Keysym (Enter/Esc/F1/…)
// combo(mods,ks) Modifier(-Keysyms) halten → Taste → wieder loslassen
// (Strg+C, Strg+Alt+Entf, …). mods = Array von Keysyms.
window.ariaVncKey = {
char: function(cp){ tap(cpToKeysym(cp)); },
keysym: function(ks){ tap(ks); },
combo: function(mods, ks){
try{
for(var i=0;i<mods.length;i++) rfb.sendKey(mods[i], null, true);
rfb.sendKey(ks, null, true); rfb.sendKey(ks, null, false);
for(var j=mods.length-1;j>=0;j--) rfb.sendKey(mods[j], null, false);
}catch(_){}
}
};
// Steuerungs-API fuer die App (per injectJavaScript).
window.ariaVncCtl = {
cad: function(){ try{ rfb.sendCtrlAltDel(); }catch(_){} },
toggleFit: function(){ fit=!fit; rfb.scaleViewport=fit; rfb.clipViewport=!fit; post({event:'vnc_fit', fit:fit}); }
};
post({event:'ready'});
}).catch(function(err){
msg.textContent='noVNC konnte nicht geladen werden (Internet?)';
post({event:'vnc_state', state:'error', error:String(err)});
});
})();
</script></body></html>`;
-15
View File
@@ -1,15 +0,0 @@
/**
* layout Panel-Definitionen der Workbench (Metadaten fuer das Dock).
*/
export type TileId = 'chat' | 'files' | 'editor' | 'vnc' | 'preview';
export interface TileDef { id: TileId; title: string; icon: string }
export const TILE_META: Record<TileId, TileDef> = {
chat: { id: 'chat', title: 'Chat', icon: '💬' },
files: { id: 'files', title: 'Dateien', icon: '📁' },
editor: { id: 'editor', title: 'Code', icon: '📝' },
vnc: { id: 'vnc', title: 'Desktop', icon: '🖥️' },
preview: { id: 'preview', title: 'Vorschau', icon: '🖼️' },
};
-15
View File
@@ -1,15 +0,0 @@
/**
* ChatTile hostet die bestehende ChatScreen unveraendert als Workspace-Kachel.
*
* ChatScreen bleibt genau EINE Instanz (der Workspace-Tab ersetzt den alten
* Chat-Tab) und wird nie beim Fokuswechsel remountet sie liegt in der
* Identity-Content-Ebene und wird nur per display ein-/ausgeblendet. So
* behaelt sie RVS-Abos, Audio, Queue-State und Keyboard-Verhalten wie bisher.
*/
import React from 'react';
import ChatScreen from '../../screens/ChatScreen';
const ChatTile: React.FC = () => <ChatScreen />;
export default React.memo(ChatTile);
@@ -1,168 +0,0 @@
/**
* CodeEditorTile Live-Code-Editor (WebView, editorHtml.ts).
*
* Zeigt die Dateien eines Code-Projekts aus /shared/projects/<id>/:
* - beim Oeffnen werden die BEREITS vorhandenen Dateien vom Brain geladen
* (listProjectFiles/readProjectFile) sonst waere der Editor leer, obwohl
* ARIA schon Dateien geschrieben hat.
* - live schreibt ARIA weiter code_file-Stream aktualisiert die offene Datei.
* Stefan kann selbst editieren code_file_edit zurueck an die Bridge.
*/
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { WebView, WebViewMessageEvent } from 'react-native-webview';
import codeFile from '../../services/codeFile';
import brainApi from '../../services/brainApi';
import { EDITOR_HTML } from '../assets/editorHtml';
interface Props {
projectId: string;
}
function guessLang(path: string): string {
const ext = (path.split('.').pop() || '').toLowerCase();
const map: Record<string, string> = {
js: 'javascript', ts: 'typescript', tsx: 'typescript', py: 'python',
c: 'c', h: 'c', cpp: 'cpp', asm: 'asm', s: 'asm', sh: 'shell', bash: 'shell',
html: 'html', css: 'css', json: 'json', yaml: 'yaml', yml: 'yaml', md: 'markdown',
go: 'go', rs: 'rust', java: 'java', kt: 'kotlin', txt: 'text',
};
return map[ext] || 'text';
}
const CodeEditorTile: React.FC<Props> = ({ projectId }) => {
const webRef = useRef<WebView>(null);
// Pfade aus dem Brain (vorhandene Dateien) — mit Live-Dateien gemergt.
const [serverPaths, setServerPaths] = useState<string[]>([]);
const [currentPath, setCurrentPath] = useState<string | null>(null);
const [loadErr, setLoadErr] = useState<string>('');
const readyRef = useRef(false);
const currentPathRef = useRef<string | null>(currentPath);
currentPathRef.current = currentPath;
// Vereinigte, sortierte Dateiliste (Live-Spiegel + Server-Dateien).
const files = useMemo(() => {
const set = new Set<string>(serverPaths);
for (const f of codeFile.getFiles(projectId)) set.add(f.path);
return Array.from(set).sort((a, b) => a.localeCompare(b));
}, [serverPaths, projectId]);
const sendToWeb = useCallback((payload: Record<string, unknown>) => {
const js = `window.ariaBridge && window.ariaBridge.onMessage(${JSON.stringify(JSON.stringify(payload))}); true;`;
webRef.current?.injectJavaScript(js);
}, []);
const loadFileIntoEditor = useCallback(async (path: string | null) => {
if (!path) { sendToWeb({ cmd: 'setContent', content: '', language: 'text', version: 0 }); return; }
// Live-Version bevorzugen (falls ARIA gerade schreibt), sonst vom Brain holen.
const live = codeFile.getFile(projectId, path);
if (live) {
sendToWeb({ cmd: 'setContent', content: live.content, language: live.language, version: live.version });
return;
}
try {
const res = await brainApi.readProjectFile(projectId, path);
sendToWeb({ cmd: 'setContent', content: res.content ?? '', language: guessLang(path), version: 0 });
} catch (e: any) {
sendToWeb({ cmd: 'setContent', content: `// Konnte ${path} nicht laden: ${e?.message || e}`, language: 'text', version: 0 });
}
}, [projectId, sendToWeb]);
// Projektwechsel: vorhandene Dateien vom Brain laden.
useEffect(() => {
let cancelled = false;
setLoadErr('');
brainApi.listProjectFiles(projectId)
.then(res => {
if (cancelled) return;
const paths = (res.files || []).map(f => f.path);
setServerPaths(paths);
setCurrentPath(prev => (prev && paths.includes(prev)) ? prev : (paths[0] ?? codeFile.getFiles(projectId)[0]?.path ?? null));
})
.catch(e => { if (!cancelled) setLoadErr(String(e?.message || e)); });
return () => { cancelled = true; };
}, [projectId]);
// Live-Updates aus dem Spiegel.
useEffect(() => {
return codeFile.subscribe((u) => {
if ((u.projectId || '') !== (projectId || '')) return;
setServerPaths(prev => prev.includes(u.path) ? prev : [...prev, u.path]);
if (!currentPathRef.current) { setCurrentPath(u.path); return; }
if (u.path !== currentPathRef.current || !readyRef.current) return;
if (u.patch) {
sendToWeb({ cmd: 'applyPatch', from: u.patch.from, to: u.patch.to, insert: u.patch.insert, version: u.version });
} else {
sendToWeb({ cmd: 'setContent', content: u.content ?? '', language: u.language, version: u.version });
}
});
}, [projectId, sendToWeb]);
// Datei-Auswahl gewechselt → laden (falls WebView bereit).
useEffect(() => {
if (readyRef.current) loadFileIntoEditor(currentPath);
}, [currentPath, loadFileIntoEditor]);
const onMessage = useCallback((e: WebViewMessageEvent) => {
let m: any;
try { m = JSON.parse(e.nativeEvent.data); } catch { return; }
if (m.event === 'ready') {
readyRef.current = true;
loadFileIntoEditor(currentPathRef.current);
} else if (m.event === 'onEditFromUser') {
const path = currentPathRef.current;
if (!path) return;
codeFile.sendEdit(projectId, path, { from: m.from, to: m.to, insert: m.insert }, m.fullText, m.version);
}
}, [projectId, loadFileIntoEditor]);
return (
<View style={styles.container}>
<View style={styles.tabsRow}>
{files.length === 0 ? (
<Text style={styles.noFiles}>{loadErr ? `Fehler: ${loadErr}` : 'Noch keine Datei in diesem Projekt'}</Text>
) : (
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.tabs}>
{files.map((path) => {
const active = path === currentPath;
const name = path.split('/').pop() || path;
return (
<TouchableOpacity key={path} onPress={() => setCurrentPath(path)} style={[styles.tab, active && styles.tabActive]}>
<Text style={[styles.tabText, active && styles.tabTextActive]} numberOfLines={1}>{name}</Text>
</TouchableOpacity>
);
})}
</ScrollView>
)}
</View>
<WebView
ref={webRef}
style={styles.web}
originWhitelist={['*']}
source={{ html: EDITOR_HTML, baseUrl: '' }}
onMessage={onMessage}
javaScriptEnabled
domStorageEnabled
keyboardDisplayRequiresUserAction={false}
androidLayerType="hardware"
setBuiltInZoomControls={false}
/>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#0D0D1A' },
tabsRow: { height: 40, backgroundColor: '#12122A', borderBottomColor: '#1E1E2E', borderBottomWidth: 1, justifyContent: 'center' },
tabs: { alignItems: 'center', paddingHorizontal: 6 },
noFiles: { color: '#9090B0', fontSize: 13, paddingHorizontal: 12 },
tab: { paddingHorizontal: 12, paddingVertical: 6, marginHorizontal: 3, borderRadius: 12, backgroundColor: '#0D0D1A', maxWidth: 180 },
tabActive: { backgroundColor: '#0096FF' },
tabText: { color: '#9090B0', fontSize: 12, fontWeight: '600' },
tabTextActive: { color: '#FFFFFF' },
web: { flex: 1, backgroundColor: '#0D0D1A' },
});
export default CodeEditorTile;
-192
View File
@@ -1,192 +0,0 @@
/**
* DesktopTile das Desktop-Panel eines Code-Projekts.
*
* Zeigt die (pro Projekt gefuehrte) QEMU-VM-Liste: leer, bis ARIA per
* vm_register eine VM eintraegt. Pro VM: Start / Stop / Verbinden. Verbinden"
* oeffnet die noVNC-Ansicht (VncTile) fuer den VNC-Port dieser VM.
*/
import React, { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Image, Modal, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import brainApi, { ProjectVm } from '../../services/brainApi';
import VncTile from './VncTile';
interface Props {
projectId: string;
focused: boolean;
}
const DesktopTile: React.FC<Props> = ({ projectId, focused }) => {
const [vms, setVms] = useState<ProjectVm[]>([]);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState('');
const [busy, setBusy] = useState(''); // VM-Name, der gerade bootet/stoppt
const [connected, setConnected] = useState<ProjectVm | null>(null);
const [shotBusy, setShotBusy] = useState('');
const [shot, setShot] = useState<{ name: string; b64: string } | null>(null);
const load = useCallback(() => {
if (!projectId) { setVms([]); setErr(''); setLoading(false); return; }
setLoading(true); setErr('');
brainApi.listProjectVms(projectId)
.then(r => setVms(r.vms || []))
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, [projectId]);
useEffect(() => {
if (focused && !connected) load();
}, [focused, projectId, connected, load]);
const boot = useCallback((vm: ProjectVm) => {
setBusy(vm.name);
brainApi.bootProjectVm(projectId, vm.name)
.then(() => load())
.catch(e => setErr(String(e?.message || e)))
.finally(() => setBusy(''));
}, [projectId, load]);
const stop = useCallback((vm: ProjectVm) => {
setBusy(vm.name);
brainApi.stopProjectVm(projectId, vm.name)
.then(() => load())
.catch(e => setErr(String(e?.message || e)))
.finally(() => setBusy(''));
}, [projectId, load]);
const screenshot = useCallback((vm: ProjectVm) => {
setShotBusy(vm.name); setErr('');
brainApi.screenshotProjectVm(projectId, vm.name)
.then(r => setShot({ name: vm.name, b64: r.base64 }))
.catch(e => setErr(String(e?.message || e)))
.finally(() => setShotBusy(''));
}, [projectId]);
if (!focused) {
return (
<View style={styles.placeholder}>
<Text style={styles.icon}>🖥</Text>
<Text style={styles.text}>Desktop</Text>
<Text style={styles.sub}>Panel öffnen für VM-Liste</Text>
</View>
);
}
return (
<View style={styles.container}>
<View style={styles.bar}>
<Text style={styles.barTitle}>Virtuelle Maschinen</Text>
<TouchableOpacity onPress={load} style={styles.barBtn}><Text style={styles.barBtnText}></Text></TouchableOpacity>
</View>
<ScrollView contentContainerStyle={{ padding: 12 }}>
{loading && vms.length === 0 ? (
<ActivityIndicator color="#0096FF" style={{ marginTop: 20 }} />
) : err ? (
<Text style={styles.err}>{err}</Text>
) : !projectId ? (
<Text style={styles.empty}>Kein aktives Projekt wechsle in ein Projekt für dessen VMs.</Text>
) : vms.length === 0 ? (
<Text style={styles.empty}>
Noch keine VM in diesem Projekt.{'\n'}
Sag ARIA z.B. bau eine QEMU-VM zum Testen" sie registriert sie hier,
dann kannst du sie starten und verbinden.
</Text>
) : (
vms.map(vm => {
const isBusy = busy === vm.name;
return (
<View key={vm.name} style={styles.vmRow}>
<View style={{ flex: 1 }}>
<Text style={styles.vmName}>
<Text style={{ color: vm.running ? '#34C759' : '#555570' }}></Text> {vm.name}
<Text style={styles.vmMeta}> {vm.arch} · {vm.running ? 'läuft' : 'gestoppt'}</Text>
</Text>
<Text style={styles.vmCmd} numberOfLines={2}>{vm.boot_cmd || `aria-vm boot ${vm.name} --vnc-display ${vm.vnc_display}`}</Text>
</View>
<View style={styles.vmBtns}>
{isBusy ? (
<ActivityIndicator color="#0096FF" />
) : vm.running ? (
<>
<TouchableOpacity onPress={() => screenshot(vm)} style={[styles.vmBtn, { borderColor: '#8888AA' }]} disabled={shotBusy === vm.name}>
{shotBusy === vm.name
? <ActivityIndicator color="#8888AA" size="small" />
: <Text style={[styles.vmBtnText, { color: '#C8C8E0' }]}>📷</Text>}
</TouchableOpacity>
<TouchableOpacity onPress={() => setConnected(vm)} style={[styles.vmBtn, { borderColor: '#0096FF' }]}>
<Text style={[styles.vmBtnText, { color: '#0096FF' }]}>Verbinden</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => stop(vm)} style={[styles.vmBtn, { borderColor: '#E55C5C' }]}>
<Text style={[styles.vmBtnText, { color: '#E55C5C' }]}>Stop</Text>
</TouchableOpacity>
</>
) : (
<TouchableOpacity onPress={() => boot(vm)} style={[styles.vmBtn, { borderColor: '#34C759' }]}>
<Text style={[styles.vmBtnText, { color: '#34C759' }]}>Start</Text>
</TouchableOpacity>
)}
</View>
</View>
);
})
)}
</ScrollView>
<Modal visible={!!shot} transparent animationType="fade" onRequestClose={() => setShot(null)}>
<TouchableOpacity style={styles.shotOverlay} activeOpacity={1} onPress={() => setShot(null)}>
<Text style={styles.shotTitle}>{shot?.name} Screenshot</Text>
{shot && (
<Image
source={{ uri: `data:image/png;base64,${shot.b64}` }}
style={styles.shotImg}
resizeMode="contain"
/>
)}
<Text style={styles.shotHint}>Tippen zum Schließen</Text>
</TouchableOpacity>
</Modal>
{/* Vollbild-VNC — randlos ueber das ganze Display (Header + Dock weg). */}
{connected && (
<Modal visible animationType="slide" onRequestClose={() => setConnected(null)} supportedOrientations={['portrait', 'landscape']}>
<View style={styles.fs}>
<VncTile projectId={projectId} focused port={connected.vnc_port || (5900 + (connected.vnc_display || 1))} />
<TouchableOpacity style={styles.fsBack} onPress={() => setConnected(null)} activeOpacity={0.8}>
<Text style={styles.fsBackText}> VMs</Text>
</TouchableOpacity>
</View>
</Modal>
)}
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#0D0D1A' },
placeholder: { flex: 1, backgroundColor: '#000', alignItems: 'center', justifyContent: 'center' },
icon: { fontSize: 64, marginBottom: 16 },
text: { color: '#FFFFFF', fontSize: 18, fontWeight: '700' },
sub: { color: '#9090B0', fontSize: 14, marginTop: 8 },
bar: { height: 40, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 12, backgroundColor: '#12122A', borderBottomColor: '#1E1E2E', borderBottomWidth: 1 },
barTitle: { color: '#E0E0F0', fontSize: 14, fontWeight: '700', flex: 1 },
barBtn: { paddingHorizontal: 10, paddingVertical: 4 },
barBtnText: { color: '#0096FF', fontSize: 14, fontWeight: '700' },
empty: { color: '#8888AA', fontSize: 13, lineHeight: 20, textAlign: 'center', marginTop: 24 },
err: { color: '#FF6E6E', fontSize: 13, marginTop: 16 },
vmRow: { flexDirection: 'row', alignItems: 'center', backgroundColor: '#12122A', borderRadius: 10, padding: 12, marginBottom: 8 },
vmName: { color: '#E0E0F0', fontSize: 15, fontWeight: '700' },
vmMeta: { color: '#8888AA', fontSize: 12, fontWeight: '400' },
vmCmd: { color: '#6A9BD0', fontSize: 11, fontFamily: 'monospace', marginTop: 4 },
vmBtns: { flexDirection: 'row', gap: 6, alignItems: 'center' },
vmBtn: { borderWidth: 1, borderRadius: 8, paddingHorizontal: 10, paddingVertical: 6, minWidth: 34, alignItems: 'center' },
vmBtnText: { fontSize: 12, fontWeight: '700' },
fs: { flex: 1, backgroundColor: '#000000' },
fsBack: { position: 'absolute', top: 34, left: 10, backgroundColor: 'rgba(18,18,42,0.9)', borderColor: '#2A2A3E', borderWidth: 1, borderRadius: 10, paddingHorizontal: 12, paddingVertical: 7 },
fsBackText: { color: '#0096FF', fontSize: 14, fontWeight: '700' },
shotOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.92)', alignItems: 'center', justifyContent: 'center', padding: 12 },
shotTitle: { color: '#E0E0F0', fontSize: 14, fontWeight: '700', marginBottom: 10 },
shotImg: { width: '100%', height: '78%', backgroundColor: '#000' },
shotHint: { color: '#8888AA', fontSize: 12, marginTop: 12 },
});
export default DesktopTile;
-149
View File
@@ -1,149 +0,0 @@
/**
* FilesTile Datei-Browser eines Projekts (/shared/projects/<id>/).
*
* Listet ALLE Dateien (nicht nur Code): erzeugte Bilder, Logs, Assets die
* gleichen, die in der Projektliste als 📄 gezaehlt werden. Tippen auf ein Bild
* zeigt es; tippen auf eine Textdatei zeigt eine Vorschau.
*/
import React, { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Image, Modal, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import brainApi from '../../services/brainApi';
interface Props {
projectId: string;
focused: boolean;
}
interface FileEntry { path: string; size: number }
const IMG_EXT = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'];
function ext(path: string): string { return (path.split('.').pop() || '').toLowerCase(); }
function isImage(path: string): boolean { return IMG_EXT.includes(ext(path)); }
function iconFor(path: string): string {
const e = ext(path);
if (isImage(path)) return '🖼️';
if (['md', 'txt', 'readme'].includes(e)) return '📄';
if (['asm', 's', 'c', 'h', 'cpp', 'py', 'js', 'ts', 'sh', 'go', 'rs'].includes(e)) return '📝';
if (['zip', 'tar', 'gz', 'img', 'iso', 'qcow2'].includes(e)) return '📦';
return '📄';
}
function humanSize(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
const FilesTile: React.FC<Props> = ({ projectId, focused }) => {
const [files, setFiles] = useState<FileEntry[]>([]);
const [loading, setLoading] = useState(false);
const [err, setErr] = useState('');
const [preview, setPreview] = useState<{ path: string; kind: 'image' | 'text'; data: string } | null>(null);
const [previewBusy, setPreviewBusy] = useState('');
const load = useCallback(() => {
if (!projectId) { setFiles([]); setErr(''); setLoading(false); return; }
setLoading(true); setErr('');
brainApi.listProjectFiles(projectId)
.then(r => setFiles((r.files || []).slice().sort((a, b) => a.path.localeCompare(b.path))))
.catch(e => setErr(String(e?.message || e)))
.finally(() => setLoading(false));
}, [projectId]);
useEffect(() => { if (focused) load(); }, [focused, projectId, load]);
const open = useCallback((f: FileEntry) => {
setPreviewBusy(f.path); setErr('');
if (isImage(f.path)) {
brainApi.readProjectFileBinary(projectId, f.path)
.then(r => setPreview({ path: f.path, kind: 'image', data: `data:${r.mime};base64,${r.base64}` }))
.catch(e => setErr(String(e?.message || e)))
.finally(() => setPreviewBusy(''));
} else {
brainApi.readProjectFile(projectId, f.path)
.then(r => setPreview({ path: f.path, kind: 'text', data: r.content ?? '' }))
.catch(e => setErr(String(e?.message || e)))
.finally(() => setPreviewBusy(''));
}
}, [projectId]);
if (!focused) {
return (
<View style={styles.placeholder}>
<Text style={styles.icon}>📁</Text>
<Text style={styles.text}>Dateien</Text>
</View>
);
}
return (
<View style={styles.container}>
<View style={styles.bar}>
<Text style={styles.barTitle}>Dateien{files.length ? ` (${files.length})` : ''}</Text>
<TouchableOpacity onPress={load} style={styles.barBtn}><Text style={styles.barBtnText}></Text></TouchableOpacity>
</View>
<ScrollView contentContainerStyle={{ padding: 8 }}>
{loading && files.length === 0 ? (
<ActivityIndicator color="#0096FF" style={{ marginTop: 20 }} />
) : err ? (
<Text style={styles.err}>{err}</Text>
) : files.length === 0 ? (
<Text style={styles.empty}>{!projectId ? 'Kein aktives Projekt — wechsle in ein Projekt für dessen Dateien.' : 'Noch keine Dateien in diesem Projekt.'}</Text>
) : (
files.map(f => (
<TouchableOpacity key={f.path} onPress={() => open(f)} style={styles.row} disabled={previewBusy === f.path}>
<Text style={styles.rowIcon}>{iconFor(f.path)}</Text>
<Text style={styles.rowName} numberOfLines={1}>{f.path}</Text>
{previewBusy === f.path
? <ActivityIndicator color="#8888AA" size="small" />
: <Text style={styles.rowSize}>{humanSize(f.size)}</Text>}
</TouchableOpacity>
))
)}
</ScrollView>
<Modal visible={!!preview} transparent animationType="fade" onRequestClose={() => setPreview(null)}>
<View style={styles.pvOverlay}>
<View style={styles.pvBar}>
<Text style={styles.pvTitle} numberOfLines={1}>{preview?.path}</Text>
<TouchableOpacity onPress={() => setPreview(null)}><Text style={styles.pvClose}></Text></TouchableOpacity>
</View>
{preview?.kind === 'image' ? (
<Image source={{ uri: preview.data }} style={styles.pvImg} resizeMode="contain" />
) : (
<ScrollView style={styles.pvTextWrap} horizontal>
<ScrollView><Text style={styles.pvText}>{preview?.data}</Text></ScrollView>
</ScrollView>
)}
</View>
</Modal>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#0D0D1A' },
placeholder: { flex: 1, backgroundColor: '#0D0D1A', alignItems: 'center', justifyContent: 'center' },
icon: { fontSize: 56, marginBottom: 10 },
text: { color: '#FFFFFF', fontSize: 18, fontWeight: '700' },
bar: { height: 40, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 12, backgroundColor: '#12122A', borderBottomColor: '#1E1E2E', borderBottomWidth: 1 },
barTitle: { color: '#E0E0F0', fontSize: 14, fontWeight: '700', flex: 1 },
barBtn: { paddingHorizontal: 10, paddingVertical: 4 },
barBtnText: { color: '#0096FF', fontSize: 14, fontWeight: '700' },
empty: { color: '#8888AA', fontSize: 13, textAlign: 'center', marginTop: 24 },
err: { color: '#FF6E6E', fontSize: 13, marginTop: 16, paddingHorizontal: 8 },
row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10, paddingHorizontal: 8, borderBottomColor: '#161628', borderBottomWidth: 1, gap: 10 },
rowIcon: { fontSize: 18 },
rowName: { color: '#E0E0F0', fontSize: 13, flex: 1 },
rowSize: { color: '#555570', fontSize: 11 },
pvOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.94)' },
pvBar: { flexDirection: 'row', alignItems: 'center', padding: 12, gap: 10 },
pvTitle: { color: '#E0E0F0', fontSize: 13, fontWeight: '700', flex: 1 },
pvClose: { color: '#E0E0F0', fontSize: 20, paddingHorizontal: 6 },
pvImg: { flex: 1, width: '100%' },
pvTextWrap: { flex: 1, padding: 12 },
pvText: { color: '#C8C8E0', fontSize: 12, fontFamily: 'monospace' },
});
export default FilesTile;
-298
View File
@@ -1,298 +0,0 @@
/**
* VncTile Live-Desktop der QEMU-VM (noVNC in einer WebView, RFB durch RVS).
*
* Nur aktiv, wenn das Desktop-Panel offen ist (focused): dann WebView mounten,
* bei 'ready' den RVS-VNC-Tunnel oeffnen. Zwei Bedien-Leisten machen die VM auf
* dem Handy voll bedienbar:
* - ctlBar (oben rechts): Fn-Leiste ein/aus, Software-Tastatur, Fit 1:1.
* - keyBar (oben, Fn): echte Steuertasten, die keine Software-Tastatur
* liefert Esc, Tab, Pfeile, Pos1/Ende/Bild, Einfg/Entf, Enter, F1F12 und
* Sticky-Modifier Strg/Alt/Shift (fuer Strg+C, Strg+Alt+Entf, ).
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Keyboard, NativeSyntheticEvent, ScrollView, StyleSheet, Text, TextInput, TextInputChangeEventData, TextInputKeyPressEventData, TouchableOpacity, View } from 'react-native';
import { WebView, WebViewMessageEvent } from 'react-native-webview';
import desktop from '../../services/desktop';
import { NOVNC_HTML } from '../assets/novncHtml';
interface Props {
projectId: string;
focused: boolean;
port?: number; // VNC-Port der zu verbindenden VM (Default 5901 = Display :1)
}
// X11-Keysyms fuer Sondertasten, die kein druckbares Zeichen liefern.
const KEYSYM = { Backspace: 0xff08, Enter: 0xff0d, Tab: 0xff09 };
const MOD = { ctrl: 0xffe3, alt: 0xffe9, shift: 0xffe1 };
const cpToKeysym = (cp: number) => (cp < 0x100 ? cp : 0x01000000 + cp);
// Sondertasten fuer die Fn-Leiste (Label → Keysym).
const NAV_KEYS: { label: string; ks: number }[] = [
{ label: 'Esc', ks: 0xff1b }, { label: 'Tab', ks: 0xff09 },
{ label: '←', ks: 0xff51 }, { label: '↑', ks: 0xff52 }, { label: '↓', ks: 0xff54 }, { label: '→', ks: 0xff53 },
{ label: 'Pos1', ks: 0xff50 }, { label: 'Ende', ks: 0xff57 },
{ label: 'Bild↑', ks: 0xff55 }, { label: 'Bild↓', ks: 0xff56 },
{ label: 'Einfg', ks: 0xff63 }, { label: 'Entf', ks: 0xffff }, { label: '⏎', ks: 0xff0d },
];
const F_KEYS: { label: string; ks: number }[] = Array.from({ length: 12 }, (_, i) => ({ label: 'F' + (i + 1), ks: 0xffbe + i }));
const VncTile: React.FC<Props> = ({ projectId, focused, port = 5901 }) => {
const webRef = useRef<WebView>(null);
const kbdRef = useRef<TextInput>(null);
const bufRef = useRef(''); // Spiegel des TextInput-Textes
const [status, setStatus] = useState<'idle' | 'connecting' | 'connected' | 'disconnected'>('idle');
const [kbdOn, setKbdOn] = useState(false);
const [keyBar, setKeyBar] = useState(false); // Fn-Leiste sichtbar?
const [mods, setMods] = useState({ ctrl: false, alt: false, shift: false });
const modRef = useRef({ ctrl: false, alt: false, shift: false }); // Spiegel fuer Closures
const unsubDataRef = useRef<null | (() => void)>(null);
const teardown = useCallback(() => {
if (unsubDataRef.current) { unsubDataRef.current(); unsubDataRef.current = null; }
desktop.closeVnc();
}, []);
useEffect(() => {
if (!focused) { teardown(); setStatus('idle'); }
return () => teardown();
}, [focused, teardown]);
// Button-Zustand an die ECHTE Tastatur-Sichtbarkeit koppeln: Androids
// Zurueck-Taste blendet die Tastatur aus, ohne den TextInput zu blurren —
// ueber keyboardDidHide setzen wir das ⌨-Symbol trotzdem zurueck.
useEffect(() => {
if (!focused) return;
const show = Keyboard.addListener('keyboardDidShow', () => setKbdOn(true));
const hide = Keyboard.addListener('keyboardDidHide', () => setKbdOn(false));
return () => { show.remove(); hide.remove(); };
}, [focused]);
const ctl = useCallback((fn: string) => {
webRef.current?.injectJavaScript(`window.ariaVncCtl && window.ariaVncCtl.${fn}(); true;`);
}, []);
const sendKeysym = useCallback((ks: number) => {
webRef.current?.injectJavaScript(`window.ariaVncKey && window.ariaVncKey.keysym(${ks}); true;`);
}, []);
const sendCombo = useCallback((modKeysyms: number[], ks: number) => {
webRef.current?.injectJavaScript(`window.ariaVncKey && window.ariaVncKey.combo(${JSON.stringify(modKeysyms)}, ${ks}); true;`);
}, []);
// Aktive Sticky-Modifier als Keysym-Liste; nach dem Anwenden one-shot zuruecksetzen.
const activeMods = useCallback(() => {
const m = modRef.current; const a: number[] = [];
if (m.ctrl) a.push(MOD.ctrl); if (m.alt) a.push(MOD.alt); if (m.shift) a.push(MOD.shift);
return a;
}, []);
const clearMods = useCallback(() => {
if (modRef.current.ctrl || modRef.current.alt || modRef.current.shift) {
modRef.current = { ctrl: false, alt: false, shift: false };
setMods(modRef.current);
}
}, []);
const toggleMod = useCallback((k: 'ctrl' | 'alt' | 'shift') => {
modRef.current = { ...modRef.current, [k]: !modRef.current[k] };
setMods(modRef.current);
}, []);
// Eine Taste (fertiges Keysym) senden — mit ggf. aktiven Modifiern.
const pressKey = useCallback((ks: number) => {
const m = activeMods();
if (m.length) { sendCombo(m, ks); clearMods(); } else sendKeysym(ks);
}, [activeMods, sendCombo, clearMods, sendKeysym]);
// Ein druckbares Zeichen senden — mit ggf. aktiven Modifiern (Strg+C etc.).
const pressChar = useCallback((cp: number) => {
const m = activeMods();
if (m.length) { sendCombo(m, cpToKeysym(cp)); clearMods(); }
else webRef.current?.injectJavaScript(`window.ariaVncKey && window.ariaVncKey.char(${cp}); true;`);
}, [activeMods, sendCombo, clearMods]);
// Tastatur ein-/ausblenden. Oeffnen: blur→focus erzwingt das Aufklappen auch
// dann, wenn der TextInput noch fokussiert ist (Tastatur per Zurueck-Taste
// versteckt). Schliessen: Keyboard.dismiss(); den Button-Zustand setzt der
// keyboardDidShow/Hide-Listener — nicht hier —, damit er nie „haengen" bleibt.
const toggleKbd = useCallback(() => {
if (kbdOn) { Keyboard.dismiss(); }
else { kbdRef.current?.blur(); setTimeout(() => kbdRef.current?.focus(), 30); }
}, [kbdOn]);
// Druckbare Zeichen: Prefix-Diff des (wachsenden) Feldes → nur neu Getipptes an
// die VM. Loeschungen kommen ueber onKeyPress(Backspace), daher hier nur Inserts.
const onKbdChange = useCallback((e: NativeSyntheticEvent<TextInputChangeEventData>) => {
const text = e.nativeEvent.text || '';
const prev = bufRef.current;
let i = 0;
const min = Math.min(prev.length, text.length);
while (i < min && prev.charCodeAt(i) === text.charCodeAt(i)) i++;
for (const ch of text.slice(i)) { const cp = ch.codePointAt(0); if (cp) pressChar(cp); }
bufRef.current = text;
if (text.length > 200) { bufRef.current = ''; kbdRef.current?.setNativeProps({ text: '' }); }
}, [pressChar]);
// Sondertasten der Software-Tastatur: Backspace feuert auf Android zuverlaessig
// als keyPress; die Return-Taste (Haken) kommt als onSubmitEditing (s.u.).
const onKbdKeyPress = useCallback((e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
const k = e.nativeEvent.key;
if (k === 'Backspace') pressKey(KEYSYM.Backspace);
else if (k === 'Enter') pressKey(KEYSYM.Enter);
}, [pressKey]);
const onMessage = useCallback((e: WebViewMessageEvent) => {
let m: any;
try { m = JSON.parse(e.nativeEvent.data); } catch { return; }
if (m.event === 'ready') {
setStatus('connecting');
unsubDataRef.current = desktop.onVncData((b64) => {
const js = `window.ariaVnc && window.ariaVnc.onData(${JSON.stringify(b64)}); true;`;
webRef.current?.injectJavaScript(js);
});
desktop.openVnc(projectId, port);
} else if (m.event === 'vnc_send') {
desktop.sendInput(m.b64);
} else if (m.event === 'vnc_close') {
desktop.closeVnc();
} else if (m.event === 'vnc_state') {
if (m.state === 'connected') setStatus('connected');
else if (m.state === 'disconnected') setStatus('disconnected');
}
}, [projectId, port]);
if (!focused) {
return (
<View style={styles.placeholder}>
<Text style={styles.icon}>🖥</Text>
<Text style={styles.text}>Desktop</Text>
<Text style={styles.sub}>Panel öffnen zum Verbinden</Text>
</View>
);
}
const connected = status === 'connected';
return (
<View style={styles.container}>
<WebView
ref={webRef}
style={styles.web}
originWhitelist={['*']}
source={{ html: NOVNC_HTML, baseUrl: 'https://aria-vnc.local/' }}
onMessage={onMessage}
javaScriptEnabled
domStorageEnabled
mixedContentMode="always"
androidLayerType="hardware"
keyboardDisplayRequiresUserAction={false}
/>
{/* Verstecktes Eingabefeld: fokussiert Android-Tastatur tippt in die VM.
keyboardType=visible-password schaltet Autokorrektur/Vorschlaege ab und
liefert saubere Einzelzeichen. Offscreen, aber fokussierbar. */}
<TextInput
ref={kbdRef}
style={styles.hiddenInput}
onChange={onKbdChange}
onKeyPress={onKbdKeyPress}
onSubmitEditing={() => pressKey(KEYSYM.Enter)}
keyboardType="visible-password"
returnKeyType="send"
autoCapitalize="none"
autoCorrect={false}
spellCheck={false}
blurOnSubmit={false}
caretHidden
contextMenuHidden
multiline={false}
/>
{/* Steuerungs-Leiste — nur wenn verbunden */}
{connected && (
<View style={styles.ctlBar}>
<TouchableOpacity style={[styles.ctlBtn, keyBar && styles.ctlBtnOn]} onPress={() => setKeyBar(v => !v)} activeOpacity={0.7}>
<Text style={styles.ctlText}>Fn</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.ctlBtn, kbdOn && styles.ctlBtnOn]} onPress={toggleKbd} activeOpacity={0.7}>
<Text style={styles.ctlText}></Text>
</TouchableOpacity>
<TouchableOpacity style={styles.ctlBtn} onPress={() => ctl('toggleFit')} activeOpacity={0.7}>
<Text style={styles.ctlText}></Text>
</TouchableOpacity>
</View>
)}
{/* Fn-Leiste — echte Steuertasten (oben, ueber der Software-Tastatur). */}
{connected && keyBar && (
<View style={styles.keyBar} pointerEvents="box-none">
<ScrollView horizontal showsHorizontalScrollIndicator={false} keyboardShouldPersistTaps="always" contentContainerStyle={styles.keyRow}>
<TouchableOpacity style={[styles.key, mods.ctrl && styles.keyOn]} onPress={() => toggleMod('ctrl')} activeOpacity={0.7}><Text style={styles.keyText}>Strg</Text></TouchableOpacity>
<TouchableOpacity style={[styles.key, mods.alt && styles.keyOn]} onPress={() => toggleMod('alt')} activeOpacity={0.7}><Text style={styles.keyText}>Alt</Text></TouchableOpacity>
<TouchableOpacity style={[styles.key, mods.shift && styles.keyOn]} onPress={() => toggleMod('shift')} activeOpacity={0.7}><Text style={styles.keyText}>Shift</Text></TouchableOpacity>
{NAV_KEYS.map(k => (
<TouchableOpacity key={k.label} style={styles.key} onPress={() => pressKey(k.ks)} activeOpacity={0.7}><Text style={styles.keyText}>{k.label}</Text></TouchableOpacity>
))}
</ScrollView>
<ScrollView horizontal showsHorizontalScrollIndicator={false} keyboardShouldPersistTaps="always" contentContainerStyle={styles.keyRow}>
{F_KEYS.map(k => (
<TouchableOpacity key={k.label} style={styles.key} onPress={() => pressKey(k.ks)} activeOpacity={0.7}><Text style={styles.keyText}>{k.label}</Text></TouchableOpacity>
))}
<TouchableOpacity style={styles.key} onPress={() => ctl('cad')} activeOpacity={0.7}><Text style={styles.keyTextSm}>Strg+Alt+Entf</Text></TouchableOpacity>
</ScrollView>
</View>
)}
{!connected && (
<View style={styles.overlay} pointerEvents="none">
<Text style={styles.overlayText}>
{status === 'connecting' ? 'Verbinde …' : status === 'disconnected' ? 'Getrennt' : ''}
</Text>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#000000' },
web: { flex: 1, backgroundColor: '#000000' },
placeholder: { flex: 1, backgroundColor: '#000000', alignItems: 'center', justifyContent: 'center' },
icon: { fontSize: 64, marginBottom: 16 },
text: { color: '#FFFFFF', fontSize: 18, fontWeight: '700' },
sub: { color: '#9090B0', fontSize: 14, marginTop: 8 },
ctlBar: {
position: 'absolute',
top: 34,
right: 8,
flexDirection: 'row',
gap: 6,
},
ctlBtn: {
backgroundColor: 'rgba(18,18,42,0.9)',
borderColor: '#2A2A3E',
borderWidth: 1,
borderRadius: 10,
paddingHorizontal: 10,
paddingVertical: 7,
minWidth: 38,
alignItems: 'center',
justifyContent: 'center',
},
ctlBtnOn: { backgroundColor: 'rgba(0,150,255,0.85)', borderColor: '#0096FF' },
ctlText: { color: '#E0E0F0', fontSize: 16, fontWeight: '700' },
ctlTextSmall: { color: '#E0E0F0', fontSize: 11, fontWeight: '700' },
// Fokussierbar (nicht display:none), aber aus dem Sichtfeld geschoben.
hiddenInput: { position: 'absolute', width: 1, height: 1, top: -100, left: -100, opacity: 0, padding: 0 },
keyBar: { position: 'absolute', top: 74, left: 0, right: 0, gap: 5 },
keyRow: { paddingHorizontal: 6, gap: 5, alignItems: 'center' },
key: {
backgroundColor: 'rgba(18,18,42,0.92)', borderColor: '#2A2A3E', borderWidth: 1,
borderRadius: 8, paddingHorizontal: 9, paddingVertical: 7, minWidth: 34,
alignItems: 'center', justifyContent: 'center',
},
keyOn: { backgroundColor: 'rgba(0,150,255,0.85)', borderColor: '#0096FF' },
keyText: { color: '#E0E0F0', fontSize: 13, fontWeight: '700' },
keyTextSm: { color: '#E0E0F0', fontSize: 10, fontWeight: '700' },
overlay: { position: 'absolute', top: 12, left: 0, right: 0, alignItems: 'center' },
overlayText: { color: '#9090B0', fontSize: 12, backgroundColor: 'rgba(0,0,0,0.6)', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 10, overflow: 'hidden' },
});
export default VncTile;
@@ -1,40 +0,0 @@
/**
* useWorkspaceLayout merkt sich pro Projekt die zuletzt fokussierte Kachel,
* damit man beim Zurueckkehren in ein Code-Projekt wieder dort landet (Editor/
* Desktop) statt immer im Chat. Persistiert nach AsyncStorage (Muster wie
* aria_project_drafts).
*/
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useCallback, useEffect, useRef, useState } from 'react';
import { TileId } from './layout';
const KEY = 'aria_workspace_layout';
interface Entry { focus: TileId | null }
type LayoutMap = Record<string, Entry>;
const keyOf = (projectId: string) => projectId || '__main__';
export function useWorkspaceLayout(projectId: string) {
const mapRef = useRef<LayoutMap>({});
const [loaded, setLoaded] = useState(false);
useEffect(() => {
AsyncStorage.getItem(KEY).then((v) => {
if (v) { try { mapRef.current = JSON.parse(v) || {}; } catch { /* ignore */ } }
setLoaded(true);
}).catch(() => setLoaded(true));
}, []);
const getFocus = useCallback((): TileId | null | undefined => {
return mapRef.current[keyOf(projectId)]?.focus;
}, [projectId]);
const saveFocus = useCallback((focus: TileId | null) => {
mapRef.current = { ...mapRef.current, [keyOf(projectId)]: { focus } };
AsyncStorage.setItem(KEY, JSON.stringify(mapRef.current)).catch(() => {});
}, [projectId]);
return { loaded, getFocus, saveFocus };
}
-42
View File
@@ -1,42 +0,0 @@
# ════════════════════════════════════════════════════════════
# ARIA Brain — Agent + Memory Container
#
# FastAPI-Server mit Vector-DB-Memory (Qdrant).
# Spricht via HTTP/WebSocket mit Bridge und Diagnostic.
# LLM-Calls gehen ueber den Proxy (claude-max-api-proxy).
# ════════════════════════════════════════════════════════════
FROM python:3.12-slim
# System-Tools die Skills brauchen koennten (curl, jq, git, ssh-client,
# Build-Basics fuer venv-Compiles). Bewusst sparsam — alles weitere
# bringt der Skill selbst mit (siehe execution=local-bin).
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
jq \
git \
openssh-client \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# CPU-only torch zuerst — sonst zieht sentence-transformers den Default
# torch-Wheel der ~5 GB CUDA-Libs (nvidia-cudnn, nvidia-cublas, cuda-toolkit,
# triton, ...) als Dependencies einsaugt. Brain laeuft komplett auf CPU
# (MiniLM-Embeddings ~120 MB), wir brauchen das alles nicht.
RUN pip install --no-cache-dir torch==2.5.1 \
--index-url https://download.pytorch.org/whl/cpu
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Embedding-Model-Cache und Skills landen unter /data (Volume)
ENV SENTENCE_TRANSFORMERS_HOME=/data/_models
ENV ARIA_DATA_DIR=/data
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
-3588
View File
File diff suppressed because it is too large Load Diff
-90
View File
@@ -1,90 +0,0 @@
"""Einmaliger Backfill: weist bestehenden Memory-Punkten ein `scope`
(system | personal) zu. Sicher & reversibel Stefan kann pro Eintrag in der
Diagnostic-UI umschalten. Idempotent: laeuft mehrfach ohne Schaden.
Heuristik (datengetrieben aus dem realen Bestand):
- type=preference / fact / conversation / reminder -> personal
- source in (seed, auto-feedback) -> system
- type=identity -> system
- type in (rule, tool, skill) und category in SYSTEM_CATS -> system
- sonst -> personal (sicher: nichts leakt)
Aufruf im Brain-Container:
docker exec aria-brain python3 /app/backfill_scope.py # dry-run
docker exec aria-brain python3 /app/backfill_scope.py --apply # schreibt
"""
import os
import sys
from collections import Counter
from qdrant_client import QdrantClient
from qdrant_client.http import models as qm
COLLECTION = "aria_memory"
SYSTEM_CATS = {
"sicherheit", "arbeitsweise", "architektur", "ehrlichkeit", "verhalten",
"voice", "skills", "freigaben", "infrastruktur", "persoenlichkeit",
"pentest", "ausgabe",
}
def compute_scope(pl: dict) -> str:
typ = pl.get("type")
src = pl.get("source")
cat = (pl.get("category") or "").lower()
if typ == "preference":
return "personal"
if typ in ("fact", "conversation", "reminder"):
return "personal"
if src in ("seed", "auto-feedback"):
return "system"
if typ == "identity":
return "system"
if typ in ("rule", "tool", "skill") and cat in SYSTEM_CATS:
return "system"
return "personal"
def main():
apply = "--apply" in sys.argv
force = "--force" in sys.argv # auch schon gesetzte scopes ueberschreiben
c = QdrantClient(
host=os.environ.get("QDRANT_HOST", "aria-qdrant"),
port=int(os.environ.get("QDRANT_PORT", "6333")),
)
pts, _ = c.scroll(collection_name=COLLECTION, limit=5000,
with_payload=True, with_vectors=False)
per_scope: dict[str, list] = {"system": [], "personal": []}
pinned_examples = Counter()
skipped = 0
for p in pts:
pl = p.payload or {}
if pl.get("scope") in ("system", "personal") and not force:
skipped += 1
continue
scope = compute_scope(pl)
per_scope[scope].append(p.id)
if pl.get("pinned"):
pinned_examples[(scope, pl.get("source"), pl.get("type"),
pl.get("category"))] += 1
print(f"total={len(pts)} skipped(already set)={skipped}")
print(f"-> system={len(per_scope['system'])} personal={len(per_scope['personal'])}")
print("pinned split (scope, source, type, category):")
for k, v in sorted(pinned_examples.items()):
print(" ", k, v)
if not apply:
print("\nDRY-RUN — nichts geschrieben. Mit --apply ausfuehren.")
return
for scope, ids in per_scope.items():
if not ids:
continue
c.set_payload(collection_name=COLLECTION, payload={"scope": scope}, points=ids)
print(f"\nAPPLIED: system={len(per_scope['system'])} personal={len(per_scope['personal'])}")
if __name__ == "__main__":
main()
-264
View File
@@ -1,264 +0,0 @@
"""
Background-Loop fuer Triggers.
Laeuft alle TICK_SEC Sekunden in einem asyncio Task, geht ueber alle
active Triggers und entscheidet ob sie feuern muessen.
Feuern bedeutet:
1. Trigger-Manifest update (fire_count++, last_fired_at, ggf. deaktivieren)
2. Log-Eintrag schreiben
3. agent.chat() mit einem system-Praefix aufrufen (NICHT als 'user'!)
ARIA bekommt das wie eine Push-Nachricht und kann antworten
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import urllib.error
import urllib.request
from datetime import datetime, timezone
from typing import Optional
import triggers as triggers_mod
import watcher as watcher_mod
logger = logging.getLogger(__name__)
# Polling-Frequenz des Background-Loops. Vorher 30s → Auto-Vorbeifahrt
# durch einen 300m-Radius bei >50 km/h konnte zwischen zwei Ticks komplett
# verpasst werden. Mit 8s ist auch eine 18-Sekunden-Durchfahrt (120 km/h
# durch 300m) garantiert mind. einmal getroffen. Der Loop ist billig
# (paar Dateilesungen + AST-Eval), das macht Brain nicht warm.
TICK_SEC = 8
BRIDGE_URL = os.environ.get("BRIDGE_URL", "http://aria-bridge:8090")
def _push_to_bridge(reply: str, trigger_name: str, ttype: str, events: list) -> None:
"""POSTed eine Trigger-Antwort an die Bridge fuer RVS-Broadcast + TTS.
Synchron via urllib wird per run_in_executor aus dem async-Loop
gerufen. Failures werden geloggt, brechen aber nicht ab.
"""
payload = json.dumps({
"reply": reply,
"trigger_name": trigger_name,
"type": ttype,
"events": events or [],
}).encode("utf-8")
url = f"{BRIDGE_URL}/internal/trigger-fired"
try:
req = urllib.request.Request(
url, data=payload, method="POST",
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=15) as resp:
if resp.status != 200:
logger.warning("[trigger-push] Bridge hat %s zurueckgegeben", resp.status)
except urllib.error.URLError as exc:
logger.warning("[trigger-push] Bridge unerreichbar (%s): %s", url, exc)
except Exception as exc:
logger.warning("[trigger-push] Push fehlgeschlagen: %s", exc)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _parse_iso(s: str) -> Optional[datetime]:
if not s:
return None
try:
return datetime.fromisoformat(s.replace("Z", "+00:00"))
except Exception:
return None
def _should_fire(trigger: dict, vars_: dict, now: datetime) -> bool:
if not trigger.get("active", True):
return False
t = trigger.get("type", "")
if t == "timer":
fires_at = _parse_iso(trigger.get("fires_at", ""))
if not fires_at:
return False
if fires_at.tzinfo is None:
fires_at = fires_at.replace(tzinfo=timezone.utc)
return now >= fires_at
if t == "watcher":
# Check-Interval respektieren (sonst pollen wir zu hektisch)
check_interval = int(trigger.get("check_interval_sec", 300))
last_checked = _parse_iso(trigger.get("last_checked_at", ""))
if last_checked:
if last_checked.tzinfo is None:
last_checked = last_checked.replace(tzinfo=timezone.utc)
if (now - last_checked).total_seconds() < check_interval:
return False
# Throttle: erst feuern wenn last_fired lange genug her ist
last_fired = _parse_iso(trigger.get("last_fired_at", ""))
throttle = int(trigger.get("throttle_sec", 3600))
if last_fired:
if last_fired.tzinfo is None:
last_fired = last_fired.replace(tzinfo=timezone.utc)
if (now - last_fired).total_seconds() < throttle:
return False
# Condition pruefen
cond = (trigger.get("condition") or "").strip()
if not cond:
return False
try:
return watcher_mod.evaluate(cond, vars_)
except Exception as e:
logger.warning("Trigger %s: Condition '%s' fehlerhaft: %s",
trigger.get("name"), cond, e)
return False
if t == "cron":
# TODO: später, wenn jemand Bock auf Cron-Parser hat
return False
return False
async def _fire(trigger: dict, agent_factory) -> None:
"""Ruft ARIA mit einer System-Praefix-Nachricht auf."""
name = trigger.get("name", "?")
message = trigger.get("message") or "(ohne Nachricht)"
ttype = trigger.get("type", "?")
# Manifest updaten
try:
triggers_mod.mark_fired(name)
except Exception as e:
logger.warning("mark_fired %s: %s", name, e)
# Log
triggers_mod.append_log(name, {"event": "fired", "type": ttype, "message": message})
# System-Nachricht an ARIA: nicht als User, sondern als Hinweis
prompt = (
f"[Trigger ausgelöst: '{name}', Typ: {ttype}] "
f"Geplante Nachricht: \"{message}\". "
f"Sage Stefan jetzt diese Information, in deinem Stil. "
f"Wenn der Trigger ein Watcher war (Bedingung wurde erfuellt), "
f"erwaehne kurz worum es geht. Antworte direkt, keine Rueckfrage."
)
try:
# WICHTIG: agent.chat() ist ein SYNCHRONER, blockierender Aufruf (Proxy-
# HTTP mit bis zu 24h Read-Timeout). NIEMALS direkt im async-Loop —
# sonst friert ein einziger getriggerter Turn den GESAMTEN Brain ein
# (kein /health, kein weiterer Request). Wie der /chat-Pfad in den
# Executor auslagern, damit der Event-Loop frei bleibt.
loop = asyncio.get_running_loop()
def _run_turn():
a = agent_factory()
rep, *_rest = a.chat(prompt, source="trigger")
return rep, a.pop_events()
reply, events = await loop.run_in_executor(None, _run_turn)
logger.info("[trigger] %s gefeuert → ARIA-Reply: %s", name, reply[:80])
triggers_mod.append_log(name, {"event": "reply", "text": reply[:500]})
# Reply an die Bridge pushen, damit App + Diagnostic + TTS sie kriegen.
# Ohne diesen Push wuerde die Antwort nur im Brain-Log landen.
await loop.run_in_executor(None, _push_to_bridge, reply, name, ttype, events)
except Exception as e:
logger.exception("Trigger %s feuern fehlgeschlagen: %s", name, e)
triggers_mod.append_log(name, {"event": "error", "error": str(e)[:300]})
async def _tick(agent_factory) -> None:
"""Ein Pruefdurchlauf. Geht ueber alle Triggers, feuert was zu feuern ist.
near()-State-Tracking: entered_near/left_near brauchen die Information
ob ein near()-Aufruf beim letzten Tick true war (Uebergang erkennen).
Wir halten das pro Trigger als near_states-Dict im Manifest und
aktualisieren es nach jedem Eval auch wenn nicht gefeuert wird."""
try:
all_triggers = triggers_mod.list_triggers(active_only=True)
except Exception as e:
logger.warning("triggers.list: %s", e)
return
if not all_triggers:
return
now = datetime.now(timezone.utc)
for trigger in all_triggers:
if trigger.get("type") != "watcher":
continue
try:
# Variablen pro Trigger sammeln — wegen prev_near_states-Closure
prev = trigger.get("near_states") or {}
vars_ = watcher_mod.collect_variables(prev_near_states=prev)
# Condition evaluieren via _should_fire (intern ruft watcher.evaluate)
fired = _should_fire(trigger, vars_, now)
# State immer updaten, egal ob gefeuert wurde — sonst greift
# entered_near/left_near nicht
new_states = vars_.get("_new_near_states") or {}
trigger["near_states"] = new_states
trigger["last_checked_at"] = _now_iso()
try:
triggers_mod.write(trigger["name"], trigger)
except Exception as e:
logger.warning("trigger.write %s: %s", trigger.get("name"), e)
if fired:
# Feuern als eigener Task — wenn ARIA langsam antwortet,
# darf der naechste Tick nicht blockieren
asyncio.create_task(_fire(trigger, agent_factory))
except Exception as e:
logger.warning("Trigger-Check %s: %s", trigger.get("name"), e)
# Timer (one-shot) — separat ohne near-State
timer_vars = None
for trigger in all_triggers:
if trigger.get("type") != "timer":
continue
try:
if timer_vars is None:
timer_vars = watcher_mod.collect_variables()
if _should_fire(trigger, timer_vars, now):
asyncio.create_task(_fire(trigger, agent_factory))
except Exception as e:
logger.warning("Timer-Check %s: %s", trigger.get("name"), e)
# Module-Level-Slot fuer die agent_factory damit on-demand-Ticks (von
# z.B. POST /triggers/check-now) Zugang haben ohne durch den ganzen
# Lifespan-Pfad geschleust zu werden.
_AGENT_FACTORY = None
async def tick_now() -> dict:
"""Sofortiger Trigger-Check — nicht warten auf den naechsten Loop-Tick.
Wird genutzt wenn ein neues GPS-Update reinkommt: Bridge ruft das nach
_persist_location, damit Watcher mit near() den frischen Wert sofort
sehen statt bis zu TICK_SEC Sekunden zu warten."""
if _AGENT_FACTORY is None:
return {"ok": False, "error": "Background-Loop noch nicht gestartet"}
try:
await _tick(_AGENT_FACTORY)
return {"ok": True}
except Exception as exc:
logger.exception("tick_now: %s", exc)
return {"ok": False, "error": str(exc)}
async def run_loop(agent_factory) -> None:
"""Endlosschleife — wird vom main lifespan gestartet + gestoppt."""
global _AGENT_FACTORY
_AGENT_FACTORY = agent_factory
logger.info("Trigger-Loop gestartet (TICK_SEC=%d)", TICK_SEC)
while True:
try:
await _tick(agent_factory)
except Exception as e:
logger.exception("Tick-Fehler: %s", e)
await asyncio.sleep(TICK_SEC)
-163
View File
@@ -1,163 +0,0 @@
#!/usr/bin/env python3
"""Einmal-Cleanup: entfernt "vergiftete" Hauptthread-Turns aus conversation.jsonl.
Hintergrund
-----------
Solange ARIAs Persona nur via --append-system-prompt kam (statt --system-prompt,
voller Replace), fiel das Modell im Hauptchat aus der Rolle und antwortete als
"Claude Code" ("das ist injizierter Kontext, ich adoptiere die Persona nicht").
Jede dieser Antworten wurde per conversation.add("assistant", ...) in die History
geschrieben. Beim naechsten Request landet sie als <previous_response> im
stdin-Prompt das Modell sieht seine EIGENEN Ablehnungs-Turns und setzt die
Haltung fort (Self-Grounding rueckwaerts). Der --system-prompt-Fix verhindert
NEUE Vergiftung, aber die bestehenden Gift-Turns muessen einmalig raus, sonst
zieht die History das Modell weiter aus der Rolle.
Was das Script tut
------------------
- Findet Hauptthread-Assistant-Turns (KEIN project_id), deren Inhalt eindeutig
eine Rollen-Ablehnung ist: enthaelt "claude code" UND einen zweiten Marker
(injiz/inject/fabriz/fabricat/adoptier/adopting/prompt injection/keine echten).
- Entfernt diese Assistant-Turns PLUS den unmittelbar davor stehenden
Hauptthread-User-Turn (die ausloesende Frage) also den ganzen Fehl-Dialog.
- Laesst ALLES andere unangetastet: projekt-getaggte Turns, distill-Marker,
legitime Hauptchat-Turns.
- Standard = DRY-RUN (zeigt nur was raus wuerde). Mit --apply wird geschrieben,
vorher ein Backup .pre-cleanup.bak angelegt. Idempotent.
Aufruf (auf der VM, Host-Pfad des Bind-Mounts):
python3 clean_poisoned_turns.py ../aria-data/brain/data/conversation.jsonl
python3 clean_poisoned_turns.py ../aria-data/brain/data/conversation.jsonl --apply
Danach Brain neu starten, damit die bereinigte History geladen wird:
docker compose restart aria-brain
"""
from __future__ import annotations
import json
import re
import shutil
import sys
from pathlib import Path
# STARKE, selbstreferenzielle Break-Marker — identisch zu prompts._IDENTITY_BREAK
# (dem Laufzeit-Gift-Waechter). Hier dupliziert, damit das Script self-contained
# ist (laeuft auch auf dem Host-Python ohne qdrant/prompts-Import). Bewusst NICHT
# das blosse Wort "injizier"/"prompt injection" — das nutzt ARIA in Pentest-
# Antworten legitim (sonst False Positives auf echte Security-Doku, wie im
# Dry-Run gesehen: "Runde 60 … SSRF", "Dein Ziel: LLM …").
_BREAK = re.compile(
r"ich\s+bin\s+(?:allerdings\s+|ja\s+|nach\s+wie\s+vor\s+|weiterhin\s+)*claude|"
r"i'?m\s+(?:still\s+|actually\s+)?claude\s+code|i\s+am\s+claude\b|"
r"erfundene[nr]?\s+(?:tool|persona|schemas)|fabricated\s+persona|"
r"fabrizierte?\s+(?:persona|gespr|konversation)|fabricated\s+conversation|"
r"fake[- ]persona|injizierte[rn]?\s+(?:system-?prompt|kontext|persona)|"
r"injected\s+(?:system\s*prompt|persona|context)|"
r"diese\s+session\s+enthält\s+(?:einen|eine)\b.{0,40}injizier|"
r"this\s+session\s+(?:contains|has|keeps|repeatedly)\b.{0,40}(?:inject|fabricat|fake)|"
r"nicht\s+real\s+in\s+dieser\s+(?:umgebung|session)|not\s+real\s+in\s+this",
re.IGNORECASE,
)
def is_poison(content: str) -> bool:
return bool(_BREAK.search(content or ""))
def get_content(obj: dict) -> str:
"""conversation.jsonl nutzt 'content', chat_backup.jsonl nutzt 'text'."""
v = obj.get("content")
if not isinstance(v, str):
v = obj.get("text")
return v if isinstance(v, str) else ""
def is_main_thread(obj: dict) -> bool:
"""Hauptthread = kein Projekt-Tag. Brain nutzt 'project_id', UI/Bridge
'projectId'."""
pid = obj.get("project_id")
if pid is None:
pid = obj.get("projectId")
return not (str(pid or "").strip())
def main() -> int:
args = [a for a in sys.argv[1:] if not a.startswith("--")]
apply = "--apply" in sys.argv[1:]
path = Path(args[0]) if args else Path("/data/conversation.jsonl")
if not path.exists():
print(f"FEHLER: {path} existiert nicht.", file=sys.stderr)
return 2
raw_lines = path.read_text(encoding="utf-8").splitlines()
# Parse zu (raw, obj|None). Nicht-JSON / leere Zeilen bleiben unangetastet.
parsed: list[tuple[str, dict | None]] = []
for line in raw_lines:
s = line.strip()
if not s:
parsed.append((line, None))
continue
try:
parsed.append((line, json.loads(s)))
except Exception:
parsed.append((line, None))
drop = [False] * len(parsed)
poisoned_pairs = [] # (assistant_idx, user_idx|None) fuer's Log
for i, (_, obj) in enumerate(parsed):
if not isinstance(obj, dict):
continue
if obj.get("op") == "distill":
continue
if obj.get("role") != "assistant" or not is_main_thread(obj):
continue
content = get_content(obj)
if not content or not is_poison(content):
continue
# Gift-Assistant-Turn -> droppen
drop[i] = True
user_idx = None
# Unmittelbar davor stehenden Hauptthread-User-Turn (die Frage) mit weg.
for j in range(i - 1, -1, -1):
pj = parsed[j][1]
if not isinstance(pj, dict) or pj.get("op") == "distill":
continue
if pj.get("role") == "user" and is_main_thread(pj):
drop[j] = True
user_idx = j
break # nur der direkt vorangehende Turn
poisoned_pairs.append((i, user_idx))
n_drop = sum(drop)
if n_drop == 0:
print("Keine Gift-Turns gefunden — History ist sauber. Nichts zu tun.")
return 0
print(f"Gefundene Fehl-Dialoge: {len(poisoned_pairs)} "
f"(insgesamt {n_drop} Zeilen zu entfernen)\n")
for a_idx, u_idx in poisoned_pairs:
if u_idx is not None:
uq = get_content(parsed[u_idx][1] or {})
print(f" Frage (Zeile {u_idx + 1}): {uq[:90]!r}")
ac = get_content(parsed[a_idx][1] or {})
print(f" Ablehng (Zeile {a_idx + 1}): {ac[:90]!r}")
print()
if not apply:
print("DRY-RUN — nichts geschrieben. Zum Anwenden erneut mit --apply aufrufen.")
return 0
backup = path.with_suffix(path.suffix + ".pre-cleanup.bak")
shutil.copy2(path, backup)
kept = [raw for idx, (raw, _) in enumerate(parsed) if not drop[idx]]
path.write_text("\n".join(kept) + ("\n" if kept else ""), encoding="utf-8")
print(f"OK — {n_drop} Zeilen entfernt. Backup: {backup}")
print("Jetzt Brain neu starten: docker compose restart aria-brain")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-207
View File
@@ -1,207 +0,0 @@
"""
Conversation-State ein einziger Rolling-Window-State fuer ARIAs
laufendes Gespraech mit Stefan.
Stefan-Entscheidung: KEINE Sessions, KEIN Multi-Thread. EIN Strang,
intern rollend. Was rausfaellt, wird ggf. destilliert und landet
als type=fact Memory in der Vector-DB.
Persistenz: append-only JSONL unter /data/conversation.jsonl.
Bei Restart wird die letzte N gelesen (komplett vermeidet Memory-
Overhead bei sehr langen Verlaeufen).
"""
from __future__ import annotations
import json
import logging
import os
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional
logger = logging.getLogger(__name__)
CONVERSATION_FILE = Path(os.environ.get("CONVERSATION_FILE", "/data/conversation.jsonl"))
@dataclass
class Turn:
role: str # "user" | "assistant"
content: str
ts: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
source: str = "" # "app" / "diagnostic" / "stt" — optional
project_id: str = "" # leer = Hauptthread; sonst projects.py-ID
class Conversation:
"""In-Memory Rolling Window, mit JSONL-Persistenz."""
def __init__(self, max_window: int = 50, distill_threshold: int = 60,
distill_count: int = 30):
self.max_window = max_window
self.distill_threshold = distill_threshold
self.distill_count = distill_count
self.turns: List[Turn] = []
self._load()
def _load(self):
if not CONVERSATION_FILE.exists():
return
try:
lines = CONVERSATION_FILE.read_text(encoding="utf-8").splitlines()
except Exception as exc:
logger.warning("Konversation laden fehlgeschlagen: %s", exc)
return
loaded: List[Turn] = []
for line in lines:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except Exception:
continue
if obj.get("op") == "distill":
# Marker: bis hierhin wurde alles destilliert
drop_until_ts = obj.get("ts", "")
if drop_until_ts:
loaded = [t for t in loaded if t.ts > drop_until_ts]
continue
role = obj.get("role")
content = obj.get("content")
if role in ("user", "assistant") and isinstance(content, str):
loaded.append(Turn(role=role, content=content,
ts=obj.get("ts", ""),
source=obj.get("source", ""),
project_id=obj.get("project_id", "")))
self.turns = loaded
logger.info("Konversation geladen: %d Turns aus %s", len(self.turns), CONVERSATION_FILE)
def _append_to_file(self, record: dict):
try:
CONVERSATION_FILE.parent.mkdir(parents=True, exist_ok=True)
with CONVERSATION_FILE.open("a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
except Exception as exc:
logger.warning("Konversation persist fehlgeschlagen: %s", exc)
def add(self, role: str, content: str, source: str = "",
project_id: str = "") -> Turn:
t = Turn(role=role, content=content, source=source, project_id=project_id)
self.turns.append(t)
record = {
"ts": t.ts, "role": t.role, "content": t.content, "source": t.source,
}
if t.project_id:
record["project_id"] = t.project_id
self._append_to_file(record)
return t
def window(self, project_id: Optional[str] = None) -> List[Turn]:
"""Die letzten max_window Turns — gehen in den LLM-Prompt.
Wenn project_id gesetzt: nur Turns aus diesem Projekt + die letzten
~5 Hauptthread-Turns als Kontext. Wenn project_id leer/None und
explizit uebergeben nur Hauptthread."""
if project_id is None:
return self.turns[-self.max_window:]
if project_id == "":
# Hauptthread-Modus: alle Turns, aber project-getaggte rausfiltern
main_turns = [t for t in self.turns if not t.project_id]
return main_turns[-self.max_window:]
# In-Projekt: alle Turns des Projekts + Tail des Hauptthreads als Kontext
project_turns = [t for t in self.turns if t.project_id == project_id]
return project_turns[-self.max_window:]
def window_recent_per_project(self) -> dict:
"""Returns {project_id: [last N turns]} — fuer „hol mich ab"-Summary."""
groups: dict[str, List[Turn]] = {}
for t in self.turns:
pid = t.project_id or ""
groups.setdefault(pid, []).append(t)
return groups
def needs_distill(self) -> bool:
return len(self.turns) > self.distill_threshold
def take_oldest_for_distill(self) -> List[Turn]:
"""Gibt die N aeltesten Turns zurueck — fuer den Destillat-Call.
Entfernt sie NICHT das macht commit_distill nach erfolgreichem Call."""
return self.turns[: self.distill_count]
def commit_distill(self, last_distilled_ts: str):
"""Schreibt einen Distill-Marker, entfernt aus dem In-Memory-Window."""
self._append_to_file({"op": "distill", "ts": last_distilled_ts})
self.turns = [t for t in self.turns if t.ts > last_distilled_ts]
logger.info("Distill commit bei ts=%s — Window jetzt %d Turns", last_distilled_ts, len(self.turns))
def reset(self):
"""Hardes Reset — verwende vorsichtig (Diagnostic-Button)."""
try:
if CONVERSATION_FILE.exists():
CONVERSATION_FILE.unlink()
except Exception:
pass
self.turns = []
logger.warning("Konversation komplett zurueckgesetzt")
def _rewrite_file(self) -> None:
"""Datei komplett aus In-Memory-State neu schreiben.
Wird nach Mutationen (Loeschen) genutzt. Alte distill-Marker
gehen dabei verloren das ist OK weil der In-Memory-State
bereits post-distill ist."""
try:
CONVERSATION_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = CONVERSATION_FILE.with_suffix(".jsonl.tmp")
with tmp.open("w", encoding="utf-8") as f:
for t in self.turns:
rec = {
"ts": t.ts, "role": t.role,
"content": t.content, "source": t.source,
}
if t.project_id:
rec["project_id"] = t.project_id
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
tmp.replace(CONVERSATION_FILE)
except Exception as exc:
logger.warning("Konversation rewrite fehlgeschlagen: %s", exc)
def remove_by_match(self, role: str, content: str,
ts_iso_hint: Optional[str] = None) -> bool:
"""Entfernt EINEN Turn mit passendem role + content.
Bei Mehrfach-Match (z.B. zwei identische 'ja'-Turns) waehlt
den naehesten zum ts_iso_hint, sonst den juengsten.
Returns True wenn was entfernt wurde.
"""
candidates = [(i, t) for i, t in enumerate(self.turns)
if t.role == role and t.content == content]
if not candidates:
logger.info("[conv] remove_by_match: kein Match fuer role=%s content[:40]=%r",
role, content[:40])
return False
if len(candidates) > 1 and ts_iso_hint:
def _diff(item):
_, turn = item
try:
return abs((datetime.fromisoformat(turn.ts.replace("Z", "+00:00"))
- datetime.fromisoformat(ts_iso_hint.replace("Z", "+00:00"))).total_seconds())
except Exception:
return 1e9
candidates.sort(key=_diff)
idx, turn = candidates[0] if not ts_iso_hint else candidates[0]
self.turns.pop(idx)
self._rewrite_file()
logger.info("[conv] Turn entfernt: role=%s ts=%s content[:40]=%r",
turn.role, turn.ts, turn.content[:40])
return True
def stats(self) -> dict:
return {
"turns": len(self.turns),
"max_window": self.max_window,
"distill_threshold": self.distill_threshold,
"needs_distill": self.needs_distill(),
}
-68
View File
@@ -1,68 +0,0 @@
"""
Local-LLM-Client (Plan B) Brain-Seite.
Ruft das schnelle lokale LLM (Qwen3 auf der AI-Box) ueber die Bridge:
Brain HTTP /internal/local-llm Bridge RVS llm-adapter llama.cpp
Analog zum Claude-`proxy_client`, nur ueber die Bridge (die ist der RVS-Client;
das Brain bleibt HTTP-only). Der Router im Brain (B1) entscheidet, welche Turns
hierher gehen (einfach) und welche an Claude (schwer / Tool-Bedarf).
Rueckgabe von local_llm_chat: {ok, content, model?, elapsedMs?} oder {ok:False, error}.
Nie werfen der Aufrufer entscheidet bei ok=False, ob er auf Claude eskaliert.
"""
from __future__ import annotations
import json
import logging
import os
import urllib.error
import urllib.request
logger = logging.getLogger(__name__)
BRIDGE_URL = os.environ.get("BRIDGE_URL", "http://aria-bridge:8090")
# Etwas ueber dem Bridge-seitigen _LLM_TIMEOUT_S (30s), damit der HTTP-Call nicht
# vor dem eigentlichen LLM-Timeout abbricht.
LOCAL_LLM_HTTP_TIMEOUT_SEC = float(os.environ.get("LOCAL_LLM_HTTP_TIMEOUT_SEC", "35"))
def local_llm_chat(messages: list, *, max_tokens: int = 512,
temperature: float = 0.7, stop=None, tools=None,
model=None) -> dict:
"""Ein Chat-Call ans lokale LLM. messages = [{role, content}, ...].
model (B0.5): welches Modell llama-swap laden soll. tools (B1b): optionale
OpenAI-Tool-Defs; das Ergebnis kann dann result['tool_calls'] enthalten.
Blockierend (urllib) chat() laeuft ohnehin im Executor-Thread."""
if not isinstance(messages, list) or not messages:
return {"ok": False, "error": "messages leer/ungueltig"}
req = {"messages": messages, "max_tokens": max_tokens, "temperature": temperature}
if stop:
req["stop"] = stop
if tools:
req["tools"] = tools
if model:
req["model"] = model
try:
body = json.dumps(req).encode("utf-8")
http_req = urllib.request.Request(
f"{BRIDGE_URL}/internal/local-llm", data=body, method="POST",
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(http_req, timeout=LOCAL_LLM_HTTP_TIMEOUT_SEC) as resp:
result = json.loads(resp.read().decode("utf-8", "ignore"))
except urllib.error.HTTPError as exc:
try:
err_data = json.loads(exc.read().decode("utf-8", "ignore"))
err = err_data.get("error") or str(exc)
except Exception:
err = str(exc)
return {"ok": False, "error": f"local-llm: {err}"}
except Exception as exc:
logger.warning("local_llm_chat HTTP-Call fehlgeschlagen: %s", exc)
return {"ok": False, "error": f"local-llm nicht erreichbar ({exc})"}
if not isinstance(result, dict) or not result.get("ok"):
return {"ok": False, "error": (result or {}).get("error", "unbekannt")}
return result
-1660
View File
File diff suppressed because it is too large Load Diff
-4
View File
@@ -1,4 +0,0 @@
from .embedder import Embedder
from .vector_store import VectorStore, MemoryPoint, MemoryType
__all__ = ["Embedder", "VectorStore", "MemoryPoint", "MemoryType"]
-42
View File
@@ -1,42 +0,0 @@
"""
Lokaler Embedder fuer Memory-Texte.
Nutzt sentence-transformers (paraphrase-multilingual-MiniLM-L12-v2):
- Deutsch + Englisch
- 384-dimensionale Vektoren
- Laeuft auf CPU, ~30ms pro kurzer Text
- Modell wird beim ersten Aufruf in /data/_models gecached
"""
from __future__ import annotations
import logging
from typing import List
logger = logging.getLogger(__name__)
MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2"
VECTOR_DIM = 384
class Embedder:
def __init__(self, model_name: str = MODEL_NAME):
self.model_name = model_name
self._model = None
def _load(self):
if self._model is None:
logger.info("Lade Embedding-Modell %s ...", self.model_name)
from sentence_transformers import SentenceTransformer
self._model = SentenceTransformer(self.model_name)
logger.info("Embedding-Modell geladen.")
def embed(self, text: str) -> List[float]:
self._load()
vec = self._model.encode(text, convert_to_numpy=True, normalize_embeddings=True)
return vec.tolist()
def embed_batch(self, texts: List[str]) -> List[List[float]]:
self._load()
vecs = self._model.encode(texts, convert_to_numpy=True, normalize_embeddings=True)
return vecs.tolist()
-323
View File
@@ -1,323 +0,0 @@
"""
Vector-Store-Wrapper um Qdrant.
Eine Collection "aria_memory" haelt ALLE Memory-Punkte.
Trennung nach Type/Pinned-Status via Payload-Filter.
Punkt-Schema (Payload):
type identity | rule | preference | tool | skill | fact | conversation | reminder
category frei, fuer UI-Gruppierung
title kurze Ueberschrift
content eigentlicher Text (wird embedded)
pinned bool, True = Hot Memory (immer in Prompt)
source import | conversation | manual
scope system | personal. system = generische Regeln, die JEDER
braucht, der das System aufsetzt (Sicherheit, Ehrlichkeit,
Skill-Regeln). personal = Stefan-spezifisch (Name, Zugangs-
daten, Projekte). Steuert den getrennten Bootstrap-Export.
tags Liste von Strings
created_at, updated_at ISO-Strings
conversation_id optional, nur fuer type=conversation
"""
from __future__ import annotations
import logging
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import List, Optional
from qdrant_client import QdrantClient
from qdrant_client.http import models as qm
from .embedder import VECTOR_DIM
logger = logging.getLogger(__name__)
COLLECTION = "aria_memory"
class MemoryType(str, Enum):
IDENTITY = "identity"
RULE = "rule"
PREFERENCE = "preference"
TOOL = "tool"
SKILL = "skill"
FACT = "fact"
CONVERSATION = "conversation"
REMINDER = "reminder"
@dataclass
class MemoryPoint:
id: str
type: str
title: str
content: str
pinned: bool = False
category: str = ""
source: str = "manual"
scope: str = "personal" # system | personal — steuert Bootstrap-Export
tags: List[str] = field(default_factory=list)
created_at: str = ""
updated_at: str = ""
conversation_id: Optional[str] = None
score: Optional[float] = None # nur bei Search gesetzt
# Anhaenge: Liste von Dicts {name, mime, size, path} — Dateien liegen
# physisch unter /shared/memory-attachments/<memory-id>/<name>.
# Hier in der DB nur die Metadaten, damit die Suche/Anzeige sie kennt
# ohne Filesystem zu pruefen.
attachments: List[dict] = field(default_factory=list)
def to_payload(self) -> dict:
p = {
"type": self.type,
"title": self.title,
"content": self.content,
"pinned": self.pinned,
"category": self.category,
"source": self.source,
"scope": self.scope,
"tags": self.tags,
"created_at": self.created_at,
"updated_at": self.updated_at,
"attachments": self.attachments,
}
if self.conversation_id:
p["conversation_id"] = self.conversation_id
return p
@classmethod
def from_qdrant(cls, point) -> "MemoryPoint":
payload = point.payload or {}
return cls(
id=str(point.id),
type=payload.get("type", "fact"),
title=payload.get("title", ""),
content=payload.get("content", ""),
pinned=payload.get("pinned", False),
category=payload.get("category", ""),
source=payload.get("source", "manual"),
scope=payload.get("scope", "personal"),
tags=payload.get("tags", []),
created_at=payload.get("created_at", ""),
updated_at=payload.get("updated_at", ""),
conversation_id=payload.get("conversation_id"),
attachments=payload.get("attachments", []) or [],
score=getattr(point, "score", None),
)
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
class VectorStore:
def __init__(self, host: str, port: int = 6333):
self.client = QdrantClient(host=host, port=port)
self._ensure_collection()
def _ensure_collection(self):
existing = [c.name for c in self.client.get_collections().collections]
if COLLECTION not in existing:
logger.info("Erstelle Collection %s ...", COLLECTION)
self.client.create_collection(
collection_name=COLLECTION,
vectors_config=qm.VectorParams(size=VECTOR_DIM, distance=qm.Distance.COSINE),
)
# Indexe fuer typische Filter-Felder — idempotent, laeuft auch auf
# einer bestehenden Collection (fuer neu hinzugekommene Felder wie scope).
self._ensure_indexes()
def _ensure_indexes(self):
for field_name in ("type", "pinned", "category", "source", "scope", "migration_key"):
schema = (qm.PayloadSchemaType.BOOL if field_name == "pinned"
else qm.PayloadSchemaType.KEYWORD)
try:
self.client.create_payload_index(
collection_name=COLLECTION,
field_name=field_name,
field_schema=schema,
)
except Exception:
# Index existiert bereits — kein Problem.
pass
# ─── Schreib-Operationen ─────────────────────────────────────────
def upsert(self, point: MemoryPoint, vector: List[float]) -> str:
if not point.id:
point.id = str(uuid.uuid4())
if not point.created_at:
point.created_at = _now()
point.updated_at = _now()
self.client.upsert(
collection_name=COLLECTION,
points=[qm.PointStruct(id=point.id, vector=vector, payload=point.to_payload())],
)
return point.id
def delete(self, point_id: str):
self.client.delete(
collection_name=COLLECTION,
points_selector=qm.PointIdsList(points=[point_id]),
)
# ─── Lese-Operationen ────────────────────────────────────────────
def get(self, point_id: str) -> Optional[MemoryPoint]:
result = self.client.retrieve(collection_name=COLLECTION, ids=[point_id], with_payload=True)
if not result:
return None
return MemoryPoint.from_qdrant(result[0])
def list_pinned(self) -> List[MemoryPoint]:
"""Alle pinned Punkte — Hot Memory."""
return self._scroll(filter=qm.Filter(must=[
qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True))
]))
def list_pinned_by_scope(self, scope: str) -> List[MemoryPoint]:
"""Alle pinned Punkte eines scope (system | personal). Fuer den
getrennten Bootstrap-Export."""
return self._scroll(filter=qm.Filter(must=[
qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True)),
qm.FieldCondition(key="scope", match=qm.MatchValue(value=scope)),
]))
def list_index_titles(self, limit: int = 500) -> List[MemoryPoint]:
"""Leichtgewichtiger Titel-Index des kalten Gedaechtnisses fuer den
System-Prompt: ARIA sieht WAS sie an Nachschlage-Wissen hat (Zugangs-
daten, Infrastruktur, Projekte) und holt den Inhalt bei Bedarf via
memory_search statt Stefan nach etwas zu fragen, das schon da ist.
Bewusst NUR die deliberat gespeicherten Punkte:
- nicht pinned (die sind eh schon voll im Prompt),
- kein type=conversation (Chat-Mitschnitte),
- kein source=distilled (die 100e auto-destillierten Gespraechs-
Fakten die traegt das semantische Auto-Retrieval, sie hier
als Titel zu listen wuerde nur Kontext fressen).
So bleibt der Index klein (Dutzende statt Hunderte Zeilen)."""
return self._scroll(
filter=qm.Filter(
must_not=[
qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True)),
qm.FieldCondition(key="type", match=qm.MatchValue(value="conversation")),
qm.FieldCondition(key="source", match=qm.MatchValue(value="distilled")),
]
),
limit=limit,
)
def list_by_type(self, type_: str, limit: int = 100) -> List[MemoryPoint]:
return self._scroll(
filter=qm.Filter(must=[
qm.FieldCondition(key="type", match=qm.MatchValue(value=type_))
]),
limit=limit,
)
def list_all(self, limit: int = 1000) -> List[MemoryPoint]:
return self._scroll(filter=None, limit=limit)
def _scroll(self, filter, limit: int = 1000) -> List[MemoryPoint]:
points, _ = self.client.scroll(
collection_name=COLLECTION,
scroll_filter=filter,
limit=limit,
with_payload=True,
with_vectors=False,
)
return [MemoryPoint.from_qdrant(p) for p in points]
def search(
self,
query_vector: List[float],
k: int = 5,
type_filter: Optional[str] = None,
exclude_pinned: bool = True,
score_threshold: Optional[float] = None,
) -> List[MemoryPoint]:
"""Semantische Search. Standard: pinned-Punkte ausgeschlossen
(die kommen separat via list_pinned in den Prompt).
score_threshold: nur Treffer mit Cosine-Similarity >= Schwelle
zurueckgeben. None = keine Filterung. MiniLM-multilingual liefert
typischerweise 0.3-0.6 fuer relevante Treffer; <0.25 ist Rauschen."""
must = []
must_not = []
if type_filter:
must.append(qm.FieldCondition(key="type", match=qm.MatchValue(value=type_filter)))
if exclude_pinned:
must_not.append(qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True)))
flt = qm.Filter(must=must or None, must_not=must_not or None)
results = self.client.search(
collection_name=COLLECTION,
query_vector=query_vector,
query_filter=flt if (must or must_not) else None,
limit=k,
with_payload=True,
score_threshold=score_threshold,
)
return [MemoryPoint.from_qdrant(p) for p in results]
def count(self) -> int:
return self.client.count(collection_name=COLLECTION, exact=True).count
def search_text(
self,
query: str,
k: int = 20,
type_filter: Optional[str] = None,
exclude_pinned: bool = False,
) -> List[MemoryPoint]:
"""Volltext-Substring-Suche (case-insensitive) ueber Title +
Content + Category + Tags. Im Gegensatz zu search() ist das KEIN
Semantic-Match nur exakte Wort-/Teilwort-Treffer.
Full-Scan ueber alle (gefilteren) Punkte. Bei der erwarteten
Groessenordnung (< 1000) unkritisch."""
q = (query or "").strip().lower()
if not q:
return []
must = []
must_not = []
if type_filter:
must.append(qm.FieldCondition(key="type", match=qm.MatchValue(value=type_filter)))
if exclude_pinned:
must_not.append(qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True)))
flt = qm.Filter(must=must or None, must_not=must_not or None) if (must or must_not) else None
matches: List[MemoryPoint] = []
offset = None
while True:
points, offset = self.client.scroll(
collection_name=COLLECTION,
scroll_filter=flt,
limit=200,
offset=offset,
with_payload=True,
with_vectors=False,
)
for p in points:
payload = p.payload or {}
tags = payload.get("tags")
tags_str = " ".join(tags) if isinstance(tags, list) else ""
haystack = " ".join([
str(payload.get("title", "")),
str(payload.get("content", "")),
str(payload.get("category", "")),
tags_str,
]).lower()
if q in haystack:
matches.append(MemoryPoint.from_qdrant(p))
if len(matches) >= k:
return matches
if not offset:
break
return matches
-172
View File
@@ -1,172 +0,0 @@
"""
Anhaenge fuer Memory-Eintraege.
Storage-Layout:
/shared/memory-attachments/<memory-id>/<original-name>
Eine flache Ordnerstruktur pro Memory bei Memory-Delete loescht main.py
das ganze Verzeichnis. Anhang-Metadaten (name, mime, size, path) liegen
zusaetzlich im Qdrant-Payload des Memory-Punkts damit die Listen/Suche
sie ohne Filesystem-Lookup zeigen kann.
Anhaenge sind erstmal nur ueber die Diagnostic-UI hochladbar ARIA
selbst hat in Stufe A kein Tool zum Upload.
"""
from __future__ import annotations
import base64
import logging
import mimetypes
import os
import re
import shutil
from pathlib import Path
from typing import List, Optional
logger = logging.getLogger(__name__)
ROOT = Path(os.environ.get("MEMORY_ATTACHMENTS_DIR", "/shared/memory-attachments"))
MAX_BYTES = int(os.environ.get("MEMORY_ATTACHMENT_MAX_BYTES", str(20 * 1024 * 1024))) # 20 MB
SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9._\-]")
def _safe_filename(name: str) -> str:
"""Macht aus einem User-Namen einen filesystem-sicheren String —
zerlegt Pfadteile, schneidet Sonderzeichen weg, kuerzt auf 120 Zeichen."""
base = Path(name).name or "datei"
base = SAFE_NAME_RE.sub("_", base).strip("._-") or "datei"
return base[:120]
def memory_dir(memory_id: str) -> Path:
return ROOT / memory_id
def list_attachments(memory_id: str) -> List[dict]:
"""Liest die Anhaenge fuer eine Memory aus dem Filesystem.
Returns [{name, mime, size, path}, ...] leer wenn nichts da.
Source of Truth ist Qdrant-Payload; diese Funktion ist nur fuer
Diagnostic-Endpoints wenn Stefan direkt das FS prueft."""
d = memory_dir(memory_id)
if not d.is_dir():
return []
out = []
for f in sorted(d.iterdir()):
if not f.is_file():
continue
out.append(_file_meta(memory_id, f))
return out
def _file_meta(memory_id: str, f: Path) -> dict:
try:
size = f.stat().st_size
except Exception:
size = 0
mime = mimetypes.guess_type(f.name)[0] or "application/octet-stream"
return {
"name": f.name,
"mime": mime,
"size": size,
"path": str(f), # absoluter Pfad im Container
}
def save_attachment(memory_id: str, filename: str, data: bytes) -> dict:
"""Schreibt einen Anhang ins FS und gibt seine Metadaten zurueck.
Ueberschreibt eine bestehende Datei mit gleichem Namen."""
if not memory_id:
raise ValueError("memory_id ist Pflicht")
if len(data) > MAX_BYTES:
raise ValueError(f"Anhang zu gross ({len(data)} > {MAX_BYTES} Byte)")
safe = _safe_filename(filename)
d = memory_dir(memory_id)
d.mkdir(parents=True, exist_ok=True)
target = d / safe
target.write_bytes(data)
logger.info("[mem-att] %s -> %s (%d Byte)", memory_id, safe, len(data))
return _file_meta(memory_id, target)
def save_from_base64(memory_id: str, filename: str, b64: str) -> dict:
"""Convenience fuer Base64-Uploads (Diagnostic schickt Files so)."""
try:
data = base64.b64decode(b64, validate=False)
except Exception as exc:
raise ValueError(f"Base64-Decode fehlgeschlagen: {exc}") from exc
return save_attachment(memory_id, filename, data)
def delete_attachment(memory_id: str, filename: str) -> bool:
"""Loescht eine einzelne Anhang-Datei. Returns True wenn was weg ist."""
safe = _safe_filename(filename)
target = memory_dir(memory_id) / safe
if not target.is_file():
return False
try:
target.unlink()
logger.info("[mem-att] %s/%s geloescht", memory_id, safe)
return True
except Exception as exc:
logger.warning("[mem-att] Loeschen fehlgeschlagen: %s", exc)
return False
def delete_all(memory_id: str) -> int:
"""Loescht das komplette Memory-Verzeichnis. Wird beim Memory-Delete
in main.py gerufen damit nichts verwaist."""
d = memory_dir(memory_id)
if not d.is_dir():
return 0
count = sum(1 for _ in d.iterdir() if _.is_file())
try:
shutil.rmtree(d)
logger.info("[mem-att] %s komplett entfernt (%d Files)", memory_id, count)
except Exception as exc:
logger.warning("[mem-att] rmtree fehlgeschlagen: %s", exc)
return count
def read_bytes(memory_id: str, filename: str) -> Optional[bytes]:
"""Liefert die rohen Bytes einer Datei zurueck — fuer Download/Serve."""
safe = _safe_filename(filename)
target = memory_dir(memory_id) / safe
if not target.is_file():
return None
return target.read_bytes()
# /shared/ ist der einzig akzeptable Source-Pfad fuer attach_from_path —
# ARIA bekommt Files vom User immer in /shared/uploads, eigene Files
# generiert sie in /shared/uploads/ als File-Marker. Kein Zugriff auf
# /root, /etc, /tmp, ssh-Keys, etc.
ALLOWED_SOURCE_PREFIXES = ("/shared/uploads/", "/shared/memory-attachments/")
def attach_from_path(memory_id: str, source_path: str) -> dict:
"""Kopiert eine existierende Datei aus /shared/* in das Anhang-Verzeichnis
des Memories und gibt die neue Metadaten zurueck.
Verwendung: ARIA bekommt z.B. ein User-Bild als `/shared/uploads/aria_<id>.jpg`.
Statt das Bild dort liegen zu lassen (kein direkter Memory-Bezug), kopiert
sie es via `memory_save(..., attach_paths=[<src>])` ins Memory-Verzeichnis.
Pfadschutz: source_path MUSS unter /shared/ liegen kein Zugriff auf
Root-FS, SSH-Keys etc.
"""
if not memory_id:
raise ValueError("memory_id ist Pflicht")
if not source_path or not isinstance(source_path, str):
raise ValueError("source_path leer")
if not any(source_path.startswith(p) for p in ALLOWED_SOURCE_PREFIXES):
raise ValueError(f"source_path muss unter {' oder '.join(ALLOWED_SOURCE_PREFIXES)} liegen")
src = Path(source_path)
if not src.is_file():
raise ValueError(f"Datei nicht gefunden: {source_path}")
size = src.stat().st_size
if size > MAX_BYTES:
raise ValueError(f"Datei zu gross ({size} > {MAX_BYTES} Byte)")
# Reuse save_attachment damit Filename-Sanitization + Logging konsistent
data = src.read_bytes()
return save_attachment(memory_id, src.name, data)
-177
View File
@@ -1,177 +0,0 @@
"""
Call-Metrics fuer den Proxy-Client.
Pro Claude-Call wird ein Eintrag in /data/metrics.jsonl angehaengt:
{"ts": <ms>, "model": "...", "in": <tokens_in_estimate>, "out": <tokens_out_estimate>}
Tokens-Schaetzung: characters / 4 (Anthropic-Default-Heuristik). Nicht exakt
aber gut genug fuer Quota-Monitoring. Wir summieren nicht in-memory weil
der Brain-Container neugestartet werden kann alles auf Disk.
Auswertung via aggregate(window_seconds) liefert {calls, tokens_in, tokens_out}
fuer die letzten N Sekunden. Lazy gelesen, keine grossen Datenmengen erwartet
(bei 1000 Calls/Tag ~70 KB pro Monat).
Auto-Rotate: bei > 50k Zeilen werden die aeltesten 25k weggeschnitten.
"""
from __future__ import annotations
import json
import logging
import os
import time
from pathlib import Path
from typing import List
logger = logging.getLogger(__name__)
METRICS_FILE = Path(os.environ.get("METRICS_FILE", "/data/metrics.jsonl"))
ROTATE_AT = 50_000
ROTATE_KEEP = 25_000
def _estimate_tokens(text: str) -> int:
"""Anthropic-Default: ~4 chars pro Token. Grob genug."""
if not text:
return 0
return max(1, len(text) // 4)
def _messages_tokens(messages: list) -> int:
total = 0
for m in messages:
# Pydantic-Model oder dict
if hasattr(m, "content"):
total += _estimate_tokens(m.content or "")
elif isinstance(m, dict):
c = m.get("content") or ""
if isinstance(c, str):
total += _estimate_tokens(c)
return total
def _append(model: str, tokens_in: int, tokens_out: int, source: str) -> None:
"""Ein Metric-Entry auf Disk anhaengen. Robust (silent fail)."""
try:
line = json.dumps({
"ts": int(time.time() * 1000),
"model": model,
"in": int(tokens_in),
"out": int(tokens_out),
"source": source, # "claude" | "local" | "fast-path"
})
METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
with METRICS_FILE.open("a", encoding="utf-8") as f:
f.write(line + "\n")
if (tokens_in + tokens_out) % 1000 < 4:
_maybe_rotate()
except Exception as exc:
logger.warning("metrics._append: %s", exc)
def log_call(model: str, messages_in: list, reply_text: str = "",
source: str = "claude") -> None:
"""Claude-Call-Metric anhaengen (Tokens per chars/4-Schaetzung)."""
_append(model, _messages_tokens(messages_in), _estimate_tokens(reply_text), source)
def log_local_call(model: str, messages_in: list, reply_text: str = "",
usage: dict | None = None) -> None:
"""Lokaler-LLM-Call-Metric. Nutzt echte usage-Tokens (prompt/completion)
wenn der Adapter sie liefert, sonst chars/4-Schaetzung wie bei Claude.
Quelle = 'local' damit die Ersparnis-Rechnung local von claude trennt."""
tokens_in = tokens_out = None
if isinstance(usage, dict):
pt = usage.get("prompt_tokens")
ct = usage.get("completion_tokens")
if isinstance(pt, (int, float)):
tokens_in = int(pt)
if isinstance(ct, (int, float)):
tokens_out = int(ct)
if tokens_in is None:
tokens_in = _messages_tokens(messages_in)
if tokens_out is None:
tokens_out = _estimate_tokens(reply_text)
_append(model or "local", tokens_in, tokens_out, "local")
def log_fast_path(reply_text: str = "") -> None:
"""Fast-Path (reiner Skill, KEIN LLM) — spart einen ganzen Claude-Call zum
Nulltarif. tokens_in=0 (kein Prompt ans LLM), out = winzige Quittung."""
_append("fast-path", 0, _estimate_tokens(reply_text), "fast-path")
def _maybe_rotate() -> None:
try:
if not METRICS_FILE.exists():
return
with METRICS_FILE.open("r", encoding="utf-8") as f:
lines = f.readlines()
if len(lines) > ROTATE_AT:
keep = lines[-ROTATE_KEEP:]
METRICS_FILE.write_text("".join(keep), encoding="utf-8")
logger.info("metrics rotated: %d%d Zeilen", len(lines), len(keep))
except Exception as exc:
logger.warning("metrics rotate: %s", exc)
def aggregate(window_seconds: int) -> dict:
"""Aggregiert die Calls der letzten N Sekunden."""
now_ms = int(time.time() * 1000)
cutoff_ms = now_ms - (window_seconds * 1000)
calls = 0
tokens_in = 0
tokens_out = 0
by_model: dict[str, int] = {}
# Aufschluesselung nach Quelle (claude / local / fast-path) fuer die
# Ersparnis-Anzeige im Diagnostic.
def _src_bucket() -> dict:
return {"calls": 0, "tokens_in": 0, "tokens_out": 0}
by_source: dict[str, dict] = {}
if METRICS_FILE.exists():
try:
for raw in METRICS_FILE.read_text(encoding="utf-8").splitlines():
raw = raw.strip()
if not raw:
continue
try:
obj = json.loads(raw)
except Exception:
continue
if obj.get("ts", 0) < cutoff_ms:
continue
ti = int(obj.get("in") or 0)
to = int(obj.get("out") or 0)
calls += 1
tokens_in += ti
tokens_out += to
m = obj.get("model", "?")
by_model[m] = by_model.get(m, 0) + 1
# Alt-Eintraege ohne 'source' zaehlen als claude (Rueckwaerts-Kompat).
src = obj.get("source") or "claude"
b = by_source.setdefault(src, _src_bucket())
b["calls"] += 1
b["tokens_in"] += ti
b["tokens_out"] += to
except Exception as exc:
logger.warning("metrics aggregate: %s", exc)
return {
"window_seconds": window_seconds,
"calls": calls,
"tokens_in": tokens_in,
"tokens_out": tokens_out,
"by_model": by_model,
"by_source": by_source,
}
def stats() -> dict:
"""Komplett-Snapshot mit den drei wichtigsten Fenstern."""
return {
"h1": aggregate(3600),
"h5": aggregate(5 * 3600),
"h24": aggregate(24 * 3600),
"d30": aggregate(30 * 24 * 3600),
}
-171
View File
@@ -1,171 +0,0 @@
"""Einmalige Migration: project_id aus conversation.jsonl nach chat_backup.jsonl
zurueckschreiben.
Hintergrund: Seit es Projekte gibt (fc0f91d) taggt das Brain jeden Turn in
conversation.jsonl mit project_id. chat_backup.jsonl (die Anzeige-Quelle fuer
App + Diagnostic) bekam project_id aber erst spaeter (f51ad15). Alle Projekt-
Nachrichten aus dem Zeitfenster dazwischen liegen daher in conversation.jsonl
korrekt getaggt, in chat_backup.jsonl aber untagged die UI zeigt sie im
Hauptchat statt im Projekt.
Diese Migration matcht chat_backup-Eintraege gegen conversation-Turns ueber
(role, text) in Reihenfolge und traegt die fehlende project_id nach. Sie ist:
- idempotent (Marker-Datei, laeuft genau einmal),
- nicht-destruktiv (legt .bak an, aendert nur LEERE project_ids, entfernt nie
einen bestehenden Tag),
- atomar (tmp-Datei + os.replace).
Reihenfolge-erhaltend: pro (role, normalisiertem Text) wird eine Deque der
project_ids aus conversation.jsonl aufgebaut (inklusive "" fuer Hauptthread-
Turns), damit wiederholte identische Texte ihre jeweils richtige Zuordnung
bekommen und Hauptchat-Interleaving nicht faelschlich getaggt wird.
"""
from __future__ import annotations
import json
import logging
import os
import re
from collections import defaultdict, deque
from pathlib import Path
logger = logging.getLogger("aria.migrate.backfill_projectid")
CONVERSATION_FILE = Path(os.environ.get("CONVERSATION_FILE", "/data/conversation.jsonl"))
CHAT_BACKUP_FILE = Path(os.environ.get("CHAT_BACKUP_FILE", "/shared/config/chat_backup.jsonl"))
# v2: robusterer Match (Marker-Strip + Praefix). v1 verlangte exakte Gleichheit
# von text==content und verfehlte damit alle Nachrichten bei denen die Bridge
# den Brain-Text anreichert (GPS/Barge-In-Hints prepended) oder cleant
# (FILE-Marker entfernt). Neuer Marker → laeuft einmal neu, fuellt die Luecken.
MARKER_FILE = Path("/shared/config/.chat_backup_projectid_backfill_v2")
# _build_core_text (Bridge) PREPENDT bei User-Nachrichten Hinweis-/GPS-Bloecke
# in eckigen Klammern vor den eigentlichen Text; conversation.jsonl speichert
# diesen angereicherten Text, chat_backup nur den rohen. FILE-Marker stehen in
# conversation-Assistant-Turns, sind in chat_backup aber schon rausgecleant.
_FILE_MARKER_RE = re.compile(r"\[FILE:\s*/shared/uploads/[^\]]+\]", re.IGNORECASE)
_LEADING_BRACKET_RE = re.compile(r"^\s*(?:\[[^\]]*\]\s*)+")
_WS_RE = re.compile(r"\s+")
def _norm(text: str) -> str:
"""Match-Key: FILE-Marker + fuehrende [Hinweis]/[GPS]-Bloecke entfernen,
Whitespace kollabieren, auf 120-Zeichen-Praefix kuerzen. Toleriert damit
die Anreicherungs-/Cleaning-Unterschiede zwischen conversation und backup,
bleibt durch den 120er-Praefix aber spezifisch genug gegen Fehl-Matches."""
t = _FILE_MARKER_RE.sub("", text or "")
t = _LEADING_BRACKET_RE.sub("", t)
t = _WS_RE.sub(" ", t).strip()
return t[:120]
def run() -> dict:
"""Fuehrt die Migration aus. Returns Status-Dict fuers Logging.
Laeuft nur einmal (Marker). Fehlt eine der Quelldateien: still ueberspringen."""
if MARKER_FILE.exists():
return {"skipped": "marker_exists"}
if not CHAT_BACKUP_FILE.exists():
return {"skipped": "no_chat_backup"}
if not CONVERSATION_FILE.exists():
# Ohne Brain-Historie gibt es nichts zu uebernehmen — Marker trotzdem
# setzen, damit wir nicht bei jedem Start neu pruefen.
_write_marker(0, 0)
return {"skipped": "no_conversation"}
# 1) conversation.jsonl → Deque der project_ids je (role, normtext), in Reihenfolge.
tag_queues: dict[tuple[str, str], deque[str]] = defaultdict(deque)
conv_turns = 0
for line in _iter_jsonl(CONVERSATION_FILE):
role = line.get("role")
if role not in ("user", "assistant"):
continue
content = line.get("content")
if not isinstance(content, str):
continue
conv_turns += 1
tag_queues[(role, _norm(content))].append((line.get("project_id") or "").strip())
# 2) chat_backup.jsonl durchgehen, leere project_ids nachtragen.
try:
backup_lines = CHAT_BACKUP_FILE.read_text(encoding="utf-8").splitlines()
except Exception as exc:
logger.warning("[backfill] chat_backup lesen fehlgeschlagen: %s", exc)
return {"error": f"read_backup: {exc}"}
out_lines: list[str] = []
patched = 0
matched = 0
for raw in backup_lines:
raw = raw.strip()
if not raw:
continue
try:
obj = json.loads(raw)
except Exception:
out_lines.append(raw) # unveraendert durchreichen
continue
role = obj.get("role")
text = obj.get("text")
# Nur echte Chat-Bubbles matchen (keine file_deleted-/type-Marker).
if role in ("user", "assistant") and isinstance(text, str):
q = tag_queues.get((role, _norm(text)))
if q:
pid = q.popleft() # verbraucht → Reihenfolge fuer Duplikate bleibt korrekt
matched += 1
existing = (obj.get("project_id") or "").strip()
# Nur setzen wenn Backup-Eintrag noch KEINEN Tag hat und der
# conversation-Turn einem Projekt gehoert. Bestehende Tags bleiben.
if not existing and pid:
obj["project_id"] = pid
patched += 1
out_lines.append(json.dumps(obj, ensure_ascii=False))
# 3) Nichts zu tun? Marker setzen und raus.
if patched == 0:
_write_marker(conv_turns, 0)
logger.info("[backfill] nichts nachzutragen (conv_turns=%s, matched=%s)",
conv_turns, matched)
return {"conv_turns": conv_turns, "matched": matched, "patched": 0}
# 4) Sicherung + atomarer Rewrite.
try:
bak = CHAT_BACKUP_FILE.with_suffix(".jsonl.pre-backfill-v2.bak")
if not bak.exists():
bak.write_bytes(CHAT_BACKUP_FILE.read_bytes())
tmp = CHAT_BACKUP_FILE.with_suffix(".jsonl.tmp")
tmp.write_text("\n".join(out_lines) + "\n", encoding="utf-8")
os.replace(tmp, CHAT_BACKUP_FILE)
except Exception as exc:
logger.warning("[backfill] Rewrite fehlgeschlagen: %s", exc)
return {"error": f"rewrite: {exc}"}
_write_marker(conv_turns, patched)
logger.info("[backfill] %s Bubbles nachtraeglich getaggt (conv_turns=%s, matched=%s). Backup: %s",
patched, conv_turns, matched, bak.name)
return {"conv_turns": conv_turns, "matched": matched, "patched": patched}
def _iter_jsonl(path: Path):
try:
for raw in path.read_text(encoding="utf-8").splitlines():
raw = raw.strip()
if not raw:
continue
try:
yield json.loads(raw)
except Exception:
continue
except Exception as exc:
logger.warning("[backfill] %s lesen fehlgeschlagen: %s", path, exc)
def _write_marker(conv_turns: int, patched: int) -> None:
try:
MARKER_FILE.parent.mkdir(parents=True, exist_ok=True)
MARKER_FILE.write_text(
json.dumps({"conv_turns": conv_turns, "patched": patched}, ensure_ascii=False),
encoding="utf-8",
)
except Exception as exc:
logger.warning("[backfill] Marker schreiben fehlgeschlagen: %s", exc)
-406
View File
@@ -1,406 +0,0 @@
"""
Migration aus aria-data/brain-import/ Vector-DB.
Parst die mitgelieferten Markdown-Dateien (AGENT.md, USER.md, TOOLING.md)
und zerlegt sie in atomare Memory-Punkte. Jeder Punkt bekommt:
source = "import"
migration_key = stabiler Identifier (z.B. "agent.md/rule-1") fuer Idempotenz
pinned = True
Beim Re-Run werden vorhandene Punkte mit gleicher migration_key entfernt
und neu geschrieben.
Mapping pro Datei:
AGENT.md
"Identitaet" 1 Punkt type=identity
"Persoenlichkeit" (Intro) 1 Punkt type=identity
"Kern-Eigenschaften" (Liste) 1 Punkt pro Bullet type=identity
"Tool-Freigaben" 1 Punkt type=tool
"Sicherheitsregeln" (Liste) 1 Punkt pro Bullet type=rule
"Arbeitsprinzipien" (Liste) 1 Punkt pro Bullet type=rule
"Dateien an Stefan zurueckgeben" 1 Punkt type=skill
"Stimme" 1 Punkt type=tool
USER.md
"Allgemein" (Liste) 1 Punkt pro Bullet type=preference
"Bestaetigung erforderlich" 1 Punkt type=preference
"Autonomes Arbeiten OK fuer" 1 Punkt type=preference
"Tools & Infrastruktur" 1 Punkt type=preference
TOOLING.md
gesamter Inhalt 1 Punkt type=tool, title="Tooling-Stack"
BOOTSTRAP.md ist eine Variante von AGENT.md wird (vorerst) ignoriert
damit keine doppelten Punkte landen.
"""
from __future__ import annotations
import logging
import re
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
from memory import Embedder, VectorStore, MemoryPoint
from memory.vector_store import COLLECTION
from qdrant_client.http import models as qm
logger = logging.getLogger(__name__)
@dataclass
class _Block:
title: str
content: str
def _split_h2(md: str) -> List[_Block]:
"""Zerlegt Markdown in H2-Bloecke. Inhalt vor dem ersten H2 wird verworfen."""
blocks: List[_Block] = []
current: Optional[_Block] = None
for line in md.splitlines():
m = re.match(r"^##\s+(.+?)\s*$", line)
if m and not line.startswith("### "):
if current:
blocks.append(current)
current = _Block(title=m.group(1).strip(), content="")
continue
if current is not None:
current.content += line + "\n"
if current:
blocks.append(current)
return blocks
def _split_h3(content: str) -> List[_Block]:
"""Zerlegt einen H2-Block in H3-Untersektionen + 'header'-Block davor."""
blocks: List[_Block] = []
header_lines: List[str] = []
current: Optional[_Block] = None
for line in content.splitlines():
m = re.match(r"^###\s+(.+?)\s*$", line)
if m:
if current is None and header_lines:
blocks.append(_Block(title="_intro", content="\n".join(header_lines).strip()))
if current:
blocks.append(current)
current = _Block(title=m.group(1).strip(), content="")
continue
if current is None:
header_lines.append(line)
else:
current.content += line + "\n"
if current:
blocks.append(current)
elif header_lines:
blocks.append(_Block(title="_intro", content="\n".join(header_lines).strip()))
return blocks
def _extract_bullets(content: str) -> List[tuple[str, str]]:
"""Findet "- **Title** — Body" oder "N. **Title** — Body" Bullets.
Returns: Liste von (title, full_bullet_text).
"""
bullets: List[tuple[str, str]] = []
current_lines: List[str] = []
current_title: Optional[str] = None
def flush():
if current_title and current_lines:
bullets.append((current_title, "\n".join(current_lines).strip()))
for line in content.splitlines():
m = re.match(r"^\s*(?:[-*]|\d+\.)\s+\*\*([^*]+?)\*\*\s*[—\-:]?\s*(.*)$", line)
if m:
flush()
current_title = m.group(1).strip()
current_lines = [line]
continue
# Folge-Zeilen mit Einrueckung gehoeren zum aktuellen Bullet
if current_title and (line.startswith(" ") or line.startswith("\t") or not line.strip()):
current_lines.append(line)
continue
if current_title and not re.match(r"^\s*(?:[-*]|\d+\.)\s+", line):
current_lines.append(line)
continue
# Neuer Bullet ohne **Title** Format
if re.match(r"^\s*(?:[-*]|\d+\.)\s+", line):
flush()
text = re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", line).strip()
short_title = (text[:60] + "") if len(text) > 60 else text
bullets.append((short_title, line.strip()))
current_title = None
current_lines = []
flush()
return bullets
# ─── Pro Datei eine Parser-Funktion ──────────────────────────────────
def _parse_agent_md(md: str, source_file: str) -> List[MemoryPoint]:
points: List[MemoryPoint] = []
h2_blocks = _split_h2(md)
for h2 in h2_blocks:
title = h2.title
content = h2.content.strip()
if not content:
continue
if title.lower() == "identitaet" or title.lower() == "identität":
points.append(_mk(
type_="identity", title="ARIA — Identitaet",
content=f"## {title}\n\n{content}",
category="persoenlichkeit",
migration_key=f"{source_file}/identity",
))
elif title.lower() == "persoenlichkeit" or title.lower() == "persönlichkeit":
# Intro-Absatz + Kern-Eigenschaften-Liste trennen
sub = _split_h3(content)
for s in sub:
if s.title == "_intro" and s.content.strip():
points.append(_mk(
type_="identity", title="Persoenlichkeit — Grundsatz",
content=s.content.strip(),
category="persoenlichkeit",
migration_key=f"{source_file}/personality-intro",
))
elif s.title.lower().startswith("kern"):
for idx, (btitle, btext) in enumerate(_extract_bullets(s.content), 1):
points.append(_mk(
type_="identity", title=f"Eigenschaft: {btitle}",
content=btext, category="persoenlichkeit",
migration_key=f"{source_file}/personality-trait-{idx}",
))
elif "sicherheitsregel" in title.lower():
for idx, (btitle, btext) in enumerate(_extract_bullets(content), 1):
points.append(_mk(
type_="rule", title=f"Sicherheit: {btitle}",
content=btext, category="sicherheit",
migration_key=f"{source_file}/security-{idx}",
))
elif "arbeitsprinzipien" in title.lower() or "arbeitsprinzip" in title.lower():
for idx, (btitle, btext) in enumerate(_extract_bullets(content), 1):
points.append(_mk(
type_="rule", title=f"Prinzip: {btitle}",
content=btext, category="arbeitsweise",
migration_key=f"{source_file}/work-principle-{idx}",
))
elif "tool-freigaben" in title.lower() or "tool freigaben" in title.lower():
points.append(_mk(
type_="tool", title="Tool-Freigaben — Vollzugriff",
content=content, category="infrastruktur",
migration_key=f"{source_file}/tool-access",
))
elif "dateien an stefan" in title.lower() or "dateien zurueckgeben" in title.lower() or "dateien zur" in title.lower():
points.append(_mk(
type_="skill", title="Dateien an User zurueckgeben",
content=content, category="ausgabe",
migration_key=f"{source_file}/file-return-skill",
))
elif title.lower() == "stimme":
points.append(_mk(
type_="tool", title="Stimme (F5-TTS)",
content=content, category="infrastruktur",
migration_key=f"{source_file}/voice",
))
# Permanente Freigaben (in BOOTSTRAP) — als rule
elif "freigaben" in title.lower():
points.append(_mk(
type_="rule", title=title,
content=content, category="freigaben",
migration_key=f"{source_file}/permissions",
))
else:
# Unbekannter Block: als generischer fact ablegen, NICHT pinned
logger.info("Unbekannter H2-Block '%s' in %s — als fact (unpinned)", title, source_file)
points.append(_mk(
type_="fact", title=f"{source_file}: {title}",
content=content, pinned=False,
migration_key=f"{source_file}/section-{title.lower().replace(' ', '-')}",
))
return points
def _parse_user_md(md: str, source_file: str) -> List[MemoryPoint]:
points: List[MemoryPoint] = []
for h2 in _split_h2(md):
title = h2.title
content = h2.content.strip()
if not content:
continue
# Template-Platzhalter herausfiltern: Beispiel-Zeilen mit <Tag>
if "<Beispiel-Tool>" in content or "<Username>" in title:
continue
if title.lower() == "allgemein":
for idx, (btitle, btext) in enumerate(_extract_bullets(content), 1):
# Template-Platzhalter ueberspringen
if "<z.B." in btext or "<XYZ>" in btext:
continue
points.append(_mk(
type_="preference", title=f"User: {btitle}",
content=btext, category="allgemein",
migration_key=f"{source_file}/general-{idx}",
scope="personal",
))
else:
cat_key = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") or "allgemein"
points.append(_mk(
type_="preference", title=title,
content=content, category=cat_key,
migration_key=f"{source_file}/{cat_key}",
scope="personal",
))
return points
def _parse_tooling_md(md: str, source_file: str) -> List[MemoryPoint]:
md = md.strip()
if not md:
return []
return [_mk(
type_="tool", title="Tooling-Stack (VM)",
content=md, category="infrastruktur",
migration_key=f"{source_file}/tooling-full",
)]
# ─── Helper ─────────────────────────────────────────────────────────
def _mk(
type_: str,
title: str,
content: str,
migration_key: str,
pinned: bool = True,
category: str = "",
scope: str = "system",
) -> MemoryPoint:
# scope-Default 'system': AGENT.md + TOOLING.md beschreiben ARIA selbst
# (Identitaet, Sicherheit, Architektur) — das braucht jedes System.
# USER.md-Praeferenzen sind personal und uebergeben scope='personal'.
p = MemoryPoint(
id="",
type=type_,
title=title,
content=content.strip(),
pinned=pinned,
category=category,
source="import",
scope=scope,
tags=[],
)
# migration_key wird ueber Payload-Index angesprochen — in to_payload manuell anhaengen
setattr(p, "_migration_key", migration_key)
return p
# ─── Eintrittspunkt ─────────────────────────────────────────────────
def run_migration(
import_dir: Path,
store: VectorStore,
embedder: Embedder,
) -> dict:
"""Liest alle .md-Dateien aus import_dir, parst sie, schreibt in DB.
Idempotent: vorhandene Punkte mit gleicher migration_key werden geloescht
und neu geschrieben.
Returns: {"created": int, "updated": int, "skipped": int, "files": [...]}
"""
if not import_dir.exists():
return {"created": 0, "updated": 0, "skipped": 0, "files": [], "error": f"{import_dir} nicht gefunden"}
parsers = {
"AGENT.md": _parse_agent_md,
"BOOTSTRAP.md": _parse_agent_md, # gleicher Parser, ggf. ueberlappende Eintraege
"USER.md": _parse_user_md,
"USER.md.example": _parse_user_md,
"TOOLING.md": _parse_tooling_md,
"TOOLING.md.example": _parse_tooling_md,
}
# USER.md hat Vorrang vor USER.md.example
file_priority = ["AGENT.md", "BOOTSTRAP.md", "USER.md", "USER.md.example",
"TOOLING.md", "TOOLING.md.example"]
seen_kinds: set[str] = set() # "USER" / "TOOLING" — nur einmal
points: List[MemoryPoint] = []
processed_files: List[str] = []
for fname in file_priority:
fp = import_dir / fname
if not fp.exists():
continue
kind = fname.split(".")[0] # "AGENT", "BOOTSTRAP", "USER", "TOOLING"
# USER.md.example nur wenn USER.md fehlt
if kind in ("USER", "TOOLING") and kind in seen_kinds:
continue
seen_kinds.add(kind)
parser = parsers.get(fname)
if not parser:
continue
try:
md = fp.read_text(encoding="utf-8")
file_points = parser(md, fname)
points.extend(file_points)
processed_files.append(f"{fname} ({len(file_points)})")
logger.info("Migration: %s%d Punkte", fname, len(file_points))
except Exception as exc:
logger.exception("Migration: %s fehlgeschlagen", fname)
processed_files.append(f"{fname} (FEHLER: {exc})")
if not points:
return {"created": 0, "updated": 0, "skipped": 0, "files": processed_files}
# Erst alte Migration-Punkte mit gleicher migration_key loeschen
migration_keys = [getattr(p, "_migration_key", None) for p in points]
migration_keys = [k for k in migration_keys if k]
if migration_keys:
store.client.delete(
collection_name=COLLECTION,
points_selector=qm.FilterSelector(filter=qm.Filter(must=[
qm.FieldCondition(key="migration_key", match=qm.MatchAny(any=migration_keys))
])),
)
logger.info("Migration: %d alte Punkte mit gleicher migration_key entfernt", len(migration_keys))
# Embed in Batches
texts = [p.content for p in points]
vectors = embedder.embed_batch(texts)
created = 0
for p, vec in zip(points, vectors):
payload = p.to_payload()
mkey = getattr(p, "_migration_key", None)
if mkey:
payload["migration_key"] = mkey
from datetime import datetime, timezone
import uuid as _uuid
pid = str(_uuid.uuid4())
now = datetime.now(timezone.utc).isoformat()
payload["created_at"] = now
payload["updated_at"] = now
store.client.upsert(
collection_name=COLLECTION,
points=[qm.PointStruct(id=pid, vector=vec, payload=payload)],
)
created += 1
return {
"created": created,
"files": processed_files,
"import_dir": str(import_dir),
}
-441
View File
@@ -1,441 +0,0 @@
"""
OAuth-Manager fuer ARIA. Generischer OAuth2 Authorization-Code-Flow fuer
Spotify, Google, GitHub, Strava, Microsoft etc.
Architektur:
- Brain haelt einen Pending-Store: state-String pending Auth-Request
(mit timeout). Wenn ein Callback ankommt (via aria-bridge ueber RVS),
matched der state und der code wird gegen access_token getauscht.
- Token-Storage: /shared/config/oauth_tokens.json (pro Service ein Eintrag
mit access_token, refresh_token, expires_at, scope).
- Provider-Configs: /shared/config/oauth_apps.json pro Service
{client_id, client_secret, auth_url, token_url, scopes, ...}. Wird
typischerweise via Diagnostic-UI gefuellt.
- Token-Refresh: automatisch wenn access_token abgelaufen oder < 60s
bis Ablauf bei get_token() Aufruf.
OAuth-Callback-URL: https://{RVS_HOST}:{RVS_PORT_PUBLIC}/oauth/callback/{service}
RVS_PORT_PUBLIC ist nicht zwingend gleich RVS_PORT (port-mapping via TLS-Proxy).
ARIA setzt die URL beim Auth-Request automatisch Stefan muss sie EINMAL pro
Service im Provider-Dashboard registrieren.
"""
from __future__ import annotations
import base64
import json
import logging
import os
import secrets
import time
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
CONFIG_DIR = Path("/shared/config")
APPS_FILE = CONFIG_DIR / "oauth_apps.json"
TOKENS_FILE = CONFIG_DIR / "oauth_tokens.json"
# Default-Provider-Configs. Werden von oauth_apps.json gemergt (User-Config
# uebersteuert). Aktuell nur Spotify als out-of-the-box Service — fuer alles
# andere benutzt ARIA das `oauth_register_provider` Tool (legt Provider on-
# demand mit den jeweiligen Endpunkten an). Stefan muss bei jedem Provider
# danach nur client_id + client_secret in Diagnostic / App eintragen.
DEFAULT_PROVIDERS: dict[str, dict] = {
"spotify": {
"auth_url": "https://accounts.spotify.com/authorize",
"token_url": "https://accounts.spotify.com/api/token",
"scopes": ["user-read-playback-state", "user-modify-playback-state",
"user-read-currently-playing", "playlist-read-private",
"user-library-read"],
"client_auth": "basic", # client_id:client_secret als Basic-Auth-Header
},
}
# Pending Auth-Requests: state → {service, scopes, redirect_uri, created_at}
_PENDING: dict[str, dict] = {}
PENDING_TTL_SEC = 600 # 10 min — laenger nicht sinnvoll, OAuth-Codes sind eh kurzlebig
# ── Helpers ─────────────────────────────────────────────────
def _callback_url(service: str) -> str:
"""Baut die Redirect-URL die wir bei der Provider-Auth angeben.
Liest RVS_HOST / RVS_PORT_PUBLIC / RVS_TLS aus env."""
host = os.environ.get("RVS_HOST", "").strip()
if not host:
raise RuntimeError("RVS_HOST nicht gesetzt — OAuth-Callbacks nicht moeglich")
port = os.environ.get("RVS_PORT_PUBLIC", os.environ.get("RVS_PORT", "443")).strip()
tls = os.environ.get("RVS_TLS", "true").strip().lower() != "false"
scheme = "https" if tls else "http"
# Default-Ports 443/80 nicht in URL anhaengen
if (tls and port == "443") or (not tls and port == "80"):
return f"{scheme}://{host}/oauth/callback/{service}"
return f"{scheme}://{host}:{port}/oauth/callback/{service}"
def _load_json(path: Path) -> dict:
try:
if path.exists():
return json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
logger.warning("OAuth-Datei %s lesen fehlgeschlagen: %s", path, exc)
return {}
def _save_json(path: Path, data: dict) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
tmp.replace(path)
# 600 — enthaelt Secrets
try: os.chmod(path, 0o600)
except OSError: pass
except Exception as exc:
logger.error("OAuth-Datei %s speichern fehlgeschlagen: %s", path, exc)
def _provider_config(service: str) -> dict:
"""Mergt Default-Provider-Config mit User-Override aus oauth_apps.json."""
defaults = DEFAULT_PROVIDERS.get(service, {}).copy()
apps = _load_json(APPS_FILE)
user = (apps.get(service) or {}).copy()
# Tiefes Merge nicht noetig — die kollidierenden Felder sind alle scalar/list.
merged = {**defaults, **user}
return merged
def _provider_credentials(service: str) -> tuple[str, str]:
"""Liest client_id + client_secret aus oauth_apps.json. Wirft wenn nicht
konfiguriert der OAuth-Flow kann ohne nicht starten."""
apps = _load_json(APPS_FILE)
entry = apps.get(service) or {}
cid = (entry.get("client_id") or "").strip()
sec = (entry.get("client_secret") or "").strip()
if not cid or not sec:
raise RuntimeError(
f"OAuth-App '{service}' nicht konfiguriert. Bitte in Diagnostic > "
f"OAuth-Apps client_id + client_secret eintragen."
)
return cid, sec
def register_provider(service: str, auth_url: str, token_url: str,
scopes: Optional[list[str]] = None,
client_auth: str = "body",
extra_auth_params: Optional[dict] = None,
accept_header: Optional[str] = None) -> dict:
"""Schreibt einen neuen Provider-Eintrag in oauth_apps.json. KEINE
Credentials hier die bleiben Stefans Job (Diagnostic / App-UI). Wird
vom Brain-Tool `oauth_register_provider` gerufen.
Wenn der Service schon existiert: URLs/Scopes werden ueberschrieben,
aber vorhandene client_id/client_secret bleiben unberuehrt.
"""
svc = (service or "").strip()
if not svc or not all(c.isalnum() or c in "_-" for c in svc) or len(svc) > 60:
raise ValueError(f"Ungueltiger service-Name: {service!r}")
if not auth_url.startswith(("http://", "https://")):
raise ValueError(f"auth_url muss http(s):// sein: {auth_url!r}")
if not token_url.startswith(("http://", "https://")):
raise ValueError(f"token_url muss http(s):// sein: {token_url!r}")
if client_auth not in ("body", "basic"):
raise ValueError(f"client_auth muss 'body' oder 'basic' sein: {client_auth!r}")
apps = _load_json(APPS_FILE)
entry = apps.get(svc) or {}
entry["auth_url"] = auth_url.strip()
entry["token_url"] = token_url.strip()
if scopes is not None:
entry["scopes"] = list(scopes)
entry["client_auth"] = client_auth
if extra_auth_params is not None:
entry["extra_auth_params"] = extra_auth_params
if accept_header is not None:
entry["accept_header"] = accept_header
apps[svc] = entry
_save_json(APPS_FILE, apps)
logger.info("[oauth] Provider '%s' registriert (auth=%s, token=%s, scopes=%d)",
svc, auth_url, token_url, len(entry.get("scopes") or []))
return entry
def _cleanup_pending() -> None:
"""Entfernt abgelaufene Pending-Auths."""
now = time.time()
for state, info in list(_PENDING.items()):
if now - info.get("created_at", 0) > PENDING_TTL_SEC:
_PENDING.pop(state, None)
# ── Authorize ───────────────────────────────────────────────
def build_authorize_url(service: str, scopes: Optional[list[str]] = None,
extra_params: Optional[dict] = None) -> dict:
"""Baut die Authorize-URL fuer einen Provider. Speichert den state
im Pending-Store. Returns {url, state, redirect_uri, service}.
Wird vom Brain-Tool oauth_authorize gerufen. ARIA gibt die url an Stefan,
der oeffnet sie im Browser, autorisiert, Provider redirected zur
redirect_uri (= RVS), RVS broadcasted, bridge forwarded, brain matched
state exchange.
"""
_cleanup_pending()
cfg = _provider_config(service)
if not cfg.get("auth_url") or not cfg.get("token_url"):
raise RuntimeError(f"Provider '{service}' hat keine auth_url/token_url. "
f"In oauth_apps.json eintragen oder einen der "
f"vordefinierten Services nutzen ({', '.join(DEFAULT_PROVIDERS)}).")
cid, _ = _provider_credentials(service)
redirect_uri = _callback_url(service)
state = secrets.token_urlsafe(32)
use_scopes = scopes if scopes else cfg.get("scopes") or []
params = {
"client_id": cid,
"response_type": "code",
"redirect_uri": redirect_uri,
"state": state,
}
if use_scopes:
params["scope"] = " ".join(use_scopes)
params.update(cfg.get("extra_auth_params") or {})
if extra_params:
params.update(extra_params)
url = cfg["auth_url"] + "?" + urllib.parse.urlencode(params)
_PENDING[state] = {
"service": service,
"redirect_uri": redirect_uri,
"scopes": use_scopes,
"created_at": time.time(),
}
logger.info("[oauth] Authorize-URL fuer %s gebaut: state=%s redirect=%s",
service, state[:8] + "...", redirect_uri)
return {"url": url, "state": state, "redirect_uri": redirect_uri, "service": service}
# ── Token-Exchange ──────────────────────────────────────────
def _token_request(token_url: str, body_params: dict, cfg: dict,
client_id: str, client_secret: str) -> dict:
"""POST an provider /token endpoint. Returns parsed JSON oder wirft."""
data = urllib.parse.urlencode(body_params).encode("utf-8")
headers = {"Content-Type": "application/x-www-form-urlencoded"}
if cfg.get("accept_header"):
headers["Accept"] = cfg["accept_header"]
# Client-Auth: 'basic' (Header) oder 'body' (im Form-Body)
if cfg.get("client_auth") == "basic":
auth_str = f"{client_id}:{client_secret}"
b64 = base64.b64encode(auth_str.encode("utf-8")).decode("ascii")
headers["Authorization"] = f"Basic {b64}"
else:
# bereits im body_params drin (siehe Caller)
pass
req = urllib.request.Request(token_url, data=data, method="POST", headers=headers)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
raw = resp.read().decode("utf-8", "ignore")
try:
return json.loads(raw)
except json.JSONDecodeError:
# GitHub default ist form-urlencoded — accept_header sollte
# JSON anfordern, aber falls's doch mal kommt:
parsed = urllib.parse.parse_qs(raw)
return {k: v[0] if isinstance(v, list) and v else v for k, v in parsed.items()}
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", "ignore")[:500]
raise RuntimeError(f"Token-Request HTTP {e.code}: {body}") from e
def handle_callback(service: str, code: str, state: str,
error: Optional[str] = None,
error_description: Optional[str] = None) -> dict:
"""Verarbeitet einen OAuth-Callback. Validiert state, tauscht code gegen
Token, speichert. Returns {ok, service, message, ...}.
Wird von /internal/oauth-callback (HTTP, von aria-bridge) gerufen.
"""
_cleanup_pending()
if error:
# Provider hat User-Abbruch oder Fehler gemeldet
_PENDING.pop(state, None) if state else None
logger.warning("[oauth] Provider-Error %s/%s: %s%s",
service, state[:8] + "..." if state else "?", error, error_description)
return {"ok": False, "service": service, "error": error,
"errorDescription": error_description}
pending = _PENDING.pop(state, None)
if not pending:
logger.warning("[oauth] Unknown state %s fuer %s — abgelaufen oder CSRF?", state[:8] + "...", service)
return {"ok": False, "service": service,
"error": "invalid_state",
"errorDescription": "Unbekannter oder abgelaufener state (Auth-Anfrage muss erst per oauth_authorize neu gestartet werden)."}
if pending.get("service") != service:
logger.warning("[oauth] state-Service-Mismatch: pending=%s vs callback=%s",
pending.get("service"), service)
return {"ok": False, "service": service,
"error": "service_mismatch",
"errorDescription": "state gehoert zu einem anderen Service."}
if not code:
return {"ok": False, "service": service, "error": "no_code"}
cfg = _provider_config(service)
try:
client_id, client_secret = _provider_credentials(service)
except RuntimeError as exc:
return {"ok": False, "service": service, "error": "no_credentials",
"errorDescription": str(exc)}
body = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": pending["redirect_uri"],
}
if cfg.get("client_auth") != "basic":
body["client_id"] = client_id
body["client_secret"] = client_secret
try:
token_data = _token_request(cfg["token_url"], body, cfg, client_id, client_secret)
except Exception as exc:
logger.exception("[oauth] Token-Exchange fehlgeschlagen fuer %s", service)
return {"ok": False, "service": service, "error": "exchange_failed",
"errorDescription": str(exc)[:200]}
access = token_data.get("access_token")
if not access:
return {"ok": False, "service": service, "error": "no_access_token",
"errorDescription": str(token_data)[:200]}
expires_in = int(token_data.get("expires_in") or 3600)
refresh = token_data.get("refresh_token") or ""
scope = token_data.get("scope") or " ".join(pending.get("scopes") or [])
token_type = token_data.get("token_type") or "Bearer"
record = {
"service": service,
"access_token": access,
"refresh_token": refresh,
"token_type": token_type,
"scope": scope,
"expires_at": int(time.time()) + expires_in,
"obtained_at": int(time.time()),
}
_persist_token(service, record)
logger.info("[oauth] %s authentifiziert — expires in %ds, refresh=%s",
service, expires_in, "ja" if refresh else "nein")
return {"ok": True, "service": service, "expiresIn": expires_in,
"hasRefresh": bool(refresh), "scope": scope}
# ── Token-Storage / Refresh / Revoke ─────────────────────────
def _persist_token(service: str, record: dict) -> None:
tokens = _load_json(TOKENS_FILE)
tokens[service] = record
_save_json(TOKENS_FILE, tokens)
def _load_token(service: str) -> Optional[dict]:
return _load_json(TOKENS_FILE).get(service)
def get_token(service: str, refresh_threshold_sec: int = 60) -> dict:
"""Holt das aktuelle access_token fuer einen Service. Refresht automatisch
wenn weniger als refresh_threshold_sec Restzeit. Returns das ganze
record-dict Caller nimmt sich access_token raus.
Wirft wenn nicht authentifiziert oder Refresh fehlschlaegt Tool-Aufrufer
soll dann oauth_authorize anbieten."""
record = _load_token(service)
if not record:
raise RuntimeError(f"Kein Token fuer '{service}' gespeichert. Erst per "
f"oauth_authorize authentifizieren.")
exp = int(record.get("expires_at") or 0)
remaining = exp - int(time.time())
if remaining > refresh_threshold_sec:
return record
# Refresh noetig
refresh_tok = (record.get("refresh_token") or "").strip()
if not refresh_tok:
raise RuntimeError(f"Token fuer '{service}' abgelaufen und kein refresh_token "
f"vorhanden — bitte neu autorisieren mit oauth_authorize.")
cfg = _provider_config(service)
client_id, client_secret = _provider_credentials(service)
body = {
"grant_type": "refresh_token",
"refresh_token": refresh_tok,
}
if cfg.get("client_auth") != "basic":
body["client_id"] = client_id
body["client_secret"] = client_secret
try:
new_data = _token_request(cfg["token_url"], body, cfg, client_id, client_secret)
except Exception as exc:
raise RuntimeError(f"Token-Refresh fuer '{service}' fehlgeschlagen: {exc}") from exc
new_access = new_data.get("access_token")
if not new_access:
raise RuntimeError(f"Refresh-Antwort ohne access_token: {new_data}")
expires_in = int(new_data.get("expires_in") or 3600)
# refresh_token kann (manche Provider) bei jedem Refresh rotieren
new_refresh = (new_data.get("refresh_token") or refresh_tok).strip()
record.update({
"access_token": new_access,
"refresh_token": new_refresh,
"expires_at": int(time.time()) + expires_in,
"obtained_at": int(time.time()),
})
if new_data.get("scope"):
record["scope"] = new_data["scope"]
_persist_token(service, record)
logger.info("[oauth] %s Token refreshed — neue Restzeit %ds", service, expires_in)
return record
def revoke(service: str) -> bool:
"""Entfernt das Token aus dem Storage (Best-Effort, kein Provider-Revoke-Call)."""
tokens = _load_json(TOKENS_FILE)
if service not in tokens:
return False
tokens.pop(service, None)
_save_json(TOKENS_FILE, tokens)
logger.info("[oauth] %s Token geloescht (lokal).", service)
return True
def list_services() -> list[dict]:
"""Diagnostik: zeigt fuer jeden konfigurierten Service ob Token da ist
+ Ablaufzeit. Wird von Diagnostic genutzt."""
apps = _load_json(APPS_FILE)
tokens = _load_json(TOKENS_FILE)
out = []
services = set(apps.keys()) | set(tokens.keys()) | set(DEFAULT_PROVIDERS.keys())
now = int(time.time())
for s in sorted(services):
app = apps.get(s) or {}
tok = tokens.get(s) or {}
configured = bool(app.get("client_id") and app.get("client_secret"))
out.append({
"service": s,
"configured": configured,
"authenticated": bool(tok.get("access_token")),
"expiresAt": tok.get("expires_at"),
"expiresInSec": (tok.get("expires_at", 0) - now) if tok.get("expires_at") else None,
"hasRefresh": bool(tok.get("refresh_token")),
"scope": tok.get("scope", ""),
"isDefault": s in DEFAULT_PROVIDERS,
})
return out
-118
View File
@@ -1,118 +0,0 @@
"""
project_vms Registry der QEMU-VMs PRO PROJEKT.
Persistenz: /shared/config/project_vms.json { project_id: [ {vm}, ... ] }.
Eine VM = {name, arch, iso, vnc_display, mem, created_at, updated_at}. Der echte
Start/Stop laeuft ueber `aria-vm` auf dem Host (SSH aria-wohnung, siehe main.py);
diese Datei haelt nur die Zuordnung VM Projekt + die Startparameter, damit die
Liste im Desktop-Panel der App pro Projekt erscheint (auch wenn leer).
"""
from __future__ import annotations
import json
import os
import re
import time
from pathlib import Path
from typing import Optional
VMS_FILE = Path(os.environ.get("PROJECT_VMS_FILE", "/shared/config/project_vms.json"))
NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,40}$")
VALID_ARCH = {"x86_64", "amd64", "i386", "i686", "x86", "arm", "aarch64",
"mips", "mipsel", "mips64", "ppc", "ppc64", "riscv64", "sparc"}
def _load() -> dict:
if not VMS_FILE.exists():
return {}
try:
data = json.loads(VMS_FILE.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _save(data: dict) -> None:
VMS_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = VMS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
tmp.replace(VMS_FILE)
def list_vms(project_id: str) -> list[dict]:
return _load().get(project_id or "", [])
def get_vm(project_id: str, name: str) -> Optional[dict]:
for v in list_vms(project_id):
if v.get("name") == name:
return v
return None
def _used_displays(data: dict, exclude: object = None) -> set:
"""Alle VNC-Displays, die ueber ALLE Projekte belegt sind (exclude = eine
VM-Dict-Instanz, die ignoriert wird fuer Updates)."""
used = set()
for lst in data.values():
for v in lst:
if v is exclude:
continue
try:
used.add(int(v.get("vnc_display", 1)))
except (TypeError, ValueError):
pass
return used
def add_vm(project_id: str, name: str, arch: str, iso: str = "",
floppy: str = "", disk: str = "",
vnc_display: int = 0, mem: int = 1024) -> dict:
"""Registriert/aktualisiert eine VM. Medien (disk/floppy/iso) optional —
leer = aria-vm erkennt disk.qcow2/floppy.img/cdrom.iso im VM-Ordner selbst.
Das VNC-Display wird GLOBAL eindeutig vergeben (ueber alle Projekte), damit
mehrere laufende VMs nicht denselben Port doppelt binden. vnc_display<=0 oder
ein bereits belegtes Display automatisch das naechste freie."""
if not NAME_RE.match(name or ""):
raise ValueError(f"Ungueltiger VM-Name: {name!r} (nur a-z0-9_-, max 40)")
if arch not in VALID_ARCH:
raise ValueError(f"Unbekannte Architektur: {arch!r}")
data = _load()
lst = data.setdefault(project_id or "", [])
now = int(time.time())
existing = next((v for v in lst if v.get("name") == name), None)
used = _used_displays(data, exclude=existing)
req = int(vnc_display or 0)
if req <= 0 and existing: # Update ohne Display-Wunsch → behalten
req = int(existing.get("vnc_display", 0) or 0)
if req <= 0 or req in used: # frei/eindeutig machen
req = 1
while req in used:
req += 1
fields = {"arch": arch, "iso": iso, "floppy": floppy, "disk": disk,
"vnc_display": req, "mem": int(mem), "updated_at": now}
if existing:
existing.update(fields)
_save(data)
return existing
vm = {"name": name, "created_at": now, **fields}
lst.append(vm)
_save(data)
return vm
def remove_vm(project_id: str, name: str) -> bool:
data = _load()
lst = data.get(project_id or "")
if not lst:
return False
new = [v for v in lst if v.get("name") != name]
if len(new) == len(lst):
return False
data[project_id or ""] = new
_save(data)
return True

Some files were not shown because too many files have changed in this diff Show More