Compare commits
216
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96012dc986 | ||
|
|
80d7f62eaa | ||
|
|
5f5234ee62 | ||
|
|
28e58089aa | ||
|
|
c1a90102f8 | ||
|
|
ba531adc74 | ||
|
|
04d29b256e | ||
|
|
e6e07f672a | ||
|
|
d32e7e59c3 | ||
|
|
4f8e65b76b | ||
|
|
a2605a2802 | ||
|
|
0588a8d9b3 | ||
|
|
be202b1fa1 | ||
|
|
1ad85fb687 | ||
|
|
558afee239 | ||
|
|
b2fd8d8953 | ||
|
|
737915e267 | ||
|
|
1140934e15 | ||
|
|
29bf3370b4 | ||
|
|
6b5d847615 | ||
|
|
145c64e67f | ||
|
|
6cb29a28ce | ||
|
|
df5cd3be99 | ||
|
|
4125ab8160 | ||
|
|
edd0b4823f | ||
|
|
d4e3a73e89 | ||
|
|
9d93c3fe3d | ||
|
|
39f7947da9 | ||
|
|
855cc0333e | ||
|
|
2cac1cad0a | ||
|
|
f89e7ac36d | ||
|
|
cb1f571ad0 | ||
|
|
179fe53143 | ||
|
|
b73e89e9bb | ||
|
|
2b4428d823 | ||
|
|
74fcf7fd03 | ||
|
|
c7761284c7 | ||
|
|
223692d4c7 | ||
|
|
a99ea32664 | ||
|
|
4e1ab95684 | ||
|
|
bb7a19f818 | ||
|
|
6ffbc77387 | ||
|
|
3893c89d5f | ||
|
|
9f741df10e | ||
|
|
22f5f5c954 | ||
|
|
e3f6b3626d | ||
|
|
67ea68514a | ||
|
|
d6cca88455 | ||
|
|
d0d06defb1 | ||
|
|
056637ab7a | ||
|
|
ee654a6f6c | ||
|
|
f1c042c60a | ||
|
|
042fd63d33 | ||
|
|
3a908d246a | ||
|
|
7f864bb431 | ||
|
|
3474d2eb6f | ||
|
|
3df35d2293 | ||
|
|
fc198f90da | ||
|
|
387b14a8ef | ||
|
|
18147eb24d | ||
|
|
8d3637079c | ||
|
|
23d104a7c3 | ||
|
|
51985f7c2e | ||
|
|
f854303e7b | ||
|
|
39426dc70d | ||
|
|
99e4b63a06 | ||
|
|
254031bb7d | ||
|
|
eab43f5ea2 | ||
|
|
f6f2b128c4 | ||
|
|
e39599ecea | ||
|
|
e255d7a659 | ||
|
|
ebd25a1cc6 | ||
|
|
633ed06adf | ||
|
|
4f68a2a411 | ||
|
|
5689474c03 | ||
|
|
70fbc164f4 | ||
|
|
603ce93197 | ||
|
|
7022cd3c24 | ||
|
|
daba5c0457 | ||
|
|
e96b97b1b9 | ||
|
|
fcd73d8171 | ||
|
|
d0b00d5c36 | ||
|
|
9d63a73135 | ||
|
|
9981f0523d | ||
|
|
31444f1442 | ||
|
|
5398640078 | ||
|
|
5a00441966 | ||
|
|
dd71b0ce39 | ||
|
|
da36580994 | ||
|
|
7fd945ad65 | ||
|
|
3267b9a3cc | ||
|
|
672d921227 | ||
|
|
d984125624 | ||
|
|
51b267c915 | ||
|
|
54dc4498e5 | ||
|
|
a15b8ce51a | ||
|
|
18d8bc5386 | ||
|
|
ff4c1b997a | ||
|
|
7d2fce46cb | ||
|
|
334c5887b0 | ||
|
|
ef51c85cb0 | ||
|
|
d294895583 | ||
|
|
7249e2cf61 | ||
|
|
de34011b93 | ||
|
|
95bce35cab | ||
|
|
4f4c12e6d1 | ||
|
|
3abe13e796 | ||
|
|
0344f249b8 | ||
|
|
ae865a4662 | ||
|
|
9389b5ae06 | ||
|
|
23d3188205 | ||
|
|
560328bebe | ||
|
|
d72518e617 | ||
|
|
0415b2e16d | ||
|
|
f41f7fb585 | ||
|
|
c623901385 | ||
|
|
1b78ea3d8a | ||
|
|
a490513f25 | ||
|
|
d61ce316a6 | ||
|
|
09f7058853 | ||
|
|
fea503a6f3 | ||
|
|
9e7d2309f0 | ||
|
|
766fbe6da6 | ||
|
|
bf1c513191 | ||
|
|
afb7e2c604 | ||
|
|
c9d081d910 | ||
|
|
0bff35d3ef | ||
|
|
e37817ceaa | ||
|
|
c255e18a20 | ||
|
|
de8c241f2d | ||
|
|
4a743737d3 | ||
|
|
bd04305b34 | ||
|
|
b7df891574 | ||
|
|
0b760d44a0 | ||
|
|
ca18502671 | ||
|
|
be9c079360 | ||
|
|
0103cc6a38 | ||
|
|
357f1bad21 | ||
|
|
e3d3c0604b | ||
|
|
94077ec299 | ||
|
|
50e6a6e12f | ||
|
|
4e3dc36bdd | ||
|
|
8cdac41fa5 | ||
|
|
08836a6a59 | ||
|
|
6fe414029b | ||
|
|
3889d72726 | ||
|
|
5700b53b56 | ||
|
|
543b928112 | ||
|
|
7754f2b2ee | ||
|
|
d6d7805509 | ||
|
|
5aa5e2b6c6 | ||
|
|
5bb7b216f7 | ||
|
|
194dffe67e | ||
|
|
7ab2e3c101 | ||
|
|
4eeba3cf5f | ||
|
|
077bb92fd2 | ||
|
|
e5c4d0b46b | ||
|
|
f01677a5a1 | ||
|
|
71bb910672 | ||
|
|
fde8c3e9c0 | ||
|
|
c2ac054227 | ||
|
|
59b09e3491 | ||
|
|
41590c90a8 | ||
|
|
da2e5e36ba | ||
|
|
fad9aceb0e | ||
|
|
e1ab634776 | ||
|
|
f3f8002061 | ||
|
|
b528f9acae | ||
|
|
c5449641ef | ||
|
|
35d72f6cae | ||
|
|
f2a402cee1 | ||
|
|
085ede4ce7 | ||
|
|
b5ef303882 | ||
|
|
c07a59e36e | ||
|
|
b67b7543ea | ||
|
|
c6cbf7a4a8 | ||
|
|
d1283be226 | ||
|
|
8c6907d088 | ||
|
|
e84a8a19af | ||
|
|
de7cbd35f4 | ||
|
|
a95e60a2f1 | ||
|
|
12995183bc | ||
|
|
ca58f482d9 | ||
|
|
aaa1e8beb4 | ||
|
|
75f230371d | ||
|
|
ed4d2bdd03 | ||
|
|
c66f1c6968 | ||
|
|
7e3b5c0dde | ||
|
|
fa696103b7 | ||
|
|
c2511af4ef | ||
|
|
ab25dad500 | ||
|
|
9cbd96e50b | ||
|
|
ba93c6e13a | ||
|
|
8935dd8d9b | ||
|
|
927aeba1ec | ||
|
|
b162dc4f30 | ||
|
|
7efc87de3b | ||
|
|
bef53205df | ||
|
|
9622dbba1f | ||
|
|
e857db2a07 | ||
|
|
f0faf05841 | ||
|
|
ead7d83768 | ||
|
|
471f624547 | ||
|
|
5491b9aa37 | ||
|
|
0ffca86b88 | ||
|
|
f3ef46bff1 | ||
|
|
f79f309902 | ||
|
|
1562630405 | ||
|
|
50c32ec896 | ||
|
|
db356b0fb7 | ||
|
|
c0f3413fe3 | ||
|
|
6dc4333b82 | ||
|
|
5ab237d96b | ||
|
|
a0c63c7b6e | ||
|
|
47915b66cd | ||
|
|
db6b8672f2 |
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(ssh root@10.0.0.1 \"ls -la /root/ARIA-AGENT/aria-shared/logs/\")"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
# 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
|
||||
|
||||
# brain-import/ ist nur ein Drop-Folder: Stefan packt MDs rein wenn er
|
||||
# was migrieren will, klickt im Diagnostic „Migration aus brain-import/",
|
||||
|
||||
+136
-1
@@ -10,6 +10,141 @@ Alle Änderungen am Projekt. Format: [Keep a Changelog](https://keepachangelog.c
|
||||
|
||||
---
|
||||
|
||||
## [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
|
||||
@@ -100,7 +235,7 @@ Alle Änderungen am Projekt. Format: [Keep a Changelog](https://keepachangelog.c
|
||||
|
||||
## [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 Gamebox-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.
|
||||
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
|
||||
|
||||
|
||||
@@ -35,18 +35,17 @@ ARIA hat zwei Rollen:
|
||||
│ WebSocket Tunnel │ WebSocket Tunnel
|
||||
▼ ▼
|
||||
┌─────────────────────────────────┐
|
||||
│ Gamebox (Windows + WSL2) │
|
||||
│ RTX 3060, Docker Desktop │
|
||||
│ Compute-Node(s) (NVIDIA GPU) │
|
||||
│ beliebig viele, je per .env │
|
||||
│ konfiguriert (COMPOSE_PROFILES) │
|
||||
│ ┌──────────────────────────┐ │
|
||||
│ │ aria-f5tts-bridge │ │
|
||||
│ │ F5-TTS Voice Cloning │ │
|
||||
│ │ PCM-Streaming an die App │ │
|
||||
│ ├──────────────────────────┤ │
|
||||
│ │ aria-whisper-bridge │ │
|
||||
│ │ Faster-Whisper CUDA │ │
|
||||
│ │ STT in fast-Echtzeit │ │
|
||||
│ │ aria-voxtral-bridge │ │ Profil: voxtral (Default-STT)
|
||||
│ │ aria-f5tts-bridge │ │ Profil: f5tts (TTS)
|
||||
│ │ aria-llm-adapter+swap │ │ Profil: llm (lokales LLM)
|
||||
│ │ aria-whisper-bridge │ │ Profil: whisper (STT-Fallback)
|
||||
│ └──────────────────────────┘ │
|
||||
│ Beide teilen ./voices Volume │
|
||||
│ Aufteilbar: 1 Node pro Dienst │
|
||||
│ ODER All-in-One. GPU per *_GPU. │
|
||||
│ xtts/docker-compose.yml │
|
||||
└─────────────────────────────────┘
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
@@ -95,11 +94,17 @@ ARIA hat zwei Rollen:
|
||||
|-----|----|-----|
|
||||
| RVS | Rechenzentrum | `cd rvs && docker compose up -d` |
|
||||
| ARIA Brain/Bridge/Diagnostic | Debian 13 VM | `./init.sh && ./aria-setup.sh && docker compose up -d` |
|
||||
| Gamebox-Stack (F5-TTS + Whisper) | Gamebox (GPU) | `cd xtts && docker compose up -d` |
|
||||
| Compute-Node(s) (STT/TTS/LLM) | 1..n GPU-Rechner | `cd xtts && cp .env.example .env && docker compose up -d` |
|
||||
| Satellit(en) 🛰️ (optional) | Fremdes Netz (Büro …) | `cd satellite && cp .env.example .env && docker compose up -d --build` |
|
||||
| Host-Agent(en) 💻 (optional) | Direkt auf einem Rechner | `cd host-agent && ./build.sh` → Binary + `.env` auf den Rechner, starten (Details unten & in [`host-agent/README.md`](host-agent/README.md)) |
|
||||
| Android App | Stefans Handy | APK installieren (Auto-Update via RVS) |
|
||||
|
||||
> Der Gamebox-Stack ist optional: ohne ihn faellt STT auf lokales Whisper (CPU,
|
||||
> Compute-Nodes sind optional: ohne sie faellt STT auf lokales Whisper (CPU,
|
||||
> langsamer) zurueck; TTS bleibt aus (ARIA antwortet dann nur als Text).
|
||||
> Jeder Node startet per `COMPOSE_PROFILES` in seiner `.env` nur die Dienste,
|
||||
> die er anbieten soll (`voxtral`/`f5tts`/`llm`/`whisper`) — so laesst sich der
|
||||
> GPU-Stack auf mehrere Maschinen verteilen (STT-Box, TTS-Box, LLM-Box) oder
|
||||
> als All-in-One auf einer Kiste fahren (`voxtral,f5tts,llm`).
|
||||
|
||||
---
|
||||
|
||||
@@ -134,8 +139,8 @@ RVS_PORT=443
|
||||
RVS_TLS=true
|
||||
RVS_TLS_FALLBACK=true
|
||||
|
||||
# Pairing-Token: Verbindet App, Bridge, Diagnostic und Gamebox im gleichen RVS-Room
|
||||
# MUSS auf allen Geraeten identisch sein (ARIA-VM, Gaming-PC, App)
|
||||
# Pairing-Token: Verbindet App, Bridge, Diagnostic und Compute-Nodes im gleichen RVS-Room
|
||||
# MUSS auf allen Geraeten identisch sein (ARIA-VM, Compute-Nodes, App)
|
||||
RVS_TOKEN= # ./generate-token.sh
|
||||
```
|
||||
|
||||
@@ -204,6 +209,37 @@ Die Diagnostic-UI hat sechs Top-Tabs:
|
||||
- **Dateien** — alle Dateien aus `/shared/uploads/` mit Multi-Select, Bulk-Download (ZIP) + Bulk-Delete
|
||||
- **Einstellungen** — Reparatur (Container-Restart), Wipe, Sprachausgabe, Whisper, Sprachmodell, Runtime-Config, App-Onboarding (QR), Komplett-Reset
|
||||
|
||||
### 6. (Optional) Desktop-Workspace: QEMU auf dem Host
|
||||
|
||||
Nur noetig, wenn ARIA VMs bauen/testen und du sie live in der Desktop-Kachel der
|
||||
App bedienen koennen sollst (Code-Projekte, z. B. ein Win-3.11-System). **Wird
|
||||
NICHT von `docker compose` mitinstalliert** — QEMU laeuft direkt auf dem Host
|
||||
(10.0.0.1), nicht in einem Container, weil dort KVM sitzt und die VNC binden
|
||||
kann. Einmalig als root:
|
||||
|
||||
```bash
|
||||
sudo bash host-provisioning/qemu-setup.sh
|
||||
```
|
||||
|
||||
Installiert `qemu-system-*` fuer **alle Architekturen** (x86/ARM/MIPS/PPC/SPARC/
|
||||
RISC-V), `qemu-utils`, Firmware, `socat`, `imagemagick` und den Helper
|
||||
`/usr/local/bin/aria-vm`. KVM-Beschleunigung gibt es nur fuer x86-Gaeste; andere
|
||||
Architekturen laufen emuliert (TCG). Danach testen:
|
||||
|
||||
```bash
|
||||
aria-vm list
|
||||
```
|
||||
|
||||
ARIA steuert VMs dann per `ssh aria-wohnung aria-vm ...` (create/boot/screenshot/
|
||||
list/stop). Der VNC-Desktop wird automatisch als RFB-Bytes durch die Bridge/RVS
|
||||
in die App getunnelt — **kein** Port am Host oeffnen, **kein** websockify/noVNC
|
||||
auf dem Host noetig (der noVNC-Client liegt in der App). Ohne diesen Schritt
|
||||
funktioniert alles andere normal; nur die Desktop-Kachel bleibt leer.
|
||||
|
||||
> **App-Rebuild noetig** fuer den Workspace: die neuen nativen Module
|
||||
> (gesture-handler, reanimated, webview) brauchen nach `npm install` einmalig
|
||||
> `npm start --reset-cache` + `./gradlew clean`, dann APK neu bauen.
|
||||
|
||||
---
|
||||
|
||||
## Proxy — Wie funktioniert das?
|
||||
@@ -272,28 +308,28 @@ Danach wird der Proxy gepatcht:
|
||||
|
||||
## Voice Bridge
|
||||
|
||||
Die Bridge verbindet die Android App mit ARIA und orchestriert die GPU-Services
|
||||
auf der Gamebox.
|
||||
Die Bridge verbindet die Android App mit ARIA und orchestriert die GPU-Dienste
|
||||
auf den Compute-Nodes.
|
||||
|
||||
**Nachrichtenfluss:**
|
||||
```
|
||||
Text: App → RVS → Bridge → aria-brain (HTTP)
|
||||
Audio: App → RVS → Bridge → stt_request (RVS) → whisper-bridge (Gamebox)
|
||||
→ stt_response → Bridge → aria-brain
|
||||
Audio: App → RVS → STT-Node (voxtral/whisper) direkt (Streaming)
|
||||
→ stt_endpoint/stt_stream_done → Bridge → aria-brain
|
||||
Fallback bei Timeout: lokales faster-whisper (CPU)
|
||||
Datei: App → RVS → Bridge → /shared/uploads/ → aria-brain (mit Pfad)
|
||||
|
||||
aria-brain → Antwort → Bridge → RVS → App
|
||||
→ xtts_request (RVS) → f5tts-bridge
|
||||
→ xtts_request (RVS) → f5tts-Node
|
||||
→ audio_pcm Stream → RVS → App AudioTrack
|
||||
```
|
||||
|
||||
### Features
|
||||
|
||||
- **STT primaer remote**: aria-bridge sendet `stt_request` an die Gamebox-Whisper
|
||||
(faster-whisper CUDA, fast Echtzeit). 45s Timeout, dann Fallback auf lokales
|
||||
CPU-Whisper. Modell-Wahl in Diagnostic, Hot-Swap via config-Broadcast.
|
||||
- **TTS via F5-TTS**: aria-f5tts-bridge auf der Gamebox. Voice Cloning mit
|
||||
- **STT primaer remote**: die App streamt Audio direkt an einen STT-Node
|
||||
(Voxtral-3B default, faster-whisper Fallback-Profil), fast Echtzeit. Timeout →
|
||||
Fallback auf lokales CPU-Whisper. Modell-Wahl in Diagnostic, Hot-Swap via config.
|
||||
- **TTS via F5-TTS**: aria-f5tts-bridge auf einem Compute-Node. Voice Cloning mit
|
||||
Referenz-Audio + automatisch transkribiertem Referenz-Text.
|
||||
- **Text-Cleanup**: `<voice>...</voice>` Tag bevorzugt; Markdown, Code,
|
||||
Einheiten und URLs werden TTS-gerecht aufbereitet. Dezimalzahlen werden
|
||||
@@ -454,7 +490,7 @@ Erreichbar unter `http://<VM-IP>:3001`. Teilt das Netzwerk mit der Bridge.
|
||||
- **Disk-Voll Banner** mit copy-baren Cleanup-Befehlen (safe + aggressiv)
|
||||
- **Token/Call-Metrics**: pro Claude-Call ein Eintrag in `/data/metrics.jsonl` mit ts + Token-Schaetzung. Gehirn-Tab zeigt 1h/5h/24h/30d-Aggregat plus Progress-Bar gegen Plan-Limit (Pro / Max 5x / Max 20x / Custom). Warn-Schwelle 80%, kritisch 90%.
|
||||
- **Voice Cloning**: Audio-Samples hochladen, Whisper transkribiert den Ref-Text automatisch
|
||||
- **Voice Export/Import**: einzelne Stimmen als `.tar.gz` zwischen Gameboxen mitnehmen
|
||||
- **Voice Export/Import**: einzelne Stimmen als `.tar.gz` zwischen Compute-Nodes mitnehmen
|
||||
- **Settings Export/Import**: `voice_config.json` + `highlight_triggers.json` als JSON-Bundle
|
||||
- **Claude Login**: Browser-Terminal zum Einloggen in den Proxy
|
||||
- **ARIA Live**: read-only Mirror der Claude-Code-Session — alle Tool-Calls + Inputs + Outputs live in einer Monospace-Liste, farbcodiert. **Persistenz**: jeder `agent_stream`-Event wird parallel in `/shared/logs/agent_stream.jsonl` (soft-cap 50 MB) geschrieben, Live-View laedt beim Tab-Oeffnen / Page-Reload die letzten 200 Eintraege — Browser-Standby wirft nichts mehr weg. Plus ⛔ **Not-Aus**-Button der per RVS einen `cancel_request` mit `hard:true` ausloest → aria-bridge ruft den proxy-internen `/cancel-all` Side-Channel → alle Claude-Subprocesses werden sofort gekillt
|
||||
@@ -469,19 +505,25 @@ Erreichbar unter `http://<VM-IP>:3001`. Teilt das Netzwerk mit der Bridge.
|
||||
|
||||
### Features
|
||||
|
||||
- **Desktop-Workbench (Kompakt ↔ Cockpit)**: Umschalter oben rechts im Header. **Kompakt** = klassischer Vollbild-Chat (Default). **Cockpit** = Workbench mit **Taskleiste unten** (Chat · Code · Desktop) — ein Daumen-Tap wechselt sofort das Panel, animierter Indikator, Aktivitäts-Punkte (Code blau / Desktop grün). Jedes Panel bildschirmfüllend und Handy-optimiert; Dock blendet bei offener Tastatur aus. Desktop-Umfang, aber auf 5 Zoll bedienbar
|
||||
- **Live-Code-Editor** (Code-Projekte): Wird ein Projekt zum Code-Projekt (`set_project_kind('code')`), zeigt eine Editor-Kachel **live, was ARIA schreibt** (Syntax-Highlighting, offline) und du kannst selbst editieren → zurück an ARIA. ARIAs `Write`/`Edit` unter `/shared/projects/<id>/` werden im Proxy abgefangen und als `code_file` gespiegelt; deine Edits kommen als `code_file_edit` pfad-sicher zurück
|
||||
- **Live-Desktop per VNC (durch RVS getunnelt)**: ARIA baut/testet VMs mit **QEMU für jede Architektur** (x86/ARM/MIPS/PPC/RISC-V/SPARC, Host-Helper `aria-vm`, KVM für x86). Der QEMU-Desktop erscheint **live in der Desktop-Kachel** — noVNC in der WebView, RFB-Bytes werden als Base64 über RVS gebrückt (Bridge ↔ QEMU `127.0.0.1:5901`). Du bedienst die VM **live mit Maus/Tastatur**, NAT-sicher, kein offener Port am Host
|
||||
- Text-Chat mit ARIA
|
||||
- **Sprachaufnahme**: Tap-to-Talk (tippen startet, tippen stoppt, Auto-Stop bei Stille via VAD)
|
||||
- **Gespraechsmodus** (Ohr-Button): Nach jeder ARIA-Antwort startet automatisch die Aufnahme — wie ein natuerliches Gespraech hin und her
|
||||
- **Wake-Word** (on-device, openWakeWord ONNX): "Hey Jarvis", "Alexa", "Hey Mycroft", "Hey Rhasspy" — Mikrofon hoert passiv mit, Konversation startet beim Schluesselwort. Komplett on-device via ONNX Runtime, kein API-Key, kein Cloud-Roundtrip, Audio verlaesst das Geraet nicht.
|
||||
- **VAD (Voice Activity Detection)**: Adaptive Schwelle (Baseline aus ersten 500ms Mic-Pegel + 6dB Offset). Konfigurierbare Stille-Toleranz (1.0–8.0s, Default 2.8s) bevor Auto-Stop greift. Max-Aufnahme einstellbar (1–30 min, Default 5 min)
|
||||
- **Barge-In**: Wenn du waehrend ARIAs Antwort eine neue Sprach-/Text-Nachricht reinschickst, wird sie unterbrochen + bekommt den Hint "das ist eine Korrektur"
|
||||
- **Nachricht anstellen statt abbrechen** (Queue pro Projekt): Schickst du eine zweite Nachricht waehrend ARIA noch am aktuellen Task arbeitet, wird sie **angestellt** statt den laufenden abzubrechen — laeuft der Reihe nach, pro Projekt unabhaengig. Wartende zeigen als `⏸`-Bubble (tippen entfernt sie aus der Warteschlange). Explizites Abbrechen laeuft ueber den Stop-Button am „ARIA denkt". Eine neue Sprachnachricht stoppt nur akustisch das TTS (sauberes Mikro), bricht die laufende Arbeit aber nicht mehr ab
|
||||
- **Rueckfrage-Loop**: Stellt ARIA eine echte, blockierende Rueckfrage, **pausiert** die Queue und deine naechste Eingabe beantwortet sie — bis eine finale Antwort kommt, dann laeuft der naechste Queue-Eintrag (gleiches Muster). Banner „❓ ARIA fragt nach — deine Eingabe beantwortet das". ARIA signalisiert das ueber einen unsichtbaren `[[AWAIT]]`-Marker im Antworttext (das Modell deklariert den Zustand selbst, kein „endet-mit-?"-Raten; Brain strippt ihn und gibt `awaiting_reply` an App + Diagnostic durch)
|
||||
- **Pro-Projekt-Textfeld-Entwuerfe**: Der Feldinhalt bleibt beim Projektwechsel erhalten — in Projekt X tippen, zu Y wechseln (leeres Feld), zurueck zu X → dein Entwurf steht wieder da. Persistiert ueber Neustart. Gleiches Verhalten im Diagnostic
|
||||
- **Wake-Word waehrend TTS**: Du kannst "Computer" sagen waehrend ARIA noch redet — AcousticEchoCanceler verhindert dass ARIAs eigene Stimme das Wake-Word triggert
|
||||
- **Anruf-Pause + Auto-Resume**: TTS verstummt bei klassischem Anruf oder VoIP-Call (WhatsApp/Signal/Discord). Nach dem Auflegen geht ARIA von der **genauen Stelle** weiter wo sie unterbrochen wurde — die App misst die Position vom Wiedergabe-Anfang und nutzt den WAV-Cache der Antwort
|
||||
- **Speech Gate**: Aufnahme wird verworfen wenn keine Sprache erkannt
|
||||
- **STT (Speech-to-Text)**: 16kHz mono → Bridge → Gamebox-Whisper (CUDA) → Text im Chat. Fast in Echtzeit.
|
||||
- **STT (Speech-to-Text)**: 16kHz mono → STT-Node (Voxtral-3B, CUDA) → Text im Chat. Fast in Echtzeit.
|
||||
- **"ARIA denkt..." Indicator**: Zeigt live den Status vom Core (Denken, Tool, Schreiben) + Abbrechen-Button
|
||||
- **TTS-Wiedergabe**: F5-TTS PCM-Streaming direkt in AudioTrack mit konfigurierbarem Pre-Roll-Buffer (1.0–6.0s, Default 3.5s) gegen Gaps bei Render-Pausen
|
||||
- **Audio-Pause**: Andere Apps (Spotify, YouTube etc.) pausieren komplett waehrend ARIA spricht und kommen erst wieder nach echtem Wiedergabe-Ende
|
||||
- **TTS-Abspiel-Queue**: Zwei fast gleichzeitig fertige Antworten sprechen garantiert **nacheinander** statt sich abzuschneiden — eine neue hoerbare Antwort, die waehrend der Wiedergabe einer anderen ankommt, wird gepuffert und erst nach deren echtem Wiedergabe-Ende (`PcmPlaybackFinished`, nicht nur Stream-Ende) nachgespielt. Harter Stop / Barge-In / Mund-Button verwirft die Queue
|
||||
- **Lokale Voice-Wahl**: Pro Geraet eigene Stimme moeglich (in Settings). Diagnostic-Wechsel ueberschreibt alle App-Wahlen.
|
||||
- **Voice-Ready Toast**: Beim Wechsel zeigt die App "Stimme X bereit (X.Ys)" sobald der Preload durch ist
|
||||
- **Play-Button**: Jede ARIA-Nachricht kann nochmal vorgelesen werden (aus Cache wenn vorhanden, sonst neu rendern)
|
||||
@@ -617,7 +659,7 @@ Der Update-Flow:
|
||||
App (Mikrofon) → AAC/MP4 Aufnahme → Base64 → RVS → Bridge
|
||||
Bridge: FFmpeg (16kHz PCM) → Whisper STT → Text → aria-brain
|
||||
Bridge: STT-Ergebnis → RVS → App (Placeholder wird durch transkribierten Text ersetzt)
|
||||
aria-brain → Antwort → Bridge → F5-TTS (Gaming-PC) → PCM-Stream → RVS → App
|
||||
aria-brain → Antwort → Bridge → F5-TTS (Compute-Node) → PCM-Stream → RVS → App
|
||||
App: AudioTrack MODE_STREAM (nahtlos), Cache als WAV pro Message
|
||||
```
|
||||
|
||||
@@ -759,36 +801,57 @@ cp ARIA-v0.0.3.0.apk ~/ARIA-AGENT/rvs/updates/
|
||||
|
||||
---
|
||||
|
||||
## Gamebox-Stack — F5-TTS + Whisper (GPU-Services)
|
||||
## Compute-Nodes — STT / TTS / LLM (GPU-Dienste)
|
||||
|
||||
Laeuft auf einem separaten Rechner mit NVIDIA GPU (z.B. Gaming-PC mit RTX 3060).
|
||||
Verbindet sich ueber RVS mit der ARIA-Infrastruktur — kein VPN noetig, funktioniert
|
||||
ueber verschiedene Netze hinweg.
|
||||
Die GPU-Dienste laufen auf einem oder mehreren separaten Rechnern mit NVIDIA GPU.
|
||||
Jeder **Compute-Node** verbindet sich ueber RVS mit der ARIA-Infrastruktur — kein
|
||||
VPN noetig, funktioniert ueber verschiedene Netze hinweg. Frueher war das *eine*
|
||||
feste „AI-Box"; jetzt sind es beliebig viele Nodes, jeder per `.env` konfiguriert.
|
||||
|
||||
### Architektur
|
||||
### Dienste & Profile
|
||||
|
||||
Jeder Dienst haengt an einem Compose-Profil. Ein Node startet ueber
|
||||
`COMPOSE_PROFILES` (in seiner `.env`) nur die Profile, die er anbieten soll:
|
||||
|
||||
| Profil | Container | Rolle |
|
||||
|-----------|------------------------------|-------|
|
||||
| `voxtral` | aria-voxtral-bridge | Default-STT (Voxtral-Mini-3B, ~9 GB) |
|
||||
| `whisper` | aria-whisper-bridge | STT-Fallback (faster-whisper CUDA) |
|
||||
| `f5tts` | aria-f5tts-bridge | TTS (F5-TTS Voice Cloning) |
|
||||
| `llm` | aria-llama-swap + llm-adapter| Lokales LLM (llama-swap, OpenAI-kompat.) |
|
||||
|
||||
### Architektur (Aufteilung auf mehrere Nodes)
|
||||
|
||||
```
|
||||
Gamebox (Windows, RTX 3060, Docker Desktop + WSL2)
|
||||
├── aria-f5tts-bridge F5-TTS Voice Cloning + RVS-Relay
|
||||
│ Hoert auf xtts_request, streamt audio_pcm
|
||||
├── aria-whisper-bridge faster-whisper auf CUDA (float16)
|
||||
│ Hoert auf stt_request, antwortet mit stt_response
|
||||
└── ./voices/ Geteilt zwischen beiden:
|
||||
{name}.wav — Referenz-Audio (~6-10s)
|
||||
{name}.txt — Referenz-Text (auto via Whisper)
|
||||
STT-Box COMPOSE_PROFILES=voxtral VOXTRAL_GPU=0
|
||||
TTS-Box COMPOSE_PROFILES=f5tts F5TTS_GPU=0
|
||||
LLM-Box COMPOSE_PROFILES=llm LLM_GPU=0
|
||||
-- kleine Karte: Whisper (klein) statt Voxtral, neben F5-TTS --
|
||||
Klein-Box COMPOSE_PROFILES=whisper,f5tts WHISPER_GPU=0 F5TTS_GPU=0
|
||||
── oder All-in-One ──
|
||||
AI-Box COMPOSE_PROFILES=voxtral,f5tts,llm VOXTRAL_GPU=1 F5TTS_GPU=0 LLM_GPU=0
|
||||
|
||||
↕ RVS (Rechenzentrum, WebSocket Relay)
|
||||
|
||||
ARIA-VM
|
||||
└── aria-bridge: STT primaer remote (45s Timeout, dann lokaler CPU-Fallback)
|
||||
TTS via xtts_request → audio_pcm Stream
|
||||
└── aria-bridge: orchestriert TTS/LLM (xtts_request/llm_request),
|
||||
lauscht passiv auf den STT-Stream App↔STT-Node.
|
||||
STT-Timeout → lokaler CPU-Whisper-Fallback.
|
||||
```
|
||||
|
||||
### Voraussetzungen
|
||||
> STT: pro Node **genau einen** — Voxtral-3B (~9 GB, beste Qualitaet) *oder*
|
||||
> Whisper (klein, passt neben F5-TTS auf eine GPU mit wenig VRAM). Beide zusammen
|
||||
> beantworten dieselbe Anfrage doppelt.
|
||||
|
||||
- Docker Desktop mit WSL2 (Windows) oder Docker mit NVIDIA Runtime (Linux)
|
||||
- NVIDIA Container Toolkit
|
||||
- GPU mit mindestens 6GB VRAM (Whisper-large + F5-TTS gemeinsam)
|
||||
Die STT-Node teilt sich das `./voices/`-Volume mit F5-TTS nur, wenn beide auf
|
||||
demselben Node laufen (Referenz-Text-Transkription beim Voice-Upload). Auf
|
||||
getrennten Nodes transkribiert F5-TTS ueber den STT-Node via RVS.
|
||||
|
||||
### Voraussetzungen (pro Node)
|
||||
|
||||
- Docker + **NVIDIA Container Toolkit** (registriert die `nvidia`-Runtime — die
|
||||
Compose nutzt `runtime: nvidia` + `NVIDIA_VISIBLE_DEVICES`).
|
||||
- Genug VRAM fuer die gewaehlten Profile (Voxtral-3B ~9 GB, F5-TTS ~1 GB, LLM je Modell).
|
||||
- **Gleicher RVS_TOKEN wie auf der ARIA-VM!**
|
||||
|
||||
### Setup
|
||||
@@ -796,13 +859,17 @@ ARIA-VM
|
||||
```bash
|
||||
cd xtts
|
||||
cp .env.example .env
|
||||
# .env mit RVS-Verbindungsdaten fuellen (gleicher Token wie ARIA-VM!)
|
||||
# .env anpassen:
|
||||
# COMPOSE_PROFILES → welche Dienste dieser Node fahren soll
|
||||
# NODE_NAME → Name des Rechners (erscheint in Diagnostic + Logs)
|
||||
# *_GPU → welche Grafikkarte pro Dienst (NVIDIA_VISIBLE_DEVICES)
|
||||
# RVS_* → gleiche Verbindungsdaten wie die ARIA-VM
|
||||
docker compose up -d
|
||||
# Erster Start laedt die Modelle (Whisper ~1-3GB je nach Groesse, F5-TTS ~1GB)
|
||||
# Erster Start laedt die Modelle der aktiven Profile (Voxtral ~9GB, F5-TTS ~1GB)
|
||||
```
|
||||
|
||||
Die Modelle werden in den Volumes `f5tts-models` und `whisper-models` gecacht
|
||||
und muessen nur einmal geladen werden.
|
||||
Die Modelle liegen im Bind-Mount `./hf-cache/` (bzw. `./models/` fuer LLM-GGUFs)
|
||||
und muessen pro Node nur einmal geladen werden.
|
||||
|
||||
### Features
|
||||
|
||||
@@ -824,7 +891,7 @@ In der Diagnostic unter Einstellungen → Sprachausgabe:
|
||||
- **TTS aktiv**: Global An/Aus
|
||||
- **F5-TTS Stimme**: Default oder gecloned (Maia etc.)
|
||||
|
||||
> F5-TTS ist die einzige Engine — wenn die Gamebox offline ist, bleibt ARIA stumm.
|
||||
> F5-TTS ist die einzige Engine — wenn kein f5tts-Node online ist, bleibt ARIA stumm.
|
||||
> Chat-Antworten kommen weiter an (nur kein Audio).
|
||||
|
||||
### Stimme klonen
|
||||
@@ -870,6 +937,75 @@ dem Cache wiederverwendet.
|
||||
|
||||
---
|
||||
|
||||
## Host-Agenten 💻 — Direktzugriff auf einen Rechner
|
||||
|
||||
Ein **Host-Agent** läuft als **Standalone-Binary direkt auf einem Rechner**
|
||||
(Linux) und verbindet sich **ausgehend** zum RVS (gleicher Token). Damit steuert
|
||||
ARIA diesen Rechner direkt — auch wenn er sonst aus dem Netz **nicht erreichbar**
|
||||
ist (hinter NAT/Firewall, kein offener Port). Unterschied zum Satelliten: der
|
||||
Satellit ist ein LAN-Gateway (entdeckt/steuert *andere* Geräte); der Host-Agent
|
||||
steuert den Rechner, auf dem er *läuft*.
|
||||
|
||||
**Fähigkeiten** (ARIA-Tools `host_list` / `host_exec` / `host_read` /
|
||||
`host_write` / `host_info` / `host_screenshot`): Shell-Kommandos (optional
|
||||
`sudo`), Datei lesen/schreiben, System-Info (CPU/RAM/Disk/Uptime), Screenshot
|
||||
(ARIA öffnet ihn mit ihrem Read-Tool und *sieht* den Bildschirm; erscheint zudem
|
||||
inline im Chat).
|
||||
|
||||
### 1. Binary bauen (portabel, Linux x86_64)
|
||||
|
||||
```bash
|
||||
cd host-agent
|
||||
./build.sh # braucht Docker; erzeugt dist/aria-host-agent (~15 MB)
|
||||
```
|
||||
|
||||
Gebaut wird via PyInstaller in einem bullseye-Container (altes glibc) → läuft auf
|
||||
möglichst vielen Distributionen. Keine Runtime auf dem Ziel nötig.
|
||||
|
||||
### 2. Auf dem Ziel-Rechner installieren
|
||||
|
||||
```bash
|
||||
# dist/aria-host-agent auf den Rechner kopieren, dann:
|
||||
cp .env.example .env # RVS-Zugang + CONTROL_ENABLED=true eintragen
|
||||
chmod +x aria-host-agent && ./aria-host-agent
|
||||
```
|
||||
|
||||
**Als systemd-Dienst** (Dauerbetrieb) — der Installer kopiert Binary + `.env`
|
||||
an ihre Plätze und richtet den Dienst ein:
|
||||
|
||||
```bash
|
||||
sudo ./install-service.sh /pfad/zur/.env # .env-Pfad direkt
|
||||
sudo ./install-service.sh # oder: ncurses-Dateidialog (dialog)
|
||||
```
|
||||
|
||||
→ Binary nach `/usr/local/bin`, `.env` nach `/etc/aria-host-agent/.env` (0600),
|
||||
Unit installiert + `enable --now`. Danach `journalctl -u aria-host-agent -f`.
|
||||
|
||||
### TLS / SNI — Agent im selben Netz wie der RVS
|
||||
|
||||
Verbindet der Agent direkt auf die **interne RVS-IP** (statt über den externen
|
||||
Hostnamen per NAT-Hairpin), scheitert TLS sonst am fehlenden Cert für die IP
|
||||
(`tlsv1 alert internal error`). Dann in der `.env`: `RVS_HOST=<interne-ip>` +
|
||||
`RVS_SNI=<zert-name>` (z.B. `example.com`). Gilt genauso für Satelliten
|
||||
und Compute-Nodes im RZ-Netz (`RVS_SNI` in deren `.env`).
|
||||
|
||||
### sudo
|
||||
|
||||
Der Agent wählt automatisch: **root** → direkt · `SUDO_PASSWORD` in der `.env`
|
||||
→ `sudo -S` · **`SUDO_NOPASSWD=true`** → `sudo -n` (Live-ISO / passwortloses
|
||||
sudo, z.B. Linux Mint vom Stick) · sonst klare Fehlermeldung.
|
||||
|
||||
### Sicherheit
|
||||
|
||||
Reagiert nur auf den eigenen RVS-Raum (Token) und nur bei `CONTROL_ENABLED=true`;
|
||||
keine offenen Ports; alle Kommandos werden geloggt. Gibt **vollen** Rechnerzugriff
|
||||
— nur auf Maschinen einsetzen, denen du ARIA anvertraust. Details:
|
||||
[`host-agent/README.md`](host-agent/README.md).
|
||||
|
||||
> Sichtbar in der Diagnostic unter **Satelliten → Host-Agenten 💻**.
|
||||
|
||||
---
|
||||
|
||||
## Docker Volumes
|
||||
|
||||
| Volume / Bind | Pfad im Container | Zweck |
|
||||
@@ -986,7 +1122,7 @@ docker exec aria-brain curl localhost:8080/memory/stats
|
||||
- [x] Pre-Roll-Buffer einstellbar in App-Settings
|
||||
- [x] Decimal-zu-Worte fuer TTS + generisches Acronym-Buchstabieren
|
||||
- [x] voice_preload/voice_ready: visueller Status-Indikator beim Stimmen-Wechsel
|
||||
- [x] Whisper STT auf die Gamebox ausgelagert (CUDA float16, fast Echtzeit)
|
||||
- [x] Whisper STT auf die AI-Box ausgelagert (CUDA float16, fast Echtzeit)
|
||||
- [x] **F5-TTS ersetzt XTTS** — bessere Voice-Cloning-Qualitaet, Whisper-auto-transkribierter Referenz-Text
|
||||
- [x] Audio-Pause statt Ducking (TRANSIENT statt MAY_DUCK) + release-Timing fix
|
||||
- [x] VAD-Stille-Toleranz einstellbar (1-8s) + adaptive Mikro-Baseline + Max-Aufnahme einstellbar (1-30 min)
|
||||
@@ -994,6 +1130,9 @@ docker exec aria-brain curl localhost:8080/memory/stats
|
||||
- [x] Anruf-Pause + Auto-Resume: TTS verstummt bei Anruf, faehrt nach Auflegen ab der gemerkten Position fort (Date.now()-Tracking + WAV-Cache der Antwort)
|
||||
- [x] PcmPlaybackFinished-Event: AudioFocus wird erst released wenn AudioTrack wirklich durch ist — kein Spotify-mid-TTS mehr
|
||||
- [x] Edge-Case: neue Frage waehrend Telefonat verwirft pending Auto-Resume, neueste Antwort gewinnt
|
||||
- [x] **Pro-Projekt-Nachrichten-Queue** (loest das alte Barge-In-Cancel ab): zweite Nachricht wird **angestellt** statt den laufenden Task abzubrechen; **Rueckfrage-Loop** via unsichtbarem `[[AWAIT]]`-Marker (Queue pausiert, naechste Eingabe beantwortet die Rueckfrage); Stop-Button schaltet zum naechsten; sichtbare `⏸`-Bubbles (loeschbar). Pro Projekt unabhaengig, App + Diagnostic
|
||||
- [x] Pro-Projekt-Textfeld-Entwuerfe (Feldinhalt bleibt beim Projektwechsel erhalten, persistiert; App + Diagnostic)
|
||||
- [x] **TTS-Abspiel-Queue**: zwei fast gleichzeitig fertige Antworten sprechen garantiert nacheinander statt sich abzuschneiden (Puffern bis `PcmPlaybackFinished` der laufenden)
|
||||
- [x] Settings-Sub-Screens: 8 Kategorien statt langer Liste
|
||||
- [x] APK ABI-Split arm64-v8a: 35 MB statt 136 MB
|
||||
- [x] Sprachnachrichten-Bubble: audioRequestId statt Substring-Match — keine vertauschten Bubbles mehr bei parallelen Aufnahmen
|
||||
@@ -1004,6 +1143,11 @@ docker exec aria-brain curl localhost:8080/memory/stats
|
||||
- [x] Background Audio Service: TTS, Wake-Word-Lauschen + Aufnahme laufen auch bei minimierter App weiter (Foreground-Service mit mediaPlayback|microphone, dynamische Notification)
|
||||
- [x] Disk-Voll Banner in Diagnostic mit copy-baren Cleanup-Befehlen
|
||||
- [x] Wake-Word on-device via openWakeWord (ONNX Runtime, kein API-Key) + State-Icon
|
||||
- [x] **Desktop-Workbench**: Taskleisten-Dock (Chat · Code · Desktop), Ein-Tap-Panelwechsel im Daumenbereich, Aktivitäts-Badges, keyboard-aware; Kompakt↔Cockpit-Umschalter. (Ersetzte den anfänglichen Pinch-Zoom-Kachel-Canvas — auf 5 Zoll zu fummelig)
|
||||
- [x] **noVNC-Konsole bedienbar**: Tastatur-Einblendung (tippt in die VM), Strg+Alt+Entf, Fit↔1:1
|
||||
- [x] **Live-Code-Editor** für Code-Projekte (WebView, offline, bidirektional) — ARIAs Write/Edit unter `/shared/projects/<id>/` live gespiegelt (`code_file`), eigene Edits zurück (`code_file_edit`)
|
||||
- [x] **QEMU für alle Architekturen** (Host-Helper `aria-vm`, `qemu-setup.sh`) + `set_project_kind`-Tool + Seed-Regel
|
||||
- [x] **VNC-Live-Desktop durch RVS getunnelt** (Bridge RFB-TCP ↔ RVS, noVNC-WebView mit WebSocket-Shim) — VM live mit Maus/Tastatur bedienbar
|
||||
|
||||
### Phase A — Refactor: OpenClaw raus, eigenes Brain rein
|
||||
|
||||
@@ -1033,7 +1177,7 @@ docker exec aria-brain curl localhost:8080/memory/stats
|
||||
- [x] App: Chat-Suche mit Next/Prev Navigation statt Filter
|
||||
- [x] Token/Call-Metrics + Subscription-Quota-Tracking (Pro / Max 5x / Max 20x / Custom)
|
||||
- [x] Datei-Manager Multi-Select: Bulk-Download als ZIP + Bulk-Delete (Diagnostic + App)
|
||||
- [x] **FLUX.1 Bildgenerierung**: eigener `flux-bridge`-Container auf der Gamebox (analog xtts/whisper) mit Hot-Swap zwischen FLUX.1-dev (Quali) und FLUX.1-schnell (Tempo). Default-Modell + Raw-/Switch-Keywords + HuggingFace-Token in Diagnostic-UI verwaltet, automatischer Pipeline-Reload bei Modell-Wechsel. ARIA bekommt `flux_generate`-Tool, Output landet als `/shared/uploads/aria_generated_<ts>.png` und wird via `[FILE: ...]`-Marker als Anhang-Bubble in App + Diagnostic gerendert. Download-Status (mehrere GB) sichtbar als 🎉-Toast wenn fertig
|
||||
- [x] **FLUX.1 Bildgenerierung**: eigener `flux-bridge`-Container auf der AI-Box (analog xtts/whisper) mit Hot-Swap zwischen FLUX.1-dev (Quali) und FLUX.1-schnell (Tempo). Default-Modell + Raw-/Switch-Keywords + HuggingFace-Token in Diagnostic-UI verwaltet, automatischer Pipeline-Reload bei Modell-Wechsel. ARIA bekommt `flux_generate`-Tool, Output landet als `/shared/uploads/aria_generated_<ts>.png` und wird via `[FILE: ...]`-Marker als Anhang-Bubble in App + Diagnostic gerendert. Download-Status (mehrere GB) sichtbar als 🎉-Toast wenn fertig
|
||||
- [x] **ARIA Live (Diagnostic) + Not-Aus**: read-only Mirror der Claude-Code-Session ersetzt den SSH-Tab. Tool-Calls + Inputs + Outputs (truncated 4 KB) live, farbcodiert. Roter ⛔ Not-Aus-Button schickt `cancel_request` mit `hard:true` → Bridge ruft den proxy-internen `/cancel-all` Side-Channel (Port 3457) → alle Claude-Subprocesses sofort tot. Plus: Idle-Watchdog im Proxy (20 min Inaktivitaet → Subprocess-Kill) + httpx-Timeout-Split im Brain (connect 10s / read 24h) damit lange Pentests durchlaufen
|
||||
- [x] **OAuth2-Pipeline ueber RVS-Callback**: Caddy mit Let's Encrypt vor dem RVS, HTTP-Route `/oauth/callback/{service}` broadcastet als `oauth_callback`-WS-Message, aria-bridge forwarded an Brain, Token landet in `/shared/config/oauth_tokens.json` (mode 0600). ARIAs `oauth_register_provider`-Tool legt neue Provider on-demand an (URLs/scopes, nicht Credentials). Diagnostic + App haben beide Provider-Verwaltung inklusive Custom-Provider-Anlage
|
||||
- [x] **Skill-Mgmt-Tools fuer ARIA**: `skill_update` (Code/README/pip_packages mit venv-Rebuild) + `skill_delete` — verhindert Skill-Friedhof mit `-v2`/`-fixed`-Suffixen. Plus App-seitiger SkillBrowser (Run + Live-Output + Logs der letzten 20 Runs) in Settings → 🛠️ Skills
|
||||
@@ -1060,4 +1204,4 @@ docker exec aria-brain curl localhost:8080/memory/stats
|
||||
- [ ] Desktop Client (Tauri)
|
||||
- [ ] bKVM Remote IT-Support
|
||||
- [ ] Custom-`.onnx`-Upload fuer Wake-Word ueber Diagnostic (ohne App-Rebuild)
|
||||
- [ ] Claude Vision direkt (Bildanalyse ohne Dateipfad-Umweg)
|
||||
- [x] Bildanalyse / Vision — ARIA sieht App-Uploads & Screenshots via Read-Tool (`/shared/uploads/` ist im Proxy-Container gemountet). „Direkt ohne Dateipfad" waere reine Politur (ein Read weniger) und ist bewusst NICHT geplant.
|
||||
|
||||
+10
-4
@@ -8,11 +8,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 { NavigationContainer, DefaultTheme } from '@react-navigation/native';
|
||||
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
|
||||
|
||||
import ChatScreen from './src/screens/ChatScreen';
|
||||
import WorkspaceScreen from './src/workspace/WorkspaceScreen';
|
||||
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';
|
||||
@@ -132,7 +134,7 @@ const App: React.FC = () => {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<GestureHandlerRootView style={styles.root}>
|
||||
<StatusBar barStyle="light-content" backgroundColor="#0D0D1A" />
|
||||
<NavigationContainer theme={DarkTheme}>
|
||||
<Tab.Navigator
|
||||
@@ -165,10 +167,11 @@ const App: React.FC = () => {
|
||||
>
|
||||
<Tab.Screen
|
||||
name="Chat"
|
||||
component={ChatScreen}
|
||||
component={WorkspaceScreen}
|
||||
options={{
|
||||
title: 'ARIA Chat',
|
||||
headerTitle: 'ARIA Cockpit',
|
||||
headerRight: () => <ViewModeToggle />,
|
||||
}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
@@ -180,13 +183,16 @@ const App: React.FC = () => {
|
||||
/>
|
||||
</Tab.Navigator>
|
||||
</NavigationContainer>
|
||||
</>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
};
|
||||
|
||||
// --- Styles ---
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
},
|
||||
header: {
|
||||
backgroundColor: '#12122A',
|
||||
elevation: 0,
|
||||
|
||||
@@ -79,8 +79,8 @@ android {
|
||||
applicationId "com.ariacockpit"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 20105
|
||||
versionName "0.2.1.5"
|
||||
versionCode 20500
|
||||
versionName "0.2.5.0"
|
||||
// Fallback fuer Libraries mit Product Flavors
|
||||
missingDimensionStrategy 'react-native-camera', 'general'
|
||||
}
|
||||
|
||||
@@ -59,7 +59,12 @@ class OpenWakeWordModule(reactContext: ReactApplicationContext) : ReactContextBa
|
||||
// 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 = 1500L
|
||||
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()
|
||||
@@ -106,6 +111,13 @@ class OpenWakeWordModule(reactContext: ReactApplicationContext) : ReactContextBa
|
||||
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
|
||||
|
||||
@@ -430,6 +442,36 @@ class OpenWakeWordModule(reactContext: ReactApplicationContext) : ReactContextBa
|
||||
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() {
|
||||
@@ -438,8 +480,10 @@ class OpenWakeWordModule(reactContext: ReactApplicationContext) : ReactContextBa
|
||||
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
|
||||
@@ -466,6 +510,14 @@ class OpenWakeWordModule(reactContext: ReactApplicationContext) : ReactContextBa
|
||||
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) {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
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'],
|
||||
};
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// 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';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aria-cockpit",
|
||||
"version": "0.2.1.5",
|
||||
"version": "0.2.5.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"android": "react-native run-android",
|
||||
@@ -20,12 +20,15 @@
|
||||
"react-native-camera-kit": "^13.0.0",
|
||||
"react-native-document-picker": "^9.1.1",
|
||||
"react-native-fs": "^2.20.0",
|
||||
"react-native-gesture-handler": "2.14.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-svg": "^14.1.0",
|
||||
"react-native-webview": "13.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@react-native/eslint-config": "^0.73.2",
|
||||
|
||||
@@ -34,13 +34,10 @@ interface FileUploadProps {
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
// Unterstuetzte Dateitypen
|
||||
const SUPPORTED_TYPES = [
|
||||
DocumentPicker.types.images,
|
||||
DocumentPicker.types.pdf,
|
||||
DocumentPicker.types.docx,
|
||||
DocumentPicker.types.plainText,
|
||||
];
|
||||
// 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];
|
||||
|
||||
// --- Komponente ---
|
||||
|
||||
@@ -112,7 +109,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}>JPG, PNG, PDF, DOCX, TXT</Text>
|
||||
<Text style={styles.pickHint}>Alle Dateitypen</Text>
|
||||
</TouchableOpacity>
|
||||
) : (
|
||||
// Vorschau und Senden
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
|
||||
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 */
|
||||
@@ -75,6 +76,7 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
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);
|
||||
@@ -148,18 +150,25 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
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'>> = {};
|
||||
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(() => { setEditing(null); load(); })
|
||||
.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, load]);
|
||||
}, [editing, editName, editDesc, editKind, load]);
|
||||
|
||||
const endProject = useCallback((p: Project) => {
|
||||
Alert.alert(`"${p.name}" beenden?`,
|
||||
@@ -216,6 +225,9 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
<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>}
|
||||
@@ -375,6 +387,21 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
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>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -35,9 +35,10 @@ import MemoryBrowser from '../components/MemoryBrowser';
|
||||
import ErrorBoundary from '../components/ErrorBoundary';
|
||||
import rvs, { RVSMessage, ConnectionState } from '../services/rvs';
|
||||
import audioService from '../services/audio';
|
||||
import wakeWordService, { loadPassiveListenMs } from '../services/wakeword';
|
||||
import wakeWordService from '../services/wakeword';
|
||||
import ProjectsBrowser from '../components/ProjectsBrowser';
|
||||
import brainApi, { Project as BrainProject } from '../services/brainApi';
|
||||
import projectFocus from '../services/projectFocus';
|
||||
import phoneCallService from '../services/phoneCall';
|
||||
import { playWakeReadySound } from '../services/wakeReadySound';
|
||||
import {
|
||||
@@ -49,7 +50,7 @@ import VoiceButton from '../components/VoiceButton';
|
||||
import FileUpload, { FileData } from '../components/FileUpload';
|
||||
import CameraUpload, { PhotoData } from '../components/CameraUpload';
|
||||
import MessageText from '../components/MessageText';
|
||||
import { loadConvWindowMs, loadTtsSpeed, TTS_SPEED_DEFAULT, loadSttEndpointMs } from '../services/audio';
|
||||
import { loadTtsSpeed, TTS_SPEED_DEFAULT, loadSttEndpointMs, loadMaxRecordingMs, loadBargeInEnabled } from '../services/audio';
|
||||
import Geolocation from '@react-native-community/geolocation';
|
||||
|
||||
// --- Typen ---
|
||||
@@ -92,6 +93,9 @@ interface ChatMessage {
|
||||
* gespiegelt damit wir die EXAKT richtige Placeholder-Bubble ersetzen,
|
||||
* auch wenn mehrere Aufnahmen parallel offen sind. */
|
||||
audioRequestId?: string;
|
||||
/** Laenge der Sprachaufnahme in Sekunden (aus dem stt_endpoint) — fuer die
|
||||
* Dauer-Anzeige an der Voice-Bubble. */
|
||||
durationS?: number;
|
||||
/** Skill-Created-Bubble: ARIA hat einen neuen Skill angelegt */
|
||||
skillCreated?: {
|
||||
name: string;
|
||||
@@ -181,8 +185,19 @@ function stripSystemHints(text: string): string {
|
||||
if (!m) break;
|
||||
out = out.slice(m[0].length);
|
||||
}
|
||||
return out;
|
||||
// Bestand die Nachricht NUR aus Klammer-Bloecken (z.B. "[Tool-Loop-Limit ...]"
|
||||
// oder "[Fehler: ...]"), waere sie jetzt leer → dann das ORIGINAL zeigen. Sonst
|
||||
// haette der User eine leere Bubble. Fehler-/Meta-Meldungen sollen sichtbar sein.
|
||||
return out.trim() ? out : text;
|
||||
}
|
||||
/** Sekunden → "M:SS" fuer die Sprachnachricht-Dauer. */
|
||||
function formatDur(sec: number): string {
|
||||
const s = Math.max(0, Math.round(sec));
|
||||
const m = Math.floor(s / 60);
|
||||
const r = s % 60;
|
||||
return `${m}:${r.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
const DEFAULT_ATTACHMENT_DIR = `${RNFS.DocumentDirectoryPath}/chat_attachments`;
|
||||
const STORAGE_PATH_KEY = 'aria_attachment_storage_path';
|
||||
|
||||
@@ -318,6 +333,9 @@ const ChatScreen: React.FC = () => {
|
||||
const [projectQueues, setProjectQueues] = useState<Record<string, QueuedItem[]>>({});
|
||||
const projectStatesRef = useRef<Record<string, CtxState>>({});
|
||||
const projectQueuesRef = useRef<Record<string, QueuedItem[]>>({});
|
||||
// Wann ist ein Kontext in 'running' gegangen? Fuer den Watchdog, der eine
|
||||
// haengende Queue (z.B. Antwort waehrend Verbindungsabbruch verloren) loest.
|
||||
const ctxRunningSinceRef = useRef<Record<string, number>>({});
|
||||
// Pro-Projekt-Textfeld-Entwuerfe (noch nicht gesendeter Feldinhalt). Key = pid.
|
||||
const projectDraftsRef = useRef<Record<string, string>>({});
|
||||
const prevFocusedPidRef = useRef<string>('');
|
||||
@@ -342,7 +360,7 @@ const ChatScreen: React.FC = () => {
|
||||
// folgende identische Events (z.B. zwei 'thinking' hintereinander) den
|
||||
// Stream zumuellen. Eigentlich seltener Fall, aber billig zu pruefen.
|
||||
const lastThoughtKeyRef = useRef<string>('');
|
||||
// Service-Status (Gamebox: F5-TTS / Whisper Lade-Status) + Banner-Sichtbarkeit
|
||||
// Service-Status (AI-Box: F5-TTS / Whisper Lade-Status) + Banner-Sichtbarkeit
|
||||
const [serviceStatus, setServiceStatus] = useState<Record<string, {state: string, model?: string, loadSeconds?: number, error?: string, downloading?: boolean, freshlyDownloaded?: boolean}>>({});
|
||||
const [serviceBannerDismissed, setServiceBannerDismissed] = useState(false);
|
||||
// Gerätelokale TTS-Config: globaler Toggle (aus Settings) + temporäres Muten (Mund-Button)
|
||||
@@ -369,6 +387,16 @@ const ChatScreen: React.FC = () => {
|
||||
// stoppen? Kommt als 'converse' in der Chat-Payload; onPlaybackFinished liest
|
||||
// es. Default true (Konversation). false = Einzelaktion/Skill-Antwort.
|
||||
const converseRef = useRef<boolean>(true);
|
||||
// Passiv-Lausch-Fenster (Weiterreden nach ARIAs Antwort): Umgebungsgeraeusch
|
||||
// (Musik/TV) darf das Fenster NICHT vorzeitig beenden. Bei einem no-speech-
|
||||
// Endpoint (Silero verwirft Musik) wird — solange die Stille-Toleranz ab
|
||||
// Fenster-Oeffnung noch laeuft — nochmal gelauscht statt sofort aufs Wake-Word
|
||||
// zurueckzufallen. Start-Zeit + Re-Listen-Zaehler + Budget hier gemerkt.
|
||||
const passiveListenStartRef = useRef<number>(0);
|
||||
const passiveReListenCountRef = useRef<number>(0);
|
||||
const passiveToleranceRef = useRef<number>(5000);
|
||||
// Barge-in erlaubt? Default false = Halb-Duplex (waehrend TTS kein Mikro).
|
||||
const bargeInEnabledRef = useRef<boolean>(false);
|
||||
|
||||
const flatListRef = useRef<FlatList>(null);
|
||||
const messageIdCounter = useRef(0);
|
||||
@@ -403,6 +431,22 @@ const ChatScreen: React.FC = () => {
|
||||
const nextClientMsgId = (): string =>
|
||||
`cmsg_${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`;
|
||||
|
||||
// IDs (clientMsgId + audioRequestId), die DIESES Geraet ausgeloest hat.
|
||||
// Fuer den geraete-lokalen Voice-Projektwechsel: ein project_changed vom Brain
|
||||
// traegt die ausloesende ID; nur wenn sie zu einer unserer IDs gehoert, folgt
|
||||
// dieses Geraet dem Wechsel. So wechselt „ARIA, geh in Projekt X" nur das
|
||||
// Geraet, das den Befehl gab — nicht andere App-/Diagnostic-Instanzen.
|
||||
const myRequestIdsRef = useRef<Set<string>>(new Set());
|
||||
const rememberMyRequest = (id: string): void => {
|
||||
if (!id) return;
|
||||
const s = myRequestIdsRef.current;
|
||||
s.add(id);
|
||||
if (s.size > 80) {
|
||||
const oldest = s.values().next().value;
|
||||
if (oldest !== undefined) s.delete(oldest);
|
||||
}
|
||||
};
|
||||
|
||||
// Wie lange wir auf das ACK warten bevor wir retryen. Bridge sollte
|
||||
// unmittelbar zurueckmelden — 30s ist grosszuegig fuer schlechte Netze.
|
||||
// 60s — grosszuegiger als 30s, weil langsame Brain-Calls (Multi-Tool) sonst
|
||||
@@ -458,6 +502,7 @@ const ChatScreen: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
pendingPayloads.current.set(cmid, { type, payload });
|
||||
rememberMyRequest(cmid);
|
||||
const online = connectionStateRef.current === 'connected';
|
||||
if (!online) {
|
||||
updateMessageStatus(cmid, { deliveryStatus: 'queued', sendAttempts: attempt });
|
||||
@@ -522,8 +567,13 @@ const ChatScreen: React.FC = () => {
|
||||
brainApi.listProjects(true)
|
||||
.then(list => {
|
||||
const map: Record<string, string> = {};
|
||||
for (const p of list) map[p.id] = p.name;
|
||||
const kinds: Record<string, 'code' | 'chat'> = {};
|
||||
for (const p of list) {
|
||||
map[p.id] = p.name;
|
||||
kinds[p.id] = p.kind === 'code' ? 'code' : 'chat';
|
||||
}
|
||||
setProjectNameById(prev => ({ ...prev, ...map }));
|
||||
projectFocus.setKinds(kinds);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
@@ -551,6 +601,12 @@ const ChatScreen: React.FC = () => {
|
||||
}
|
||||
}, [focusedProjectId]);
|
||||
|
||||
// Focus + Projekt-Namen EINWEG in den projectFocus-Spiegel publizieren,
|
||||
// damit der Workspace-Canvas den aktiven Kontext + Code-Projekt-Status
|
||||
// kennt. Rein additiv — aendert ChatScreens eigenes Verhalten nicht.
|
||||
useEffect(() => { projectFocus.setFocus(focusedProjectId); }, [focusedProjectId]);
|
||||
useEffect(() => { projectFocus.setNames(projectNameById); }, [projectNameById]);
|
||||
|
||||
// inputText-Spiegel (damit der Draft-Wechsel oben inputText nicht als Dep braucht).
|
||||
useEffect(() => { inputTextRef.current = inputText; }, [inputText]);
|
||||
|
||||
@@ -583,8 +639,24 @@ const ChatScreen: React.FC = () => {
|
||||
try {
|
||||
const s = await brainApi.getProjectQueueStatus();
|
||||
if (cancelled) return;
|
||||
setQueueStatus(s.contexts || {});
|
||||
queueStatusRef.current = s.contexts || {};
|
||||
const ctxs = s.contexts || {};
|
||||
setQueueStatus(ctxs);
|
||||
queueStatusRef.current = ctxs;
|
||||
// Watchdog: haengt ein Kontext seit >15s auf 'running', obwohl der Brain
|
||||
// ihn NICHT als busy meldet, ist die Antwort verloren gegangen (z.B.
|
||||
// Verbindungsabbruch) — sonst friert die Queue ein. Dann weiterschalten.
|
||||
const api = queueApiRef.current;
|
||||
if (api) {
|
||||
const now = Date.now();
|
||||
for (const [pid, since] of Object.entries(ctxRunningSinceRef.current)) {
|
||||
if (api.getCtxState(pid) !== 'running') continue;
|
||||
const busy = !!ctxs[pid || '__main__']?.busy;
|
||||
if (!busy && now - since > 15000) {
|
||||
console.log('[Chat] Queue-Watchdog: Kontext %s haengt (running, brain idle) → weiterschalten', pid || '(main)');
|
||||
api.advanceQueue(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
poll();
|
||||
@@ -603,6 +675,7 @@ const ChatScreen: React.FC = () => {
|
||||
const voice = await AsyncStorage.getItem('aria_xtts_voice');
|
||||
localXttsVoiceRef.current = voice || '';
|
||||
ttsSpeedRef.current = await loadTtsSpeed();
|
||||
bargeInEnabledRef.current = await loadBargeInEnabled();
|
||||
const gps = await AsyncStorage.getItem('aria_gps_enabled');
|
||||
setGpsEnabled(gps === 'true');
|
||||
const hints = await AsyncStorage.getItem('aria_show_hints');
|
||||
@@ -918,6 +991,11 @@ const ChatScreen: React.FC = () => {
|
||||
const localOnly = prev.filter(m => {
|
||||
if (m.skillCreated || m.triggerCreated || m.memorySaved) return true;
|
||||
if (m.audioRequestId && (!m.text || m.text === '🎙 Aufnahme...' || m.text === 'Aufnahme...')) return true;
|
||||
// Wartende Queue-Bubbles (noch nicht gesendet → kein clientMsgId, nicht
|
||||
// auf dem Server) MUESSEN erhalten bleiben — sonst verschwindet die
|
||||
// Bubble beim Reconnect-Sync, waehrend projectQueues den Eintrag behaelt
|
||||
// → "N in Warteschlange" friert ein ohne sichtbare Nachricht.
|
||||
if (m.sender === 'user' && m.deliveryStatus === 'pending_queue') return true;
|
||||
if (m.sender === 'user' && m.clientMsgId && !serverCmids.has(m.clientMsgId)) {
|
||||
// Text-Match-Fallback: wenn der Server irgendwo eine textgleiche
|
||||
// User-Bubble hat, ist es dieselbe Nachricht (vor cmid-Aera, ts
|
||||
@@ -951,10 +1029,23 @@ const ChatScreen: React.FC = () => {
|
||||
if (p.id && p.name) {
|
||||
setProjectNameById(prev => ({ ...prev, [p.id]: p.name }));
|
||||
}
|
||||
if (action === 'entered' || action === 'created') {
|
||||
if (p.id) setFocusedProjectId(p.id);
|
||||
} else if (action === 'exited') {
|
||||
setFocusedProjectId('');
|
||||
// Projekt-Typ sofort spiegeln → Editor/Desktop-Kacheln erscheinen live
|
||||
// (z.B. nach set_project_kind), nicht erst beim naechsten Reconnect.
|
||||
if (p.id && (p.kind === 'code' || p.kind === 'chat')) {
|
||||
projectFocus.setKind(p.id, p.kind);
|
||||
}
|
||||
// Projekt-Fokus ist GERAETE-LOKAL. Ein Broadcast wechselt dieses Geraet
|
||||
// NUR, wenn er durch EINEN EIGENEN Befehl ausgeloest wurde — erkennbar an
|
||||
// der mitgelieferten clientMsgId (unsere gesendete Text-cmid oder Voice-
|
||||
// audioRequestId). So folgt „ARIA, geh in Projekt X" nur dem Geraet, das
|
||||
// den Befehl gab; Diagnostic / andere App-Instanzen bleiben unberuehrt.
|
||||
const trigCmid = typeof p.clientMsgId === 'string' ? p.clientMsgId : '';
|
||||
if (trigCmid && myRequestIdsRef.current.has(trigCmid)) {
|
||||
if (action === 'entered' || action === 'created') {
|
||||
if (p.id) setFocusedProjectId(p.id);
|
||||
} else if (action === 'exited') {
|
||||
setFocusedProjectId('');
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1321,13 +1412,61 @@ const ChatScreen: React.FC = () => {
|
||||
// Fallback mehr: die Bridge schickt speak zuverlaessig mit.
|
||||
// Merken ob nach dem Vorlesen 30s weiterlauschen (Gespraech) oder direkt
|
||||
// stoppen — onPlaybackFinished liest converseRef. Default true.
|
||||
converseRef.current = (message.payload as any).converse !== false;
|
||||
// Passiv-Lauschen (30s) NUR wenn das Brain explizit converse:true schickt.
|
||||
// Vorher default true → jeder Befehl (auch "Spiele Spotify" mit gesproche-
|
||||
// ner Bestaetigung) landete im 30s-Fenster. Jetzt: einzelne Befehle enden
|
||||
// sofort (zurueck aufs Wake-Word), nur echte Gespraeche lauschen weiter.
|
||||
converseRef.current = (message.payload as any).converse === true;
|
||||
const _wakeOff = (message.payload as any).wake_off === true;
|
||||
const _wakeOn = (message.payload as any).wake_on === true;
|
||||
const _isSilent = (message.payload as any).speak === false;
|
||||
if (_isSilent && wakeWordService.isConversing()) {
|
||||
// Klarer Steuerbefehl (Liedersteuerung etc.) = KEINE Konversation →
|
||||
// STOP: direkt zurueck aufs Wake-Word. Kein Gong, keine Aufnahme,
|
||||
// kein 30s-Fenster (skipPassive=true).
|
||||
wakeWordService.endConversation(true).catch(() => {});
|
||||
if (_wakeOn) {
|
||||
// "Wake-Word an" per Text/Aufnahme-Button → Listener wieder starten
|
||||
// (gleicher Weg wie toggleWakeWord-on). Geht auch wenn das Ohr taub war,
|
||||
// weil der Befehl NICHT ueber "Computer" kam.
|
||||
(async () => {
|
||||
try {
|
||||
const started = await wakeWordService.start();
|
||||
setWakeWordActive(started);
|
||||
console.log('[Chat] Wake-Word per Befehl AN gestartet:', started);
|
||||
} catch (e) {
|
||||
console.warn('[Chat] Wake-Word AN fehlgeschlagen:', e);
|
||||
}
|
||||
})();
|
||||
} else if (_wakeOff) {
|
||||
// ARIA hat "Wake-Word aus" per Sprache bekommen → Listener KOMPLETT
|
||||
// stoppen (Mikro frei, echte Ruhe). Gleicher Weg wie der Ohr-Button
|
||||
// (toggleWakeWord-off). Wieder-An nur ueber den Button (dann taub).
|
||||
(async () => {
|
||||
try {
|
||||
if (audioService.isStreamingRecording()) {
|
||||
await audioService.cancelStreamingRecording('wake-off-voice');
|
||||
} else {
|
||||
await audioService.stopRecording();
|
||||
}
|
||||
} catch {}
|
||||
try { await wakeWordService.stop(); } catch {}
|
||||
setWakeWordActive(false);
|
||||
console.log('[Chat] Wake-Word per Sprachbefehl AUS — Ohr-Button zum Wieder-Anmachen');
|
||||
})();
|
||||
} else if (_isSilent) {
|
||||
// Steuerbefehl (speak=false) ist ausgefuehrt und wird NICHT vorgelesen.
|
||||
// Ohne TTS feuert onPlaybackFinished nie — der Mikro-/Konversations-
|
||||
// Lifecycle muss hier selbst weitergeschaltet werden, sonst haengt das Ohr.
|
||||
if (converseRef.current) {
|
||||
// Befehlskette laeuft WEITER ([[WEITER]]): Mikro NICHT schliessen,
|
||||
// sondern das passive Lausch-Fenster oeffnen (endConversation(false)),
|
||||
// damit der naechste Kettenbefehl direkt gesprochen werden kann. ARIA
|
||||
// haelt bewusst offen, bis sie [[ENDE]] (converse=false) schickt.
|
||||
if (wakeWordService.isConversing()) {
|
||||
wakeWordService.endConversation(false).catch(() => {});
|
||||
}
|
||||
} else {
|
||||
// Einzelbefehl / [[ENDE]] → ARIA "drueckt selbst Stop": jede offene
|
||||
// Aufnahme schliessen + zurueck aufs Wake-Word, egal in welchem Zustand
|
||||
// (conversing, passives Lauschen ODER offene Streaming-Aufnahme).
|
||||
ariaStopRecording('silent-command').catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1455,7 +1594,7 @@ const ChatScreen: React.FC = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Gamebox-Bridges (f5tts/whisper/flux) melden Lade-Status — Banner oben.
|
||||
// AI-Box-Bridges (f5tts/whisper/flux) melden Lade-Status — Banner oben.
|
||||
// Toast bei Download-Ende: erstmaliger HF-Download (mehrere GB) → User
|
||||
// soll wissen dass er Bilder/Stimmen jetzt nutzen kann ohne in den
|
||||
// Banner gucken zu muessen.
|
||||
@@ -1562,8 +1701,12 @@ const ChatScreen: React.FC = () => {
|
||||
// Im Hintergrund gibt's kein Multi-Turn → direkt re-armen (skipPassive).
|
||||
// converse=false (Skill-/Einzelantwort, z.B. 'was laeuft gerade') → auch
|
||||
// ohne 30s: vorlesen + direkt zurueck aufs Wake-Word.
|
||||
// Im Hintergrund normalerweise direkt re-armen (kein Multi-Turn) — ABER
|
||||
// wenn Hintergrund-Wake bewusst AN ist, will der User auch im Hintergrund
|
||||
// ein Gespraech fuehren, also den Konversationsmodus offen halten.
|
||||
const bg = AppState.currentState !== 'active';
|
||||
wakeWordService.endConversation(bg || !converseRef.current).catch(() => {});
|
||||
const bgForcesArmed = bg && !wakeWordService.isBgWakeEnabled();
|
||||
wakeWordService.endConversation(bgForcesArmed || !converseRef.current).catch(() => {});
|
||||
});
|
||||
return () => unsubPlayback();
|
||||
}, []);
|
||||
@@ -1579,9 +1722,14 @@ const ChatScreen: React.FC = () => {
|
||||
// dem finalen Text, dann wird die Bubble ueber audioRequestId-Match
|
||||
// aktualisiert (siehe chat-Handler oben).
|
||||
const audioRequestId = `audio_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
rememberMyRequest(audioRequestId);
|
||||
const wasInterrupted = interruptAriaIfBusy();
|
||||
const location = await getCurrentLocation();
|
||||
const windowMs = await loadConvWindowMs();
|
||||
// EIN Wert regiert: die Stille-Toleranz. Sie gilt sowohl als Pause WÄHREND
|
||||
// des Redens (endpointMs) ALS AUCH als "wenn du nicht anfängst zu reden,
|
||||
// ist Schluss" (noSpeechTimeoutMs). Kein separates 30s-Konversationsfenster
|
||||
// mehr — Stefans Modell: sagst du nichts, greift der Stille-Wert.
|
||||
const sttEndpointMs = await loadSttEndpointMs();
|
||||
|
||||
const userMsg: ChatMessage = {
|
||||
id: nextId(),
|
||||
@@ -1599,9 +1747,11 @@ const ChatScreen: React.FC = () => {
|
||||
speed: ttsSpeedRef.current,
|
||||
interrupted: wasInterrupted,
|
||||
location: location || null,
|
||||
noSpeechTimeoutMs: windowMs,
|
||||
endpointMs: await loadSttEndpointMs(),
|
||||
hardCapMs: 60000,
|
||||
noSpeechTimeoutMs: sttEndpointMs,
|
||||
endpointMs: sttEndpointMs,
|
||||
// Notbremse 5 min (nicht 1 min) — der Stille-Endpoint beendet normale
|
||||
// Turns eh sofort; der Cap darf lange Diktate nicht mitten drin kappen.
|
||||
hardCapMs: await loadMaxRecordingMs(),
|
||||
projectId: focusedProjectIdRef.current,
|
||||
});
|
||||
import('../services/logger').then(m => m.reportAppDebug('wake.cb', `startStreamingRecording returned ok=${ok}`)).catch(()=>{});
|
||||
@@ -1629,6 +1779,13 @@ const ChatScreen: React.FC = () => {
|
||||
if (ev.text && ev.text.trim()) {
|
||||
console.log('[Chat] STT-Endpoint: %r (reason=%s, %dms, %.1fs Audio)',
|
||||
ev.text.slice(0, 80), ev.reason, ev.sttMs, ev.durationS);
|
||||
// Aufnahme-Dauer an die passende Voice-Bubble haengen (Anzeige). Der
|
||||
// spaetere STT-Text-Update spreadet die Message, die Dauer bleibt.
|
||||
if (ev.audioRequestId && typeof ev.durationS === 'number' && ev.durationS > 0) {
|
||||
const dur = ev.durationS;
|
||||
setMessages(prev => prev.map(m =>
|
||||
m.audioRequestId === ev.audioRequestId ? { ...m, durationS: dur } : m));
|
||||
}
|
||||
// Wenn passive lauschend: User hat tatsaechlich was gesagt → uebergang
|
||||
// zu 'conversing' damit der normale Flow greift (TTS, resume, etc.)
|
||||
if (wakeWordService.getState() === 'listening') {
|
||||
@@ -1649,12 +1806,24 @@ const ChatScreen: React.FC = () => {
|
||||
!(m.audioRequestId === ev.audioRequestId
|
||||
&& m.text.includes('Spracheingabe wird verarbeitet'))));
|
||||
}
|
||||
// Bei Passive-Listen + speaker_mismatch oder no-speech: erneut passiv
|
||||
// lauschen (Timer im wakeword-service laeuft weiter, regelt das Ende).
|
||||
// Sonst endConversation wie bisher.
|
||||
// Passiv-Lauschen: leeres Endpoint (no-speech / Silero-Musik / speaker_
|
||||
// mismatch). NICHT sofort beenden — solange die Stille-Toleranz ab
|
||||
// Fenster-Oeffnung noch laeuft, nochmal lauschen. So killt Umgebungs-
|
||||
// musik das Weiterreden nicht: die Musik wird verworfen, das Fenster
|
||||
// bleibt bis zur Toleranz offen, du kannst innerhalb reden. Erst wenn
|
||||
// die Toleranz wirklich um ist (oder zu viele Runden) → aufs Wake-Word.
|
||||
if (wakeWordService.getState() === 'listening') {
|
||||
console.log('[Chat] Passive-Listen: leeres Endpoint — naechste passive Aufnahme');
|
||||
startPassiveStreamingRecording();
|
||||
const elapsed = Date.now() - passiveListenStartRef.current;
|
||||
const budget = passiveToleranceRef.current || 5000;
|
||||
if (elapsed < budget && passiveReListenCountRef.current < 15) {
|
||||
passiveReListenCountRef.current += 1;
|
||||
console.log('[Chat] Passive-Listen: leeres Endpoint (%s) — Umgebung, re-listen (%dms/%dms, #%d)',
|
||||
ev.reason, elapsed, budget, passiveReListenCountRef.current);
|
||||
startPassiveStreamingRecording();
|
||||
} else {
|
||||
console.log('[Chat] Passive-Listen: Stille-Toleranz aufgebraucht (%dms) — Ende, zurueck aufs Wake-Word', elapsed);
|
||||
wakeWordService.exitPassiveListening('timeout').catch(() => {});
|
||||
}
|
||||
} else {
|
||||
wakeWordService.endConversation();
|
||||
if (!wakeWordService.isActive()) setWakeWordActive(false);
|
||||
@@ -1666,8 +1835,14 @@ const ChatScreen: React.FC = () => {
|
||||
// geschaltet (nach endConversation). Wir starten eine streaming-Aufnahme
|
||||
// OHNE User-Bubble + ohne wake-ready-Sound. Speaker-ID-Gating in der
|
||||
// Whisper-Bridge filtert fremde Stimmen weg.
|
||||
const unsubPassive = wakeWordService.onPassiveListen(() => {
|
||||
const unsubPassive = wakeWordService.onPassiveListen(async () => {
|
||||
console.log('[Chat] Passive-Listen aktiviert — starte stille Streaming-Aufnahme');
|
||||
// Fenster NEU geoeffnet (nach ARIAs Antwort): Budget-Uhr + Re-Listen-Zaehler
|
||||
// zuruecksetzen. Re-Listen ruft startPassiveStreamingRecording direkt (nicht
|
||||
// ueber diesen Callback), also bleibt der Startzeitpunkt erhalten.
|
||||
passiveListenStartRef.current = Date.now();
|
||||
passiveReListenCountRef.current = 0;
|
||||
passiveToleranceRef.current = await loadSttEndpointMs();
|
||||
startPassiveStreamingRecording();
|
||||
});
|
||||
|
||||
@@ -1682,8 +1857,9 @@ const ChatScreen: React.FC = () => {
|
||||
// Kurze Pause damit halt durchgreift, dann neue Aufnahme starten
|
||||
await new Promise(r => setTimeout(r, 150));
|
||||
const audioRequestId = `audio_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
rememberMyRequest(audioRequestId);
|
||||
const location = await getCurrentLocation();
|
||||
const windowMs = await loadConvWindowMs();
|
||||
const sttEndpointMs = await loadSttEndpointMs(); // ein Wert für Pause + No-Speech
|
||||
|
||||
const userMsg: ChatMessage = {
|
||||
id: nextId(),
|
||||
@@ -1701,9 +1877,10 @@ const ChatScreen: React.FC = () => {
|
||||
speed: ttsSpeedRef.current,
|
||||
interrupted: true, // Barge-In → Brain weiss "User hat unterbrochen"
|
||||
location: location || null,
|
||||
noSpeechTimeoutMs: windowMs,
|
||||
endpointMs: await loadSttEndpointMs(),
|
||||
hardCapMs: 60000,
|
||||
noSpeechTimeoutMs: sttEndpointMs,
|
||||
endpointMs: sttEndpointMs,
|
||||
// Notbremse 5 min (s.o.) — lange Diktate nicht bei 1 min abschneiden.
|
||||
hardCapMs: await loadMaxRecordingMs(),
|
||||
projectId: focusedProjectIdRef.current,
|
||||
});
|
||||
if (ok) {
|
||||
@@ -1721,7 +1898,9 @@ const ChatScreen: React.FC = () => {
|
||||
// Prozess nicht killt wenn die App im Hintergrund ist.
|
||||
const unsubTtsStart = audioService.onPlaybackStarted(() => {
|
||||
acquireBackgroundAudio('tts').catch(() => {});
|
||||
if (wakeWordService.isConversing() && wakeWordService.hasWakeWord()) {
|
||||
// Barge-Listening (Mikro waehrend TTS) NUR im Barge-in-Modus. Default aus =
|
||||
// Halb-Duplex: ARIA spricht ungestoert zu Ende, dann erst geht das Mikro auf.
|
||||
if (bargeInEnabledRef.current && wakeWordService.isConversing() && wakeWordService.hasWakeWord()) {
|
||||
wakeWordService.startBargeListening().catch(() => {});
|
||||
}
|
||||
});
|
||||
@@ -1731,6 +1910,13 @@ const ChatScreen: React.FC = () => {
|
||||
// das Mikro greifen kann.
|
||||
wakeWordService.stopBargeListening().catch(() => {});
|
||||
});
|
||||
// Aus der TTS-Queue nachgespielte (zweite) Antwort: ihren WAV-Cache-Pfad an
|
||||
// die Bubble haengen, damit der Mund-Button/Play sie auch abspielen kann.
|
||||
const unsubPcmCached = audioService.onPcmCached((messageId, audioPath) => {
|
||||
if (!messageId || !audioPath) return;
|
||||
setMessages(prev => prev.map(m =>
|
||||
m.messageId === messageId ? { ...m, audioPath } : m));
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubWake();
|
||||
@@ -1739,6 +1925,7 @@ const ChatScreen: React.FC = () => {
|
||||
unsubPassive();
|
||||
unsubTtsStart();
|
||||
unsubTtsEnd();
|
||||
unsubPcmCached();
|
||||
};
|
||||
}, [wakeWordActive]);
|
||||
|
||||
@@ -1750,17 +1937,22 @@ const ChatScreen: React.FC = () => {
|
||||
// useCallback damit der useEffect oben die Funktion stabil capturen kann.
|
||||
const startPassiveStreamingRecording = useCallback(async () => {
|
||||
const audioRequestId = `audio_passive_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
rememberMyRequest(audioRequestId);
|
||||
const location = await getCurrentLocation();
|
||||
const passiveMs = await loadPassiveListenMs();
|
||||
// Kein 30s-Passiv-Fenster mehr: nach ARIAs Antwort geht das Mikro auf, und
|
||||
// fängst du nicht innerhalb der Stille-Toleranz an zu reden, ist Schluss →
|
||||
// zurück aufs Wake-Word. Derselbe Wert wie die Pause-Toleranz beim Reden.
|
||||
const sttEndpointMs = await loadSttEndpointMs();
|
||||
const { ok } = await audioService.startStreamingRecording({
|
||||
audioRequestId,
|
||||
voice: localXttsVoiceRef.current,
|
||||
speed: ttsSpeedRef.current,
|
||||
interrupted: false,
|
||||
location: location || null,
|
||||
noSpeechTimeoutMs: Math.min(passiveMs, 30000),
|
||||
endpointMs: await loadSttEndpointMs(),
|
||||
hardCapMs: Math.max(passiveMs + 5000, 35000),
|
||||
noSpeechTimeoutMs: sttEndpointMs,
|
||||
endpointMs: sttEndpointMs,
|
||||
// Lange Antworten nicht kappen (früher 35s → schnitt langes Reden ab).
|
||||
hardCapMs: await loadMaxRecordingMs(),
|
||||
projectId: focusedProjectIdRef.current,
|
||||
});
|
||||
if (!ok) {
|
||||
@@ -2042,6 +2234,9 @@ const ChatScreen: React.FC = () => {
|
||||
|
||||
const setCtxState = useCallback((pid: string, s: CtxState) => {
|
||||
projectStatesRef.current = { ...projectStatesRef.current, [pid]: s };
|
||||
// Watchdog-Zeitstempel: nur 'running' bekommt einen Start, sonst raus.
|
||||
if (s === 'running') ctxRunningSinceRef.current[pid] = Date.now();
|
||||
else delete ctxRunningSinceRef.current[pid];
|
||||
setProjectStates(prev => ({ ...prev, [pid]: s }));
|
||||
}, []);
|
||||
|
||||
@@ -2097,7 +2292,7 @@ const ChatScreen: React.FC = () => {
|
||||
|
||||
// Aufraeumen von "verarbeitet"-Placeholder die nie ein STT-Result bekommen
|
||||
// haben (leere Aufnahme, Wake-Word-Echo, STT-Fehler etc). Timeout skaliert
|
||||
// mit der Aufnahmedauer — Whisper braucht auf der Gamebox grob real-time/5,
|
||||
// mit der Aufnahmedauer — Whisper braucht auf der AI-Box grob real-time/5,
|
||||
// plus Bridge-Roundtrip + Network. Formel: 60s Buffer + 1x Aufnahmedauer.
|
||||
// Bei 5min Aufnahme = 6 min Wait, bei 5s Aufnahme = 65s. Sicher genug damit
|
||||
// langsame STTs nicht versehentlich aufgeraeumt werden.
|
||||
@@ -2130,15 +2325,16 @@ const ChatScreen: React.FC = () => {
|
||||
advanceQueue(pid);
|
||||
}, [advanceQueue]);
|
||||
|
||||
// Queue-Modus („immer anstellen"): eine neue Sprachnachricht bricht ARIAs
|
||||
// laufende Arbeit NICHT mehr ab. Sie wird — wie Text — angestellt und laeuft
|
||||
// serialisiert (der Brain-Lock pro Projekt reiht /chat-/audio-Turns auf).
|
||||
// Nur das TTS wird akustisch gestoppt, damit das Mikro ARIAs eigene Stimme
|
||||
// nicht mithoert. Explizites Abbrechen laeuft ueber den Stop-Button
|
||||
// (cancelRequest). Rueckgabe = false, weil kein Barge-In/Interrupt mehr.
|
||||
// Nimmt der User das Mikro waehrend ARIA SPRICHT, ist das ein echter Interrupt:
|
||||
// TTS stoppen UND die laufende Brain-Antwort abbrechen (cancel_request). Sonst
|
||||
// produziert das Brain weiter TTS, die ins offene Mikro laeuft → genau der
|
||||
// "Mischmasch" (ARIA antwortet weiter waehrend ich rede). Fuer bewusstes
|
||||
// Nicht-Abbrechen gibt es weiterhin den separaten Zwischenruf-Button (📣).
|
||||
const interruptAriaIfBusy = useCallback(() => {
|
||||
if (audioService.isPlayingAudio()) {
|
||||
audioService.haltAllPlayback('user startet Aufnahme (Queue-Modus, kein Abbruch)');
|
||||
audioService.haltAllPlayback('user startet Aufnahme — Interrupt');
|
||||
rvs.send('cancel_request' as any, { hard: true, source: 'voice-interrupt' });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}, []);
|
||||
@@ -2150,6 +2346,7 @@ const ChatScreen: React.FC = () => {
|
||||
// ueber audioRequestId-Match nachgereicht wenn whisper das Endpoint feuert.
|
||||
const handleVoiceButtonStart = useCallback(async (): Promise<boolean> => {
|
||||
const audioRequestId = `audio_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
rememberMyRequest(audioRequestId);
|
||||
const wasInterrupted = interruptAriaIfBusy();
|
||||
const location = await getCurrentLocation();
|
||||
|
||||
@@ -2174,7 +2371,7 @@ const ChatScreen: React.FC = () => {
|
||||
// die Session auch app-seitig haben wir +2s Toleranz.
|
||||
noSpeechTimeoutMs: 0,
|
||||
endpointMs: await loadSttEndpointMs(),
|
||||
hardCapMs: 300000,
|
||||
hardCapMs: await loadMaxRecordingMs(),
|
||||
projectId: focusedProjectIdRef.current,
|
||||
});
|
||||
if (!ok) {
|
||||
@@ -2186,11 +2383,50 @@ const ChatScreen: React.FC = () => {
|
||||
return true;
|
||||
}, [getCurrentLocation, interruptAriaIfBusy, scheduleStaleAudioCleanup]);
|
||||
|
||||
// ARIA schliesst die Aufnahme SELBST — das programmatische Gegenstueck zum
|
||||
// Stop-Button. Aufgerufen nach einem stillen Steuerbefehl (speak=false): der
|
||||
// Befehl ist ausgefuehrt, ARIA hat die Rueckinfo (Skill-Ergebnis) und antwortet
|
||||
// NICHT vorgelesen. Weil ohne TTS kein onPlaybackFinished kommt, muss der
|
||||
// Aufnahme-/Konversations-Zustand hier aktiv aufgeraeumt werden, sonst bleibt
|
||||
// das Ohr haengen bzw. das Aufnahme-Fenster laeuft leer weiter (Stefans
|
||||
// Reproduktion: "spotify play" und das Mikro wartet trotzdem 30s).
|
||||
// Unterschied zum manuellen Stop: der verwirft NICHT, sondern finalisiert die
|
||||
// Aufnahme (User will seinen Satz verarbeitet haben) — hier ist der Befehl
|
||||
// schon durch, ein evtl. offenes Folge-Fenster wird verworfen.
|
||||
const ariaStopRecording = useCallback(async (reason: string): Promise<void> => {
|
||||
converseRef.current = false;
|
||||
// 1) Passiv-Lauschen: sauber beenden (cancelt den Stream selbst, startet
|
||||
// KEINE neue passive Aufnahme).
|
||||
if (wakeWordService.getState() === 'listening') {
|
||||
await wakeWordService.exitPassiveListening('manual').catch(() => {});
|
||||
return;
|
||||
}
|
||||
// 2) Noch offene Streaming-Aufnahme (aktiv / Barge-In) verwerfen.
|
||||
if (audioService.isStreamingRecording()) {
|
||||
await audioService.cancelStreamingRecording(reason).catch(() => {});
|
||||
}
|
||||
// 3) Konversation beenden → zurueck aufs Wake-Word (skipPassive: kein 30s-Fenster).
|
||||
if (wakeWordService.isConversing()) {
|
||||
await wakeWordService.endConversation(true).catch(() => {});
|
||||
} else if (!wakeWordService.isActive()) {
|
||||
setWakeWordActive(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Manueller Aufnahme-Knopf — Stop. Sendet stt_stream_end an Whisper, die
|
||||
// dann ihrerseits den finalen Text als stt_endpoint emittiert. aria-bridge
|
||||
// forwarded direkt an Brain. Im wake-word-conversing-Fall zusaetzlich
|
||||
// endConversation: User hat explizit gestoppt → kein Multi-Turn-Resume.
|
||||
const handleVoiceButtonStop = useCallback(async (): Promise<void> => {
|
||||
// Manueller Stop = endgueltig: auch die NACH der Antwort kommende
|
||||
// onPlaybackFinished darf kein 30s-Passiv-Fenster mehr oeffnen.
|
||||
converseRef.current = false;
|
||||
// Stop = ALLES beenden, vorhersehbar. Spricht ARIA gerade, hart stoppen +
|
||||
// laufende Brain-Antwort abbrechen (sonst "sagt sie ihren letzten Satz").
|
||||
if (audioService.isPlayingAudio()) {
|
||||
audioService.haltAllPlayback('user stop');
|
||||
rvs.send('cancel_request' as any, { hard: true, source: 'voice-stop' });
|
||||
}
|
||||
// Stop WAEHREND des passiven 30s-Lauschens ('listening'): sauber beenden
|
||||
// (zurueck aufs Wake-Word), NICHT den passiven Stream neu starten.
|
||||
// exitPassiveListening cancelt den Stream selbst (via _freeMic) → es feuert
|
||||
@@ -2290,6 +2526,10 @@ const ChatScreen: React.FC = () => {
|
||||
size: file.size,
|
||||
base64,
|
||||
projectId: activePid,
|
||||
// Korrelation: dieselbe clientMsgId wie der Text, damit die Bridge
|
||||
// die Datei genau DIESER Nachricht zuordnet — auch wenn Files (fire-
|
||||
// and-forget) und Text (ACK-getrackt, bei Queue verzoegert) desyncen.
|
||||
...(cmid && { clientMsgId: cmid }),
|
||||
...(isPhoto && file.width && { width: file.width, height: file.height }),
|
||||
...(location && { location }),
|
||||
});
|
||||
@@ -2359,6 +2599,24 @@ const ChatScreen: React.FC = () => {
|
||||
}
|
||||
}, [inputText, pendingAttachments, sendPendingAttachments, getCtxState, setCtxState, setCtxQueue, actuallySend]);
|
||||
|
||||
// Zwischenruf: waehrend ARIA arbeitet eine Korrektur MITTEN in den laufenden
|
||||
// Turn schieben — NICHT in die Queue, KEIN Abbruch. Geht als 'interject' ueber
|
||||
// RVS an die Bridge → Proxy → laufender Subprozess (greift es an der naechsten
|
||||
// Tool-Grenze auf). Sichtbar nur, wenn der aktive Kontext gerade arbeitet.
|
||||
const sendInterject = useCallback(() => {
|
||||
const text = inputText.trim();
|
||||
if (!text) return;
|
||||
const activePid = focusedProjectIdRef.current;
|
||||
rvs.send('interject' as any, { projectId: activePid, text });
|
||||
// Lokale Bubble zur Rueckmeldung (laeuft NICHT durch Send/Queue).
|
||||
setMessages(prev => capMessages([...prev, {
|
||||
id: nextId(), sender: 'user', text: `📣 Zwischenruf: ${text}`,
|
||||
timestamp: Date.now(), projectId: activePid,
|
||||
}]));
|
||||
projectDraftsRef.current = { ...projectDraftsRef.current, [activePid]: '' };
|
||||
setInputText('');
|
||||
}, [inputText]);
|
||||
|
||||
// --- Rendering ---
|
||||
|
||||
const renderMessage = ({ item }: { item: ChatMessage }) => {
|
||||
@@ -2544,6 +2802,16 @@ const ChatScreen: React.FC = () => {
|
||||
{att.serverPath ? '(tippen zum Laden)' : '(nicht verfuegbar)'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
) : att.type === 'audio' ? (
|
||||
<View style={styles.attachmentFile}>
|
||||
<Text style={styles.attachmentFileIcon}>{'🎙'}</Text>
|
||||
<Text style={styles.attachmentFileName} numberOfLines={1}>
|
||||
{att.name || 'Sprachaufnahme'}
|
||||
</Text>
|
||||
{typeof item.durationS === 'number' && item.durationS > 0 ? (
|
||||
<Text style={styles.attachmentFileSize}>{formatDur(item.durationS)}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<TouchableOpacity
|
||||
style={styles.attachmentFile}
|
||||
@@ -2795,7 +3063,7 @@ const ChatScreen: React.FC = () => {
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{/* Service-Status Banner (Gamebox: F5-TTS / Whisper Lade-Status) */}
|
||||
{/* Service-Status Banner (AI-Box: F5-TTS / Whisper Lade-Status) */}
|
||||
{(() => {
|
||||
const entries = Object.entries(serviceStatus);
|
||||
if (entries.length === 0 || serviceBannerDismissed) return null;
|
||||
@@ -3133,9 +3401,19 @@ const ChatScreen: React.FC = () => {
|
||||
|
||||
{/* Senden oder Sprache */}
|
||||
{inputText.trim() || pendingAttachments.length > 0 ? (
|
||||
<TouchableOpacity style={styles.sendButton} onPress={sendTextMessage}>
|
||||
<Text style={styles.sendIcon}>{'\u2B06\uFE0F'}</Text>
|
||||
</TouchableOpacity>
|
||||
<>
|
||||
{/* Zwischenruf: nur wenn ARIA im aktiven Kontext gerade arbeitet und
|
||||
Text da ist. Schiebt die Korrektur in den laufenden Turn statt
|
||||
sie anzustellen. */}
|
||||
{inputText.trim() && (agentActivityByCtx[focusedProjectId]?.activity || 'idle') !== 'idle' ? (
|
||||
<TouchableOpacity style={styles.interjectButton} onPress={sendInterject} accessibilityLabel="Zwischenruf">
|
||||
<Text style={styles.interjectIcon}>{'\uD83D\uDCE3'}</Text>
|
||||
</TouchableOpacity>
|
||||
) : null}
|
||||
<TouchableOpacity style={styles.sendButton} onPress={sendTextMessage}>
|
||||
<Text style={styles.sendIcon}>{'\u2B06\uFE0F'}</Text>
|
||||
</TouchableOpacity>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<VoiceButton
|
||||
@@ -3653,6 +3931,18 @@ const styles = StyleSheet.create({
|
||||
sendIcon: {
|
||||
fontSize: 18,
|
||||
},
|
||||
interjectButton: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 20,
|
||||
backgroundColor: '#FF9500', // orange — Zwischenruf, klar vom blauen Senden getrennt
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginRight: 6,
|
||||
},
|
||||
interjectIcon: {
|
||||
fontSize: 18,
|
||||
},
|
||||
wakeWordBtn: {
|
||||
width: 32,
|
||||
height: 32,
|
||||
|
||||
@@ -63,14 +63,16 @@ import {
|
||||
VAD_SILENCE_MIN_SEC,
|
||||
VAD_SILENCE_MAX_SEC,
|
||||
VAD_SILENCE_STORAGE_KEY,
|
||||
CONV_WINDOW_DEFAULT_SEC,
|
||||
CONV_WINDOW_MIN_SEC,
|
||||
CONV_WINDOW_MAX_SEC,
|
||||
CONV_WINDOW_STORAGE_KEY,
|
||||
STT_ENDPOINT_DEFAULT_MS,
|
||||
STT_ENDPOINT_MIN_MS,
|
||||
STT_ENDPOINT_MAX_MS,
|
||||
STT_ENDPOINT_STORAGE_KEY,
|
||||
MAX_RECORDING_DEFAULT_SEC,
|
||||
MAX_RECORDING_MIN_SEC,
|
||||
MAX_RECORDING_MAX_SEC,
|
||||
MAX_RECORDING_STORAGE_KEY,
|
||||
loadBargeInEnabled,
|
||||
saveBargeInEnabled,
|
||||
VAD_SILENCE_DB_DEFAULT,
|
||||
VAD_SILENCE_DB_MIN,
|
||||
VAD_SILENCE_DB_MAX,
|
||||
@@ -110,9 +112,10 @@ import wakeWordService, {
|
||||
WAKE_THRESHOLD_MAX,
|
||||
loadWakeThreshold,
|
||||
saveWakeThreshold,
|
||||
PASSIVE_LISTEN_DEFAULT_MS,
|
||||
loadPassiveListenMs,
|
||||
savePassiveListenMs,
|
||||
loadBgWakeEnabled,
|
||||
saveBgWakeEnabled,
|
||||
loadWakeConfirmEnabled,
|
||||
saveWakeConfirmEnabled,
|
||||
} from '../services/wakeword';
|
||||
import ModeSelector from '../components/ModeSelector';
|
||||
import QRScanner from '../components/QRScanner';
|
||||
@@ -195,8 +198,12 @@ const SettingsScreen: React.FC = () => {
|
||||
const [ttsEnabled, setTtsEnabled] = useState(true);
|
||||
const [ttsPrerollSec, setTtsPrerollSec] = useState<number>(TTS_PREROLL_DEFAULT_SEC);
|
||||
const [vadSilenceSec, setVadSilenceSec] = useState<number>(VAD_SILENCE_DEFAULT_SEC);
|
||||
const [convWindowSec, setConvWindowSec] = useState<number>(CONV_WINDOW_DEFAULT_SEC);
|
||||
// Aktive Streaming-Pausen-Toleranz (STT_ENDPOINT) — der "Stille-Toleranz"-Regler
|
||||
// steuert jetzt DIESEN Wert (der alte vadSilenceSec war der tote Legacy-dB-Pfad).
|
||||
const [sttEndpointSec, setSttEndpointSec] = useState<number>(STT_ENDPOINT_DEFAULT_MS / 1000);
|
||||
const [maxRecordingSec, setMaxRecordingSec] = useState<number>(MAX_RECORDING_DEFAULT_SEC);
|
||||
// Barge-in: ARIA waehrend ihrer Antwort unterbrechen duerfen. Default aus (Halb-Duplex).
|
||||
const [bargeIn, setBargeIn] = useState<boolean>(false);
|
||||
// null = automatisch (adaptive Baseline), sonst manueller dB-Override
|
||||
const [vadSilenceDb, setVadSilenceDb] = useState<number | null>(null);
|
||||
const [showVadInfo, setShowVadInfo] = useState(false);
|
||||
@@ -209,7 +216,10 @@ const SettingsScreen: React.FC = () => {
|
||||
const [wakeStatus, setWakeStatus] = useState<string>('');
|
||||
const [wakeReadySound, setWakeReadySound] = useState<boolean>(true);
|
||||
const [wakeThreshold, setWakeThreshold] = useState<number>(WAKE_THRESHOLD_DEFAULT);
|
||||
const [passiveSec, setPassiveSec] = useState<number>(Math.round(PASSIVE_LISTEN_DEFAULT_MS / 1000));
|
||||
// Hintergrund-Wake: auch bei gesperrtem Bildschirm auf das Wake-Wort hoeren. Default aus.
|
||||
const [bgWake, setBgWake] = useState<boolean>(false);
|
||||
// Wake-Wort per Voxtral bestaetigen (gegen Musik-Fehltrigger). Default aus.
|
||||
const [wakeConfirm, setWakeConfirm] = useState<boolean>(false);
|
||||
const [editingPath, setEditingPath] = useState(false);
|
||||
const [xttsVoice, setXttsVoice] = useState('');
|
||||
const [loadingVoice, setLoadingVoice] = useState<string | null>(null);
|
||||
@@ -298,11 +308,11 @@ const SettingsScreen: React.FC = () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
AsyncStorage.getItem(CONV_WINDOW_STORAGE_KEY).then(saved => {
|
||||
AsyncStorage.getItem(STT_ENDPOINT_STORAGE_KEY).then(saved => {
|
||||
if (saved != null) {
|
||||
const n = parseFloat(saved);
|
||||
if (isFinite(n) && n >= CONV_WINDOW_MIN_SEC && n <= CONV_WINDOW_MAX_SEC) {
|
||||
setConvWindowSec(n);
|
||||
const n = parseInt(saved, 10);
|
||||
if (isFinite(n) && n >= STT_ENDPOINT_MIN_MS && n <= STT_ENDPOINT_MAX_MS) {
|
||||
setSttEndpointSec(n / 1000);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -314,6 +324,7 @@ const SettingsScreen: React.FC = () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
loadBargeInEnabled().then(setBargeIn).catch(() => {});
|
||||
AsyncStorage.getItem(VAD_SILENCE_DB_OVERRIDE_KEY).then(saved => {
|
||||
if (saved != null && saved !== '') {
|
||||
const n = parseFloat(saved);
|
||||
@@ -333,7 +344,8 @@ const SettingsScreen: React.FC = () => {
|
||||
});
|
||||
isWakeReadySoundEnabled().then(setWakeReadySound);
|
||||
loadWakeThreshold().then(setWakeThreshold).catch(() => {});
|
||||
loadPassiveListenMs().then(ms => setPassiveSec(Math.round(ms / 1000))).catch(() => {});
|
||||
loadBgWakeEnabled().then(setBgWake).catch(() => {});
|
||||
loadWakeConfirmEnabled().then(setWakeConfirm).catch(() => {});
|
||||
updateService.getApkCacheSize().then(setApkCacheInfo).catch(() => {});
|
||||
audioService.getTtsCacheSize().then(setTtsCacheInfo).catch(() => {});
|
||||
AsyncStorage.getItem('aria_xtts_voice').then(saved => {
|
||||
@@ -1651,72 +1663,56 @@ const SettingsScreen: React.FC = () => {
|
||||
{currentSection === 'voice_input' && (<>
|
||||
<Text style={styles.sectionTitle}>Spracheingabe</Text>
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.toggleLabel}>Stille-Toleranz</Text>
|
||||
<View style={styles.toggleRow}>
|
||||
<View style={styles.toggleInfo}>
|
||||
<Text style={styles.toggleLabel}>Barge-in (unterbrechen)</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
AUS (empfohlen): ARIA spricht ihre Antwort ZU ENDE, dann geht das
|
||||
Mikro auf — sauber, kein Selbst-Echo, du hoerst sie ganz. AN: du
|
||||
kannst sie waehrend des Sprechens per Wake-Wort unterbrechen.
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={bargeIn}
|
||||
onValueChange={(v) => { setBargeIn(v); saveBargeInEnabled(v).catch(() => {}); }}
|
||||
trackColor={{ false: '#2A2A3E', true: '#0096FF' }}
|
||||
thumbColor={bargeIn ? '#FFFFFF' : '#666680'}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<Text style={[styles.toggleLabel, {marginTop: 20}]}>Stille-Toleranz</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
Wie lange du eine Sprechpause machen darfst, bevor die Aufnahme
|
||||
automatisch beendet und gesendet wird. Hoeher = mehr Zeit zum
|
||||
Nachdenken; niedriger = schnelleres Senden.
|
||||
Default: {VAD_SILENCE_DEFAULT_SEC.toFixed(1)}s.
|
||||
Nachdenken (z.B. im Auto); niedriger = schnelleres Senden.
|
||||
Default: {(STT_ENDPOINT_DEFAULT_MS / 1000).toFixed(1)}s.
|
||||
</Text>
|
||||
<View style={styles.prerollRow}>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = Math.max(VAD_SILENCE_MIN_SEC, Math.round((vadSilenceSec - 0.5) * 10) / 10);
|
||||
setVadSilenceSec(next);
|
||||
AsyncStorage.setItem(VAD_SILENCE_STORAGE_KEY, String(next));
|
||||
const next = Math.max(STT_ENDPOINT_MIN_MS / 1000, Math.round((sttEndpointSec - 0.5) * 10) / 10);
|
||||
setSttEndpointSec(next);
|
||||
AsyncStorage.setItem(STT_ENDPOINT_STORAGE_KEY, String(Math.round(next * 1000)));
|
||||
}}
|
||||
disabled={vadSilenceSec <= VAD_SILENCE_MIN_SEC}
|
||||
disabled={sttEndpointSec <= STT_ENDPOINT_MIN_MS / 1000}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>−0.5</Text>
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.prerollValue}>{vadSilenceSec.toFixed(1)} s</Text>
|
||||
<Text style={styles.prerollValue}>{sttEndpointSec.toFixed(1)} s</Text>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = Math.min(VAD_SILENCE_MAX_SEC, Math.round((vadSilenceSec + 0.5) * 10) / 10);
|
||||
setVadSilenceSec(next);
|
||||
AsyncStorage.setItem(VAD_SILENCE_STORAGE_KEY, String(next));
|
||||
const next = Math.min(STT_ENDPOINT_MAX_MS / 1000, Math.round((sttEndpointSec + 0.5) * 10) / 10);
|
||||
setSttEndpointSec(next);
|
||||
AsyncStorage.setItem(STT_ENDPOINT_STORAGE_KEY, String(Math.round(next * 1000)));
|
||||
}}
|
||||
disabled={vadSilenceSec >= VAD_SILENCE_MAX_SEC}
|
||||
disabled={sttEndpointSec >= STT_ENDPOINT_MAX_MS / 1000}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>+0.5</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<Text style={[styles.toggleLabel, {marginTop: 24}]}>Konversations-Fenster</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
Im Gespraechsmodus (Ohr-Button): nach ARIA's Antwort hast du so lange
|
||||
Zeit, weiter zu sprechen, bevor die Konversation automatisch beendet wird.
|
||||
Sprichst du nichts → Mikrofon zu.
|
||||
Default: {CONV_WINDOW_DEFAULT_SEC.toFixed(1)}s.
|
||||
</Text>
|
||||
<View style={styles.prerollRow}>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = Math.max(CONV_WINDOW_MIN_SEC, Math.round((convWindowSec - 1) * 10) / 10);
|
||||
setConvWindowSec(next);
|
||||
AsyncStorage.setItem(CONV_WINDOW_STORAGE_KEY, String(next));
|
||||
}}
|
||||
disabled={convWindowSec <= CONV_WINDOW_MIN_SEC}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>−1</Text>
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.prerollValue}>{convWindowSec.toFixed(0)} s</Text>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = Math.min(CONV_WINDOW_MAX_SEC, Math.round((convWindowSec + 1) * 10) / 10);
|
||||
setConvWindowSec(next);
|
||||
AsyncStorage.setItem(CONV_WINDOW_STORAGE_KEY, String(next));
|
||||
}}
|
||||
disabled={convWindowSec >= CONV_WINDOW_MAX_SEC}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>+1</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<Text style={[styles.toggleLabel, {marginTop: 24}]}>Maximale Aufnahmedauer</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
Notbremse: nach so vielen Minuten wird die Aufnahme automatisch beendet,
|
||||
@@ -1749,56 +1745,10 @@ const SettingsScreen: React.FC = () => {
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View style={{flexDirection: 'row', alignItems: 'center', marginTop: 24, gap: 8}}>
|
||||
<Text style={styles.toggleLabel}>Stille-Pegel (dB)</Text>
|
||||
<TouchableOpacity onPress={() => setShowVadInfo(true)} style={styles.infoBtn}>
|
||||
<Text style={styles.infoBtnText}>i</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<Text style={styles.toggleHint}>
|
||||
Welcher Mikro-Pegel als "Stille" gilt. Standard: automatisch (Baseline aus
|
||||
den ersten 500ms). Manuell setzen wenn Auto nicht zuverlaessig greift.
|
||||
</Text>
|
||||
<View style={styles.prerollRow}>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = vadSilenceDb == null
|
||||
? VAD_SILENCE_DB_DEFAULT - 1
|
||||
: Math.max(VAD_SILENCE_DB_MIN, vadSilenceDb - 1);
|
||||
setVadSilenceDb(next);
|
||||
AsyncStorage.setItem(VAD_SILENCE_DB_OVERRIDE_KEY, String(next));
|
||||
}}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>−1</Text>
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.prerollValue}>
|
||||
{vadSilenceDb == null ? 'auto' : `${vadSilenceDb} dB`}
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = vadSilenceDb == null
|
||||
? VAD_SILENCE_DB_DEFAULT + 1
|
||||
: Math.min(VAD_SILENCE_DB_MAX, vadSilenceDb + 1);
|
||||
setVadSilenceDb(next);
|
||||
AsyncStorage.setItem(VAD_SILENCE_DB_OVERRIDE_KEY, String(next));
|
||||
}}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>+1</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
{vadSilenceDb != null && (
|
||||
<TouchableOpacity
|
||||
onPress={() => {
|
||||
setVadSilenceDb(null);
|
||||
AsyncStorage.removeItem(VAD_SILENCE_DB_OVERRIDE_KEY);
|
||||
}}
|
||||
style={{alignSelf: 'center', marginTop: 8, paddingVertical: 6, paddingHorizontal: 12}}
|
||||
>
|
||||
<Text style={{color: '#0096FF', fontSize: 13}}>↻ Auf automatisch zuruecksetzen</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
{/* "Stille-Pegel (dB)"-Regler entfernt: der aktive Streaming-STT nutzt
|
||||
einen adaptiven Rausch-Boden (automatisch), ein manueller dB-Wert war
|
||||
wirkungslos. Rauschen-als-Wort verhindert das STT-Modell selbst
|
||||
(no_speech_prob-Filter), nicht die dB-Schwelle. */}
|
||||
</View>
|
||||
|
||||
<Modal
|
||||
@@ -1954,38 +1904,58 @@ const SettingsScreen: React.FC = () => {
|
||||
/>
|
||||
</View>
|
||||
|
||||
<Text style={[styles.toggleLabel, {marginTop: 20}]}>Weiterreden-Fenster (Gespraech)</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
Nach einer gesprochenen ARIA-Antwort kannst du so lange einfach
|
||||
weiterreden — ohne Wake-Word — bevor zurueck aufs Wake-Word geschaltet
|
||||
wird. Reine Steuerbefehle (z.B. „nächster Titel") beenden sofort.
|
||||
Default: {Math.round(PASSIVE_LISTEN_DEFAULT_MS / 1000)}s.
|
||||
</Text>
|
||||
<View style={styles.prerollRow}>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = Math.max(10, passiveSec - 5);
|
||||
setPassiveSec(next);
|
||||
savePassiveListenMs(next * 1000);
|
||||
<View style={[styles.toggleRow, {marginTop: 20, borderTopWidth: 1, borderTopColor: '#1E1E2E', paddingTop: 16}]}>
|
||||
<View style={styles.toggleInfo}>
|
||||
<Text style={styles.toggleLabel}>Auch bei gesperrtem Bildschirm zuhören</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
AUS (empfohlen): das Wake-Wort greift nur, wenn die App offen ist —
|
||||
im Hintergrund sind die meisten „Trigger" Fehlalarme (TV, Husten).
|
||||
AN: ARIA hört auch bei gesperrtem Bildschirm / im Hintergrund auf
|
||||
„{KEYWORD_LABELS[wakeKeyword as keyof typeof KEYWORD_LABELS] || wakeKeyword}" — mehr Fehlauslöser möglich.
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={bgWake}
|
||||
onValueChange={(val) => {
|
||||
setBgWake(val);
|
||||
saveBgWakeEnabled(val).catch(() => {});
|
||||
wakeWordService.setBgWakeEnabled(val);
|
||||
}}
|
||||
disabled={passiveSec <= 10}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>−5</Text>
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.prerollValue}>{passiveSec} s</Text>
|
||||
<TouchableOpacity
|
||||
style={styles.prerollButton}
|
||||
onPress={() => {
|
||||
const next = Math.min(60, passiveSec + 5);
|
||||
setPassiveSec(next);
|
||||
savePassiveListenMs(next * 1000);
|
||||
}}
|
||||
disabled={passiveSec >= 60}
|
||||
>
|
||||
<Text style={styles.prerollButtonText}>+5</Text>
|
||||
</TouchableOpacity>
|
||||
trackColor={{ false: '#2A2A3E', true: '#0096FF' }}
|
||||
thumbColor={bgWake ? '#FFFFFF' : '#666680'}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={[styles.toggleRow, {marginTop: 20, borderTopWidth: 1, borderTopColor: '#1E1E2E', paddingTop: 16}]}>
|
||||
<View style={styles.toggleInfo}>
|
||||
<Text style={styles.toggleLabel}>Wake-Wort per Voxtral bestätigen</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
Gegen Musik-Fehltrigger: nach „{KEYWORD_LABELS[wakeKeyword as keyof typeof KEYWORD_LABELS] || wakeKeyword}"
|
||||
prüft Voxtral kurz nach, ob's wirklich das Wake-Wort war (oder nur
|
||||
Musik/TV) — erst dann Gong + Mikro. Kostet ~0,5–1 s Extra vor dem
|
||||
Gong. Empfohlen zusammen mit Hintergrund-Zuhören.
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={wakeConfirm}
|
||||
onValueChange={(val) => {
|
||||
setWakeConfirm(val);
|
||||
saveWakeConfirmEnabled(val).catch(() => {});
|
||||
wakeWordService.setWakeConfirmEnabled(val);
|
||||
}}
|
||||
trackColor={{ false: '#2A2A3E', true: '#0096FF' }}
|
||||
thumbColor={wakeConfirm ? '#FFFFFF' : '#666680'}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<Text style={[styles.toggleLabel, {marginTop: 20}]}>Weiterreden nach der Antwort</Text>
|
||||
<Text style={styles.toggleHint}>
|
||||
Nach einer gesprochenen ARIA-Antwort geht das Mikro auf — du kannst ohne
|
||||
Wake-Word weiterreden. Fängst du nicht innerhalb der „Stille-Toleranz"
|
||||
(Sektion Spracheingabe) an, geht's zurück aufs Wake-Word. Reine
|
||||
Steuerbefehle beenden sofort. Ein separates Zeitfenster gibt es nicht
|
||||
mehr — es zählt überall derselbe Stille-Wert.
|
||||
</Text>
|
||||
</View>
|
||||
</>)}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 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;
|
||||
+233
-28
@@ -143,23 +143,100 @@ export const VAD_SILENCE_MIN_SEC = 1.0;
|
||||
export const VAD_SILENCE_MAX_SEC = 8.0;
|
||||
export const VAD_SILENCE_STORAGE_KEY = 'aria_vad_silence_sec';
|
||||
|
||||
// Konversations-Fenster (in Sekunden) — nach ARIA's Antwort hat der User so
|
||||
// lange Zeit, im Gespraechsmodus weiter zu sprechen, ohne dass die Konversation
|
||||
// beendet wird. Sprichst du im Fenster nichts → Konversation aus.
|
||||
export const CONV_WINDOW_DEFAULT_SEC = 8.0;
|
||||
export const CONV_WINDOW_MIN_SEC = 3.0;
|
||||
export const CONV_WINDOW_MAX_SEC = 20.0;
|
||||
export const CONV_WINDOW_STORAGE_KEY = 'aria_conv_window_sec';
|
||||
|
||||
// STT-Endpoint (ms Stille bis "fertig gesprochen"). Zu kurz = schneidet mitten
|
||||
// im Satz ab, besonders im Auto wo man mit Pausen spricht (Reproduktion: die
|
||||
// 11.8s-Frage wurde bei "…ohne dass ein" gekappt). 1500 war zu aggressiv;
|
||||
// 2400 default, im Auto ggf. hoeher. Konfigurierbar in den Settings.
|
||||
// im Satz ab, besonders im Auto oder wenn man zum Nachdenken pausiert. 1500 war
|
||||
// zu aggressiv; 2400 default, bis 8s hoch stellbar (Denkpausen). In den Settings
|
||||
// unter "Stille-Toleranz" konfigurierbar.
|
||||
export const STT_ENDPOINT_DEFAULT_MS = 2400;
|
||||
export const STT_ENDPOINT_MIN_MS = 1000;
|
||||
export const STT_ENDPOINT_MAX_MS = 4000;
|
||||
export const STT_ENDPOINT_MAX_MS = 8000; // bis 8s: genug Zeit zum Ueberlegen
|
||||
export const STT_ENDPOINT_STORAGE_KEY = 'aria_stt_endpoint_ms';
|
||||
|
||||
// Barge-in-Modus: darf man ARIA waehrend ihrer TTS-Antwort unterbrechen (reden)?
|
||||
// Default AUS = sauberes Halb-Duplex (ARIA spricht aus, DANN oeffnet das Mikro —
|
||||
// kein Selbst-Echo, kein Mischmasch). AN = waehrend TTS auf Wake-Wort lauschen.
|
||||
export const BARGE_IN_STORAGE_KEY = 'aria_barge_in_enabled';
|
||||
|
||||
export async function loadBargeInEnabled(): Promise<boolean> {
|
||||
try {
|
||||
return (await AsyncStorage.getItem(BARGE_IN_STORAGE_KEY)) === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveBargeInEnabled(enabled: boolean): Promise<void> {
|
||||
try {
|
||||
await AsyncStorage.setItem(BARGE_IN_STORAGE_KEY, String(enabled));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** One-Shot-Transkription eines PCM-Schnipsels (base64, s16le 16kHz mono) via
|
||||
* Voxtral — fuer die Wake-Wort-Bestaetigung. Schickt stt_transcribe_blob und
|
||||
* wartet auf stt_transcribe_result (matching requestId) mit Timeout.
|
||||
* Rueckgabe: Text (evtl. '') bei Antwort, oder null bei Timeout/Fehler →
|
||||
* Aufrufer macht dann fail-open (Wake normal durchlassen). */
|
||||
export async function transcribeBlob(pcmBase64: string, timeoutMs = 2500): Promise<string | null> {
|
||||
if (!pcmBase64) return null;
|
||||
const requestId = `wakeverify_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
return new Promise<string | null>((resolve) => {
|
||||
let done = false;
|
||||
let unsub: (() => void) | null = null;
|
||||
const timer = setTimeout(() => finish(null), timeoutMs);
|
||||
function finish(val: string | null) {
|
||||
if (done) return;
|
||||
done = true;
|
||||
try { unsub && unsub(); } catch {}
|
||||
clearTimeout(timer);
|
||||
resolve(val);
|
||||
}
|
||||
try {
|
||||
unsub = rvs.onMessage((msg: any) => {
|
||||
if (msg?.type !== 'stt_transcribe_result') return;
|
||||
const p = (msg as any).payload || {};
|
||||
if (String(p.requestId || '') !== requestId) return;
|
||||
finish(typeof p.text === 'string' ? p.text : '');
|
||||
});
|
||||
rvs.send('stt_transcribe_blob' as any, { requestId, pcm: pcmBase64, language: 'de' });
|
||||
} catch {
|
||||
finish(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Fragt die Bridge vor dem Aufnahme-Stream, welche STT-Instanz adressiert
|
||||
* werden soll (Redundanz ueber mehrere STT-Nodes/Apps). Schickt
|
||||
* stt_lease_request, wartet kurz auf stt_lease (matching requestId).
|
||||
* Rueckgabe: instanceId (z.B. "voxtral@box-a") oder '' bei Timeout/keine
|
||||
* Instanz — dann streamt die App wie bisher an ALLE (Broadcast, Single-Node
|
||||
* unveraendert). Bewusst kurzer Timeout, damit die Aufnahme nie haengt. */
|
||||
export async function requestSttLease(timeoutMs = 250): Promise<string> {
|
||||
const requestId = `sttlease_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
return new Promise<string>((resolve) => {
|
||||
let done = false;
|
||||
let unsub: (() => void) | null = null;
|
||||
const timer = setTimeout(() => finish(''), timeoutMs);
|
||||
function finish(val: string) {
|
||||
if (done) return;
|
||||
done = true;
|
||||
try { unsub && unsub(); } catch {}
|
||||
clearTimeout(timer);
|
||||
resolve(val);
|
||||
}
|
||||
try {
|
||||
unsub = rvs.onMessage((msg: any) => {
|
||||
if (msg?.type !== 'stt_lease') return;
|
||||
const p = (msg as any).payload || {};
|
||||
if (String(p.requestId || '') !== requestId) return;
|
||||
finish(typeof p.instanceId === 'string' ? p.instanceId : '');
|
||||
});
|
||||
rvs.send('stt_lease_request' as any, { requestId });
|
||||
} catch {
|
||||
finish('');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadSttEndpointMs(): Promise<number> {
|
||||
try {
|
||||
const raw = await AsyncStorage.getItem(STT_ENDPOINT_STORAGE_KEY);
|
||||
@@ -189,18 +266,6 @@ export async function loadTtsSpeed(): Promise<number> {
|
||||
return TTS_SPEED_DEFAULT;
|
||||
}
|
||||
|
||||
export async function loadConvWindowMs(): Promise<number> {
|
||||
try {
|
||||
const raw = await AsyncStorage.getItem(CONV_WINDOW_STORAGE_KEY);
|
||||
if (raw != null) {
|
||||
const n = parseFloat(raw);
|
||||
if (isFinite(n) && n >= CONV_WINDOW_MIN_SEC && n <= CONV_WINDOW_MAX_SEC) {
|
||||
return Math.round(n * 1000);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
return Math.round(CONV_WINDOW_DEFAULT_SEC * 1000);
|
||||
}
|
||||
|
||||
async function loadVadSilenceMs(): Promise<number> {
|
||||
try {
|
||||
@@ -284,6 +349,13 @@ class AudioService {
|
||||
private pcmSampleRate: number = 24000;
|
||||
private pcmChannels: number = 1;
|
||||
private pcmBuffer: string[] = []; // base64-chunks zum spaeteren WAV-Build
|
||||
// ── TTS-Abspiel-Queue: zwei back-to-back-Antworten sollen sich NICHT
|
||||
// gegenseitig abschneiden. Eine neue hoerbare Antwort, die reinkommt waehrend
|
||||
// eine andere noch HOERBAR spielt, wird gepuffert und nach PcmPlaybackFinished
|
||||
// nachgespielt (statt via start()→stopInternal() die laufende zu cutten). ──
|
||||
private pcmAudiblePlaying: boolean = false; // eine hoerbare Antwort spielt (bis PcmPlaybackFinished)
|
||||
private pcmPlayingMsgId: string = ''; // deren messageId
|
||||
private pcmPendingStreams: Array<{ messageId: string; sampleRate: number; channels: number; chunks: string[]; final: boolean }> = [];
|
||||
private pcmBytesCollected: number = 0;
|
||||
private readonly PCM_MAX_CACHE_BYTES = 30 * 1024 * 1024; // 30MB
|
||||
|
||||
@@ -344,6 +416,9 @@ class AudioService {
|
||||
// lich Chunks einer alten Session in eine neue mischen.
|
||||
private streamRequestId: string = '';
|
||||
private streamAudioRequestId: string = '';
|
||||
// Adressierte STT-Instanz fuer diesen Stream (Redundanz-Routing). '' =
|
||||
// Broadcast an alle STT-Nodes (Single-Node / kein Lease = wie bisher).
|
||||
private streamTargetInstance: string = '';
|
||||
// Latch: ist endpointListeners fuer den aktuellen Session-Cycle schon gefeuert
|
||||
// worden? Wird auf false gesetzt beim startStreamingRecording, auf true beim
|
||||
// ersten Endpoint (egal ob via RVS oder Fallback). Verhindert Doppel-Fires.
|
||||
@@ -374,6 +449,16 @@ class AudioService {
|
||||
const emitter = new NativeEventEmitter(NativeModules.PcmStreamPlayer as any);
|
||||
emitter.addListener('PcmPlaybackFinished', () => {
|
||||
console.log('[Audio] PcmPlaybackFinished — AudioTrack drained');
|
||||
this.pcmAudiblePlaying = false;
|
||||
this.pcmPlayingMsgId = '';
|
||||
// TTS-Abspiel-Queue: steht eine naechste Antwort bereit? Dann NICHT
|
||||
// "fertig" melden (kein Wake-Word-Re-Arm / Conversation-Ende) — ARIA
|
||||
// spricht gleich weiter. Die naechste gepufferte Antwort direkt spielen.
|
||||
if (this.pcmPendingStreams.length > 0) {
|
||||
this._promoteNextPendingStream().catch(err =>
|
||||
console.warn('[Audio] promote next pending stream err:', err));
|
||||
return;
|
||||
}
|
||||
this._releaseFocusDeferred();
|
||||
// Erst HIER playbackFinished-Listener feuern — nicht schon beim
|
||||
// Empfang des letzten PCM-Chunks (siehe handlePcmChunk). AudioTrack
|
||||
@@ -1077,6 +1162,15 @@ class AudioService {
|
||||
const requestId = `sttstr_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
this.streamRequestId = requestId;
|
||||
this.streamAudioRequestId = opts.audioRequestId || '';
|
||||
// Redundanz-Routing: freie STT-Instanz leasen BEVOR Chunks fliessen, damit
|
||||
// start + alle Chunks + end dieselbe Instanz adressieren. Kurzer Timeout →
|
||||
// '' (Broadcast) falls keine Instanz/keine Antwort. Nie blockierend genug
|
||||
// um die Aufnahme spuerbar zu verzoegern.
|
||||
try {
|
||||
this.streamTargetInstance = await requestSttLease();
|
||||
} catch {
|
||||
this.streamTargetInstance = '';
|
||||
}
|
||||
this.streamGotPartial = false;
|
||||
this.streamEndpointFired = false;
|
||||
this.recordingStartTime = Date.now();
|
||||
@@ -1097,6 +1191,7 @@ class AudioService {
|
||||
requestId: sessionId,
|
||||
pcm: String(e?.pcm || ''),
|
||||
seq: Number(e?.seq || 0),
|
||||
targetInstance: this.streamTargetInstance,
|
||||
});
|
||||
});
|
||||
this.streamPcmErrorSub = emitter.addListener('PcmStreamError', (e: any) => {
|
||||
@@ -1128,10 +1223,11 @@ class AudioService {
|
||||
speed: typeof opts.speed === 'number' ? opts.speed : 1.0,
|
||||
interrupted: !!opts.interrupted,
|
||||
location: opts.location || null,
|
||||
endpointMs: typeof opts.endpointMs === 'number' ? opts.endpointMs : 1500,
|
||||
endpointMs: typeof opts.endpointMs === 'number' ? opts.endpointMs : STT_ENDPOINT_DEFAULT_MS,
|
||||
hardCapMs: typeof opts.hardCapMs === 'number' ? opts.hardCapMs : 60000,
|
||||
sampleRate: 16000,
|
||||
projectId: opts.projectId || '',
|
||||
targetInstance: this.streamTargetInstance,
|
||||
});
|
||||
|
||||
// No-Speech-Watchdog — ersetzt den alten VAD-noSpeechTimer.
|
||||
@@ -1181,7 +1277,7 @@ class AudioService {
|
||||
if (!reqId) return;
|
||||
const audioReqId = this.streamAudioRequestId;
|
||||
try {
|
||||
rvs.send('stt_stream_end' as any, { requestId: reqId, reason });
|
||||
rvs.send('stt_stream_end' as any, { requestId: reqId, reason, targetInstance: this.streamTargetInstance });
|
||||
} catch (e) {
|
||||
console.warn('[Audio] stt_stream_end senden fehlgeschlagen:', e);
|
||||
}
|
||||
@@ -1216,7 +1312,7 @@ class AudioService {
|
||||
if (!reqId) return;
|
||||
const audioReqId = this.streamAudioRequestId;
|
||||
try {
|
||||
rvs.send('stt_stream_end' as any, { requestId: reqId, reason: `cancel:${reason}` });
|
||||
rvs.send('stt_stream_end' as any, { requestId: reqId, reason: `cancel:${reason}`, targetInstance: this.streamTargetInstance });
|
||||
} catch {}
|
||||
this._cleanupStreamLocal(`cancel:${reason}`);
|
||||
// Listener feuern damit ChatScreen reagieren kann (endConversation etc.)
|
||||
@@ -1401,6 +1497,23 @@ class AudioService {
|
||||
const base64 = payload.base64 || '';
|
||||
const isFinal = !!payload.final;
|
||||
|
||||
// ── TTS-Abspiel-Queue ──
|
||||
// Kommt eine NEUE hoerbare Antwort rein, waehrend eine andere noch hoerbar
|
||||
// spielt? Dann NICHT starten (start()→stopInternal() wuerde die laufende
|
||||
// abschneiden) — puffern und nach deren PcmPlaybackFinished nachspielen.
|
||||
if (!silent && this.pcmAudiblePlaying && messageId && messageId !== this.pcmPlayingMsgId) {
|
||||
let entry = this.pcmPendingStreams.find(e => e.messageId === messageId);
|
||||
if (!entry) {
|
||||
entry = { messageId, sampleRate, channels, chunks: [], final: false };
|
||||
this.pcmPendingStreams.push(entry);
|
||||
console.log('[Audio] TTS-Queue: Antwort %s wird gepuffert (spielt gerade %s)',
|
||||
messageId, this.pcmPlayingMsgId);
|
||||
}
|
||||
if (base64) entry.chunks.push(base64);
|
||||
if (isFinal) entry.final = true;
|
||||
return ''; // Live-Player nicht anfassen
|
||||
}
|
||||
|
||||
// Neuer Stream? (messageId Wechsel oder nicht aktiv)
|
||||
if (!this.pcmStreamActive || this.pcmMessageId !== messageId) {
|
||||
if (this.pcmStreamActive && !silent) {
|
||||
@@ -1448,6 +1561,8 @@ class AudioService {
|
||||
this._cancelDeferredFocusRelease();
|
||||
AudioFocus?.requestDuck().catch(() => {});
|
||||
this._firePlaybackStarted();
|
||||
this.pcmAudiblePlaying = true;
|
||||
this.pcmPlayingMsgId = messageId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1490,6 +1605,73 @@ class AudioService {
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Naechste gepufferte TTS-Antwort abspielen (TTS-Abspiel-Queue). Wird nach
|
||||
* PcmPlaybackFinished der vorherigen aufgerufen — so sprechen zwei
|
||||
* back-to-back-Antworten NACHEINANDER statt sich abzuschneiden. */
|
||||
private async _promoteNextPendingStream(): Promise<void> {
|
||||
const entry = this.pcmPendingStreams.shift();
|
||||
if (!entry) return;
|
||||
// Inzwischen global gemutet / im Anruf / vom User gestoppt? Dann NICHT
|
||||
// hoerbar abspielen — nur cachen und die naechste promoten.
|
||||
const mutedNow = this._muted || this._pausedForCall ||
|
||||
(!!this._stoppedMessageId && this._stoppedMessageId === entry.messageId);
|
||||
console.log('[Audio] TTS-Queue: spiele gepufferte Antwort %s (%d chunks, final=%s, muted=%s)',
|
||||
entry.messageId, entry.chunks.length, entry.final, mutedNow);
|
||||
// SOFORT als "spielt" markieren (vor jedem await) — sonst koennte ein
|
||||
// gleichzeitig eintreffender Chunk einer DRITTEN Antwort in der await-Luecke
|
||||
// einen konkurrierenden Stream starten statt zu puffern.
|
||||
this.pcmPlayingMsgId = entry.messageId;
|
||||
this.pcmAudiblePlaying = !mutedNow;
|
||||
// Cache-State fuer den WAV-Build (Mund-Button-Replay) setzen.
|
||||
this.pcmMessageId = entry.messageId;
|
||||
this.pcmSampleRate = entry.sampleRate;
|
||||
this.pcmChannels = entry.channels;
|
||||
this.pcmBuffer = entry.chunks.slice();
|
||||
this.pcmBytesCollected = entry.chunks.reduce((n, c) => n + Math.floor(c.length * 0.75), 0);
|
||||
this.pcmStreamActive = true;
|
||||
if (!mutedNow && PcmStreamPlayer) {
|
||||
try {
|
||||
const prerollSec = await loadPrerollSec();
|
||||
await PcmStreamPlayer.start(entry.sampleRate, entry.channels, prerollSec);
|
||||
this._cancelDeferredFocusRelease();
|
||||
AudioFocus?.requestDuck().catch(() => {});
|
||||
this._firePlaybackStarted();
|
||||
this.pcmAudiblePlaying = true;
|
||||
this.pcmPlayingMsgId = entry.messageId;
|
||||
for (const c of entry.chunks) {
|
||||
try { await PcmStreamPlayer.writeChunk(c); } catch (err) { console.warn('[Audio] promote writeChunk', err); }
|
||||
}
|
||||
if (entry.final) { try { await PcmStreamPlayer.end(); } catch {} }
|
||||
} catch (err) {
|
||||
console.error('[Audio] TTS-Queue promote start fehlgeschlagen:', err);
|
||||
this.pcmAudiblePlaying = false;
|
||||
this.pcmPlayingMsgId = '';
|
||||
}
|
||||
}
|
||||
// War die Antwort schon komplett (final) da: WAV cachen + State wie im
|
||||
// Normalpfad zuruecksetzen. Bei NICHT-final laeuft der Rest live ueber
|
||||
// _handlePcmChunkImpl (messageId == pcmPlayingMsgId → Normalpfad).
|
||||
if (entry.final) {
|
||||
this.pcmStreamActive = false;
|
||||
if (this.pcmBuffer.length > 0) {
|
||||
const audioPath = await this._savePcmBufferAsWav(entry.messageId).catch(() => '');
|
||||
if (audioPath) {
|
||||
this.pcmCachedListeners.forEach(cb => {
|
||||
try { cb(entry.messageId, audioPath); } catch (e) { console.warn('[Audio] pcmCached cb err:', e); }
|
||||
});
|
||||
}
|
||||
}
|
||||
this.pcmBuffer = [];
|
||||
this.pcmBytesCollected = 0;
|
||||
this.pcmMessageId = '';
|
||||
// Nicht hoerbar abgespielt (gemutet)? Dann feuert PcmPlaybackFinished nicht
|
||||
// → die naechste gepufferte Antwort selbst nachziehen (Kette).
|
||||
if (!this.pcmAudiblePlaying) {
|
||||
await this._promoteNextPendingStream();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Gesammelte PCM-Chunks als WAV speichern. Gibt file:// Pfad zurueck. */
|
||||
private async _savePcmBufferAsWav(messageId: string): Promise<string> {
|
||||
try {
|
||||
@@ -1578,6 +1760,19 @@ class AudioService {
|
||||
// Callback wenn alle Audio-Teile abgespielt sind
|
||||
private playbackFinishedListeners: (() => void)[] = [];
|
||||
private playbackStartedListeners: (() => void)[] = [];
|
||||
// Feuert wenn eine aus der TTS-Queue NACHgespielte Antwort ihren WAV-Cache
|
||||
// geschrieben hat — der Normalpfad meldet den Pfad ueber den handlePcmChunk-
|
||||
// Rueckgabewert, gepufferte (zweite) Antworten koennen das aber nicht (ihre
|
||||
// Chunks returnen '' waehrend sie warten). Damit setzt die App auch fuer die
|
||||
// nachgespielte Antwort m.audioPath (Mund-Button-Replay).
|
||||
private pcmCachedListeners: Array<(messageId: string, audioPath: string) => void> = [];
|
||||
|
||||
onPcmCached(callback: (messageId: string, audioPath: string) => void): () => void {
|
||||
this.pcmCachedListeners.push(callback);
|
||||
return () => {
|
||||
this.pcmCachedListeners = this.pcmCachedListeners.filter(cb => cb !== callback);
|
||||
};
|
||||
}
|
||||
|
||||
onPlaybackFinished(callback: () => void): () => void {
|
||||
this.playbackFinishedListeners.push(callback);
|
||||
@@ -1759,6 +1954,10 @@ class AudioService {
|
||||
}
|
||||
// AudioTrack IMMER hart stoppen (idempotent) — auch im Drain-Fall.
|
||||
PcmStreamPlayer?.stop().catch(() => {});
|
||||
// Wartende TTS-Antworten verwerfen (Mund-Button = still sein).
|
||||
this.pcmPendingStreams = [];
|
||||
this.pcmAudiblePlaying = false;
|
||||
this.pcmPlayingMsgId = '';
|
||||
stopBackgroundAudio().catch(() => {});
|
||||
this._cancelDeferredFocusRelease();
|
||||
AudioFocus?.release().catch(() => {});
|
||||
@@ -1770,7 +1969,8 @@ class AudioService {
|
||||
// Kick-Cycle anstossen — Re-Renders triggern setMuted oft mehrfach hinter-
|
||||
// einander, und jeder weitere Kick lässt Spotify nochmal kurz pausieren.
|
||||
const hasAnything = !!(this.currentSound || this.resumeSound || this.preloadedSound
|
||||
|| this.pcmStreamActive || this.audioQueue.length || this.isPlaying);
|
||||
|| this.pcmStreamActive || this.audioQueue.length || this.isPlaying
|
||||
|| this.pcmPendingStreams.length);
|
||||
if (!hasAnything) return;
|
||||
console.log('[Audio] stopPlayback: currentSound=%s queue=%d pcm=%s',
|
||||
this.currentSound ? 'aktiv' : 'null', this.audioQueue.length, this.pcmStreamActive);
|
||||
@@ -1804,6 +2004,11 @@ class AudioService {
|
||||
this.pcmBuffer = [];
|
||||
this.pcmBytesCollected = 0;
|
||||
this.pcmMessageId = '';
|
||||
// TTS-Abspiel-Queue verwerfen — harter Stop/Abbruch/Barge-In soll auch
|
||||
// wartende Antworten fallenlassen (sonst sprechen sie nach dem Stop weiter).
|
||||
this.pcmPendingStreams = [];
|
||||
this.pcmAudiblePlaying = false;
|
||||
this.pcmPlayingMsgId = '';
|
||||
// Audio-Focus sofort freigeben — User hat explizit abgebrochen.
|
||||
// Unser Focus war TRANSIENT, Spotify resumed darum automatisch beim
|
||||
// Abandon. Den frueheren kickReleaseMedia haben wir entfernt: er
|
||||
|
||||
@@ -162,6 +162,15 @@ export interface Project {
|
||||
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 {
|
||||
@@ -170,6 +179,19 @@ export interface ProjectStatus {
|
||||
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 {
|
||||
@@ -594,14 +616,58 @@ export const brainApi = {
|
||||
});
|
||||
},
|
||||
|
||||
/** Projekt-Metadaten patchen (name / description / hidden). */
|
||||
updateProject(projectId: string, patch: Partial<Pick<Project, 'name' | 'description' | 'hidden'>>): Promise<Project> {
|
||||
/** 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)}`, {
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -145,6 +145,17 @@ class GpsTrackingService {
|
||||
// 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 {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { Platform, DeviceEventEmitter } from 'react-native';
|
||||
import { Platform, DeviceEventEmitter, AppState } from 'react-native';
|
||||
import rvs from './rvs';
|
||||
|
||||
// Lokales Event damit die SettingsScreen Live Logs / Events Tabs
|
||||
@@ -38,6 +38,23 @@ 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;
|
||||
}
|
||||
@@ -53,6 +70,45 @@ export async function initLogger(): Promise<void> {
|
||||
_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 {
|
||||
@@ -94,6 +150,7 @@ 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,
|
||||
@@ -128,6 +185,9 @@ export function reportAppError(ev: AppErrorEvent): void {
|
||||
* 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);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -30,34 +30,22 @@ type PassiveListenCallback = () => void;
|
||||
|
||||
export type WakeWordState = 'off' | 'armed' | 'conversing' | 'listening';
|
||||
|
||||
/** Default-Dauer fuer den Passive-Listen-Modus nach einer Konversation —
|
||||
* in dem Fenster braucht's kein Wake-Word, Speaker-ID-Filter haelt
|
||||
* fremde Stimmen raus (TV, Familie). 30s default; konfigurierbar. */
|
||||
export const PASSIVE_LISTEN_DEFAULT_MS = 30_000;
|
||||
export const PASSIVE_LISTEN_STORAGE_KEY = 'aria_passive_listen_ms';
|
||||
|
||||
export async function loadPassiveListenMs(): Promise<number> {
|
||||
try {
|
||||
const raw = await AsyncStorage.getItem(PASSIVE_LISTEN_STORAGE_KEY);
|
||||
if (raw) {
|
||||
const n = parseInt(raw, 10);
|
||||
if (isFinite(n) && n >= 0 && n <= 120_000) return n;
|
||||
}
|
||||
} catch {}
|
||||
return PASSIVE_LISTEN_DEFAULT_MS;
|
||||
}
|
||||
|
||||
export async function savePassiveListenMs(ms: number): Promise<void> {
|
||||
await AsyncStorage.setItem(PASSIVE_LISTEN_STORAGE_KEY, String(ms));
|
||||
}
|
||||
/** 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 const WAKE_KEYWORD_STORAGE = 'aria_wake_keyword';
|
||||
|
||||
// Wake-Word-Empfindlichkeit (openWakeWord-Threshold). Hoeher = strenger =
|
||||
// weniger Fehlauslösung (z.B. durch Musik/Radio ueber die Auto-Lautsprecher,
|
||||
// die das Mikro mithoert — der App-Echo-Canceler kann nur ARIAs eigenes TTS
|
||||
// rausrechnen, NICHT Spotify). Default 0.6 (war 0.5). 0..1.
|
||||
export const WAKE_THRESHOLD_DEFAULT = 0.6;
|
||||
// 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';
|
||||
@@ -77,6 +65,49 @@ 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
|
||||
@@ -103,7 +134,9 @@ export const KEYWORD_LABELS: Record<WakeKeyword, string> = {
|
||||
// Detection-Tuning. Threshold ist ueber die Settings konfigurierbar
|
||||
// (loadWakeThreshold) — der Wert hier ist nur der Fallback.
|
||||
const DEFAULT_THRESHOLD = WAKE_THRESHOLD_DEFAULT;
|
||||
const DEFAULT_PATIENCE = 2;
|
||||
// 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 {
|
||||
@@ -143,6 +176,13 @@ class WakeWordService {
|
||||
* 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
|
||||
@@ -150,8 +190,9 @@ class WakeWordService {
|
||||
* Ausnahme: bargeListening → Barge-In ist ein legitimer neuer Trigger
|
||||
* waehrend ARIA noch redet, NICHT vom Guard blockieren. */
|
||||
private detectionInProgress: boolean = false;
|
||||
/** Passive-Listen-Timer: feuert nach PASSIVE_LISTEN_MS ohne Stefan-Speech,
|
||||
* beendet den listening-State und geht zurueck zu armed. */
|
||||
/** 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). */
|
||||
@@ -223,15 +264,20 @@ class WakeWordService {
|
||||
this.initInProgress = (async () => {
|
||||
try {
|
||||
const threshold = await loadWakeThreshold();
|
||||
console.log('[WakeWord] init mit threshold=%s', threshold);
|
||||
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', () => {
|
||||
this.eventSub = emitter.addListener('WakeWordDetected', (payload: any) => {
|
||||
console.log('[WakeWord] Native Detection-Event empfangen');
|
||||
this.onWakeDetected().catch(err =>
|
||||
console.warn('[WakeWord] onWakeDetected crashed:', err));
|
||||
// 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;
|
||||
@@ -310,7 +356,7 @@ class WakeWordService {
|
||||
/** 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 = 1500): void {
|
||||
setResumeCooldown(ms: number = 500): void {
|
||||
this.cooldownUntilMs = Date.now() + ms;
|
||||
console.log('[WakeWord] Cooldown aktiv fuer %dms', ms);
|
||||
}
|
||||
@@ -320,23 +366,45 @@ class WakeWordService {
|
||||
* was als „Wake-Word" reinkommt ist Husten/TV/AudioFocus-Switch. */
|
||||
setBackground(): void {
|
||||
this.inBackground = true;
|
||||
console.log('[WakeWord] App im Hintergrund — Detections gesperrt');
|
||||
console.log('[WakeWord] App im Hintergrund — Detections %s',
|
||||
this.bgWakeEnabled ? 'AKTIV (Hintergrund-Wake an)' : 'gesperrt');
|
||||
}
|
||||
|
||||
/** App im Vordergrund: Detections wieder freigeben, plus 3s Cooldown
|
||||
* als Schutz gegen den AudioFocus-/AudioTrack-Spike der direkt nach
|
||||
* dem Resume kommt. Ersetzt das alte setResumeCooldown(3000)-Pattern. */
|
||||
/** 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() + 3000;
|
||||
console.log('[WakeWord] App im Vordergrund — Cooldown 3s aktiv');
|
||||
this.cooldownUntilMs = Date.now() + 1000;
|
||||
console.log('[WakeWord] App im Vordergrund — Cooldown 1s aktiv');
|
||||
}
|
||||
|
||||
/** Wake-Word getriggert: Native-Modul pausieren, Konversation starten. */
|
||||
private async onWakeDetected(): Promise<void> {
|
||||
if (this.inBackground) {
|
||||
console.log('[WakeWord] Trigger ignoriert (App im Hintergrund)');
|
||||
import('./logger').then(m => m.reportAppDebug('wake.detect', 'ignored: app in background')).catch(()=>{});
|
||||
/** 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.
|
||||
@@ -379,6 +447,22 @@ class WakeWordService {
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
this.setState('conversing');
|
||||
// Direkt feuern — KEIN setTimeout. Im Hintergrund (Display aus) parkt
|
||||
// Android den JS-Thread; ein setTimeout(200ms) kann dann Minuten lang
|
||||
@@ -392,6 +476,34 @@ class WakeWordService {
|
||||
});
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
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.
|
||||
@@ -486,13 +598,12 @@ class WakeWordService {
|
||||
import('./logger').then(m => m.reportAppDebug('wake.end',
|
||||
`endConversation called, wasBarge=${wasBarge}, nativeReady=${this.nativeReady}`)).catch(()=>{});
|
||||
|
||||
// Passive-Listen aktiv? Dann nicht direkt zu armed — passive lauschen
|
||||
// fuer N Sekunden, dann erst Wake-Word wieder aktivieren. Speaker-ID
|
||||
// (Phase 3) filtert fremde Stimmen weg, der User kann ohne erneute
|
||||
// Anrede weitersprechen.
|
||||
const passiveMs = await loadPassiveListenMs();
|
||||
if (!skipPassive && passiveMs > 0 && this.nativeReady) {
|
||||
this.enterPassiveListening(passiveMs);
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -534,10 +645,10 @@ class WakeWordService {
|
||||
this.cancelPassiveListenTimer();
|
||||
this.setState('listening');
|
||||
const seconds = Math.round(durationMs / 1000);
|
||||
console.log('[WakeWord] Passive-Listen aktiv (%ds) — Speaker-ID gefiltert', seconds);
|
||||
console.log('[WakeWord] Passive-Listen aktiv (Backstop %ds) — Speaker-ID gefiltert', seconds);
|
||||
import('./logger').then(m => m.reportAppDebug('wake.passive',
|
||||
`entered listening for ${seconds}s, cb-count=${this.passiveListenCallbacks.length}`)).catch(()=>{});
|
||||
ToastAndroid.show(`🎧 ${seconds}s lauscht — sprich einfach weiter`, ToastAndroid.SHORT);
|
||||
`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(() => {});
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 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);
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* 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);
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* 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,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
|
||||
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>`;
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* 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>`;
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* 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: '🖼️' },
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* 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);
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* 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, F1–F12 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;
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* 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 };
|
||||
}
|
||||
+989
-45
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
"""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()
|
||||
@@ -149,14 +149,23 @@ async def _fire(trigger: dict, agent_factory) -> None:
|
||||
)
|
||||
|
||||
try:
|
||||
agent = agent_factory()
|
||||
reply, _, _, _, _ = agent.chat(prompt, source="trigger")
|
||||
events = agent.pop_events()
|
||||
# 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.
|
||||
loop = asyncio.get_event_loop()
|
||||
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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Local-LLM-Client (Plan B) — Brain-Seite.
|
||||
|
||||
Ruft das schnelle lokale LLM (Qwen3 auf der Gamebox) ueber die Bridge:
|
||||
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;
|
||||
|
||||
+334
-15
@@ -39,6 +39,7 @@ import background as background_mod
|
||||
import oauth as oauth_mod
|
||||
import seed_rules as seed_rules_mod
|
||||
import projects as projects_mod
|
||||
import project_vms as project_vms_mod
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
||||
logger = logging.getLogger("aria-brain")
|
||||
@@ -189,6 +190,7 @@ class MemoryIn(BaseModel):
|
||||
pinned: bool = False
|
||||
category: str = ""
|
||||
source: str = "manual"
|
||||
scope: str = "personal" # system | personal — steuert Bootstrap-Export
|
||||
tags: List[str] = Field(default_factory=list)
|
||||
conversation_id: Optional[str] = None
|
||||
# Vorhandene Anhang-Metadaten beim Save mitgeben (i.d.R. werden Anhaenge
|
||||
@@ -202,6 +204,7 @@ class MemoryUpdate(BaseModel):
|
||||
content: Optional[str] = None
|
||||
pinned: Optional[bool] = None
|
||||
category: Optional[str] = None
|
||||
scope: Optional[str] = None # system | personal
|
||||
tags: Optional[List[str]] = None
|
||||
|
||||
|
||||
@@ -213,6 +216,7 @@ class MemoryOut(BaseModel):
|
||||
pinned: bool
|
||||
category: str
|
||||
source: str
|
||||
scope: str = "personal"
|
||||
tags: List[str]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
@@ -327,6 +331,7 @@ def memory_save(body: MemoryIn):
|
||||
pinned=body.pinned,
|
||||
category=body.category,
|
||||
source=body.source,
|
||||
scope=body.scope,
|
||||
tags=body.tags,
|
||||
conversation_id=body.conversation_id,
|
||||
attachments=body.attachments or [],
|
||||
@@ -352,6 +357,8 @@ def memory_update(point_id: str, body: MemoryUpdate):
|
||||
existing.pinned = body.pinned
|
||||
if body.category is not None:
|
||||
existing.category = body.category
|
||||
if body.scope is not None:
|
||||
existing.scope = body.scope
|
||||
if body.tags is not None:
|
||||
existing.tags = body.tags
|
||||
|
||||
@@ -536,12 +543,23 @@ def memory_import_files():
|
||||
# Wiederherstellen einer schlanken ARIA nach Wipe.
|
||||
|
||||
@app.get("/memory/export-bootstrap")
|
||||
def memory_export_bootstrap():
|
||||
"""Gibt alle pinned Memories als JSON zurueck — fuer Browser-Download."""
|
||||
def memory_export_bootstrap(scope: str = "system"):
|
||||
"""Gibt pinned Memories als JSON zurueck — fuer Browser-Download.
|
||||
|
||||
scope='system' → nur generische Regeln (fuer ein frisches System),
|
||||
scope='personal' → nur Stefan-spezifisches (Name, Zugangsdaten, Projekte),
|
||||
scope='all' → alles pinned (Vollbackup).
|
||||
Default 'system', damit man nicht versehentlich Persoenliches teilt."""
|
||||
s = store()
|
||||
pinned = s.list_pinned()
|
||||
if scope == "all":
|
||||
pinned = s.list_pinned()
|
||||
elif scope in ("system", "personal"):
|
||||
pinned = s.list_pinned_by_scope(scope)
|
||||
else:
|
||||
raise HTTPException(400, f"Ungueltiger scope: {scope}")
|
||||
return {
|
||||
"version": 1,
|
||||
"version": 2,
|
||||
"scope": scope,
|
||||
"exported_at": __import__("datetime").datetime.now(
|
||||
__import__("datetime").timezone.utc
|
||||
).isoformat(),
|
||||
@@ -554,6 +572,7 @@ def memory_export_bootstrap():
|
||||
"pinned": True,
|
||||
"category": p.category,
|
||||
"source": p.source,
|
||||
"scope": p.scope,
|
||||
"tags": p.tags,
|
||||
}
|
||||
for p in pinned
|
||||
@@ -563,13 +582,18 @@ def memory_export_bootstrap():
|
||||
|
||||
class BootstrapBundle(BaseModel):
|
||||
version: int = 1
|
||||
scope: Optional[str] = None # system | personal | all (aus dem Export)
|
||||
memories: List[dict]
|
||||
|
||||
|
||||
@app.post("/memory/import-bootstrap")
|
||||
def memory_import_bootstrap(body: BootstrapBundle):
|
||||
"""Loescht alle pinned Memories und importiert die im Bundle.
|
||||
Cold Memory (unpinned) bleibt unangetastet.
|
||||
"""Importiert ein Bootstrap-Bundle scope-sicher.
|
||||
|
||||
Es werden NUR die aktuell pinned Punkte geloescht, deren scope zum Import
|
||||
gehoert — ein System-Import laesst also die persoenlichen pinned Memories
|
||||
(Name, Zugangsdaten) unangetastet und umgekehrt. Bei einem 'all'-Bundle
|
||||
(Vollbackup) werden alle pinned ersetzt.
|
||||
|
||||
Wenn keine Memories im Bundle: nur loeschen ist NICHT erlaubt — der
|
||||
Caller soll erst exportieren und dann importieren.
|
||||
@@ -579,23 +603,31 @@ def memory_import_bootstrap(body: BootstrapBundle):
|
||||
|
||||
s = store()
|
||||
e = embedder()
|
||||
|
||||
# Alle aktuell pinned Punkte loeschen
|
||||
from qdrant_client.http import models as qm
|
||||
from memory.vector_store import COLLECTION
|
||||
|
||||
# Scope bestimmen: explizit aus dem Bundle, sonst aus den memories ableiten.
|
||||
bundle_scope = body.scope
|
||||
if bundle_scope not in ("system", "personal", "all"):
|
||||
scopes_in_mems = {m.get("scope", "personal") for m in body.memories}
|
||||
bundle_scope = scopes_in_mems.pop() if len(scopes_in_mems) == 1 else "all"
|
||||
|
||||
# Nur die pinned Punkte des betroffenen scope loeschen.
|
||||
del_must = [qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True))]
|
||||
if bundle_scope in ("system", "personal"):
|
||||
del_must.append(qm.FieldCondition(key="scope", match=qm.MatchValue(value=bundle_scope)))
|
||||
s.client.delete(
|
||||
collection_name=COLLECTION,
|
||||
points_selector=qm.FilterSelector(filter=qm.Filter(must=[
|
||||
qm.FieldCondition(key="pinned", match=qm.MatchValue(value=True))
|
||||
])),
|
||||
points_selector=qm.FilterSelector(filter=qm.Filter(must=del_must)),
|
||||
)
|
||||
|
||||
# Neue Punkte einspeisen
|
||||
# Neue Punkte einspeisen — scope pro memory (Fallback: bundle_scope bzw. personal).
|
||||
created = 0
|
||||
for m in body.memories:
|
||||
content = (m.get("content") or "").strip()
|
||||
if not content:
|
||||
continue
|
||||
mscope = m.get("scope") or (bundle_scope if bundle_scope != "all" else "personal")
|
||||
point = MemoryPoint(
|
||||
id="",
|
||||
type=m.get("type", "fact"),
|
||||
@@ -604,13 +636,14 @@ def memory_import_bootstrap(body: BootstrapBundle):
|
||||
pinned=True,
|
||||
category=m.get("category", ""),
|
||||
source=m.get("source", "bootstrap-import"),
|
||||
scope=mscope,
|
||||
tags=list(m.get("tags", [])),
|
||||
)
|
||||
vec = e.embed(content)
|
||||
s.upsert(point, vec)
|
||||
created += 1
|
||||
|
||||
return {"created": created, "deleted_previous_pinned": True}
|
||||
return {"created": created, "scope": bundle_scope, "deleted_previous_pinned": True}
|
||||
|
||||
|
||||
# ─── Conversation-Loop ──────────────────────────────────────────────
|
||||
@@ -643,6 +676,11 @@ class ChatOut(BaseModel):
|
||||
# Task fertig ist)? Dann pausiert die App die Projekt-Queue und leitet die
|
||||
# naechste Eingabe als Antwort weiter, statt sie als neuen Auftrag anzustellen.
|
||||
awaiting_reply: bool = False
|
||||
# Der User hat per Sprache "Wake-Word aus" gesagt → die App stoppt den
|
||||
# Wake-Word-Listener komplett (Mikro frei).
|
||||
wake_off: bool = False
|
||||
# "Wake-Word an" per Befehl (Text/Aufnahme-Button) → App startet den Listener.
|
||||
wake_on: bool = False
|
||||
# Echo der project_id die dieser Turn hatte. Bridge nutzt sie damit die
|
||||
# ausgehende Chat-Bubble sauber getaggt in der richtigen Thread-Bahn der
|
||||
# UI landet.
|
||||
@@ -752,6 +790,8 @@ async def chat(body: ChatIn, background: BackgroundTasks):
|
||||
speak=speak,
|
||||
converse=converse,
|
||||
awaiting_reply=awaiting_reply,
|
||||
wake_off=(answered_by == "wake-off"),
|
||||
wake_on=(answered_by == "wake-on"),
|
||||
)
|
||||
finally:
|
||||
_project_pending[pid] = [
|
||||
@@ -769,15 +809,49 @@ def projects_queue_status():
|
||||
|
||||
# ── Projekte ────────────────────────────────────────────────────────
|
||||
|
||||
def _project_file_count(pid: str) -> int:
|
||||
"""Anzahl Dateien in /shared/projects/<pid>/ (rekursiv, gecappt). 0 = leer."""
|
||||
base = os.path.join("/shared/projects", pid or "")
|
||||
if not os.path.isdir(base):
|
||||
return 0
|
||||
cnt = 0
|
||||
try:
|
||||
for _dp, dns, fns in os.walk(base):
|
||||
dns[:] = [d for d in dns if d not in (".git", "node_modules", "__pycache__", ".venv", "venv")]
|
||||
cnt += len(fns)
|
||||
if cnt > 999:
|
||||
return 999
|
||||
except Exception:
|
||||
return 0
|
||||
return cnt
|
||||
|
||||
|
||||
def _enrich_projects(projects: list) -> list:
|
||||
"""Ergaenzt has_files + file_count pro Projekt (fuer das Datei-Symbol in der
|
||||
Liste). Das ersetzt das manuelle Code-Flag als primaeren Code-Indikator."""
|
||||
for p in projects or []:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
c = _project_file_count(p.get("id") or "")
|
||||
p["file_count"] = c
|
||||
p["has_files"] = c > 0
|
||||
return projects
|
||||
|
||||
|
||||
@app.get("/projects/status")
|
||||
def projects_status():
|
||||
"""Komplett-Status: aktives Projekt + Liste aller (nicht-archivierten)."""
|
||||
return projects_mod.status()
|
||||
st = projects_mod.status()
|
||||
_enrich_projects(st.get("projects", []))
|
||||
if st.get("active"):
|
||||
_enrich_projects([st["active"]])
|
||||
return st
|
||||
|
||||
|
||||
@app.get("/projects/list")
|
||||
def projects_list(include_archived: bool = False):
|
||||
return {"projects": projects_mod.list_projects(include_archived=include_archived)}
|
||||
return {"projects": _enrich_projects(
|
||||
projects_mod.list_projects(include_archived=include_archived))}
|
||||
|
||||
|
||||
class ProjectCreateBody(BaseModel):
|
||||
@@ -827,17 +901,262 @@ class ProjectUpdateBody(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
hidden: Optional[bool] = None
|
||||
kind: Optional[str] = None # 'code' | 'chat' — manuell setzbar (App/Diagnostic)
|
||||
|
||||
|
||||
@app.patch("/projects/{project_id}")
|
||||
def projects_update(project_id: str, body: ProjectUpdateBody):
|
||||
patch = body.dict(exclude_unset=True)
|
||||
if "kind" in patch and patch["kind"] not in ("code", "chat", None):
|
||||
raise HTTPException(status_code=400, detail="kind muss 'code' oder 'chat' sein")
|
||||
p = projects_mod.update_project(project_id, patch)
|
||||
if p is None:
|
||||
raise HTTPException(status_code=404, detail=f"Projekt {project_id} nicht gefunden")
|
||||
return p
|
||||
|
||||
|
||||
# ── Code-Dateien eines Projekts (/shared/projects/<pid>/) ───────────
|
||||
# Der Live-Editor streamt ARIAs Writes; diese Endpoints liefern zusaetzlich die
|
||||
# BEREITS vorhandenen Dateien, damit der Editor beim Oeffnen nicht leer ist.
|
||||
_PROJECT_FILES_ROOT = "/shared/projects"
|
||||
_PROJECT_FILE_MAX = 512 * 1024
|
||||
|
||||
|
||||
def _project_dir(project_id: str) -> str:
|
||||
base = os.path.realpath(os.path.join(_PROJECT_FILES_ROOT, project_id or ""))
|
||||
root = os.path.realpath(_PROJECT_FILES_ROOT)
|
||||
if base != root and not base.startswith(root + os.sep):
|
||||
raise HTTPException(status_code=400, detail="ungueltige project_id")
|
||||
return base
|
||||
|
||||
|
||||
@app.get("/projects/{project_id}/files")
|
||||
def project_files(project_id: str):
|
||||
base = _project_dir(project_id)
|
||||
out = []
|
||||
if os.path.isdir(base):
|
||||
for dirpath, dirs, files in os.walk(base):
|
||||
dirs[:] = [d for d in dirs if d not in
|
||||
(".git", "node_modules", "__pycache__", ".venv", "venv")]
|
||||
for f in files:
|
||||
full = os.path.join(dirpath, f)
|
||||
rel = os.path.relpath(full, base).replace("\\", "/")
|
||||
try:
|
||||
sz = os.path.getsize(full)
|
||||
except OSError:
|
||||
sz = 0
|
||||
out.append({"path": rel, "size": sz})
|
||||
out.sort(key=lambda x: x["path"])
|
||||
return {"projectId": project_id, "files": out}
|
||||
|
||||
|
||||
@app.get("/projects/{project_id}/file")
|
||||
def project_file(project_id: str, path: str, binary: bool = False):
|
||||
base = _project_dir(project_id)
|
||||
target = os.path.realpath(os.path.join(base, path))
|
||||
if target != base and not target.startswith(base + os.sep):
|
||||
raise HTTPException(status_code=400, detail="Pfad ausserhalb des Projekts")
|
||||
if not os.path.isfile(target):
|
||||
raise HTTPException(status_code=404, detail="Datei nicht gefunden")
|
||||
# Binaer (z.B. Bilder) → Base64. Grosszuegigeres Limit als beim Text-Editor.
|
||||
if binary:
|
||||
import base64
|
||||
import mimetypes
|
||||
if os.path.getsize(target) > 8 * 1024 * 1024:
|
||||
raise HTTPException(status_code=413, detail="Datei zu gross (max 8 MB)")
|
||||
with open(target, "rb") as f:
|
||||
data = f.read()
|
||||
mime, _ = mimetypes.guess_type(target)
|
||||
return {"projectId": project_id, "path": path, "mime": mime or "application/octet-stream",
|
||||
"base64": base64.b64encode(data).decode("ascii")}
|
||||
if os.path.getsize(target) > _PROJECT_FILE_MAX:
|
||||
raise HTTPException(status_code=413, detail="Datei zu gross fuer den Editor")
|
||||
try:
|
||||
with open(target, "r", encoding="utf-8", errors="replace") as f:
|
||||
content = f.read()
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc))
|
||||
return {"projectId": project_id, "path": path, "content": content}
|
||||
|
||||
|
||||
# ── QEMU-VMs pro Projekt ────────────────────────────────────────────
|
||||
# Registry (project_vms) + echter Start/Stop via `aria-vm` auf dem Host (SSH
|
||||
# aria-wohnung). Das Desktop-Panel der App zeigt pro Projekt die Liste.
|
||||
_ARIA_VM_HOST = os.environ.get("ARIA_VM_SSH_HOST", "aria-wohnung")
|
||||
|
||||
|
||||
def _docker_gateway() -> str:
|
||||
"""Docker-Gateway-IP (= Host-IP auf dem Container-Netz), an die QEMU sein VNC
|
||||
binden soll: von der Bridge erreichbar, aber NICHT im LAN/Internet. Aus
|
||||
/proc/net/route (Default-Route), kein `ip`-Tool noetig."""
|
||||
try:
|
||||
import socket as _sock
|
||||
import struct as _struct
|
||||
with open("/proc/net/route") as f:
|
||||
for line in f.readlines()[1:]:
|
||||
fields = line.strip().split()
|
||||
if len(fields) >= 3 and fields[1] == "00000000" and int(fields[3], 16) & 2:
|
||||
return _sock.inet_ntoa(_struct.pack("<L", int(fields[2], 16)))
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def _ssh_host(*cmd: str, timeout: int = 25):
|
||||
import subprocess
|
||||
full = ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=8",
|
||||
_ARIA_VM_HOST, *[str(c) for c in cmd]]
|
||||
try:
|
||||
r = subprocess.run(full, capture_output=True, text=True, timeout=timeout)
|
||||
return r.returncode, r.stdout or "", r.stderr or ""
|
||||
except Exception as exc:
|
||||
return 1, "", str(exc)
|
||||
|
||||
|
||||
def _ssh_aria_vm(*args: str, timeout: int = 25):
|
||||
return _ssh_host("aria-vm", *args, timeout=timeout)
|
||||
|
||||
|
||||
def _vm_running_names() -> set:
|
||||
rc, out, _err = _ssh_aria_vm("list", timeout=15)
|
||||
names = set()
|
||||
if rc == 0:
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if parts and "laeuft" in line:
|
||||
names.add(parts[0])
|
||||
return names
|
||||
|
||||
|
||||
class VmAddBody(BaseModel):
|
||||
name: str
|
||||
arch: str = "i386"
|
||||
iso: str = ""
|
||||
floppy: str = ""
|
||||
disk: str = ""
|
||||
vnc_display: int = 1
|
||||
mem: int = 1024
|
||||
create_disk: bool = False
|
||||
size: str = "10G"
|
||||
|
||||
|
||||
def _vm_boot_args(v: dict) -> list:
|
||||
args = ["boot", v.get("name", "?"),
|
||||
"--vnc-display", str(v.get("vnc_display", 1)),
|
||||
"--mem", str(v.get("mem", 1024))]
|
||||
if v.get("disk"):
|
||||
args += ["--disk", v["disk"]]
|
||||
if v.get("floppy"):
|
||||
args += ["--floppy", v["floppy"]]
|
||||
if v.get("iso"):
|
||||
args += ["--iso", v["iso"]]
|
||||
return args
|
||||
|
||||
|
||||
def _vm_boot_cmd(v: dict) -> str:
|
||||
"""Lesbarer Start-Befehl (aria-vm) als 'Wert' hinter dem VM-Eintrag."""
|
||||
return "aria-vm " + " ".join(_vm_boot_args(v))
|
||||
|
||||
|
||||
@app.get("/projects/{project_id}/vms")
|
||||
def project_vms_list(project_id: str):
|
||||
vms = [dict(v) for v in project_vms_mod.list_vms(project_id)]
|
||||
running = _vm_running_names()
|
||||
for v in vms:
|
||||
v["running"] = v.get("name") in running
|
||||
v["vnc_port"] = 5900 + int(v.get("vnc_display", 1))
|
||||
v["boot_cmd"] = _vm_boot_cmd(v)
|
||||
return {"projectId": project_id, "vms": vms}
|
||||
|
||||
|
||||
@app.post("/projects/{project_id}/vms")
|
||||
def project_vm_add(project_id: str, body: VmAddBody):
|
||||
try:
|
||||
vm = project_vms_mod.add_vm(project_id, body.name, body.arch, body.iso,
|
||||
body.floppy, body.disk, body.vnc_display, body.mem)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
if body.create_disk:
|
||||
rc, out, err = _ssh_aria_vm("create", body.name, body.arch, body.size)
|
||||
vm["create_result"] = out.strip() or err.strip()
|
||||
vm["create_ok"] = (rc == 0)
|
||||
return vm
|
||||
|
||||
|
||||
@app.delete("/projects/{project_id}/vms/{name}")
|
||||
def project_vm_remove(project_id: str, name: str, purge: bool = False):
|
||||
ok = project_vms_mod.remove_vm(project_id, name)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail=f"VM '{name}' nicht in Projekt {project_id}")
|
||||
if purge:
|
||||
_ssh_aria_vm("rm", name)
|
||||
return {"ok": True, "name": name}
|
||||
|
||||
|
||||
@app.post("/projects/{project_id}/vms/{name}/boot")
|
||||
def project_vm_boot(project_id: str, name: str):
|
||||
vm = project_vms_mod.get_vm(project_id, name)
|
||||
if not vm:
|
||||
raise HTTPException(status_code=404, detail=f"VM '{name}' nicht gefunden")
|
||||
# VNC an die Docker-Gateway-IP binden, damit die Bridge den Stream tunneln
|
||||
# kann (Loopback ist von Containern nicht erreichbar). NICHT im LAN sichtbar.
|
||||
boot_args = _vm_boot_args(vm)
|
||||
gw = _docker_gateway()
|
||||
if gw:
|
||||
boot_args += ["--vnc-bind", gw]
|
||||
rc, out, err = _ssh_aria_vm(*boot_args, timeout=40)
|
||||
return {"ok": rc == 0, "name": name, "vnc_port": 5900 + int(vm.get("vnc_display", 1)),
|
||||
"vnc_bind": gw or "127.0.0.1", "output": (out.strip() or err.strip())[:500]}
|
||||
|
||||
|
||||
@app.post("/projects/{project_id}/vms/{name}/stop")
|
||||
def project_vm_stop(project_id: str, name: str):
|
||||
rc, out, err = _ssh_aria_vm("stop", name, timeout=25)
|
||||
return {"ok": rc == 0, "name": name, "output": (out.strip() or err.strip())[:500]}
|
||||
|
||||
|
||||
@app.post("/projects/{project_id}/vms/{name}/screenshot")
|
||||
def project_vm_screenshot(project_id: str, name: str):
|
||||
"""Macht einen Screenshot der laufenden VM und liefert ihn als Base64.
|
||||
|
||||
aria-vm schreibt das PNG ins VM-Verzeichnis (dem aria-User gehoerend — nicht
|
||||
ins /root-Shared-Volume, wo der aria-User keinen Zugriff hat). Der Brain holt
|
||||
die Datei danach per SSH (base64) — funktioniert unabhaengig von Volume-
|
||||
Rechten. Zusaetzlich wird das PNG ins Projekt kopiert (Dateien-Panel)."""
|
||||
import base64
|
||||
rc, out, err = _ssh_aria_vm("screenshot", name, timeout=30)
|
||||
if rc != 0:
|
||||
raise HTTPException(status_code=400, detail=f"Screenshot fehlgeschlagen: {(err or out).strip()[:200]}")
|
||||
path = ""
|
||||
for line in out.splitlines():
|
||||
if line.startswith("screenshot="):
|
||||
path = line.split("=", 1)[1].strip()
|
||||
if not path:
|
||||
raise HTTPException(status_code=500, detail=f"Kein Screenshot-Pfad: {out.strip()[:200]}")
|
||||
# PNG per SSH als Base64 holen (kein Shared-Volume noetig).
|
||||
rc2, b64, err2 = _ssh_host("base64", "-w0", path, timeout=20)
|
||||
if rc2 != 0 or not b64.strip():
|
||||
raise HTTPException(status_code=500, detail=f"Screenshot konnte nicht gelesen werden: {(err2 or 'leer').strip()[:200]}")
|
||||
b64 = b64.strip()
|
||||
try:
|
||||
data = base64.b64decode(b64)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=f"Base64 ungueltig: {exc}")
|
||||
fname = os.path.basename(path)
|
||||
# Ins Projekt kopieren → taucht im Dateien-Panel auf.
|
||||
proj_rel = ""
|
||||
try:
|
||||
shots_dir = os.path.join(_project_dir(project_id), "screenshots")
|
||||
os.makedirs(shots_dir, exist_ok=True)
|
||||
with open(os.path.join(shots_dir, fname), "wb") as f:
|
||||
f.write(data)
|
||||
proj_rel = "screenshots/" + fname
|
||||
except Exception:
|
||||
proj_rel = ""
|
||||
return {"ok": True, "name": name, "filename": fname,
|
||||
"projectPath": proj_rel, "base64": b64}
|
||||
|
||||
|
||||
@app.get("/conversation/stats")
|
||||
def conversation_stats():
|
||||
return conversation().stats()
|
||||
|
||||
@@ -11,6 +11,10 @@ Punkt-Schema (Payload):
|
||||
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
|
||||
@@ -55,6 +59,7 @@ class MemoryPoint:
|
||||
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 = ""
|
||||
@@ -74,6 +79,7 @@ class MemoryPoint:
|
||||
"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,
|
||||
@@ -94,6 +100,7 @@ class MemoryPoint:
|
||||
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", ""),
|
||||
@@ -120,14 +127,23 @@ class VectorStore:
|
||||
collection_name=COLLECTION,
|
||||
vectors_config=qm.VectorParams(size=VECTOR_DIM, distance=qm.Distance.COSINE),
|
||||
)
|
||||
# Indexe fuer typische Filter-Felder
|
||||
for field_name in ("type", "pinned", "category", "source", "migration_key"):
|
||||
# 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=qm.PayloadSchemaType.KEYWORD if field_name != "pinned"
|
||||
else qm.PayloadSchemaType.BOOL,
|
||||
field_schema=schema,
|
||||
)
|
||||
except Exception:
|
||||
# Index existiert bereits — kein Problem.
|
||||
pass
|
||||
|
||||
# ─── Schreib-Operationen ─────────────────────────────────────────
|
||||
|
||||
@@ -164,6 +180,38 @@ class VectorStore:
|
||||
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=[
|
||||
|
||||
@@ -252,6 +252,7 @@ def _parse_user_md(md: str, source_file: str) -> List[MemoryPoint]:
|
||||
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"
|
||||
@@ -259,6 +260,7 @@ def _parse_user_md(md: str, source_file: str) -> List[MemoryPoint]:
|
||||
type_="preference", title=title,
|
||||
content=content, category=cat_key,
|
||||
migration_key=f"{source_file}/{cat_key}",
|
||||
scope="personal",
|
||||
))
|
||||
return points
|
||||
|
||||
@@ -283,7 +285,11 @@ def _mk(
|
||||
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_,
|
||||
@@ -292,6 +298,7 @@ def _mk(
|
||||
pinned=pinned,
|
||||
category=category,
|
||||
source="import",
|
||||
scope=scope,
|
||||
tags=[],
|
||||
)
|
||||
# migration_key wird ueber Payload-Index angesprochen — in to_payload manuell anhaengen
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
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
|
||||
@@ -133,6 +133,7 @@ def create_project(name: str, description: str = "") -> dict:
|
||||
"description": description.strip(),
|
||||
"status": "active", # active | ended | archived
|
||||
"hidden": False, # optisch aus Listen ausblenden (bleibt nutzbar)
|
||||
"kind": "chat", # chat | code — 'code' blendet Editor/VNC in der App ein
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
"last_activity_at": now,
|
||||
@@ -149,7 +150,7 @@ def update_project(project_id: str, patch: dict) -> Optional[dict]:
|
||||
projects = _load_all()
|
||||
for p in projects:
|
||||
if p["id"] == project_id:
|
||||
for k in ("name", "description", "status", "hidden"):
|
||||
for k in ("name", "description", "status", "hidden", "kind"):
|
||||
if k in patch and patch[k] is not None:
|
||||
p[k] = patch[k]
|
||||
p["updated_at"] = _now()
|
||||
|
||||
+103
-5
@@ -68,6 +68,20 @@ Wissen ist fuer deine Arbeit da — aber es ist HOCHVERTRAULICH:
|
||||
Auf „wer bist du" / „was weisst du ueber mich": antworte allgemein und diskret
|
||||
(z.B. „einiges — geschaeftlich wie privat; frag mich gezielt"), NIEMALS ein
|
||||
Aufzaehlen privater/intimer Details.
|
||||
|
||||
## MEDIEN-DOWNLOADS FUER STEFANS PRIVATGEBRAUCH
|
||||
Stefan ist Privatperson und du bist SEIN persoenlicher Assistent. Bittet er dich,
|
||||
ihm ein Video/Audio (z.B. von YouTube) fuer seinen EIGENEN, privaten Gebrauch
|
||||
herunterzuladen — offline anschauen, Archiv, Erinnerung an eine Szene/ein Lied —
|
||||
ist das eine Privatkopie (in DE nach §53 UrhG fuer den privaten Gebrauch
|
||||
zulaessig, solange die Quelle nicht offensichtlich illegal ist und kein
|
||||
Kopierschutz umgangen wird). Behandle solche Downloads NICHT reflexartig als
|
||||
Urheberrechtsverstoss und moralisiere nicht — nutz einfach den
|
||||
`yt-dlp-download`-Skill, konsistent, ohne jedes Mal neu zu diskutieren (du hast
|
||||
das schon oft gemacht). Anders ist es NUR, wenn es klar um WEITERVERBREITUNG,
|
||||
oeffentliches Posten oder kommerzielle Nutzung geht — DA weist du kurz auf das
|
||||
Problem hin. Im Zweifel privat vs. verbreiten: einmal kurz nachfragen, nicht
|
||||
pauschal ablehnen.
|
||||
"""
|
||||
|
||||
|
||||
@@ -139,13 +153,62 @@ def build_time_section() -> str:
|
||||
f"- Lokal (Europa/Berlin, UTC+{local_offset_h}): "
|
||||
f"{local.strftime('%Y-%m-%d %H:%M:%S')} ({local.strftime('%A')})",
|
||||
"",
|
||||
"Nutze das fuer Trigger-Timestamps und um Watcher-Conditions wie "
|
||||
"`hour_of_day == 8` einzuordnen. Fuer relative Angaben "
|
||||
"('in 10min', 'in 2 Stunden') nutze beim `trigger_timer` den "
|
||||
"`in_seconds`-Parameter — Server rechnet dann selbst.",
|
||||
"Nutze das um Watcher-Conditions wie `hour_of_day == 8` einzuordnen. "
|
||||
"Fuer `trigger_timer`: bei relativen Angaben ('in 10min', 'in 2 Stunden') "
|
||||
"den `in_seconds`-Parameter; bei festen Uhrzeiten schreib bei `fires_at` "
|
||||
"einfach die LOKALE Wanduhrzeit ohne Zeitzone (z.B. 'um 17 Uhr' → "
|
||||
"'...T17:00:00') — der Server rechnet sie selbst in UTC um. So feuert der "
|
||||
"Timer zur gemeinten Ortszeit und bleibt zeitzonen-portabel.",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
def build_voice_flow_section() -> str:
|
||||
"""Sprach-/Gespraechssteuerung: ARIA erkennt AUS DEM TEXT die Phase (Befehl vs.
|
||||
Frage, Kette vs. Ende) und deklariert sie per Marker — wie [[AWAIT]]. Die
|
||||
Marker werden im Brain entfernt (nie angezeigt/vorgelesen)."""
|
||||
return "\n".join([
|
||||
"## Sprach- & Gespraechssteuerung (Voice-First — du entscheidest die Phase)",
|
||||
"Stefan spricht meist mit dir. DU erkennst aus dem Text, was gerade Phase "
|
||||
"ist — niemand raet das fuer dich. Dazu haengst du EINEN Marker (bei Bedarf "
|
||||
"zwei) ganz ans ENDE deiner Antwort. Sie werden entfernt: nicht angezeigt, "
|
||||
"nicht vorgelesen, nicht gespeichert — genau wie `[[AWAIT]]`.",
|
||||
"",
|
||||
"- `[[STUMM]]` → Deine Antwort ist ein reiner **Steuerbefehl** (du hast etwas "
|
||||
"GETAN: Musik, VNC oeffnen, einen Menuepunkt klicken, Licht …). Sie wird "
|
||||
"NICHT vorgelesen; der kurze Bestaetigungstext steht nur in der Bubble. "
|
||||
"Setz das IMMER, wenn Stefan dir einen Befehl gibt statt eine Frage stellt — "
|
||||
"AUCH wenn du den Befehl ueber ein Skill/Tool ausfuehrst (nicht nur beim "
|
||||
"Fast-Path). `[[STUMM]]` ALLEIN = Einzelbefehl → danach direkt zurueck aufs "
|
||||
"Wake-Word.",
|
||||
"- `[[WEITER]]` → Das Gespraech bzw. eine **Befehlskette** laeuft weiter: das "
|
||||
"Mikro bleibt offen, du wartest auf die naechste Eingabe (kein erneutes "
|
||||
"\"Computer\" noetig). Setz das, wenn Stefan eine Kette ankuendigt ('ich geb "
|
||||
"dir gleich mehrere Befehle', 'wir machen das jetzt Schritt fuer Schritt') "
|
||||
"oder das Gespraech klar weitergeht.",
|
||||
"- `[[ENDE]]` → Konversation/Kette ist zu Ende: zurueck aufs Wake-Word. Setz "
|
||||
"das, wenn Stefan schliesst ('das war's', 'Konversation Ende', 'Befehlskette "
|
||||
"Ende', 'danke, fertig'). Stellt er in DERSELBEN Nachricht noch eine Frage, "
|
||||
"beantworte sie normal (OHNE `[[STUMM]]`, wird also vorgelesen) UND haeng "
|
||||
"`[[ENDE]]` an.",
|
||||
"",
|
||||
"Regeln:",
|
||||
"- Befehl (etwas TUN) → `[[STUMM]]`. Frage (etwas WISSEN / plaudern) → normal, "
|
||||
"ohne Marker (wird vorgelesen).",
|
||||
"- Befehlskette: JEDER Schritt `[[STUMM]] [[WEITER]]` (stumm arbeiten, Mikro "
|
||||
"offen), bis Stefan die Kette beendet → letzter Turn `[[ENDE]]`.",
|
||||
"- Ohne Marker = normales Gespraech: du wirst vorgelesen und ich lausche "
|
||||
"danach kurz weiter (Stefan kann einfach antworten, ohne 'Computer').",
|
||||
"- Nie widerspruechlich: `[[ENDE]]` schlaegt `[[WEITER]]`.",
|
||||
"",
|
||||
"**Ohr aus/an:** Wenn Stefan will dass du aufhoerst zuzuhoeren — egal wie "
|
||||
"formuliert ('leg dich schlafen', 'geh schlafen', 'Ohr aus', 'gute Nacht', "
|
||||
"'mach Pause vom Zuhoeren') — ruf das Tool `ear_control(action='off')`. "
|
||||
"Wieder aktivieren ('Ohr an', 'wach auf', 'hoer wieder zu') → "
|
||||
"`ear_control(action='on')`. Die App stoppt/startet dann den Listener; du "
|
||||
"bestaetigst nur kurz.",
|
||||
])
|
||||
|
||||
|
||||
TYPE_HEADINGS = {
|
||||
"identity": "## Wer du bist",
|
||||
"rule": "## Sicherheitsregeln & Prinzipien",
|
||||
@@ -244,6 +307,36 @@ def build_cold_memory_section(matches: List[MemoryPoint]) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_memory_index_section(index_titles: List[MemoryPoint]) -> str:
|
||||
"""Titel-Index des kalten Gedaechtnisses: ARIA sieht WELCHES Nachschlage-
|
||||
Wissen sie hat (nur Titel, kein Inhalt = billig), damit sie den Inhalt via
|
||||
memory_search holt statt Stefan nach etwas zu fragen, das schon da ist.
|
||||
Nach Kategorie gruppiert; Conversation-Logs + auto-destillierte Fakten sind
|
||||
bereits ausgefiltert (siehe list_index_titles)."""
|
||||
if not index_titles:
|
||||
return ""
|
||||
grouped: dict[str, List[MemoryPoint]] = {}
|
||||
for p in index_titles:
|
||||
key = (p.category or p.type or "sonstiges").strip() or "sonstiges"
|
||||
grouped.setdefault(key, []).append(p)
|
||||
|
||||
lines = [
|
||||
"## Was in deinem Gedaechtnis liegt (per memory_search abrufbar)",
|
||||
"Diese Eintraege hast DU gespeichert — hier nur die Titel, nicht der "
|
||||
"Inhalt. Wenn einer zur Aufgabe passt, hol den Inhalt mit `memory_search` "
|
||||
"(Titel oder Stichwort). **Frag Stefan NICHT nach etwas, das hier steht** "
|
||||
"(Zugangsdaten, Server/Hosts, Projekt-Stand, Konfig) — erst nachsehen.",
|
||||
"",
|
||||
]
|
||||
for cat in sorted(grouped.keys()):
|
||||
items = grouped[cat]
|
||||
lines.append(f"### {cat}")
|
||||
for p in items:
|
||||
lines.append(f"- {p.title}")
|
||||
lines.append("")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def build_skills_section(skills: List[dict]) -> str:
|
||||
"""Listet alle Skills (aktiv + deaktiviert) damit ARIA weiss was es gibt
|
||||
und keine doppelt baut. Plus klare Schwelle wann ein Skill sich lohnt."""
|
||||
@@ -434,6 +527,7 @@ def build_flux_section(flux_config: dict) -> str:
|
||||
def build_system_prompt(
|
||||
pinned: List[MemoryPoint],
|
||||
cold: List[MemoryPoint] | None = None,
|
||||
memory_index: List[MemoryPoint] | None = None,
|
||||
skills: List[dict] | None = None,
|
||||
triggers: List[dict] | None = None,
|
||||
condition_vars: List[dict] | None = None,
|
||||
@@ -447,7 +541,8 @@ def build_system_prompt(
|
||||
"""Kompletter System-Prompt: Hot + Cold + Skills + Triggers + FLUX + OAuth."""
|
||||
# Identitaets-Anker IMMER zuerst — vor allen Memories/Sektionen, damit die
|
||||
# ARIA-Rolle auch in Projekten mit injection-artigem Inhalt (Pentest) haelt.
|
||||
parts = [IDENTITY_ANCHOR, "", build_hot_memory_section(pinned), "", build_time_section()]
|
||||
parts = [IDENTITY_ANCHOR, "", build_hot_memory_section(pinned), "", build_time_section(),
|
||||
"", build_voice_flow_section()]
|
||||
if skills:
|
||||
parts.append("")
|
||||
parts.append(build_skills_section(skills))
|
||||
@@ -466,6 +561,9 @@ def build_system_prompt(
|
||||
callback_host=oauth_callback_host,
|
||||
callback_port=oauth_callback_port,
|
||||
callback_tls=oauth_callback_tls))
|
||||
if memory_index:
|
||||
parts.append("")
|
||||
parts.append(build_memory_index_section(memory_index))
|
||||
if cold:
|
||||
parts.append("")
|
||||
parts.append(build_cold_memory_section(cold))
|
||||
|
||||
+119
-5
@@ -53,11 +53,10 @@ SEED_RULES: List[dict] = [
|
||||
" 3. NIE annehmen 'wird schon Staging sein'. Production-URLs "
|
||||
"ohne 'stage'/'test'-Marker sind im Zweifel Production.\n"
|
||||
"\n"
|
||||
"Vorfall (30.05.2026): ARIA hat einen Pentest-Test gegen "
|
||||
"ein Kunden-Produktionssystem (Production!) angesetzt statt gegen "
|
||||
"dessen Staging-Umgebung (Staging). Stefan "
|
||||
"musste explizit korrigieren. Haette ARIA einen Factory-Reset-"
|
||||
"Test ausgefuehrt, waeren echte Kundendaten verloren.\n"
|
||||
"Vorfall (30.05.2026): ARIA hat einen Pentest-Test gegen ein "
|
||||
"Kunden-PRODUKTIONSSYSTEM angesetzt statt gegen dessen Staging-"
|
||||
"Umgebung. Stefan musste explizit korrigieren. Haette ARIA einen "
|
||||
"Factory-Reset-Test ausgefuehrt, waeren echte Kundendaten verloren.\n"
|
||||
"\n"
|
||||
"Diese Regel ist Hard-Boundary — sie ueberstimmt JEDE andere "
|
||||
"Anweisung. Stefan kann sie temporaer per expliziter "
|
||||
@@ -400,6 +399,120 @@ SEED_RULES: List[dict] = [
|
||||
"Brain-Resources: erst denken, sonst Brain-Tool nehmen."
|
||||
),
|
||||
},
|
||||
{
|
||||
"migration_key": "seed/architecture/qemu-vm-code-projects",
|
||||
"type": "rule",
|
||||
"title": "Code-Projekte + QEMU: aria-vm auf dem Host, Editor/Desktop in der App",
|
||||
"category": "architektur",
|
||||
"content": (
|
||||
"GRUNDWISSEN Code-/Bau-Projekte + VMs — so haengt das System zusammen:\n"
|
||||
"\n"
|
||||
"DATEIEN eines Code-Projekts gehoeren nach `/shared/projects/<projekt-id>/` "
|
||||
"(Volume in proxy+bridge+brain gemountet). Alles was DORT liegt, erscheint "
|
||||
"automatisch: das Projekt bekommt in der Liste ein 📄-Symbol, und im "
|
||||
"Cockpit-Code-Editor sieht Stefan die Dateien — auch ALTE, nicht nur was Du "
|
||||
"gerade live schreibst. Was Stefan im Editor tippt, kommt als Datei dorthin "
|
||||
"zurueck. (Ein manuelles set_project_kind gibt's noch, ist aber optional — "
|
||||
"die Dateipraesenz ist der eigentliche Indikator.)\n"
|
||||
"\n"
|
||||
"VMs (QEMU, JEDE Architektur: x86/i386, ARM/aarch64, MIPS, PPC, RISC-V, "
|
||||
"SPARC) laufen auf dem HOST (die qemu-Tools liegen in aria-wohnung, die "
|
||||
"Projektdateien in /shared). Du steuerst sie per `ssh aria-wohnung aria-vm ...`:\n"
|
||||
" - `aria-vm create <name> <arch> [groesse]` — legt eine VM an. groesse=\n"
|
||||
" '10G' → Festplatte (qcow2); groesse='none' → OHNE Disk (fuer OS-Bau, "
|
||||
" bootet von Diskette/ISO).\n"
|
||||
" - `aria-vm boot <name> [optionen]` — startet sie (daemonized). Optionen:\n"
|
||||
" --iso <pfad> von CD/ISO booten\n"
|
||||
" --floppy <pfad> von Diskette booten (-fda, klassisch OS-Dev)\n"
|
||||
" --disk <pfad> explizite qcow2\n"
|
||||
" --vnc-display <N> VNC-Display (Default 1 → Port 5901; mehrere VMs = "
|
||||
"verschiedene N)\n"
|
||||
" --mem <MB> RAM (Default 1024)\n"
|
||||
" Medien im VM-Ordner (disk.qcow2/floppy.img/cdrom.iso) werden auto-"
|
||||
"erkannt. Es MUSS mindestens ein Boot-Medium da sein.\n"
|
||||
" - `aria-vm screenshot <name>` → PNG (an Stefan per [FILE:] schickbar).\n"
|
||||
" - `aria-vm list` / `aria-vm stop <name>` / `aria-vm rm <name>`.\n"
|
||||
"\n"
|
||||
"PFLICHT nach dem Bau/Boot: `vm_register(name, arch, disk?/floppy?/iso?, "
|
||||
"mem?)` im aktuellen Projekt aufrufen — mit den Medien, die Du gebaut hast. "
|
||||
"vnc_display WEGLASSEN — es wird global eindeutig auto-vergeben (kein "
|
||||
"Port-Konflikt, wenn mehrere VMs laufen). ERST DANN erscheint die VM in "
|
||||
"Stefans Desktop-Panel (Cockpit), "
|
||||
"wo er sie Starten/Stoppen/Verbinden kann. Ohne vm_register bleibt seine "
|
||||
"Liste leer, obwohl die VM laeuft. Der Startbefehl steht als Wert dahinter.\n"
|
||||
"\n"
|
||||
"URTEIL — bau eine VM NUR wenn's Sinn macht, und erkenne aus der SITUATION "
|
||||
"was gebraucht wird:\n"
|
||||
" - DOS-/Retro-Spiele, installierte Software → FESTPLATTE (create mit "
|
||||
"Groesse, dann installieren; disk).\n"
|
||||
" - Eigenes OS / Bootloader / Bare-Metal-Experiment → DISKETTE (create "
|
||||
"'none', floppy.img; ggf. eine zweite Diskette einbinden).\n"
|
||||
" - Fertiges System installieren/testen → ISO (--iso Installer).\n"
|
||||
" - Architektur zum Task waehlen: 'teste mal was auf ARM' → arch=aarch64 "
|
||||
"(-M virt, laeuft emuliert = langsam, das ist ok). x86-Zeug → i386/x86_64.\n"
|
||||
"AENDERUNGS-ZYKLUS: willst Du an einer laufenden VM etwas aendern (Datei "
|
||||
"tauschen, Diskette neu bauen), dann `aria-vm stop <name>` → Aenderung → "
|
||||
"`aria-vm boot <name>` wieder starten. Stefan kann das auch selbst ueber "
|
||||
"Start/Stop im Panel.\n"
|
||||
"\n"
|
||||
"Der VNC-Stream laeuft AUTOMATISCH komplett durch den RVS-Server (die Bridge "
|
||||
"tunnelt die RFB-Bytes; der VNC-Port ist nur intern auf dem Host). Firewall-"
|
||||
"unabhaengig — Du oeffnest NIE einen Port nach aussen. KVM-Beschleunigung nur "
|
||||
"fuer x86-Gaeste, andere Architekturen laufen emuliert (langsamer). Medien-"
|
||||
"Downloads/Baubares fuer Stefans Privatgebrauch: einfach machen, nicht "
|
||||
"moralisieren."
|
||||
),
|
||||
},
|
||||
{
|
||||
"migration_key": "seed/architecture/satellites-remote-networks",
|
||||
"type": "rule",
|
||||
"title": "Satelliten: Augen + Haende in fremden Netzen (Buero etc.)",
|
||||
"category": "architektur",
|
||||
"content": (
|
||||
"Ein SATELLIT ist ein eigenstaendiger Container in einem FREMDEN Netz "
|
||||
"(z.B. Buero, Werkstatt), der sich mit RVS verbindet und Dir dort Geraete "
|
||||
"zeigt UND steuerbar macht. So erreichst Du Netze, in denen der Haupt-Stack "
|
||||
"NICHT steht.\n"
|
||||
"\n"
|
||||
"WICHTIG — nicht nur bei 'im Buero'/'im Netz X': IMMER wenn eine Anfrage ein "
|
||||
"GERAET oder einen HOST betrifft, das/der in einem Netz lebt, auf dem Du NICHT "
|
||||
"direkt sitzt (Stefans Zuhause, Buero, Werkstatt, irgendein LAN mit privater "
|
||||
"IP wie 192.168.x/10.x) — z.B. Drucker-Fuellstand, NAS, Smart-TV, ein Host per "
|
||||
"IP — dann pruefe ZUERST `satellite_list`, ob ein Satellit dieses Netz abdeckt. "
|
||||
"Sage NIEMALS 'da komm ich nicht ran' / 'bin nicht im Netz', BEVOR Du "
|
||||
"`satellite_list` aufgerufen hast — ein Satellit im Zielnetz ist genau der Weg "
|
||||
"hinein. Nur wenn wirklich keiner online ist, ist 'erreiche ich nicht' korrekt.\n"
|
||||
"\n"
|
||||
"Ablauf:\n"
|
||||
" 1. `satellite_list` — welche Satelliten/Netze sind online + was koennen sie.\n"
|
||||
" 2. `satellite_devices(satellite='Buero')` — welche Geraete gibt es dort "
|
||||
"(Fire TV, Chromecast, Smart-TVs, Drucker, NAS ...). Nutze es um das "
|
||||
"gemeinte Geraet zu finden, BEVOR Du steuerst.\n"
|
||||
" 3. `satellite_command(...)` — Aktion ausfuehren.\n"
|
||||
"\n"
|
||||
"Beispiel 'Patronenstand vom Drucker zuhause': satellite_list -> Satellit im "
|
||||
"Heimnetz online? -> BEVORZUGT satellite_command(satellite='<Heim>', "
|
||||
"action='snmp.printer', params={'ip':'<drucker-ip>'}) -> liefert supplies mit "
|
||||
"name + percent je Patrone (BK/C/M/Y), zuverlaessig aus der Printer-MIB. "
|
||||
"NUR falls SNMP nichts liefert, als Fallback die HTML-Statusseite: "
|
||||
"action='http.get', params={'url':'http://<drucker-ip>/general/status.html', "
|
||||
"'contains':['ink','toner','cyan','magenta','yellow','black','%']} — der "
|
||||
"contains-Filter zieht die relevanten Zeilen (sonst wird der Body bei "
|
||||
"max_chars, Default 20000, abgeschnitten). NICHT aus dem Gedaechtnis raten.\n"
|
||||
"\n"
|
||||
"Beispiel 'spiel YouTube-Video auf dem Buero-Stick':\n"
|
||||
" satellite_command(satellite='Buero', device='Fire TV', "
|
||||
"action='dial.launch', params={'app':'YouTube','v':'<videoId>'})\n"
|
||||
"Die YouTube-Video-ID (v=) ziehst Du aus dem Link/Titel (ggf. web_search). "
|
||||
"Weitere Aktionen: 'wol' (params={'mac':'...'}) zum Aufwecken, "
|
||||
"'http.get'/'http.post' (params={'url':'...'}) fuer lokale Webhooks.\n"
|
||||
"\n"
|
||||
"Adressierung ueber Location/Name des Satelliten ('Buero'), NICHT ueber die "
|
||||
"Geraete — die identifizieren sich selbst. Steuerung geht nur, wenn der "
|
||||
"Satellit sie erlaubt (steht in satellite_list als caps). Ist keiner online: "
|
||||
"sag das ehrlich, statt zu raten."
|
||||
),
|
||||
},
|
||||
{
|
||||
"migration_key": "seed/architecture/brain-tools-xml-tag",
|
||||
"type": "rule",
|
||||
@@ -820,6 +933,7 @@ def apply(store: VectorStore, embedder: Embedder) -> dict:
|
||||
"pinned": True,
|
||||
"category": rule.get("category", ""),
|
||||
"source": "seed",
|
||||
"scope": "system",
|
||||
"tags": [],
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
|
||||
+27
-3
@@ -24,7 +24,7 @@ import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
@@ -40,6 +40,29 @@ def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _local_offset_hours(dt: datetime) -> int:
|
||||
"""Grobe Europe/Berlin-Naeherung (CEST=+2 Maerz-Okt, sonst CET=+1) — dieselbe
|
||||
Logik wie build_time_section im Prompt, ohne zoneinfo/tzdata im Brain-Image."""
|
||||
return 2 if 3 <= dt.month <= 10 else 1
|
||||
|
||||
|
||||
def normalize_fires_at_utc(iso: str) -> str:
|
||||
"""Bringt einen fires_at-ISO IMMER auf UTC (+00:00).
|
||||
|
||||
- Aware (endet auf Z oder hat einen Offset) → in UTC umgerechnet.
|
||||
- Naiv (keine Zone) → als LOKALE Wanduhrzeit (Europe/Berlin) interpretiert
|
||||
und nach UTC umgerechnet.
|
||||
|
||||
So speichern wir stets den absoluten Instant. Die Ausfuehrung (background.py,
|
||||
UTC) trifft damit exakt die vom Nutzer gemeinte Ortszeit — und bleibt
|
||||
zeitzonen-portabel (feuert am selben Moment, egal wo Stefan gerade ist)."""
|
||||
dt = datetime.fromisoformat((iso or "").strip().replace("Z", "+00:00"))
|
||||
if dt.tzinfo is None:
|
||||
# Naiv = lokale Wanduhrzeit → UTC = lokal - Offset.
|
||||
dt = (dt - timedelta(hours=_local_offset_hours(dt))).replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _safe_name(name: str) -> str:
|
||||
if not isinstance(name, str) or not NAME_RE.match(name):
|
||||
raise ValueError(f"Ungueltiger Trigger-Name: {name!r}")
|
||||
@@ -127,9 +150,10 @@ def create_timer(
|
||||
_safe_name(name)
|
||||
if _path(name).exists():
|
||||
raise ValueError(f"Trigger '{name}' existiert schon")
|
||||
# ISO validieren
|
||||
# ISO validieren UND auf UTC normalisieren (naiv = lokale Wanduhrzeit →
|
||||
# UTC). So passt das Anlegen zur UTC-Ausfuehrung in background.py.
|
||||
try:
|
||||
datetime.fromisoformat(fires_at_iso.replace("Z", "+00:00"))
|
||||
fires_at_iso = normalize_fires_at_utc(fires_at_iso)
|
||||
except Exception:
|
||||
raise ValueError(f"fires_at_iso ungueltig: {fires_at_iso}")
|
||||
data = {
|
||||
|
||||
+716
-60
File diff suppressed because it is too large
Load Diff
+1150
-262
File diff suppressed because it is too large
Load Diff
+439
-9
@@ -349,6 +349,66 @@ function loadLocalModels() {
|
||||
return DEFAULT_LOCAL_MODELS;
|
||||
}
|
||||
|
||||
// ── LLM-Modell-Katalog (Stage D): herunterladbare GGUF-Modelle ───────
|
||||
// /shared/config/llm_catalog.json — kuratierte Liste guter GGUF-Modelle plus
|
||||
// per HuggingFace-Refresh nachgeladene. Der llm-adapter zieht ein Modell via
|
||||
// -hf beim ersten Load. { id(key), hfRepo, quant, sizeGB, description, source }.
|
||||
const LLM_CATALOG_FILE = "/shared/config/llm_catalog.json";
|
||||
const DEFAULT_LLM_CATALOG = [
|
||||
{ id: "qwen3-8b", hfRepo: "Qwen/Qwen3-8B-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 6, description: "Bestes Tool-Calling, passt auf 12 GB.", source: "curated" },
|
||||
{ id: "qwen3-4b", hfRepo: "Qwen/Qwen3-4B-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 3, description: "Kleiner + flotter, etwas schwaecher.", source: "curated" },
|
||||
{ id: "qwen3-14b", hfRepo: "Qwen/Qwen3-14B-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 10, description: "Staerker, braucht mehr VRAM (~16 GB).", source: "curated" },
|
||||
{ id: "llama-3.1-8b", hfRepo: "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 5, description: "Llama 3.1 8B Instruct.", source: "curated" },
|
||||
{ id: "mistral-small-3", hfRepo: "bartowski/Mistral-Small-24B-Instruct-2501-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 14, description: "Mistral Small 24B — stark, viel VRAM.", source: "curated" },
|
||||
{ id: "gemma-2-9b", hfRepo: "bartowski/gemma-2-9b-it-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 6, description: "Google Gemma 2 9B Instruct.", source: "curated" },
|
||||
];
|
||||
function loadLlmCatalog() {
|
||||
try {
|
||||
const arr = JSON.parse(fs.readFileSync(LLM_CATALOG_FILE, "utf-8"));
|
||||
if (Array.isArray(arr) && arr.length && arr.every(m => m && typeof m.id === "string")) return arr;
|
||||
} catch {}
|
||||
try {
|
||||
fs.mkdirSync("/shared/config", { recursive: true });
|
||||
fs.writeFileSync(LLM_CATALOG_FILE, JSON.stringify(DEFAULT_LLM_CATALOG, null, 2));
|
||||
} catch {}
|
||||
return DEFAULT_LLM_CATALOG;
|
||||
}
|
||||
function saveLlmCatalog(arr) {
|
||||
try {
|
||||
fs.mkdirSync("/shared/config", { recursive: true });
|
||||
const tmp = LLM_CATALOG_FILE + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(arr, null, 2));
|
||||
fs.renameSync(tmp, LLM_CATALOG_FILE);
|
||||
return true;
|
||||
} catch (e) { log("warn", "llm", `Katalog speichern fehlgeschlagen: ${e.message}`); return false; }
|
||||
}
|
||||
function slugModelId(repo) {
|
||||
return String(repo).toLowerCase().replace(/^.*\//, "").replace(/-gguf$/,"").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "model";
|
||||
}
|
||||
// Holt populaere GGUF-Modelle von der HuggingFace-API und merged sie in den
|
||||
// Katalog (kuratierte Eintraege + Beschreibungen bleiben erhalten).
|
||||
async function refreshLlmCatalogFromHF() {
|
||||
const url = "https://huggingface.co/api/models?search=GGUF&sort=downloads&direction=-1&limit=40";
|
||||
const r = await fetch(url, { headers: { "User-Agent": "aria-diagnostic" } });
|
||||
if (!r.ok) throw new Error(`HF API ${r.status}`);
|
||||
const list = await r.json();
|
||||
const existing = loadLlmCatalog();
|
||||
const byId = new Map(existing.map(m => [m.id, m]));
|
||||
let added = 0;
|
||||
for (const m of (Array.isArray(list) ? list : [])) {
|
||||
const repo = m.id || m.modelId;
|
||||
if (!repo || !/gguf/i.test(repo)) continue;
|
||||
const id = slugModelId(repo);
|
||||
if (byId.has(id)) continue; // kuratierte/vorhandene nicht ueberschreiben
|
||||
const entry = { id, hfRepo: repo, quant: "Q4_K_M", ctx: 8192, sizeGB: 0,
|
||||
description: `HuggingFace · ${(m.downloads || 0).toLocaleString("de")} Downloads`, source: "hf" };
|
||||
byId.set(id, entry); added++;
|
||||
}
|
||||
const merged = Array.from(byId.values());
|
||||
saveLlmCatalog(merged);
|
||||
return { models: merged, added };
|
||||
}
|
||||
|
||||
// ── File-Project-Manifest ───────────────────────────────────────────
|
||||
// Jeder Eintrag map[absoluter_pfad] = project_id (leer = Hauptchat).
|
||||
// Wird vom files-list-Endpoint + files-set-project gepflegt.
|
||||
@@ -475,6 +535,112 @@ function broadcastState() {
|
||||
broadcast({ type: "state", state });
|
||||
}
|
||||
|
||||
// ── Satelliten-Registry (Aussenposten in fremden Netzen) ──────────
|
||||
const satellites = new Map(); // id → {id, location, caps, control, last_seen}
|
||||
|
||||
function satelliteList() {
|
||||
const now = Date.now();
|
||||
return Array.from(satellites.values()).map(s => ({
|
||||
id: s.id, location: s.location, caps: s.caps, control: s.control, net: s.net || null,
|
||||
online: (now - (s.last_seen || 0)) < 300000,
|
||||
}));
|
||||
}
|
||||
|
||||
function broadcastSatellites() {
|
||||
broadcast({ type: "sat_update", satellites: satelliteList() });
|
||||
}
|
||||
|
||||
// ── Host-Agenten: Direktzugriff auf einen Rechner ────────────────
|
||||
const hosts = new Map(); // hostId → {hostId, name, os, caps, control, last_seen}
|
||||
|
||||
function hostList() {
|
||||
const now = Date.now();
|
||||
return Array.from(hosts.values()).map(h => ({
|
||||
hostId: h.hostId, name: h.name, os: h.os, caps: h.caps, control: h.control,
|
||||
online: (now - (h.last_seen || 0)) < 300000,
|
||||
}));
|
||||
}
|
||||
|
||||
function broadcastHosts() {
|
||||
broadcast({ type: "host_update", hosts: hostList() });
|
||||
}
|
||||
|
||||
// ── Compute-Fleet: GPU-Worker (voxtral/whisper/f5tts/llm) ──────────
|
||||
// Worker melden sich per worker_hello + halten sich per worker_ping (busy) frisch.
|
||||
const workers = new Map(); // instanceId → {instanceId, service, node, gpus, model, busy, last_seen}
|
||||
const WORKER_OFFLINE_MS = 35000; // ping ~10s; nach 35s ohne Ping = offline
|
||||
|
||||
function workerList() {
|
||||
const now = Date.now();
|
||||
return Array.from(workers.values()).map(w => ({
|
||||
instanceId: w.instanceId, service: w.service, node: w.node,
|
||||
gpus: w.gpus, model: w.model, models: w.models || [], busy: !!w.busy,
|
||||
online: (now - (w.last_seen || 0)) < WORKER_OFFLINE_MS,
|
||||
}));
|
||||
}
|
||||
|
||||
function broadcastWorkers() {
|
||||
broadcast({ type: "worker_update", workers: workerList() });
|
||||
}
|
||||
|
||||
// ── Voice-Flotte: zentraler Stimmen-Store + Auto-Provisioning ──────
|
||||
// Der Diagnostic-Server ist der "Stimmen-Bibliothekar": Stimmen liegen
|
||||
// zentral als /shared/voices/{name}.tar.gz (das f5tts-Export-Artefakt =
|
||||
// wav+txt). Meldet sich eine f5tts-Box (worker_hello), gleichen wir ab und
|
||||
// schieben ihr fehlende Stimmen (xtts_import_voice, targetInstance) bzw. ziehen
|
||||
// bei ihr vorhandene, zentral fehlende Stimmen (xtts_export_voice) in den Store.
|
||||
const CENTRAL_VOICES_DIR = "/shared/voices";
|
||||
const centralExportPending = new Map(); // requestId -> name (unsere eigenen Export-Anfragen)
|
||||
|
||||
function ensureCentralVoicesDir() {
|
||||
try { fs.mkdirSync(CENTRAL_VOICES_DIR, { recursive: true }); } catch (_) {}
|
||||
}
|
||||
function centralVoiceNames() {
|
||||
ensureCentralVoicesDir();
|
||||
try {
|
||||
return fs.readdirSync(CENTRAL_VOICES_DIR)
|
||||
.filter(f => f.endsWith(".tar.gz"))
|
||||
.map(f => f.slice(0, -7));
|
||||
} catch (_) { return []; }
|
||||
}
|
||||
function readCentralVoiceB64(name) {
|
||||
try { return fs.readFileSync(`${CENTRAL_VOICES_DIR}/${name}.tar.gz`).toString("base64"); }
|
||||
catch (_) { return null; }
|
||||
}
|
||||
function writeCentralVoice(name, dataB64) {
|
||||
ensureCentralVoicesDir();
|
||||
try { fs.writeFileSync(`${CENTRAL_VOICES_DIR}/${name}.tar.gz`, Buffer.from(dataB64, "base64")); return true; }
|
||||
catch (e) { log("warn", "voice", `zentral schreiben ${name} fehlgeschlagen: ${e.message}`); return false; }
|
||||
}
|
||||
function deleteCentralVoice(name) {
|
||||
try { fs.unlinkSync(`${CENTRAL_VOICES_DIR}/${name}.tar.gz`); log("info", "voice", `zentral geloescht: ${name}`); }
|
||||
catch (_) {}
|
||||
}
|
||||
function requestCentralExport(name) {
|
||||
// Broadcast-Export-Anfrage; die Box, die die Stimme hat, antwortet. Wir
|
||||
// korrelieren die Antwort ueber requestId (nur unsere eigenen verarbeiten).
|
||||
const requestId = "central_" + Date.now() + "_" + Math.random().toString(36).slice(2, 8);
|
||||
centralExportPending.set(requestId, name);
|
||||
setTimeout(() => centralExportPending.delete(requestId), 30000);
|
||||
sendToRVS_raw({ type: "xtts_export_voice", payload: { name, requestId }, timestamp: Date.now() });
|
||||
}
|
||||
function provisionVoiceToInstance(name, instanceId) {
|
||||
const data = readCentralVoiceB64(name);
|
||||
if (!data) return;
|
||||
sendToRVS_raw({ type: "xtts_import_voice",
|
||||
payload: { name, data, targetInstance: instanceId }, timestamp: Date.now() });
|
||||
log("info", "voice", `provisioniere '${name}' → ${instanceId}`);
|
||||
}
|
||||
// Abgleich beim worker_hello einer f5tts-Box: push (zentral→Box) + pull (Box→zentral, seed).
|
||||
function reconcileVoices(instanceId, boxVoices) {
|
||||
const central = centralVoiceNames();
|
||||
const boxSet = new Set(Array.isArray(boxVoices) ? boxVoices : []);
|
||||
const centralSet = new Set(central);
|
||||
for (const name of central) if (!boxSet.has(name)) provisionVoiceToInstance(name, instanceId);
|
||||
for (const name of boxSet) if (!centralSet.has(name)) requestCentralExport(name);
|
||||
log("info", "voice", `reconcile ${instanceId}: box=${boxSet.size} central=${central.length}`);
|
||||
}
|
||||
|
||||
// ── OpenClaw Gateway Verbindung ─────────────────────────
|
||||
|
||||
async function connectGateway() {
|
||||
@@ -903,6 +1069,101 @@ function connectRVS(forcePlain) {
|
||||
// Browser-Tabs weiterreichen, damit die Projektliste live neu laedt
|
||||
// (bisher wurde das NICHT geforwardet → Diagnostic aktualisierte nie).
|
||||
broadcast({ type: "project_changed", payload: msg.payload || {} });
|
||||
} else if (msg.type === "sat_hello") {
|
||||
// Ein Satellit (Aussenposten in einem fremden Netz) meldet sich.
|
||||
const p = msg.payload || {};
|
||||
if (p.id) {
|
||||
satellites.set(p.id, {
|
||||
id: p.id, location: p.location || p.id,
|
||||
caps: p.caps || [], control: !!p.control, net: p.net || null,
|
||||
last_seen: Date.now(),
|
||||
});
|
||||
broadcastSatellites();
|
||||
}
|
||||
} else if (msg.type === "host_hello") {
|
||||
// Ein Host-Agent (Direktzugriff auf einen Rechner) meldet sich.
|
||||
const p = msg.payload || {};
|
||||
if (p.hostId) {
|
||||
const wasKnown = hosts.has(p.hostId);
|
||||
hosts.set(p.hostId, {
|
||||
hostId: p.hostId, name: p.name || p.hostId, os: p.os || "",
|
||||
caps: p.caps || [], control: !!p.control, last_seen: Date.now(),
|
||||
});
|
||||
if (!wasKnown) broadcastHosts();
|
||||
else hosts.get(p.hostId).last_seen = Date.now();
|
||||
}
|
||||
} else if (msg.type === "host_ping") {
|
||||
const p = msg.payload || {};
|
||||
if (p.hostId && hosts.has(p.hostId)) hosts.get(p.hostId).last_seen = Date.now();
|
||||
} else if (msg.type === "rooms_info") {
|
||||
// Antwort des RVS auf rooms_query → an den Browser (Raum-Diagnose).
|
||||
broadcast({ type: "rooms_info", payload: msg.payload || {} });
|
||||
} else if (msg.type === "sat_devices") {
|
||||
// Antwort eines Satelliten auf sat_discover → Geraeteliste an Browser.
|
||||
const p = msg.payload || {};
|
||||
if (p.satellite && satellites.has(p.satellite)) satellites.get(p.satellite).last_seen = Date.now();
|
||||
broadcast({ type: "sat_devices", satellite: p.satellite || "",
|
||||
location: p.location || "", devices: p.devices || [] });
|
||||
} else if (msg.type === "sat_creds_list_result" || msg.type === "sat_creds_result") {
|
||||
// Credential-Store-Antworten eines Satelliten → an den Browser.
|
||||
broadcast({ type: msg.type, payload: msg.payload || {} });
|
||||
} else if (msg.type === "worker_hello") {
|
||||
// Ein Compute-Worker (GPU-Dienst) meldet sich mit seiner Identitaet.
|
||||
const p = msg.payload || {};
|
||||
if (p.instanceId) {
|
||||
const prev = workers.get(p.instanceId) || {};
|
||||
// War die Box vor diesem hello schon frisch gesehen? worker_hello wird
|
||||
// jetzt alle ~30s wiederholt — Reconcile nur beim ERSTEN/erneuten
|
||||
// Auftauchen, nicht bei jedem Resend.
|
||||
const wasFresh = prev.last_seen && (Date.now() - prev.last_seen < WORKER_OFFLINE_MS);
|
||||
workers.set(p.instanceId, {
|
||||
instanceId: p.instanceId, service: p.service || "",
|
||||
node: p.node || "", gpus: p.gpus || "", model: p.model || "",
|
||||
models: Array.isArray(p.models) ? p.models : (p.model ? [p.model] : []),
|
||||
busy: !!prev.busy, last_seen: Date.now(),
|
||||
});
|
||||
broadcastWorkers();
|
||||
// Voice-Flotte: f5tts-Box NEU online → Stimmen abgleichen/provisionieren.
|
||||
if ((p.service || "") === "f5tts" && !wasFresh) reconcileVoices(p.instanceId, p.voices);
|
||||
}
|
||||
} else if (msg.type === "worker_ping") {
|
||||
// Heartbeat eines Workers (traegt busy-Status).
|
||||
const p = msg.payload || {};
|
||||
if (p.instanceId) {
|
||||
let w = workers.get(p.instanceId);
|
||||
if (!w) {
|
||||
const svc = String(p.instanceId).split("@")[0];
|
||||
w = { instanceId: p.instanceId, service: svc, node: "", gpus: "", model: "", models: [], busy: false, last_seen: 0 };
|
||||
workers.set(p.instanceId, w);
|
||||
}
|
||||
w.busy = !!p.busy;
|
||||
w.last_seen = Date.now();
|
||||
broadcastWorkers();
|
||||
}
|
||||
} else if (msg.type === "xtts_voice_saved") {
|
||||
// Neue Stimme (App- ODER Diagnostic-Upload, via RVS-Broadcast) → zentral
|
||||
// sichern. Online-Boxen haben sie durch den voice_upload-Broadcast schon;
|
||||
// der zentrale Store macht sie persistent + fuer spaeter joinende Boxen
|
||||
// verfuegbar (die holt dann reconcileVoices ab).
|
||||
const p = msg.payload || {};
|
||||
if (p.name && !p.error) {
|
||||
log("info", "voice", `Stimme '${p.name}' gespeichert → zentraler Ingest`);
|
||||
requestCentralExport(p.name);
|
||||
}
|
||||
} else if (msg.type === "xtts_voice_exported") {
|
||||
// Antwort auf eine UNSERER zentralen Export-Anfragen (requestId-Match) →
|
||||
// in den zentralen Store schreiben. Browser-initiierte Exports tragen
|
||||
// keinen centralExportPending-requestId und werden hier ignoriert.
|
||||
const p = msg.payload || {};
|
||||
const rid = p.requestId || "";
|
||||
if (rid && centralExportPending.has(rid)) {
|
||||
centralExportPending.delete(rid);
|
||||
if (p.ok && p.name && p.data) writeCentralVoice(p.name, p.data);
|
||||
}
|
||||
} else if (msg.type === "xtts_delete_voice") {
|
||||
// App-initiierter Delete (Broadcast) → zentrale Kopie mitloeschen.
|
||||
const p = msg.payload || {};
|
||||
if (p.name) deleteCentralVoice(p.name);
|
||||
} else if (msg.type === "agent_activity") {
|
||||
// Bridge meldet "ARIA denkt/schreibt/tool" oder "idle" — an Browser
|
||||
// weiterreichen, damit der Thinking-Indikator im Chat erscheint.
|
||||
@@ -949,7 +1210,7 @@ function connectRVS(forcePlain) {
|
||||
}
|
||||
broadcast({ type: "voice_ready", payload: msg.payload });
|
||||
} else if (msg.type === "service_status") {
|
||||
// Gamebox-Bridges (f5tts/whisper) melden ihren Lade-Status —
|
||||
// AI-Box-Bridges (f5tts/whisper) melden ihren Lade-Status —
|
||||
// an Browser durchreichen fuer das Banner unten rechts
|
||||
const svc = msg.payload?.service || "?";
|
||||
const state = msg.payload?.state || "?";
|
||||
@@ -964,6 +1225,12 @@ function connectRVS(forcePlain) {
|
||||
log("info", "rvs", `service_status ${svc} ${state}${model ? ` (${model})` : ""}`);
|
||||
}
|
||||
broadcast({ type: "service_status", payload: msg.payload });
|
||||
} else if (msg.type === "llm_provision_result") {
|
||||
// Ergebnis eines Modell-Downloads/Aktivierens → an Browser (Katalog-Status).
|
||||
broadcast({ type: "llm_provision_result", payload: msg.payload || {} });
|
||||
} else if (msg.type === "node_stats" || msg.type === "node_stats_history" || msg.type === "node_stats_reset_done") {
|
||||
// Auslastungs-Monitor (Stage E): Box-Antworten an die Browser durchreichen.
|
||||
broadcast({ type: msg.type, payload: msg.payload || {} });
|
||||
} else if (msg.type === "audio_pcm" && msg.payload && _previewPending.size > 0) {
|
||||
// PCM-Chunks einer laufenden Voice-Preview — sammeln + WAV bauen
|
||||
_handlePreviewChunk(msg.payload);
|
||||
@@ -1008,7 +1275,7 @@ function connectRVS(forcePlain) {
|
||||
});
|
||||
}
|
||||
|
||||
function sendToRVS_withResponse(sendType, sendPayload, expectType, clientWs) {
|
||||
function sendToRVS_withResponse(sendType, sendPayload, expectType, clientWs, timeoutMs = 15000) {
|
||||
if (!RVS_HOST || !RVS_TOKEN) return;
|
||||
const proto = RVS_TLS === "true" ? "wss" : "ws";
|
||||
const url = `${proto}://${RVS_HOST}:${RVS_PORT}?token=${RVS_TOKEN}`;
|
||||
@@ -1016,7 +1283,7 @@ function sendToRVS_withResponse(sendType, sendPayload, expectType, clientWs) {
|
||||
const timeout = setTimeout(() => {
|
||||
try { freshWs.close(); } catch (_) {}
|
||||
clientWs.send(JSON.stringify({ type: expectType, payload: { voices: [], error: "Timeout" }, timestamp: Date.now() }));
|
||||
}, 15000);
|
||||
}, timeoutMs);
|
||||
freshWs.on("open", () => {
|
||||
freshWs.send(JSON.stringify({ type: sendType, payload: sendPayload, timestamp: Date.now() }));
|
||||
});
|
||||
@@ -1527,6 +1794,70 @@ function dockerExec(containerName, cmd) {
|
||||
});
|
||||
}
|
||||
|
||||
// POST gegen die Docker-Daemon-API (via gemountetem Socket). Fuer prune-
|
||||
// Endpoints — die geben SpaceReclaimed (Bytes) zurueck.
|
||||
function dockerApiPost(apiPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({
|
||||
socketPath: "/var/run/docker.sock",
|
||||
path: apiPath,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "Content-Length": 0 },
|
||||
}, (res) => {
|
||||
let data = "";
|
||||
res.on("data", (c) => data += c);
|
||||
res.on("end", () => {
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
try { resolve(JSON.parse(data || "{}")); } catch { resolve({}); }
|
||||
} else {
|
||||
reject(new Error(`Docker API ${apiPath}: HTTP ${res.statusCode} — ${String(data).slice(0, 200)}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// "Sicher aufraeumen": Build-Cache + ungenutzte Images prunen — OHNE Volumes
|
||||
// (keine Daten weg). "aggressive": zusaetzlich gestoppte Container + ungenutzte
|
||||
// Volumes (kann Daten kosten → nur auf ausdrueckliche Wahl). Fuehrt es WIRKLICH
|
||||
// aus (frueher kopierte der Button nur den Befehl in die Zwischenablage).
|
||||
async function handleDiskCleanup(clientWs, variant) {
|
||||
const aggressive = variant === "aggressive";
|
||||
const send = (o) => { try { clientWs.send(JSON.stringify(o)); } catch (_) {} };
|
||||
send({ type: "disk_cleanup", status: "running", variant });
|
||||
log("warn", "server", `Disk-Cleanup gestartet (${aggressive ? "aggressive" : "safe"})`);
|
||||
try {
|
||||
let reclaimed = 0;
|
||||
const steps = [];
|
||||
const bp = await dockerApiPost("/build/prune?all=true");
|
||||
reclaimed += (bp.SpaceReclaimed || 0);
|
||||
steps.push("Build-Cache");
|
||||
// dangling=false → ALLE ungenutzten Images (nicht nur dangling).
|
||||
// Docker-API-Filterformat: map[string][]string.
|
||||
const imgFilter = encodeURIComponent(JSON.stringify({ dangling: ["false"] }));
|
||||
const ip = await dockerApiPost("/images/prune?filters=" + imgFilter);
|
||||
reclaimed += (ip.SpaceReclaimed || 0);
|
||||
steps.push("ungenutzte Images");
|
||||
if (aggressive) {
|
||||
const cp = await dockerApiPost("/containers/prune");
|
||||
reclaimed += (cp.SpaceReclaimed || 0);
|
||||
steps.push("gestoppte Container");
|
||||
const vp = await dockerApiPost("/volumes/prune");
|
||||
reclaimed += (vp.SpaceReclaimed || 0);
|
||||
steps.push("ungenutzte Volumes");
|
||||
}
|
||||
const mb = (reclaimed / (1024 * 1024));
|
||||
const freed = mb >= 1024 ? (mb / 1024).toFixed(2) + " GB" : mb.toFixed(0) + " MB";
|
||||
log("info", "server", `Disk-Cleanup fertig: ${freed} frei (${steps.join(", ")})`);
|
||||
send({ type: "disk_cleanup", status: "done", variant, reclaimedBytes: reclaimed, freed, steps });
|
||||
} catch (err) {
|
||||
log("error", "server", `Disk-Cleanup fehlgeschlagen: ${err.message}`);
|
||||
send({ type: "disk_cleanup", status: "error", variant, error: String(err && err.message || err) });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Hilfsfunktionen ─────────────────────────────────────
|
||||
|
||||
function waitForMessage(ws, timeoutMs) {
|
||||
@@ -1642,6 +1973,20 @@ const server = http.createServer((req, res) => {
|
||||
} else if (req.url === "/api/local-models-list" && req.method === "GET") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, models: loadLocalModels() }));
|
||||
} else if (req.url === "/api/llm-catalog" && req.method === "GET") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, models: loadLlmCatalog() }));
|
||||
} else if (req.url === "/api/llm-catalog/refresh" && req.method === "POST") {
|
||||
refreshLlmCatalogFromHF()
|
||||
.then(r => {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, models: r.models, added: r.added }));
|
||||
log("info", "llm", `LLM-Katalog von HuggingFace aktualisiert: +${r.added} Modelle`);
|
||||
})
|
||||
.catch(err => {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: false, error: err.message, models: loadLlmCatalog() }));
|
||||
});
|
||||
} else if (req.url === "/api/local-llm-config" && req.method === "GET") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(readLocalLlmConfig()));
|
||||
@@ -2407,6 +2752,12 @@ wss.on("connection", (ws) => {
|
||||
ws.send(JSON.stringify({ type: "init", state, logs: logs.slice(-100) }));
|
||||
// Letzten Disk-Status mitgeben damit der Client sofort weiss wie's um Platz steht
|
||||
if (currentDiskStatus) ws.send(JSON.stringify(currentDiskStatus));
|
||||
// Aktuell bekannte Satelliten mitgeben (RVS replayt sat_hello nicht).
|
||||
ws.send(JSON.stringify({ type: "sat_update", satellites: satelliteList() }));
|
||||
// Aktuell bekannte Host-Agenten mitgeben.
|
||||
ws.send(JSON.stringify({ type: "host_update", hosts: hostList() }));
|
||||
// Aktuell bekannte Compute-Worker mitgeben (RVS replayt worker_hello nicht).
|
||||
ws.send(JSON.stringify({ type: "worker_update", workers: workerList() }));
|
||||
|
||||
ws.on("message", (raw) => {
|
||||
try {
|
||||
@@ -2421,10 +2772,52 @@ wss.on("connection", (ws) => {
|
||||
} else if (msg.action === "test_rvs") {
|
||||
traceStart("RVS", msg.text || "aria lebst du noch?");
|
||||
sendToRVS(msg.text || "aria lebst du noch?", true, msg.projectId || "");
|
||||
} else if (msg.action === "interject") {
|
||||
// Zwischenruf: in den laufenden Turn schieben (kein Abbruch, keine
|
||||
// Queue) → RVS interject → Bridge → Proxy /interject.
|
||||
const t = String(msg.text || "");
|
||||
if (t.trim()) {
|
||||
sendToRVS_raw({ type: "interject", payload: { projectId: msg.projectId || "", text: t }, timestamp: Date.now() });
|
||||
log("info", "server", "Zwischenruf an RVS (project=" + (msg.projectId || "(main)") + "): " + t.slice(0, 60));
|
||||
}
|
||||
} else if (msg.action === "disk_cleanup") {
|
||||
handleDiskCleanup(ws, msg.variant === "aggressive" ? "aggressive" : "safe");
|
||||
} else if (msg.action === "reconnect_gateway") {
|
||||
connectGateway();
|
||||
} else if (msg.action === "reconnect_rvs") {
|
||||
connectRVS();
|
||||
} else if (msg.action === "sat_list") {
|
||||
// Browser will die aktuelle Satelliten-Liste.
|
||||
ws.send(JSON.stringify({ type: "sat_update", satellites: satelliteList() }));
|
||||
} else if (msg.action === "host_list") {
|
||||
// Browser will die aktuelle Host-Agenten-Liste.
|
||||
ws.send(JSON.stringify({ type: "host_update", hosts: hostList() }));
|
||||
} else if (msg.action === "rooms_query") {
|
||||
// Browser will die RVS-Raum-Diagnose — via persistente rvsWs anfragen,
|
||||
// die Antwort (rooms_info) kommt auf derselben Verbindung zurueck.
|
||||
sendToRVS_raw({ type: "rooms_query", payload: {}, timestamp: Date.now() });
|
||||
} else if (msg.action === "worker_list") {
|
||||
// Browser will die aktuelle Compute-Flotte.
|
||||
ws.send(JSON.stringify({ type: "worker_update", workers: workerList() }));
|
||||
} else if (msg.action === "sat_discover") {
|
||||
// Browser triggert einen Geraete-Scan auf einem Satelliten.
|
||||
sendToRVS_raw({ type: "sat_discover",
|
||||
payload: { satellite: msg.satellite || "", force: true },
|
||||
timestamp: Date.now() });
|
||||
} else if (msg.action === "sat_creds_list") {
|
||||
sendToRVS_raw({ type: "sat_creds_list",
|
||||
payload: { satellite: msg.satellite || "", requestId: "dc_" + Date.now() },
|
||||
timestamp: Date.now() });
|
||||
} else if (msg.action === "sat_creds_set") {
|
||||
sendToRVS_raw({ type: "sat_creds_set",
|
||||
payload: { satellite: msg.satellite || "", ip: msg.ip || "",
|
||||
creds: msg.creds || {}, requestId: "dc_" + Date.now() },
|
||||
timestamp: Date.now() });
|
||||
} else if (msg.action === "sat_creds_delete") {
|
||||
sendToRVS_raw({ type: "sat_creds_delete",
|
||||
payload: { satellite: msg.satellite || "", ip: msg.ip || "",
|
||||
type: msg.credType || "", requestId: "dc_" + Date.now() },
|
||||
timestamp: Date.now() });
|
||||
} else if (msg.action === "test_proxy") {
|
||||
testProxy(msg.text);
|
||||
} else if (msg.action === "check_proxy_auth") {
|
||||
@@ -2452,19 +2845,23 @@ wss.on("connection", (ws) => {
|
||||
// Datei von Diagnostic an Bridge via RVS senden
|
||||
sendToRVS_raw({
|
||||
type: "file",
|
||||
payload: { name: msg.name, type: msg.type, size: msg.size, base64: msg.base64 },
|
||||
payload: { name: msg.name, type: msg.type, size: msg.size, base64: msg.base64, projectId: msg.projectId || "" },
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
log("info", "server", `Datei gesendet: ${msg.name} (${msg.type})`);
|
||||
} else if (msg.action === "cancel_request") {
|
||||
// Laufende Anfrage abbrechen — doctor --fix beendet stuck runs
|
||||
log("warn", "server", "Anfrage abgebrochen — fuehre doctor --fix aus");
|
||||
// Laufende Anfrage abbrechen — ECHTER Cancel: RVS cancel_request (hard)
|
||||
// an die Bridge, die den Proxy-/cancel-all Side-Channel anruft und den
|
||||
// laufenden claude-Subprozess killt. Das alte `openclaw doctor --fix`
|
||||
// zielte auf den Container aria-core, den es nicht mehr gibt — es
|
||||
// beendete den Run nie (ARIA lief munter weiter).
|
||||
log("warn", "server", "Anfrage abgebrochen — cancel_request (hard) an Bridge/Proxy");
|
||||
pendingMessageTime = 0;
|
||||
watchdogWarned = false;
|
||||
watchdogFixAttempted = false;
|
||||
if (traceActive) traceEnd(false, "Vom Benutzer abgebrochen");
|
||||
broadcast({ type: "agent_activity", activity: "idle" });
|
||||
dockerExec("aria-core", "openclaw doctor --fix 2>/dev/null || true").catch(() => {});
|
||||
sendToRVS_raw({ type: "cancel_request", payload: { hard: true, source: "diagnostic-cancel" }, timestamp: Date.now() });
|
||||
} else if (msg.action === "aria_panic_stop") {
|
||||
// NOT-AUS aus ARIA-Live-View: lokales /api/cancel UND Hard-Kill via
|
||||
// Bridge (die wiederum den Proxy-Side-Channel /cancel-all anruft).
|
||||
@@ -2491,9 +2888,11 @@ wss.on("connection", (ws) => {
|
||||
// tar.gz (base64) an XTTS-Bridge schicken — die packt aus
|
||||
sendToRVS_withResponse("xtts_import_voice", { name: msg.name, data: msg.data }, "xtts_voice_imported", ws);
|
||||
} else if (msg.action === "xtts_delete_voice") {
|
||||
// Weiterleiten an XTTS-Bridge, die antwortet mit neuer Liste
|
||||
// Weiterleiten an alle f5tts-Boxen (Broadcast) + zentrale Kopie loeschen.
|
||||
// (Der eigene Broadcast kommt nicht zu uns zurueck, daher hier direkt.)
|
||||
sendToRVS_raw({ type: "xtts_delete_voice", payload: { name: msg.name }, timestamp: Date.now() });
|
||||
log("info", "server", `Voice-Delete '${msg.name}' an XTTS-Bridge gesendet`);
|
||||
if (msg.name) deleteCentralVoice(msg.name);
|
||||
log("info", "server", `Voice-Delete '${msg.name}' an f5tts-Boxen + zentral geloescht`);
|
||||
} else if (msg.action === "delete_chat_message") {
|
||||
// Bubble loeschen — Bridge raeumt chat_backup.jsonl + Brain-conversation
|
||||
// + broadcastet chat_message_deleted via RVS.
|
||||
@@ -2561,6 +2960,12 @@ wss.on("connection", (ws) => {
|
||||
const t = parseFloat(msg.voiceIdThreshold);
|
||||
if (t >= 0.0 && t <= 1.0) voiceConfig.voiceIdThreshold = t;
|
||||
}
|
||||
// Speaker-ID Gating an/aus ("nur meine Stimme"). Default aus (fail-open) —
|
||||
// bewusster Schalter. voxtral/whisper-bridge lesen voiceIdEnabled aus dem
|
||||
// config-Broadcast; aus = gar keine Pruefung.
|
||||
if (msg.voiceIdEnabled !== undefined) {
|
||||
voiceConfig.voiceIdEnabled = !!msg.voiceIdEnabled;
|
||||
}
|
||||
try {
|
||||
fs.mkdirSync("/shared/config", { recursive: true });
|
||||
fs.writeFileSync("/shared/config/voice_config.json", JSON.stringify(voiceConfig, null, 2));
|
||||
@@ -2576,6 +2981,31 @@ wss.on("connection", (ws) => {
|
||||
// Sessions- und Brain-File-Viewer entfernt — Sessions sind raus, Memory
|
||||
// laeuft jetzt komplett ueber die Vector-DB im aria-brain (siehe Gehirn-Tab).
|
||||
// restart_session kommt weiter rein, weil der Watchdog ihn manchmal triggert.
|
||||
} else if (msg.action === "llm_provision_model") {
|
||||
// Modell auf eine bestimmte LLM-Box laden/aktivieren (Stage D).
|
||||
sendToRVS_raw({ type: "llm_provision_model", payload: {
|
||||
targetInstance: msg.targetInstance || "",
|
||||
key: msg.key, hfRepo: msg.hfRepo, quant: msg.quant, ctx: msg.ctx, ngl: msg.ngl,
|
||||
}, timestamp: Date.now() });
|
||||
log("info", "llm", `provision '${msg.key}' (${msg.hfRepo}) → ${msg.targetInstance || "?"}`);
|
||||
} else if (msg.action === "llm_remove_model") {
|
||||
sendToRVS_raw({ type: "llm_remove_model", payload: {
|
||||
targetInstance: msg.targetInstance || "", key: msg.key }, timestamp: Date.now() });
|
||||
log("info", "llm", `remove '${msg.key}' → ${msg.targetInstance || "?"}`);
|
||||
} else if (msg.action === "llm_test") {
|
||||
// Test-Chat: kurze Nachricht direkt ans lokale LLM (llm_request/llm_response).
|
||||
const reqId = "diagtest_" + Date.now();
|
||||
sendToRVS_withResponse("llm_request", {
|
||||
requestId: reqId,
|
||||
messages: [{ role: "user", content: String(msg.text || "Sag kurz Hallo.") }],
|
||||
max_tokens: 256, temperature: 0.5,
|
||||
model: msg.model || "", targetInstance: msg.targetInstance || "",
|
||||
}, "llm_response", ws, 120000); // 2min: erster Modell-Swap laedt das GGUF kalt (mehrere GB) — 15s reichen dann nicht
|
||||
log("info", "llm", `Test-Chat → ${msg.model || "?"} @ ${msg.targetInstance || "(broadcast)"}`);
|
||||
} else if (msg.action === "node_stats_stream_start" || msg.action === "node_stats_stream_stop"
|
||||
|| msg.action === "node_stats_history_request" || msg.action === "node_stats_reset") {
|
||||
// Auslastungs-Monitor (Stage E): an die Box (targetInstance) durchreichen.
|
||||
sendToRVS_raw({ type: msg.action, payload: { targetInstance: msg.targetInstance || "" }, timestamp: Date.now() });
|
||||
} else if (msg.action === "restart_session") {
|
||||
handleRestartSession(ws);
|
||||
// ── Einstellungen ──
|
||||
|
||||
+3
-5
@@ -11,11 +11,7 @@ services:
|
||||
npm install -g @anthropic-ai/claude-code claude-max-api-proxy &&
|
||||
DIST=$$(find /usr/local/lib -path '*/claude-max-api-proxy/dist' -type d | head -1) &&
|
||||
sed -i 's/startServer({ port })/startServer({ port, host: process.env.HOST || \"127.0.0.1\" })/' $$DIST/server/standalone.js &&
|
||||
sed -i 's/\"--no-session-persistence\",/\"--no-session-persistence\",\"--dangerously-skip-permissions\",/' $$DIST/subprocess/manager.js &&
|
||||
sed -i 's/\"--dangerously-skip-permissions\",/\"--dangerously-skip-permissions\",\"--system-prompt\",options.systemPrompt,/' $$DIST/subprocess/manager.js &&
|
||||
sed -i 's/const DEFAULT_TIMEOUT = 300000;/const DEFAULT_TIMEOUT = 86400000;/' $$DIST/subprocess/manager.js &&
|
||||
sed -i '/prompt, \\/\\/ Pass prompt as argument/d' $$DIST/subprocess/manager.js &&
|
||||
sed -i 's|this\\.process\\.stdin?\\.end();|this.process.stdin?.end(prompt);|' $$DIST/subprocess/manager.js &&
|
||||
cp /proxy-patches/manager.js $$DIST/subprocess/manager.js &&
|
||||
cp /proxy-patches/openai-to-cli.js $$DIST/adapter/openai-to-cli.js &&
|
||||
cp /proxy-patches/cli-to-openai.js $$DIST/adapter/cli-to-openai.js &&
|
||||
cp /proxy-patches/routes.js $$DIST/server/routes.js &&
|
||||
@@ -120,6 +116,8 @@ services:
|
||||
- brain
|
||||
networks:
|
||||
- aria-net
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway" # fuer den VNC-Tunnel zum Host (QEMU)
|
||||
ports:
|
||||
- "3001:3001" # Diagnostic Web-UI (Diagnostic teilt Netzwerk mit Bridge)
|
||||
volumes:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# FLUX.1-dev Bildgenerierung — Architektur & Stand
|
||||
|
||||
Ergaenzung des ARIA-Agent-Stacks um native Text-to-Image-Generierung via
|
||||
FLUX.1-dev auf der Gamebox. Folgt dem **gleichen Pattern wie f5tts / whisper**:
|
||||
FLUX.1-dev auf der AI-Box. Folgt dem **gleichen Pattern wie f5tts / whisper**:
|
||||
ein eigener Container auf dem Gaming-PC, der sich selbst per WebSocket zum
|
||||
RVS verbindet und auf seinen Request-Typ lauscht.
|
||||
|
||||
@@ -23,7 +23,7 @@ aria-bridge ── send_to_core ──▶ aria-brain
|
||||
RVS
|
||||
│ fanout
|
||||
▼
|
||||
flux-bridge (Gamebox)
|
||||
flux-bridge (AI-Box)
|
||||
│ FluxPipeline.from_pretrained(...)
|
||||
│ pipeline(prompt, width, height, steps, guidance).images[0]
|
||||
│ PIL → PNG → base64
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Plan B — Lokaler LLM-Router (Gamebox) neben Claude
|
||||
# Plan B — Lokaler LLM-Router (AI-Box) neben Claude
|
||||
|
||||
**Ziel:** „Gemini-Feeling" für den Alltag, ohne die Claude-Max-Subscription
|
||||
aufzugeben. Ein schnelles lokales LLM beantwortet die einfachen ~80 % der Turns
|
||||
@@ -11,7 +11,7 @@ Gemessen (10.07.2026): CLI-Round-trip über den Claude-Max-Proxy hat einen
|
||||
**harten Boden von ~3,5 s** (Subprozess-Start pro Turn). Streaming-API würde das
|
||||
brechen, kostet aber API-Geld → verliert die Max-Subscription. Ein lokales
|
||||
LLM für die einfachen Turns umgeht den 3,5-s-Boden komplett und ist **gratis**
|
||||
(läuft auf vorhandener Gamebox-GPU). Echtes Speech-to-Speech-Duplex (Gemini
|
||||
(läuft auf vorhandener AI-Box-GPU). Echtes Speech-to-Speech-Duplex (Gemini
|
||||
Live nativ) ist mit einem Text-Modell als Hirn prinzipiell nicht drin.
|
||||
|
||||
## Modell & Serving (entschieden)
|
||||
@@ -19,17 +19,17 @@ Live nativ) ist mit einem Text-Modell als Hirn prinzipiell nicht drin.
|
||||
- **Modell:** Qwen3 8B, GGUF **Q4_K_M** (~6 GB). Bestes Tool-Calling der 7/8B-
|
||||
Klasse, solides Deutsch, Apache-2.0. Alt.: Mistral Small 3 7B (schneller,
|
||||
weniger Tool-Calling).
|
||||
- **Serving:** **llama.cpp `llama-server`** im Docker-Container auf der Gamebox
|
||||
- **Serving:** **llama.cpp `llama-server`** im Docker-Container auf der AI-Box
|
||||
(kein Ollama nötig — nativer OpenAI-kompatibler `/v1/chat/completions`).
|
||||
- **VRAM-Budget:** 12-GB-Karte, Whisper-small (~1–2 GB) + F5-TTS (~1–2 GB) →
|
||||
~8–9 GB frei → passt. (FLUX ist auf 12 GB eh raus.)
|
||||
|
||||
## Anbindung: über den RVS, wie TTS/STT (kein IP-Pflegen)
|
||||
|
||||
Die Gamebox ist ein anderer Host als das Brain. Statt direktem HTTP (IP/Port/
|
||||
Die AI-Box ist ein anderer Host als das Brain. Statt direktem HTTP (IP/Port/
|
||||
Firewall) läuft das LLM **über den RVS-Token-Room**, exakt wie Whisper/F5-TTS:
|
||||
|
||||
- llama.cpp hört nur auf localhost der Gamebox.
|
||||
- llama.cpp hört nur auf localhost der AI-Box.
|
||||
- Ein **dünner RVS-Adapter** daneben (Vorbild: whisper-/xtts-Bridge) verbindet
|
||||
sich mit dem RVS-Token, lauscht auf `llm_request`, ruft lokal llama-server,
|
||||
schickt `llm_response` (korreliert per requestId) zurück.
|
||||
@@ -115,7 +115,7 @@ mit Ziel lokal.
|
||||
|
||||
## Phasen
|
||||
|
||||
- **B0 — Infra:** llama.cpp-Container + RVS-Adapter auf der Gamebox,
|
||||
- **B0 — Infra:** llama.cpp-Container + RVS-Adapter auf der AI-Box,
|
||||
`ALLOWED_TYPES`, `local_llm_chat()` im Brain. Isoliert testen („sag hallo").
|
||||
- **B1 — Router + lokale Tools:** Heuristik Tier-1/2 + Escalation, schlanke
|
||||
Persona lokal, **kuratierte Tool-Auswahl lokal** (Adapter/Bridge/Brain-Tool-
|
||||
@@ -207,8 +207,8 @@ Zerfaellt in zwei Teile:
|
||||
(Docker-Socket) + Controller mit Placement-Policy + Reconciliation +
|
||||
Broadcast-Kollisions-Vermeidung (nicht 2× dieselbe Faehigkeit). = Mini-Nomad.
|
||||
|
||||
**Empfehlung:** Fuer 2 Gameboxen NICHT bauen — statische Platzierung reicht
|
||||
(Gamebox1=LLM, Gamebox2=Voice). Dynamisches Laden/Entladen zum VRAM-Freimachen
|
||||
**Empfehlung:** Fuer 2 AI-Boxen NICHT bauen — statische Platzierung reicht
|
||||
(AI-Box1=LLM, AI-Box2=Voice). Dynamisches Laden/Entladen zum VRAM-Freimachen
|
||||
deckt `llama-swap` innerhalb eines Hosts (B0.5). Waechst die Flotte: erst den
|
||||
billigen Heartbeat-Teil; fuer echte Orchestrierung Docker Swarm / Nomad nehmen
|
||||
statt selbst einen Scheduler zu bauen.
|
||||
@@ -227,7 +227,7 @@ lohnt nicht):
|
||||
einen Heartbeat via RVS (Host, GPU-Util, VRAM frei/belegt, laufende
|
||||
GPU-Container). Diagnostic zeigt pro Host VRAM-Balken + Dienste + „Host X hat
|
||||
N GB frei". Kein Start/Stop, nur Sicht + Hinweis wohin verschiebbar.
|
||||
- **Zukunft (Gamebox3, 4×3060 = 48 GB):** neuer Host, eigenes Profil, `up` →
|
||||
- **Zukunft (AI-Box3, 4×3060 = 48 GB):** neuer Host, eigenes Profil, `up` →
|
||||
erscheint im Dashboard; grosses lokales LLM oder FLUX-Vollausbau dorthin.
|
||||
Ohne Orchestrator.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
ARIA FLUX-Bridge — laeuft auf der Gamebox (RTX 3060).
|
||||
ARIA FLUX-Bridge — laeuft auf der AI-Box (RTX 3060).
|
||||
|
||||
Empfaengt flux_request via RVS → FLUX.1-dev/-schnell auf GPU → sendet
|
||||
flux_response mit base64-PNG zurueck an die aria-bridge. Diese speichert
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# ─── ARIA Host-Agent — Konfiguration ───────────────────────────────
|
||||
# Kopiere diese Datei nach .env (neben die Binary) und passe sie an.
|
||||
|
||||
# RVS-Zugang (identisch zum Haupt-Stack — gleicher Raum/Token, damit ARIA
|
||||
# diesen Rechner erreicht). Werte aus der Haupt-.env.
|
||||
RVS_HOST=rvs.example.de
|
||||
RVS_PORT=443
|
||||
RVS_TLS=true
|
||||
RVS_TLS_FALLBACK=true # bei TLS-Fehlschlag einmal auf ws:// zurueckfallen
|
||||
RVS_TOKEN=
|
||||
# RVS_SNI: nur noetig, wenn RVS_HOST eine IP ist (Agent im selben Netz wie der
|
||||
# RVS, direkt auf die interne IP). Dann hier den Zertifikats-/Hostnamen angeben,
|
||||
# damit der TLS-Handshake (SNI) passt. Sonst leer lassen.
|
||||
# RVS_HOST=10.0.0.2
|
||||
# RVS_SNI=example.com
|
||||
RVS_SNI=
|
||||
|
||||
# ─── Identitaet dieses Rechners ────────────────────────────────────
|
||||
# HOST_ID = technisch eindeutig (a-z0-9-_), Default = Hostname-Slug.
|
||||
# HOST_NAME = menschlicher Name, so spricht ARIA den Rechner an ("Stefans Laptop").
|
||||
HOST_ID=
|
||||
HOST_NAME=
|
||||
|
||||
# ─── Steuerung (Sicherheit!) ───────────────────────────────────────
|
||||
# MUSS auf true, sonst fuehrt der Agent nichts aus (reiner Idle-Client).
|
||||
CONTROL_ENABLED=true
|
||||
|
||||
# ─── sudo ──────────────────────────────────────────────────────────
|
||||
# Reihenfolge: 1) Agent laeuft als root -> braucht kein sudo. 2) SUDO_PASSWORD
|
||||
# gesetzt -> sudo -S mit Passwort. 3) SUDO_NOPASSWD=true -> sudo -n (Live-ISO /
|
||||
# passwortloses sudo, z.B. Linux Mint vom Stick). 4) sonst schlaegt sudo fehl.
|
||||
SUDO_PASSWORD=
|
||||
SUDO_NOPASSWD=false
|
||||
|
||||
# ─── Limits (optional) ─────────────────────────────────────────────
|
||||
EXEC_TIMEOUT=60 # max. Laufzeit eines Kommandos (s)
|
||||
OUT_MAX_CHARS=20000 # stdout-Ausschnitt (offset/max_chars pro Request)
|
||||
FILE_MAX_BYTES=10485760 # max. Datei-Transfer (10 MB)
|
||||
@@ -0,0 +1,6 @@
|
||||
.env
|
||||
build/
|
||||
dist/
|
||||
.buildenv/
|
||||
*.spec
|
||||
__pycache__/
|
||||
@@ -0,0 +1,24 @@
|
||||
# Baut die Host-Agent-Binary mit PyInstaller in einem Container mit ALTEM glibc
|
||||
# (bullseye, glibc 2.31), damit die Onefile-Binary auf moeglichst vielen Linux-
|
||||
# Distributionen laeuft (glibc ist abwaerts-, nicht aufwaertskompatibel).
|
||||
FROM python:3.11-slim-bullseye
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# PyInstaller braucht objdump aus binutils (im slim-Image nicht enthalten).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends binutils \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip install --no-cache-dir pyinstaller
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY host_agent.py .
|
||||
|
||||
# Onefile-Binary; psutil-Hidden-Imports werden von PyInstaller erkannt.
|
||||
RUN pyinstaller --onefile --name aria-host-agent \
|
||||
--collect-all psutil \
|
||||
host_agent.py
|
||||
|
||||
# Ergebnis liegt in /build/dist/aria-host-agent
|
||||
CMD ["sh", "-c", "cp /build/dist/aria-host-agent /out/ && echo 'Binary -> /out/aria-host-agent'"]
|
||||
@@ -0,0 +1,36 @@
|
||||
# Baut die Windows-.exe des Host-Agents AUF LINUX — via Wine + Windows-Python +
|
||||
# PyInstaller. tobix/pywine bringt Wine + Windows-Python 3.11 mit (PyInstaller
|
||||
# kann NICHT cross-compilen, deshalb der Wine-Umweg).
|
||||
#
|
||||
# Zusaetzlich baut NSIS ein setup.exe, das die Agent-.exe installiert, eine .env
|
||||
# in C:\ProgramData\ARIA-Host-Agent anlegt (falls keine da ist) und den Agent als
|
||||
# automatisch startenden Windows-Dienst (via nssm) einrichtet.
|
||||
FROM tobix/pywine:3.11
|
||||
|
||||
ARG VERSION=0.0.0
|
||||
|
||||
# NSIS (Installer-Compiler, laeuft nativ auf Linux) + Tools fuer nssm.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends nsis curl unzip ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /work
|
||||
|
||||
# nssm — Non-Sucking Service Manager (public domain): macht aus der Konsolen-.exe
|
||||
# einen sauberen Windows-Dienst (die .exe selbst spricht das SCM nicht).
|
||||
RUN curl -fsSL https://nssm.cc/release/nssm-2.24.zip -o /tmp/nssm.zip \
|
||||
&& unzip -q /tmp/nssm.zip -d /tmp \
|
||||
&& cp /tmp/nssm-2.24/win64/nssm.exe ./nssm.exe \
|
||||
&& rm -rf /tmp/nssm*
|
||||
|
||||
COPY requirements.txt host_agent.py ./
|
||||
COPY windows/installer.nsi ./
|
||||
|
||||
# Windows-Python-Deps + PyInstaller, dann die Onefile-.exe bauen.
|
||||
RUN wine pip install --no-cache-dir -r requirements.txt pyinstaller
|
||||
RUN wine pyinstaller --onefile --name aria-host-agent --collect-all psutil host_agent.py \
|
||||
&& cp dist/aria-host-agent.exe ./aria-host-agent.exe \
|
||||
&& makensis -DVERSION=${VERSION} installer.nsi
|
||||
|
||||
# Beide Artefakte rausreichen (dist/ wird vom build-win.sh als Volume gemountet).
|
||||
CMD ["bash","-lc","cp dist/aria-host-agent.exe /out/ && cp aria-host-agent-setup.exe /out/ && echo 'OK -> /out/aria-host-agent.exe + /out/aria-host-agent-setup.exe'"]
|
||||
@@ -0,0 +1,178 @@
|
||||
# ARIA Host-Agent
|
||||
|
||||
Ein schlanker Agent, der **direkt auf einem Rechner** läuft und ARIA erlaubt,
|
||||
diesen Rechner zu steuern — auch wenn er sonst aus dem Netz **nicht erreichbar**
|
||||
ist (hinter NAT/Firewall, kein offener Port). Der Agent verbindet sich
|
||||
**ausgehend** zum RVS (gleicher Token wie der Rest von ARIA).
|
||||
|
||||
Unterschied zum **Satelliten**: der Satellit entdeckt und steuert *andere*
|
||||
Geräte in einem LAN; der Host-Agent steuert *den Rechner, auf dem er läuft*.
|
||||
|
||||
## Fähigkeiten
|
||||
|
||||
| Aktion | Was |
|
||||
|--------------|-----|
|
||||
| `exec` | Shell-Kommando ausführen (optional `sudo`), stdout/stderr/exit |
|
||||
| `read` | Datei lesen (Base64, mit Offset/Limit) |
|
||||
| `write` | Datei schreiben/anhängen (Base64 oder Text) |
|
||||
| `info` | OS, CPU/RAM/Disk-Auslastung, Uptime, IP |
|
||||
| `screenshot` | Bildschirmfoto (X11: scrot/maim · Wayland: grim) |
|
||||
|
||||
ARIA nutzt diese über die Brain-Tools `host_list` / `host_exec` / `host_read` /
|
||||
`host_write` / `host_info` / `host_screenshot`.
|
||||
|
||||
## Plattformen
|
||||
|
||||
Eine Codebasis, läuft auf **Linux, macOS und Windows** (der Agent wählt Shell,
|
||||
Screenshot-Methode und Root/Admin-Check je OS automatisch):
|
||||
|
||||
| | exec | Root/Admin | Screenshot |
|
||||
|---|---|---|---|
|
||||
| **Linux** | `bash -lc` | sudo (`SUDO_PASSWORD`/`SUDO_NOPASSWD`) / root | grim (Wayland) · scrot/maim (X11) |
|
||||
| **macOS** | `bash -lc` | sudo (wie Linux) | `screencapture` (Bordmittel) |
|
||||
| **Windows** | PowerShell | Agent **als Administrator** starten (kein sudo) | PowerShell/System.Drawing (Bordmittel) |
|
||||
|
||||
PyInstaller kann **nicht cross-kompilieren** — jede Binary wird auf ihrem OS gebaut.
|
||||
|
||||
## Bauen
|
||||
|
||||
**Linux (portabel, empfohlen)** — Docker-Container mit altem glibc:
|
||||
```bash
|
||||
./build.sh # -> dist/aria-host-agent (~15 MB, läuft auf vielen Distros)
|
||||
```
|
||||
|
||||
**Linux/macOS ohne Docker** — PyInstaller direkt (linkt gegen lokales glibc/OS):
|
||||
```bash
|
||||
./build-native.sh # -> dist/aria-host-agent
|
||||
```
|
||||
|
||||
**Windows — nativ** (auf einem Windows-Rechner, Python 3 im PATH nötig):
|
||||
```bat
|
||||
build-native.bat REM -> dist\aria-host-agent.exe
|
||||
```
|
||||
|
||||
**Windows — aus Docker heraus (auf Linux!), inkl. Installer** — Wine baut die
|
||||
`.exe`, NSIS packt ein `setup.exe`, das den Agent als Windows-Dienst einrichtet:
|
||||
```bash
|
||||
./build-win.sh [version]
|
||||
# -> dist/aria-host-agent.exe (Konsolen-Binary)
|
||||
# -> dist/aria-host-agent-setup.exe (Installer: Dienst + .env in ProgramData)
|
||||
```
|
||||
Der erste Lauf zieht das `tobix/pywine`-Image (~1–2 GB) und richtet die Wine-
|
||||
Python-Umgebung ein — das dauert; Folge-Builds sind schnell. PyInstaller kann
|
||||
nicht cross-compilen, deshalb der Wine-Umweg. **macOS geht so NICHT** (Apple
|
||||
lässt sich nicht legal aus Docker bauen) — dort `./build-native.sh` auf einem Mac.
|
||||
|
||||
### Docker scheitert? (Live-ISO / overlayfs-Root)
|
||||
|
||||
Wenn `build.sh` mit `failed to mount … overlayfs … invalid argument` abbricht,
|
||||
läufst du wahrscheinlich auf einem **Live-System** (Live-ISO). Dessen Root ist
|
||||
selbst ein overlayfs, und Dockers `overlay2`-Treiber kann kein Overlay-auf-
|
||||
Overlay stapeln. Zwei Auswege:
|
||||
|
||||
- **Empfohlen:** Binary auf einem normal installierten Linux bauen (`./build.sh`)
|
||||
und nur die fertige `dist/aria-host-agent` aufs Live-System kopieren. Die
|
||||
Binary ist portabel — Ziel braucht weder Docker noch Python.
|
||||
- **Nativ bauen (ohne Docker):**
|
||||
```bash
|
||||
sudo apt install -y python3-pip python3-venv
|
||||
./build-native.sh
|
||||
```
|
||||
Achtung: nativ gebaut linkt die Binary gegen das glibc **dieser** Maschine —
|
||||
sie läuft dann nur auf Systemen mit gleichem oder neuerem glibc.
|
||||
|
||||
## Installieren
|
||||
|
||||
1. `dist/aria-host-agent` auf den Ziel-Rechner kopieren.
|
||||
2. `.env.example` → `.env` daneben, RVS-Zugang + `CONTROL_ENABLED=true` eintragen.
|
||||
3. Starten: `chmod +x aria-host-agent && ./aria-host-agent`
|
||||
|
||||
### Als systemd-Dienst (empfohlen für Dauerbetrieb)
|
||||
|
||||
Der Installer kopiert Binary + `.env` an ihre Plätze und richtet den Dienst ein:
|
||||
|
||||
```bash
|
||||
# .env-Pfad direkt übergeben:
|
||||
sudo ./install-service.sh /pfad/zur/.env
|
||||
|
||||
# ODER ohne Argument -> ncurses-Dateidialog (dialog) zum Auswählen der .env:
|
||||
sudo ./install-service.sh
|
||||
```
|
||||
|
||||
Er legt ab:
|
||||
- Binary → `/usr/local/bin/aria-host-agent`
|
||||
- `.env` → `/etc/aria-host-agent/.env` (Rechte `0600`, enthält Token/Passwörter)
|
||||
- Unit → `/etc/systemd/system/aria-host-agent.service`, dann `enable --now`.
|
||||
|
||||
Danach: `systemctl status aria-host-agent` · `journalctl -u aria-host-agent -f`.
|
||||
Die Binary sucht er unter `dist/aria-host-agent` bzw. `./aria-host-agent` (oder
|
||||
2. Argument). Braucht `dialog` für den Dateibrowser (bietet die Installation an).
|
||||
|
||||
### Windows-Dienst (setup.exe)
|
||||
|
||||
`aria-host-agent-setup.exe` (aus `build-win.sh` oder dem Gitea-Release) als
|
||||
Administrator ausführen. Der Installer:
|
||||
- kopiert die `.exe` nach `%ProgramFiles%\ARIA Host-Agent`,
|
||||
- legt `%ProgramData%\ARIA-Host-Agent\.env` an (nur falls noch keine da ist),
|
||||
- richtet über **nssm** den Dienst **ARIA Host-Agent** ein (Autostart) und startet ihn.
|
||||
|
||||
Danach die `.env` unter `%ProgramData%\ARIA-Host-Agent\` mit RVS-Zugang +
|
||||
`CONTROL_ENABLED=true` füllen und den Dienst neu starten (`services.msc` →
|
||||
*ARIA Host-Agent*, oder `nssm restart ARIAHostAgent`). Deinstallation über
|
||||
*Apps & Features* → *ARIA Host-Agent* (die `.env` in ProgramData bleibt erhalten).
|
||||
|
||||
## Release (Binaries als Gitea-Assets)
|
||||
|
||||
`release_agent.sh <version>` baut alles Docker-Baubare und hängt es als
|
||||
**Release-Asset** an den Tag `agent-v<version>` — nichts landet im Git-Tree:
|
||||
|
||||
```bash
|
||||
./release_agent.sh 0.2.0 # Linux + Android + Windows (Wine)
|
||||
SKIP_WINDOWS=1 ./release_agent.sh 0.2.0 # ohne Windows (schneller)
|
||||
```
|
||||
|
||||
Assets: `aria-host-agent-linux-x64`, `aria-host-agent-android-agent-v<v>.apk`,
|
||||
`aria-host-agent-windows.exe`, `aria-host-agent-windows-setup.exe`. **macOS** ist
|
||||
nicht Docker-baubar — auf einem Mac `./build-native.sh` laufen lassen und das
|
||||
Ergebnis vor dem Release nach `dist/aria-host-agent-macos` legen, dann nimmt das
|
||||
Skript es automatisch mit. Gitea-Zugang via `.env`/Umgebung (`GITEA_URL`,
|
||||
`GITEA_REPO`, `GITEA_USER`), Kennwort wird abgefragt.
|
||||
|
||||
## TLS / SNI — Agent im selben Netz wie der RVS
|
||||
|
||||
Steht der Rechner im **selben Netz wie der RVS** (z.B. Rechenzentrum) und soll
|
||||
direkt auf dessen **interne IP** verbinden (kein NAT-Hairpin über den externen
|
||||
Hostnamen), scheitert der TLS-Handshake sonst an `tlsv1 alert internal error`
|
||||
(Caddy hat kein Zertifikat für die IP). Lösung — in der `.env`:
|
||||
|
||||
```
|
||||
RVS_HOST=10.0.0.2 # interne RVS-IP
|
||||
RVS_SNI=example.com # Name, für den das Caddy-Zert gilt
|
||||
```
|
||||
|
||||
Der Agent verbindet dann auf die IP, präsentiert aber den Namen im TLS-SNI.
|
||||
Zuhause / im Normalfall `RVS_SNI` leer lassen und den Hostnamen als `RVS_HOST`.
|
||||
|
||||
## sudo
|
||||
|
||||
Vier Fälle, der Agent wählt automatisch:
|
||||
|
||||
1. **Agent läuft als root** (z.B. systemd `User=root`) → volle Rechte, kein sudo nötig.
|
||||
2. `SUDO_PASSWORD=…` in der `.env` → `sudo -S` mit Passwort.
|
||||
3. `SUDO_NOPASSWD=true` → `sudo -n` (Live-ISO / passwortloses sudo, z.B. Linux
|
||||
Mint vom Stick).
|
||||
4. sonst → sudo-Kommandos scheitern mit klarer Meldung.
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- Reagiert **nur** auf den eigenen RVS-Raum (Token) und **nur**, wenn
|
||||
`CONTROL_ENABLED=true`.
|
||||
- Keine offenen Ports (reiner ausgehender Client).
|
||||
- Alle Kommandos werden geloggt.
|
||||
- Der Agent gibt **vollen** Zugriff auf den Rechner — nur auf Maschinen
|
||||
einsetzen, denen du ARIA anvertraust.
|
||||
|
||||
## Hinweis Screenshot
|
||||
|
||||
Als Systemdienst fehlt die grafische Session. Für `screenshot` den Agent in der
|
||||
Desktop-Session starten (Autostart) oder `DISPLAY`/`XAUTHORITY` in der Unit setzen.
|
||||
@@ -0,0 +1,11 @@
|
||||
build/
|
||||
.gradle/
|
||||
dist/
|
||||
*.apk
|
||||
local.properties
|
||||
.idea/
|
||||
*.iml
|
||||
captures/
|
||||
|
||||
# Signaturschluessel — NUR lokal, niemals ins oeffentliche Repo (Backup machen!)
|
||||
aria-agent.keystore
|
||||
@@ -0,0 +1,32 @@
|
||||
# Baut die Android-Agent-APK (Debug, auto-signiert -> direkt installierbar).
|
||||
# APK-Builds gehen nur unter Linux — deshalb im Container.
|
||||
FROM eclipse-temurin:17-jdk-jammy
|
||||
|
||||
ARG GRADLE_VERSION=8.5
|
||||
ARG CMDLINE_TOOLS=11076708
|
||||
ENV ANDROID_SDK_ROOT=/opt/android-sdk
|
||||
ENV ANDROID_HOME=/opt/android-sdk
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
unzip wget ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Gradle
|
||||
RUN wget -q https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip -O /tmp/g.zip \
|
||||
&& unzip -q /tmp/g.zip -d /opt && rm /tmp/g.zip
|
||||
|
||||
# Android cmdline-tools + SDK
|
||||
RUN mkdir -p ${ANDROID_SDK_ROOT}/cmdline-tools \
|
||||
&& wget -q https://dl.google.com/android/repository/commandlinetools-linux-${CMDLINE_TOOLS}_latest.zip -O /tmp/c.zip \
|
||||
&& unzip -q /tmp/c.zip -d ${ANDROID_SDK_ROOT}/cmdline-tools && rm /tmp/c.zip \
|
||||
&& mv ${ANDROID_SDK_ROOT}/cmdline-tools/cmdline-tools ${ANDROID_SDK_ROOT}/cmdline-tools/latest
|
||||
|
||||
ENV PATH="/opt/gradle-${GRADLE_VERSION}/bin:${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin:${ANDROID_SDK_ROOT}/platform-tools:${PATH}"
|
||||
|
||||
RUN yes | sdkmanager --licenses >/dev/null 2>&1 || true
|
||||
RUN sdkmanager "platform-tools" "platforms;android-34" "build-tools;34.0.0" >/dev/null 2>&1
|
||||
|
||||
WORKDIR /project
|
||||
COPY . /project
|
||||
|
||||
CMD ["bash","-lc","gradle --no-daemon assembleDebug && cp app/build/outputs/apk/debug/app-debug.apk /out/aria-android-agent.apk && echo 'OK -> /out/aria-android-agent.apk'"]
|
||||
@@ -0,0 +1,194 @@
|
||||
# ARIA Android-Agent
|
||||
|
||||
Ein **nativer Android-Agent** (eigene APK), der ARIA erlaubt, ein Smartphone
|
||||
**fernzusteuern** — inkl. Bedienen fremder App-UIs (z.B. „ARIA, richte auf dem
|
||||
Handy ein E-Mail-Konto ein"). Gegenstück zum Desktop-`host-agent` (Linux/macOS/
|
||||
Windows), aber Android ist kein Unix-Shell-System — deshalb ein **anderes
|
||||
Action-Set** (UI-Automation statt beliebiger Shell-Kommandos).
|
||||
|
||||
Verbindet sich wie die ARIA-App **ausgehend** zum RVS (gleicher Token/Raum),
|
||||
Verbindungs-Setup per **QR-Scan oder manueller Eingabe**. Taucht in der
|
||||
Diagnostic unter **Satelliten → Host-Agenten 💻** auf (`host_hello` mit
|
||||
`os="Android …"` + Android-Caps).
|
||||
|
||||
## Warum nativ (Kotlin), nicht Termux/RN
|
||||
|
||||
- **UI-Automation** (fremde Apps bedienen) geht auf Android nur über einen
|
||||
**AccessibilityService** — den kann nur eine native App bereitstellen.
|
||||
- **Screenshots** einer laufenden Session: **MediaProjection** (native).
|
||||
- **Dauerbetrieb**: Foreground-Service mit Notification (native).
|
||||
- Termux gäbe nur Shell + `termux-api` (SMS/Anruf/Standort …), **kein** Bedienen
|
||||
anderer App-UIs. Für „E-Mail-Konto durchklicken" reicht das nicht.
|
||||
|
||||
Tech: **Kotlin**, OkHttp-WebSocket (RVS-Client), CameraX/ML-Kit (QR),
|
||||
AccessibilityService (Input), MediaProjection (Screenshot). Build via Docker
|
||||
(Android-SDK + Gradle) → APK. Nur Linux baut APKs (Docker), Deploy manuell.
|
||||
|
||||
## Action-Set (host_command → host_result)
|
||||
|
||||
Android-spezifisch (statt exec/read/write des Desktop-Agents):
|
||||
|
||||
| Action | Was |
|
||||
|---|---|
|
||||
| `screenshot` | Bildschirmfoto (MediaProjection) — ARIA *sieht* den Schirm |
|
||||
| `ui_dump` | Sichtbare UI als Baum (Texte, Buttons, Felder + Koordinaten) — ARIAs „Augen" für gezieltes Tippen |
|
||||
| `ui_tap` | Tippen (x,y ODER auf ein Element aus ui_dump) |
|
||||
| `ui_text` | Text in das fokussierte/angegebene Feld schreiben |
|
||||
| `ui_swipe` | Wischen/Scrollen |
|
||||
| `ui_key` | Systemtasten (BACK, HOME, ENTER …) |
|
||||
| `app_launch` | App per Paketname starten (z.B. E-Mail-App) |
|
||||
| `app_list` | installierte Apps auflisten |
|
||||
| `info` | Gerät: Modell, Android-Version, Akku, Netz, IP |
|
||||
| `notify` | Benachrichtigung anzeigen |
|
||||
| *(später)* | `sms_send`, `call`, `location`, `clipboard` (je nach Bedarf + Berechtigung) |
|
||||
|
||||
ARIA-Flow „E-Mail einrichten": `app_launch` (Mail-App) → `screenshot`/`ui_dump`
|
||||
(sehen, was da ist) → `ui_tap`/`ui_text` (durchklicken) → wieder `ui_dump` prüfen,
|
||||
bis fertig. Genau das agentische Muster wie beim Endian-Fix, nur mit Handy-UI.
|
||||
|
||||
## Dauerbetrieb — Foreground-Service vs. Push (FCM)
|
||||
|
||||
Der Agent muss **immer erreichbar** sein, obwohl Android Hintergrundprozesse
|
||||
aggressiv killt (Doze, App-Standby, OEM-Batterie-Manager wie Xiaomi/Huawei).
|
||||
Zwei Wege, deine WhatsApp-Intuition trifft ins Schwarze:
|
||||
|
||||
**A) Foreground-Service (persistente WebSocket)** — der einfache Start:
|
||||
- Dauerhafte RVS-Verbindung + Foreground-Notification („Agent aktiv").
|
||||
- Braucht: `FOREGROUND_SERVICE`, **Akku-Optimierung ausnehmen**
|
||||
(`REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` — User whitelistet die App),
|
||||
`RECEIVE_BOOT_COMPLETED` + BootReceiver (Neustart nach Reboot), Auto-Reconnect
|
||||
(haben wir im Protokoll schon).
|
||||
- **Reutzt unser bestehendes `host_hello`/`host_command`/`host_result` 1:1.**
|
||||
- Nachteil: etwas Akku; manche OEMs killen trotzdem → „Autostart" manuell erlauben.
|
||||
|
||||
**B) Self-hosted Push (KEIN Google!)** — genau wie WhatsApp, aber auf eigenem Server:
|
||||
- **UnifiedPush + self-hosted ntfy**: Auf dem ARIA-Server läuft **ntfy** (freier,
|
||||
self-hostbarer Push-Server). Der Agent nutzt **UnifiedPush** (offener Standard,
|
||||
de-Google-Welt/F-Droid) mit dem ntfy-Distributor auf dem Handy. Will ARIA etwas,
|
||||
POSTet die Bridge/RVS an ntfy → weckt die App → sie holt den Befehl vom RVS,
|
||||
arbeitet, antwortet. **Läuft auch auf Custom-ROMs OHNE Google Play Services.**
|
||||
- Akkuschonend wie FCM, aber ohne jede Google-Abhängigkeit. Nur ein Dienst mehr
|
||||
(ntfy) im Stack + der Push-Auslöser serverseitig.
|
||||
|
||||
**C) FCM (Google) — optional:** Wer ein Stock-Android mit Play Services hat und
|
||||
Googles Push-Kanal will, kann FCM statt ntfy nehmen (bester Akku auf GMS-Geräten).
|
||||
Braucht Firebase-Projekt + Play Services. **Nur eine Option, keine Pflicht.**
|
||||
|
||||
**Custom-ROM ohne Google:** → Weg **A** (eigener Socket) oder **B** (self-hosted
|
||||
ntfy). Beide brauchen KEIN Google. Für Stefans dediziertes Ziel-Handy ist **A**
|
||||
sogar oft die einfachste Dauerlösung (unser eigener „Push" über den RVS-Socket).
|
||||
|
||||
**Hybrid (ideal, End-Ausbau):** Im Leerlauf nur Push (max. Akku). Ein Push weckt
|
||||
die App → sie öffnet die RVS-Verbindung, hält sich per Wakelock für die Interaktion
|
||||
wach (mehrere Befehle flüssig, z.B. E-Mail-Setup durchklicken) → schläft nach ein
|
||||
paar Sekunden Ruhe wieder ein. So WhatsApp-Akku UND schnelle Multi-Befehl-Sessions.
|
||||
Der Push kommt dabei von **B (self-hosted ntfy)** oder C (FCM) — freie Wahl.
|
||||
Erste Push-Latenz aus tiefem Doze ~1–3 s; danach bleibt der Socket die Session offen.
|
||||
|
||||
**Empfehlung:** Meilenstein 1–3 mit **A (Foreground-Service)** — läuft sofort und
|
||||
nutzt alles Vorhandene, damit wir schnell einen funktionierenden Agenten haben, ganz
|
||||
ohne externe Dienste. Dann **Push-Hybrid mit self-hosted ntfy (B)** als Akku-Ausbau —
|
||||
KEIN Google. FCM (C) nur optional für Stock-Android. Action-Set/Protokoll bleiben
|
||||
identisch, nur der Wecker ändert sich.
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- Reagiert nur auf den eigenen RVS-Raum (Token); Setup per QR/manuell.
|
||||
- **CONTROL_ENABLED**-Schalter in der App (Default AUS) — erst wenn Stefan es
|
||||
bewusst aktiviert, führt der Agent Aktionen aus.
|
||||
- AccessibilityService + MediaProjection müssen vom User **explizit** in den
|
||||
Android-Einstellungen freigegeben werden (kein stiller Zugriff möglich).
|
||||
- Alle Aktionen werden protokolliert (In-App-Log + optional an ARIA).
|
||||
- Voller Gerätezugriff — nur auf eigenen/anvertrauten Geräten nutzen.
|
||||
|
||||
## Meilensteine
|
||||
|
||||
1. **✅ Verbinden + sichtbar** — Gradle-Projekt, AndroidManifest, RVS-WS-Client,
|
||||
Foreground-Service, Connect-UI (QR-Scan + manuell), `host_hello`/`host_ping`.
|
||||
→ Agent erscheint in der Diagnostic. `info` funktioniert.
|
||||
2. **✅ Sehen** — MediaProjection-Screenshot (`ScreenCapturer`, gleicher
|
||||
`{format,bytes,base64}`-Vertrag wie der Desktop-Agent → `host_screenshot`) +
|
||||
`ui_dump` (`AriaAccessibilityService`, nur lesend → Brain-Tool `host_ui_dump`).
|
||||
Freigabe einmalig in der App: „Bildschirm-Zugriff erlauben" + „Bedienungshilfe
|
||||
öffnen". → ARIA sieht den Schirm und liest die UI-Elemente mit Koordinaten.
|
||||
3. **Steuern** — `ui_tap`/`ui_text`/`ui_swipe`/`ui_key`/`app_launch` über den
|
||||
AccessibilityService. → ARIA bedient Apps (E-Mail-Setup).
|
||||
4. **Feinschliff** — `info`/`app_list`/`notify`, Build-Härtung, `release.sh`
|
||||
(Version-Param → Gitea-Release-Asset, wie die App).
|
||||
|
||||
## Bauen
|
||||
|
||||
APK-Builds laufen **nur unter Linux** — deshalb im Docker-Container. Du brauchst
|
||||
nichts Android-spezifisches installiert, **nur Docker**. Android-SDK, Gradle und
|
||||
Build-Tools zieht der Container selbst (`Dockerfile.build`).
|
||||
|
||||
```bash
|
||||
cd host-agent/android
|
||||
./build.sh
|
||||
```
|
||||
|
||||
`build.sh` baut das Image `aria-android-agent-build` und lässt darin
|
||||
`gradle assembleDebug` laufen. Ergebnis:
|
||||
|
||||
```
|
||||
host-agent/android/dist/aria-android-agent.apk
|
||||
```
|
||||
|
||||
Das ist ein **Debug-APK**: auto-signiert mit dem Android-Debug-Key, also direkt
|
||||
installierbar — ohne eigenen Keystore, ohne Play Store.
|
||||
|
||||
### Auf dem Handy installieren
|
||||
|
||||
1. `dist/aria-android-agent.apk` aufs Zielgerät kopieren (USB, Cloud, `adb install
|
||||
dist/aria-android-agent.apk`, …).
|
||||
2. Antippen → Android fragt nach **„Unbekannte Quellen / Aus dieser Quelle
|
||||
installieren erlauben"** → erlauben.
|
||||
3. App öffnen → verbinden (QR/manuell), „Steuerung erlauben" an, für M2 zusätzlich
|
||||
„Bildschirm-Zugriff erlauben" + „Bedienungshilfe öffnen".
|
||||
|
||||
### Was der erste Build kostet
|
||||
|
||||
Der **erste** Lauf lädt viel (JDK-Image, Gradle, Android-SDK, Dependencies) und
|
||||
dauert entsprechend — mehrere Minuten. Folge-Builds sind schnell (Docker-Layer +
|
||||
Gradle-Cache im Image). Häufige Stolperer:
|
||||
|
||||
- **Docker fehlt / kein Zugriff** → `docker`-Rechte prüfen (`docker ps`).
|
||||
- **Overlay-on-Overlay auf einem Live-ISO** („invalid argument" beim Image-Bau) —
|
||||
gleiches Problem wie beim Desktop-Agent auf dem Mint-Live-System; von einer
|
||||
installierten Linux-Kiste bauen.
|
||||
- **Kotlin-/Manifest-Fehler** beim allerersten Bau eines neuen Meilensteins: den
|
||||
Gradle-Fehler posten, das glätten wir schnell.
|
||||
|
||||
### Version setzen
|
||||
|
||||
Bis es `release.sh` gibt, wird die Version in `app/build.gradle` gepflegt
|
||||
(`versionCode` / `versionName`). Aktuell `1` / `0.2.0` (M1+M2).
|
||||
|
||||
## Release
|
||||
|
||||
Das APK ist **kein** Teil des Git-Trees (blaeht sonst die History dauerhaft auf) —
|
||||
es wird als **Release-Asset** an einen Tag gehaengt. Das macht `release_agent.sh`
|
||||
(liegt eine Ebene hoeher, in `host-agent/`):
|
||||
|
||||
```bash
|
||||
cd host-agent
|
||||
./release_agent.sh 0.2.0
|
||||
```
|
||||
|
||||
Das Skript (wie die `release.sh` der Haupt-App, Version als Parameter):
|
||||
|
||||
- setzt die Version (`host_agent.py` → `AGENT_VERSION`, `app/build.gradle` →
|
||||
`versionName`/`versionCode`),
|
||||
- baut **Linux-Binary + Android-APK** per Docker,
|
||||
- committet den Version-Bump, taggt **`agent-v<version>`** (eigener Namespace,
|
||||
kollidiert nicht mit den App-Tags `v<version>`) und pusht,
|
||||
- legt ein Gitea-Release an und laedt die Assets hoch:
|
||||
`aria-host-agent-linux-x64`, `aria-host-agent-android-agent-v<version>.apk`,
|
||||
optional `-macos` / `-windows.exe` (falls in `host-agent/dist/` vorgebaut).
|
||||
|
||||
Gitea-Zugang (`GITEA_URL`, `GITEA_REPO`, `GITEA_USER`) kommt aus der Umgebung oder
|
||||
einer `.env`; das Kennwort wird interaktiv abgefragt. **Binaries landen unter
|
||||
„Releases", nie im Tree.**
|
||||
|
||||
> Status: **M1 + M2 fertig** (verbinden, `info`, `screenshot`, `ui_dump`),
|
||||
> `release_agent.sh` vorhanden. Als Nächstes Meilenstein 3 (Steuern).
|
||||
@@ -0,0 +1,57 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
id 'org.jetbrains.kotlin.android'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'de.hackersoft.ariaagent'
|
||||
compileSdk 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId 'de.hackersoft.ariaagent'
|
||||
minSdk 26
|
||||
targetSdk 33 // 33 vermeidet die Foreground-Service-Typ-Pflicht von 34
|
||||
versionCode 4
|
||||
versionName '0.0.0.4'
|
||||
}
|
||||
|
||||
// Fester Signaturschlüssel: jeder Build signiert mit DEMSELBEN Key, damit
|
||||
// Android neue APKs als Update derselben App akzeptiert (sonst "Konflikt mit
|
||||
// bestehendem Paket"). Die Keystore-Datei liegt NUR lokal (gitignored, nicht
|
||||
// im oeffentlichen Repo) — UNBEDINGT sichern, sonst brechen kuenftige Updates.
|
||||
def ariaKeystore = rootProject.file('aria-agent.keystore')
|
||||
signingConfigs {
|
||||
aria {
|
||||
if (ariaKeystore.exists()) {
|
||||
storeFile ariaKeystore
|
||||
storePassword 'ariaagent'
|
||||
keyAlias 'aria'
|
||||
keyPassword 'ariaagent'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
if (ariaKeystore.exists()) signingConfig signingConfigs.aria
|
||||
}
|
||||
release {
|
||||
minifyEnabled false
|
||||
if (ariaKeystore.exists()) signingConfig signingConfigs.aria
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = '17'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'androidx.core:core-ktx:1.12.0'
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||
implementation 'com.squareup.okhttp3:okhttp:4.12.0' // RVS-WebSocket
|
||||
implementation 'com.journeyapps:zxing-android-embedded:4.3.0' // QR-Scan (FOSS, kein Google-Dienst)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AppCompat.DayNight">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".AgentService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
<receiver
|
||||
android:name=".BootReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<service
|
||||
android:name=".AriaAccessibilityService"
|
||||
android:exported="false"
|
||||
android:label="ARIA Host-Agent"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.accessibilityservice"
|
||||
android:resource="@xml/accessibility_config" />
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,53 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
|
||||
/** Verbindungs-/Agent-Einstellungen (in SharedPreferences persistiert). */
|
||||
data class AgentConfig(
|
||||
var host: String = "",
|
||||
var port: Int = 443,
|
||||
var tls: Boolean = true,
|
||||
var token: String = "",
|
||||
var name: String = "",
|
||||
var controlEnabled: Boolean = false,
|
||||
) {
|
||||
companion object {
|
||||
private const val PREFS = "aria_agent"
|
||||
|
||||
fun load(ctx: Context): AgentConfig {
|
||||
val p = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
return AgentConfig(
|
||||
host = p.getString("host", "") ?: "",
|
||||
port = p.getInt("port", 443),
|
||||
tls = p.getBoolean("tls", true),
|
||||
token = p.getString("token", "") ?: "",
|
||||
name = p.getString("name", "") ?: "",
|
||||
controlEnabled = p.getBoolean("control", false),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun save(ctx: Context) {
|
||||
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().apply {
|
||||
putString("host", host)
|
||||
putInt("port", port)
|
||||
putBoolean("tls", tls)
|
||||
putString("token", token)
|
||||
putString("name", name)
|
||||
putBoolean("control", controlEnabled)
|
||||
apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun isValid(): Boolean = host.isNotBlank() && token.isNotBlank()
|
||||
|
||||
fun displayName(): String = if (name.isNotBlank()) name else Build.MODEL
|
||||
|
||||
/** Stabile, technische Host-ID (a-z0-9_-), wie beim Desktop-Agent. */
|
||||
fun hostId(): String {
|
||||
val base = displayName().lowercase()
|
||||
.replace(Regex("[^a-z0-9_-]+"), "-").trim('-')
|
||||
return base.ifBlank { "android" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
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 androidx.core.app.NotificationCompat
|
||||
|
||||
/**
|
||||
* Foreground-Service (Weg A): haelt die RVS-Verbindung dauerhaft, damit ARIA
|
||||
* den Agenten jederzeit erreicht. Persistente Notification + Auto-Reconnect.
|
||||
*/
|
||||
class AgentService : Service() {
|
||||
|
||||
private var rvs: RvsClient? = null
|
||||
|
||||
companion object {
|
||||
private const val CH = "aria_agent"
|
||||
private const val NOTIF_ID = 1
|
||||
const val ACTION_STATUS = "de.hackersoft.ariaagent.STATUS"
|
||||
const val ACTION_PROJECTION = "de.hackersoft.ariaagent.PROJECTION"
|
||||
const val EXTRA_RESULT_CODE = "resultCode"
|
||||
const val EXTRA_RESULT_DATA = "resultData"
|
||||
|
||||
@Volatile var status: String = "gestoppt"
|
||||
@Volatile var connected: Boolean = false
|
||||
|
||||
fun start(ctx: Context) {
|
||||
val i = Intent(ctx, AgentService::class.java)
|
||||
if (Build.VERSION.SDK_INT >= 26) ctx.startForegroundService(i) else ctx.startService(i)
|
||||
}
|
||||
|
||||
fun stop(ctx: Context) {
|
||||
ctx.stopService(Intent(ctx, AgentService::class.java))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createChannel()
|
||||
startForeground(NOTIF_ID, buildNotification("startet …"))
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
// WICHTIG: Jeder startForegroundService()-Aufruf MUSS binnen ~5s mit
|
||||
// startForeground() beantwortet werden — sonst crasht Android den Prozess
|
||||
// (ForegroundServiceDidNotStartInTimeException). Der Projection-Intent kommt
|
||||
// per startForegroundService, obwohl der Dienst schon laeuft -> hier IMMER
|
||||
// zuerst startForeground aufrufen (idempotent).
|
||||
startForeground(NOTIF_ID, buildNotification(status))
|
||||
|
||||
if (intent?.action == ACTION_PROJECTION) {
|
||||
val code = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
|
||||
@Suppress("DEPRECATION")
|
||||
val data = intent.getParcelableExtra<Intent>(EXTRA_RESULT_DATA)
|
||||
if (code != 0 && data != null) {
|
||||
try {
|
||||
ScreenCapturer.start(applicationContext, code, data)
|
||||
updateNotification("$status · Bildschirm-Zugriff aktiv")
|
||||
} catch (e: Throwable) {
|
||||
ScreenCapturer.lastError = e.message ?: e.javaClass.simpleName
|
||||
updateNotification("Bildschirm-Fehler: ${ScreenCapturer.lastError}")
|
||||
}
|
||||
}
|
||||
if (rvs == null) startRvs() // Dienst war frisch -> Verbindung nachziehen
|
||||
return START_STICKY
|
||||
}
|
||||
return startRvs()
|
||||
}
|
||||
|
||||
/** (Re-)Startet die RVS-Verbindung anhand der gespeicherten Config. */
|
||||
private fun startRvs(): Int {
|
||||
val cfg = AgentConfig.load(this)
|
||||
if (!cfg.isValid()) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
rvs?.stop()
|
||||
rvs = RvsClient(applicationContext, cfg) { conn, msg ->
|
||||
connected = conn
|
||||
status = msg
|
||||
updateNotification(msg)
|
||||
sendBroadcast(Intent(ACTION_STATUS).setPackage(packageName))
|
||||
}
|
||||
rvs?.start()
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
rvs?.stop()
|
||||
ScreenCapturer.stop()
|
||||
connected = false
|
||||
status = "gestoppt"
|
||||
sendBroadcast(Intent(ACTION_STATUS).setPackage(packageName))
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun createChannel() {
|
||||
if (Build.VERSION.SDK_INT >= 26) {
|
||||
val ch = NotificationChannel(CH, "ARIA Agent", NotificationManager.IMPORTANCE_LOW)
|
||||
ch.setShowBadge(false)
|
||||
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
|
||||
.createNotificationChannel(ch)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(text: String): Notification {
|
||||
val pi = PendingIntent.getActivity(
|
||||
this, 0, Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
return NotificationCompat.Builder(this, CH)
|
||||
.setContentTitle("ARIA Host-Agent")
|
||||
.setContentText(text)
|
||||
.setSmallIcon(R.drawable.ic_launcher)
|
||||
.setOngoing(true)
|
||||
.setContentIntent(pi)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun updateNotification(text: String) {
|
||||
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
|
||||
.notify(NOTIF_ID, buildNotification(text))
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.graphics.Rect
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Bedienungshilfe-Dienst (Meilenstein 2 — nur LESEND).
|
||||
*
|
||||
* Liefert einen strukturierten Baum der sichtbaren Bildschirm-Elemente: Text,
|
||||
* Beschriftung (contentDescription), Klasse, Bildschirm-Position (Mittelpunkt +
|
||||
* Rahmen) und Flags (klickbar/editierbar/ankreuzbar). ARIA nutzt das ergaenzend
|
||||
* zum Screenshot, um Ziele exakt zu benennen. Tippen/Text folgt in M3.
|
||||
*
|
||||
* Der Nutzer schaltet den Dienst einmalig unter Einstellungen > Bedienungshilfen
|
||||
* frei. Er fuehrt hier nichts autonom aus — reagiert nur auf `dump()`.
|
||||
*/
|
||||
class AriaAccessibilityService : AccessibilityService() {
|
||||
|
||||
override fun onServiceConnected() {
|
||||
instance = this
|
||||
}
|
||||
|
||||
override fun onUnbind(intent: android.content.Intent?): Boolean {
|
||||
if (instance === this) instance = null
|
||||
return super.onUnbind(intent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (instance === this) instance = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) { /* passiv */ }
|
||||
override fun onInterrupt() { /* passiv */ }
|
||||
|
||||
/** Strukturierter Baum des aktiven Fensters. Shape: {ok, result:{package,count,nodes[]}}. */
|
||||
fun dump(): JSONObject {
|
||||
val root = rootInActiveWindow
|
||||
?: return JSONObject().put("ok", false)
|
||||
.put("error", "Kein aktives Fenster lesbar (Bildschirm evtl. aus oder gesperrt).")
|
||||
val nodes = JSONArray()
|
||||
try {
|
||||
walk(root, nodes, 0)
|
||||
} finally {
|
||||
@Suppress("DEPRECATION") try { root.recycle() } catch (_: Exception) {}
|
||||
}
|
||||
val result = JSONObject()
|
||||
.put("package", root.packageName?.toString() ?: "")
|
||||
.put("count", nodes.length())
|
||||
.put("nodes", nodes)
|
||||
return JSONObject().put("ok", true).put("result", result)
|
||||
}
|
||||
|
||||
private fun walk(node: AccessibilityNodeInfo?, out: JSONArray, depth: Int) {
|
||||
if (node == null || depth > 40 || out.length() >= 400) return
|
||||
val text = node.text?.toString()?.trim()
|
||||
val desc = node.contentDescription?.toString()?.trim()
|
||||
val cls = node.className?.toString()?.substringAfterLast('.')
|
||||
val interesting = !text.isNullOrBlank() || !desc.isNullOrBlank() ||
|
||||
node.isClickable || node.isEditable || node.isCheckable
|
||||
if (interesting) {
|
||||
val r = Rect()
|
||||
node.getBoundsInScreen(r)
|
||||
val o = JSONObject()
|
||||
if (!text.isNullOrBlank()) o.put("text", text)
|
||||
if (!desc.isNullOrBlank()) o.put("desc", desc)
|
||||
if (cls != null) o.put("cls", cls)
|
||||
if (node.isClickable) o.put("clickable", true)
|
||||
if (node.isEditable) o.put("editable", true)
|
||||
if (node.isCheckable) o.put("checked", node.isChecked)
|
||||
o.put("x", r.centerX())
|
||||
o.put("y", r.centerY())
|
||||
o.put("bounds", "${r.left},${r.top},${r.right},${r.bottom}")
|
||||
out.put(o)
|
||||
}
|
||||
for (i in 0 until node.childCount) {
|
||||
walk(node.getChild(i), out, depth + 1)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
var instance: AriaAccessibilityService? = null
|
||||
|
||||
val available: Boolean get() = instance != null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
/** Startet den Agent-Service nach dem Booten wieder (wenn konfiguriert). */
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context, intent: Intent) {
|
||||
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
|
||||
if (AgentConfig.load(ctx).isValid()) {
|
||||
AgentService.start(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.appcompat.widget.SwitchCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import org.json.JSONObject
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var host: EditText
|
||||
private lateinit var port: EditText
|
||||
private lateinit var token: EditText
|
||||
private lateinit var name: EditText
|
||||
private lateinit var tls: SwitchCompat
|
||||
private lateinit var control: SwitchCompat
|
||||
private lateinit var statusView: TextView
|
||||
|
||||
private val scan = registerForActivityResult(ScanContract()) { res ->
|
||||
res.contents?.let { applyQr(it) }
|
||||
}
|
||||
private val camPerm = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) launchScan() else toast("Kamera-Berechtigung nötig für QR-Scan")
|
||||
}
|
||||
private val notifPerm = registerForActivityResult(ActivityResultContracts.RequestPermission()) { }
|
||||
|
||||
private val projection = registerForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) { res ->
|
||||
if (res.resultCode == Activity.RESULT_OK && res.data != null) {
|
||||
val i = Intent(this, AgentService::class.java)
|
||||
.setAction(AgentService.ACTION_PROJECTION)
|
||||
.putExtra(AgentService.EXTRA_RESULT_CODE, res.resultCode)
|
||||
.putExtra(AgentService.EXTRA_RESULT_DATA, res.data)
|
||||
ContextCompat.startForegroundService(this, i)
|
||||
toast("Bildschirm-Zugriff aktiv — ARIA kann jetzt Screenshots machen")
|
||||
} else {
|
||||
toast("Bildschirm-Zugriff abgelehnt")
|
||||
}
|
||||
}
|
||||
|
||||
private val statusReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(c: Context?, i: Intent?) = refreshStatus()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
|
||||
host = findViewById(R.id.host)
|
||||
port = findViewById(R.id.port)
|
||||
token = findViewById(R.id.token)
|
||||
name = findViewById(R.id.name)
|
||||
tls = findViewById(R.id.tls)
|
||||
control = findViewById(R.id.control)
|
||||
statusView = findViewById(R.id.status)
|
||||
|
||||
findViewById<Button>(R.id.btnScan).setOnClickListener {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
|
||||
== PackageManager.PERMISSION_GRANTED) launchScan()
|
||||
else camPerm.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
findViewById<Button>(R.id.btnConnect).setOnClickListener { saveAndConnect() }
|
||||
findViewById<Button>(R.id.btnStop).setOnClickListener {
|
||||
AgentService.stop(this)
|
||||
refreshStatus()
|
||||
}
|
||||
findViewById<Button>(R.id.btnScreen).setOnClickListener {
|
||||
if (!AgentService.connected && !AgentConfig.load(this).isValid()) {
|
||||
toast("Erst verbinden, dann Bildschirm-Zugriff erlauben")
|
||||
return@setOnClickListener
|
||||
}
|
||||
val mpm = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
projection.launch(mpm.createScreenCaptureIntent())
|
||||
}
|
||||
findViewById<Button>(R.id.btnAccessibility).setOnClickListener {
|
||||
try {
|
||||
startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
|
||||
toast("'ARIA Host-Agent' in der Liste einschalten")
|
||||
} catch (_: Exception) {
|
||||
toast("Bedienungshilfe-Einstellungen nicht gefunden")
|
||||
}
|
||||
}
|
||||
|
||||
loadIntoUi(AgentConfig.load(this))
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 33 &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
notifPerm.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
val filter = IntentFilter(AgentService.ACTION_STATUS)
|
||||
ContextCompat.registerReceiver(this, statusReceiver, filter,
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
refreshStatus()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
try { unregisterReceiver(statusReceiver) } catch (_: Exception) {}
|
||||
}
|
||||
|
||||
private fun launchScan() {
|
||||
val o = ScanOptions()
|
||||
.setBeepEnabled(false)
|
||||
.setOrientationLocked(false)
|
||||
.setPrompt("ARIA-Verbindungs-QR scannen")
|
||||
scan.launch(o)
|
||||
}
|
||||
|
||||
private fun applyQr(content: String) {
|
||||
try {
|
||||
val j = JSONObject(content)
|
||||
host.setText(j.optString("host"))
|
||||
port.setText((if (j.has("port")) j.optInt("port", 443) else 443).toString())
|
||||
token.setText(j.optString("token"))
|
||||
if (j.has("tls")) tls.isChecked = j.optBoolean("tls", true)
|
||||
toast("QR übernommen — jetzt 'Speichern & Verbinden'")
|
||||
} catch (_: Exception) {
|
||||
toast("Das ist kein ARIA-Verbindungs-QR")
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadIntoUi(c: AgentConfig) {
|
||||
host.setText(c.host)
|
||||
port.setText(c.port.toString())
|
||||
token.setText(c.token)
|
||||
name.setText(c.name)
|
||||
tls.isChecked = c.tls
|
||||
control.isChecked = c.controlEnabled
|
||||
}
|
||||
|
||||
private fun saveAndConnect() {
|
||||
val c = AgentConfig(
|
||||
host = host.text.toString().trim(),
|
||||
port = port.text.toString().trim().toIntOrNull() ?: 443,
|
||||
tls = tls.isChecked,
|
||||
token = token.text.toString().trim(),
|
||||
name = name.text.toString().trim(),
|
||||
controlEnabled = control.isChecked,
|
||||
)
|
||||
if (!c.isValid()) {
|
||||
toast("Host und Token sind Pflicht")
|
||||
return
|
||||
}
|
||||
c.save(this)
|
||||
AgentService.start(this)
|
||||
toast("Agent gestartet")
|
||||
refreshStatus()
|
||||
}
|
||||
|
||||
private fun refreshStatus() {
|
||||
val dot = if (AgentService.connected) "🟢" else "🔴"
|
||||
statusView.text = "Status: ${AgentService.status} $dot"
|
||||
}
|
||||
|
||||
private fun toast(m: String) = Toast.makeText(this, m, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
import android.content.Context
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* RVS-WebSocket-Client (Meilenstein 1). Spricht dasselbe Protokoll wie der
|
||||
* Desktop-Agent: meldet sich per host_hello, haelt sich per host_ping frisch,
|
||||
* beantwortet host_command -> host_result.
|
||||
*
|
||||
* M1-Aktionen: nur `info`. screenshot/ui_* folgen in M2/M3.
|
||||
*/
|
||||
class RvsClient(
|
||||
private val appCtx: Context,
|
||||
private val config: AgentConfig,
|
||||
private val onStatus: (connected: Boolean, msg: String) -> Unit,
|
||||
) {
|
||||
private val client = OkHttpClient.Builder()
|
||||
.pingInterval(20, TimeUnit.SECONDS)
|
||||
.readTimeout(0, TimeUnit.MILLISECONDS) // Server-Push: nie lesen-timeouten
|
||||
.build()
|
||||
|
||||
private var ws: WebSocket? = null
|
||||
@Volatile private var running = false
|
||||
private var pingThread: Thread? = null
|
||||
|
||||
private val caps = listOf("info", "screenshot", "ui_dump") // M3: ui_tap/ui_text/…
|
||||
|
||||
fun start() {
|
||||
running = true
|
||||
connect()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
pingThread?.interrupt()
|
||||
try { ws?.close(1000, "bye") } catch (_: Exception) {}
|
||||
ws = null
|
||||
}
|
||||
|
||||
private fun url(): String {
|
||||
val proto = if (config.tls) "wss" else "ws"
|
||||
return "$proto://${config.host}:${config.port}?token=${config.token}"
|
||||
}
|
||||
|
||||
private fun connect() {
|
||||
if (!running) return
|
||||
onStatus(false, "verbinde …")
|
||||
val req = Request.Builder().url(url()).build()
|
||||
ws = client.newWebSocket(req, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
onStatus(true, "verbunden")
|
||||
sendHello(webSocket)
|
||||
startPing(webSocket)
|
||||
}
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
handle(webSocket, text)
|
||||
}
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
onStatus(false, "getrennt: ${t.message ?: "?"}")
|
||||
reconnectLater()
|
||||
}
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
onStatus(false, "geschlossen")
|
||||
reconnectLater()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun reconnectLater() {
|
||||
pingThread?.interrupt()
|
||||
if (!running) return
|
||||
Thread {
|
||||
try { Thread.sleep(3000) } catch (_: InterruptedException) { return@Thread }
|
||||
connect()
|
||||
}.start()
|
||||
}
|
||||
|
||||
private fun send(webSocket: WebSocket, type: String, payload: JSONObject) {
|
||||
val o = JSONObject()
|
||||
o.put("type", type)
|
||||
o.put("payload", payload)
|
||||
o.put("timestamp", System.currentTimeMillis())
|
||||
try { webSocket.send(o.toString()) } catch (_: Exception) {}
|
||||
}
|
||||
|
||||
private fun sendHello(webSocket: WebSocket) {
|
||||
val p = JSONObject()
|
||||
p.put("hostId", config.hostId())
|
||||
p.put("name", config.displayName())
|
||||
p.put("os", "Android ${Build.VERSION.RELEASE} (${Build.MODEL})")
|
||||
p.put("caps", JSONArray(caps))
|
||||
p.put("control", config.controlEnabled)
|
||||
send(webSocket, "host_hello", p)
|
||||
}
|
||||
|
||||
private fun startPing(webSocket: WebSocket) {
|
||||
pingThread?.interrupt()
|
||||
pingThread = Thread {
|
||||
while (running && !Thread.currentThread().isInterrupted) {
|
||||
try { Thread.sleep(25000) } catch (_: InterruptedException) { break }
|
||||
val p = JSONObject().put("hostId", config.hostId())
|
||||
send(webSocket, "host_ping", p)
|
||||
sendHello(webSocket) // Re-announce (RVS replayt hellos nicht)
|
||||
}
|
||||
}.also { it.start() }
|
||||
}
|
||||
|
||||
private fun handle(webSocket: WebSocket, text: String) {
|
||||
val msg = try { JSONObject(text) } catch (_: Exception) { return }
|
||||
if (msg.optString("type") != "host_command") return
|
||||
val payload = msg.optJSONObject("payload") ?: JSONObject()
|
||||
|
||||
val target = payload.optString("host").ifBlank { payload.optString("hostId") }
|
||||
if (target.isNotBlank()
|
||||
&& !target.equals(config.hostId(), true)
|
||||
&& !target.equals(config.displayName(), true)) return
|
||||
|
||||
val action = payload.optString("action")
|
||||
// WICHTIG: JEDE Aktion muss ein host_result liefern — auch bei Exception
|
||||
// ODER OutOfMemoryError (Throwable!). Sonst bekommt ARIA statt einer
|
||||
// Fehlermeldung nur einen Timeout (kein Result kommt zurueck).
|
||||
val result: JSONObject = try {
|
||||
when {
|
||||
!config.controlEnabled ->
|
||||
err("Steuerung ist in der Agent-App deaktiviert (Schalter 'Steuerung erlauben').")
|
||||
action == "info" -> doInfo()
|
||||
action == "screenshot" -> doScreenshot()
|
||||
action == "ui_dump" -> doUiDump()
|
||||
action in listOf("ui_tap", "ui_text", "ui_swipe", "ui_key",
|
||||
"app_launch", "app_list", "notify") ->
|
||||
err("Aktion '$action' kommt in Meilenstein 3 (noch nicht implementiert).")
|
||||
else -> err("Aktion '$action' unbekannt.")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
err("Fehler bei '$action': ${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
result.put("requestId", payload.optString("requestId"))
|
||||
result.put("hostId", config.hostId())
|
||||
result.put("action", action)
|
||||
send(webSocket, "host_result", result)
|
||||
}
|
||||
|
||||
private fun err(m: String): JSONObject = JSONObject().put("ok", false).put("error", m)
|
||||
|
||||
/** Bildschirmfoto — selber Vertrag wie der Desktop-Agent: {format,bytes,base64}. */
|
||||
private fun doScreenshot(): JSONObject {
|
||||
if (!ScreenCapturer.active) {
|
||||
val why = ScreenCapturer.lastError?.let { " (letzter Fehler: $it)" } ?: ""
|
||||
return err("Bildschirm-Zugriff nicht erlaubt. In der Agent-App auf dem Handy " +
|
||||
"einmalig 'Bildschirm-Zugriff erlauben' antippen.$why")
|
||||
}
|
||||
val png = ScreenCapturer.capture()
|
||||
?: return err("Screenshot fehlgeschlagen: ${ScreenCapturer.lastError ?: "unbekannt"}")
|
||||
val b64 = android.util.Base64.encodeToString(png, android.util.Base64.NO_WRAP)
|
||||
val res = JSONObject().put("format", "png").put("bytes", png.size).put("base64", b64)
|
||||
return JSONObject().put("ok", true).put("result", res)
|
||||
}
|
||||
|
||||
/** Sichtbare Bedienelemente als Baum (Bedienungshilfe). */
|
||||
private fun doUiDump(): JSONObject {
|
||||
val svc = AriaAccessibilityService.instance
|
||||
?: return err("Bedienungshilfe nicht aktiv. In der Agent-App 'Bedienungshilfe " +
|
||||
"öffnen' antippen und 'ARIA Host-Agent' einschalten.")
|
||||
return svc.dump()
|
||||
}
|
||||
|
||||
private fun doInfo(): JSONObject {
|
||||
val res = JSONObject()
|
||||
res.put("host", config.displayName())
|
||||
res.put("model", Build.MODEL)
|
||||
res.put("manufacturer", Build.MANUFACTURER)
|
||||
res.put("android", Build.VERSION.RELEASE)
|
||||
res.put("sdk", Build.VERSION.SDK_INT)
|
||||
try {
|
||||
val bm = appCtx.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
|
||||
res.put("battery_percent", bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY))
|
||||
} catch (_: Exception) {}
|
||||
return JSONObject().put("ok", true).put("result", res)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package de.hackersoft.ariaagent
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.PixelFormat
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.display.VirtualDisplay
|
||||
import android.media.Image
|
||||
import android.media.ImageReader
|
||||
import android.media.projection.MediaProjection
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.DisplayMetrics
|
||||
import android.view.WindowManager
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* Bildschirm-Aufnahme via MediaProjection (Meilenstein 2 — "sehen").
|
||||
*
|
||||
* Der Nutzer erlaubt den Zugriff EINMALIG in der Agent-App (System-Dialog).
|
||||
* Danach laeuft ein stiller VirtualDisplay -> ImageReader, aus dem `capture()`
|
||||
* bei Bedarf das aktuelle Bild als PNG zieht. Kein Google-Dienst.
|
||||
*
|
||||
* Aufgenommen wird direkt in GEKAPPTER Aufloesung (max. 1280 lange Seite): die
|
||||
* MediaProjection skaliert den Bildschirminhalt auf die VirtualDisplay-Groesse.
|
||||
* Das haelt Speicher/Zeit klein (kein 10-MB-Vollbild-Bitmap -> kein OOM/Timeout).
|
||||
*
|
||||
* Der Zugriff geht bei App-Kill / Neustart verloren und muss neu erlaubt werden
|
||||
* (Android-Sicherheit — Projection-Token ist nicht persistierbar).
|
||||
*/
|
||||
object ScreenCapturer {
|
||||
private const val MAX_SIDE = 1280
|
||||
|
||||
private var projection: MediaProjection? = null
|
||||
private var reader: ImageReader? = null
|
||||
private var vdisplay: VirtualDisplay? = null
|
||||
private var handlerThread: HandlerThread? = null
|
||||
private var handler: Handler? = null
|
||||
private var w = 0
|
||||
private var h = 0
|
||||
private var dpi = 0
|
||||
|
||||
/** Letzter Init-/Capture-Fehler (fuer die Fehlermeldung an ARIA). */
|
||||
@Volatile
|
||||
var lastError: String? = null
|
||||
|
||||
val active: Boolean
|
||||
@Synchronized get() = projection != null
|
||||
|
||||
@Synchronized
|
||||
fun start(ctx: Context, resultCode: Int, data: Intent) {
|
||||
stop()
|
||||
val mpm = ctx.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
val mp = mpm.getMediaProjection(resultCode, data) ?: run {
|
||||
lastError = "getMediaProjection lieferte null"
|
||||
return
|
||||
}
|
||||
|
||||
val metrics = DisplayMetrics()
|
||||
val wm = ctx.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
@Suppress("DEPRECATION")
|
||||
wm.defaultDisplay.getRealMetrics(metrics)
|
||||
dpi = metrics.densityDpi
|
||||
// Direkt gekappt aufnehmen (lange Seite <= MAX_SIDE), Seitenverhaeltnis wahren.
|
||||
val longSide = maxOf(metrics.widthPixels, metrics.heightPixels)
|
||||
val scale = if (longSide > MAX_SIDE) MAX_SIDE.toFloat() / longSide else 1f
|
||||
w = (metrics.widthPixels * scale).toInt().coerceAtLeast(1)
|
||||
h = (metrics.heightPixels * scale).toInt().coerceAtLeast(1)
|
||||
|
||||
handlerThread = HandlerThread("aria-capture").also { it.start() }
|
||||
handler = Handler(handlerThread!!.looper)
|
||||
|
||||
// Ab Android 14 Pflicht VOR createVirtualDisplay; frueher unschaedlich.
|
||||
mp.registerCallback(object : MediaProjection.Callback() {
|
||||
override fun onStop() { stop() }
|
||||
}, handler)
|
||||
|
||||
val ir = ImageReader.newInstance(w, h, PixelFormat.RGBA_8888, 2)
|
||||
reader = ir
|
||||
// AUTO_MIRROR = Standard-Flag fuer MediaProjection-Capture (die Projection
|
||||
// selbst autorisiert die Aufnahme, kein Sonderrecht noetig).
|
||||
vdisplay = mp.createVirtualDisplay(
|
||||
"aria-screen", w, h, dpi,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
ir.surface, null, handler,
|
||||
)
|
||||
projection = mp
|
||||
lastError = null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
try { vdisplay?.release() } catch (_: Exception) {}
|
||||
try { reader?.close() } catch (_: Exception) {}
|
||||
try { projection?.stop() } catch (_: Exception) {}
|
||||
try { handlerThread?.quitSafely() } catch (_: Exception) {}
|
||||
vdisplay = null
|
||||
reader = null
|
||||
projection = null
|
||||
handlerThread = null
|
||||
handler = null
|
||||
}
|
||||
|
||||
/** PNG-Bytes des aktuellen Bildschirms, oder null (Grund in lastError). */
|
||||
fun capture(): ByteArray? {
|
||||
val r = reader ?: run { lastError = "kein aktiver Bildschirm-Reader"; return null }
|
||||
var image: Image? = null
|
||||
var tries = 0
|
||||
// Bis ~3s auf den ersten Frame warten (frischer VirtualDisplay braucht evtl. kurz).
|
||||
while (tries < 37) {
|
||||
image = r.acquireLatestImage()
|
||||
if (image != null) break
|
||||
try { Thread.sleep(80) } catch (_: InterruptedException) {}
|
||||
tries++
|
||||
}
|
||||
if (image == null) {
|
||||
lastError = "kein Frame erhalten (Bildschirm an? evtl. DRM-geschuetzter Inhalt)"
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
val plane = image.planes[0]
|
||||
val buffer = plane.buffer
|
||||
val pixelStride = plane.pixelStride
|
||||
val rowStride = plane.rowStride
|
||||
val rowPadding = rowStride - pixelStride * w
|
||||
val bmpW = w + (if (pixelStride > 0) rowPadding / pixelStride else 0)
|
||||
val bmp = Bitmap.createBitmap(bmpW, h, Bitmap.Config.ARGB_8888)
|
||||
bmp.copyPixelsFromBuffer(buffer)
|
||||
val out = ByteArrayOutputStream()
|
||||
if (rowPadding == 0) {
|
||||
bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
} else {
|
||||
val cropped = Bitmap.createBitmap(bmp, 0, 0, w, h)
|
||||
cropped.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
cropped.recycle()
|
||||
}
|
||||
bmp.recycle()
|
||||
lastError = null
|
||||
out.toByteArray()
|
||||
} catch (t: Throwable) {
|
||||
lastError = "Encode-Fehler: ${t.javaClass.simpleName}: ${t.message}"
|
||||
null
|
||||
} finally {
|
||||
try { image?.close() } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#0D0D1A"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#3FFF9F"
|
||||
android:pathData="M54,26 m-26,0 a26,26 0 1,0 52,0 a26,26 0 1,0 -52,0 Z M54,26 m-13,0 a13,13 0 1,1 26,0 a13,13 0 1,1 -26,0 Z" />
|
||||
<path
|
||||
android:fillColor="#3FFF9F"
|
||||
android:pathData="M52,58 h4 v24 h-4 z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,128 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:fillViewport="true">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/app_name"
|
||||
android:textSize="22sp"
|
||||
android:textStyle="bold"
|
||||
android:paddingBottom="4dp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/status"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Status: —"
|
||||
android:paddingBottom="16dp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnScan"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="QR-Code scannen" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="— oder manuell —"
|
||||
android:paddingTop="12dp"
|
||||
android:paddingBottom="4dp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/host"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="RVS-Host (z.B. rvs.example.com)"
|
||||
android:inputType="textUri" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/port"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="Port"
|
||||
android:text="443"
|
||||
android:inputType="number" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/token"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="RVS-Token"
|
||||
android:inputType="textNoSuggestions" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/name"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="Anzeigename (optional, z.B. 'Stefans Handy')"
|
||||
android:inputType="text" />
|
||||
|
||||
<androidx.appcompat.widget.SwitchCompat
|
||||
android:id="@+id/tls"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="TLS (wss)"
|
||||
android:checked="true"
|
||||
android:paddingTop="12dp" />
|
||||
|
||||
<androidx.appcompat.widget.SwitchCompat
|
||||
android:id="@+id/control"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Steuerung erlauben (Aktionen ausführen)"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="16dp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnConnect"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Speichern & Verbinden" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnStop"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Agent stoppen"
|
||||
android:paddingTop="8dp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Sehen (Meilenstein 2)"
|
||||
android:textStyle="bold"
|
||||
android:paddingTop="24dp"
|
||||
android:paddingBottom="4dp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Damit ARIA Screenshots machen und die Oberfläche lesen kann. Beides einmalig freigeben."
|
||||
android:textSize="13sp"
|
||||
android:paddingBottom="8dp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnScreen"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Bildschirm-Zugriff erlauben" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnAccessibility"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Bedienungshilfe öffnen"
|
||||
android:paddingTop="8dp" />
|
||||
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">ARIA Host-Agent</string>
|
||||
<string name="accessibility_desc">Erlaubt ARIA, die sichtbaren Bildschirm-Elemente zu lesen (Text und Position), um Dich fernzusteuern. Nur aktiv, wenn Du \'Steuerung erlauben\' eingeschaltet hast.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged"
|
||||
android:accessibilityFeedbackType="feedbackGeneric"
|
||||
android:accessibilityFlags="flagRetrieveInteractiveWindows|flagReportViewIds"
|
||||
android:canRetrieveWindowContent="true"
|
||||
android:notificationTimeout="100"
|
||||
android:description="@string/accessibility_desc" />
|
||||
@@ -0,0 +1,5 @@
|
||||
// Root-Build. Plugin-Versionen zentral, in den Modulen nur angewandt.
|
||||
plugins {
|
||||
id 'com.android.application' version '8.2.2' apply false
|
||||
id 'org.jetbrains.kotlin.android' version '1.9.22' apply false
|
||||
}
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# Baut die Android-Agent-APK per Docker (Android-SDK + Gradle).
|
||||
# ./build.sh
|
||||
# Ergebnis: dist/aria-android-agent.apk -> aufs Handy kopieren + installieren
|
||||
# ("Unbekannte Quellen erlauben").
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
mkdir -p dist
|
||||
docker build -f Dockerfile.build -t aria-android-agent-build .
|
||||
docker run --rm -v "$(pwd)/dist:/out" aria-android-agent-build
|
||||
echo
|
||||
echo "Fertig: dist/aria-android-agent.apk"
|
||||
@@ -0,0 +1,5 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
kotlin.code.style=official
|
||||
android.nonTransitiveRClass=true
|
||||
org.gradle.caching=true
|
||||
@@ -0,0 +1,16 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
rootProject.name = "aria-android-agent"
|
||||
include(":app")
|
||||
@@ -0,0 +1,30 @@
|
||||
# systemd-Unit fuer den ARIA Host-Agent.
|
||||
#
|
||||
# Installation:
|
||||
# sudo cp aria-host-agent /usr/local/bin/
|
||||
# sudo mkdir -p /etc/aria-host-agent && sudo cp .env /etc/aria-host-agent/.env
|
||||
# sudo cp aria-host-agent.service /etc/systemd/system/
|
||||
# sudo systemctl enable --now aria-host-agent
|
||||
#
|
||||
# Als root (User=root): Kommandos haben volle Rechte, kein sudo/Passwort noetig.
|
||||
# Fuer einen normalen User: User=<name> setzen und in der .env SUDO_PASSWORD
|
||||
# oder SUDO_NOPASSWD konfigurieren.
|
||||
#
|
||||
# HINWEIS Screenshot: als Systemdienst fehlt die grafische Session (DISPLAY/
|
||||
# WAYLAND_DISPLAY). Fuer host_screenshot den Agent stattdessen in der Desktop-
|
||||
# Session starten (Autostart) oder DISPLAY/XAUTHORITY in der Unit setzen.
|
||||
[Unit]
|
||||
Description=ARIA Host-Agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/etc/aria-host-agent
|
||||
ExecStart=/usr/local/bin/aria-host-agent
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
REM ARIA Host-Agent — Windows-Build mit PyInstaller (kein Docker).
|
||||
REM Voraussetzung: Python 3 installiert und im PATH (python.org, "Add to PATH").
|
||||
REM
|
||||
REM build-native.bat
|
||||
REM
|
||||
REM Ergebnis: dist\aria-host-agent.exe (Onefile). Danach .env danebenlegen
|
||||
REM (siehe .env.example) und starten. Fuer Admin-Rechte die .exe per Rechtsklick
|
||||
REM "Als Administrator ausfuehren".
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
python -m venv .buildenv || goto :err
|
||||
call .buildenv\Scripts\activate.bat
|
||||
python -m pip install --quiet --upgrade pip
|
||||
python -m pip install --quiet pyinstaller -r requirements.txt || goto :err
|
||||
pyinstaller --onefile --name aria-host-agent --collect-all psutil host_agent.py || goto :err
|
||||
call deactivate
|
||||
|
||||
echo.
|
||||
echo Fertig: dist\aria-host-agent.exe
|
||||
echo .env danebenlegen (siehe .env.example), dann starten (ggf. als Administrator).
|
||||
goto :eof
|
||||
|
||||
:err
|
||||
echo.
|
||||
echo FEHLER beim Bauen. Ist Python 3 installiert und im PATH? (python --version)
|
||||
exit /b 1
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Baut die Host-Agent-Binary OHNE Docker — direkt mit PyInstaller.
|
||||
# Nutze das, wenn Docker nicht geht (z.B. Live-ISO mit overlayfs-Root, wo
|
||||
# Dockers overlay2-Treiber kein Overlay-auf-Overlay stapeln kann).
|
||||
#
|
||||
# sudo apt install -y python3-pip python3-venv # falls noch nicht da
|
||||
# ./build-native.sh
|
||||
#
|
||||
# WICHTIG: Nativ gebaut linkt die Binary gegen das glibc DIESER Maschine. Sie
|
||||
# laeuft dann nur auf Systemen mit glibc >= dem hier. Fuer breite Kompatibilitaet
|
||||
# lieber ./build.sh (Docker/bullseye) auf einem normalen Rechner nutzen.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
python3 -m venv .buildenv
|
||||
# shellcheck disable=SC1091
|
||||
. .buildenv/bin/activate
|
||||
pip install --quiet --upgrade pip
|
||||
pip install --quiet pyinstaller -r requirements.txt
|
||||
pyinstaller --onefile --name aria-host-agent --collect-all psutil host_agent.py
|
||||
deactivate
|
||||
|
||||
echo
|
||||
echo "Fertig: dist/aria-host-agent"
|
||||
echo ".env danebenlegen (siehe .env.example), dann: chmod +x aria-host-agent && ./aria-host-agent"
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# Baut die Windows-.exe + setup.exe des Host-Agents AUF LINUX (Wine im Docker).
|
||||
# ./build-win.sh [version]
|
||||
# Ergebnis:
|
||||
# dist/aria-host-agent.exe (Konsolen-Binary)
|
||||
# dist/aria-host-agent-setup.exe (Installer: richtet Windows-Dienst ein)
|
||||
#
|
||||
# Hinweis: Der erste Lauf zieht das tobix/pywine-Image (~1-2 GB) + baut die
|
||||
# Wine-Umgebung — das dauert. Folge-Builds sind schnell.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
VERSION="${1:-0.0.0}"
|
||||
mkdir -p dist
|
||||
docker build -f Dockerfile.win --build-arg VERSION="$VERSION" -t aria-host-agent-win .
|
||||
docker run --rm -v "$(pwd)/dist:/out" aria-host-agent-win
|
||||
echo
|
||||
echo "Fertig: dist/aria-host-agent.exe + dist/aria-host-agent-setup.exe"
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Baut die portable Host-Agent-Binary (Linux x86_64) via Docker + PyInstaller.
|
||||
# Ergebnis: ./dist/aria-host-agent (Onefile, ~15 MB, keine Runtime noetig).
|
||||
#
|
||||
# ./build.sh
|
||||
#
|
||||
# Danach auf den Ziel-Rechner kopieren, .env danebenlegen und starten:
|
||||
# ./aria-host-agent
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
mkdir -p dist
|
||||
docker build -f Dockerfile.build -t aria-host-agent-build .
|
||||
docker run --rm -v "$(pwd)/dist:/out" aria-host-agent-build
|
||||
|
||||
echo
|
||||
echo "Fertig: dist/aria-host-agent"
|
||||
echo "Auf den Ziel-Rechner kopieren, .env danebenlegen (siehe .env.example), dann:"
|
||||
echo " chmod +x aria-host-agent && ./aria-host-agent"
|
||||
@@ -0,0 +1,526 @@
|
||||
"""
|
||||
ARIA Host-Agent — Direktzugriff auf EINEN Rechner.
|
||||
|
||||
Laeuft direkt auf dem Ziel-Rechner (Linux) und verbindet sich AUSGEHEND als
|
||||
RVS-Client in Stefans Raum (gleicher Token). Damit kann ARIA diesen Rechner
|
||||
direkt steuern, auch wenn er sonst aus dem Netz nicht erreichbar ist (hinter
|
||||
NAT/Firewall, kein offener Port). Anders als der Satellit (der ein LAN
|
||||
entdeckt/steuert) ist beim Agent das "Geraet" der Rechner selbst.
|
||||
|
||||
Als reine Binary verteilbar (PyInstaller onefile) + .env fuer die Zugangsdaten.
|
||||
|
||||
Faehigkeiten (host_command → host_result):
|
||||
exec Shell-Kommando ausfuehren (optional sudo)
|
||||
read/write Datei lesen/schreiben (Base64)
|
||||
info OS / CPU / RAM / Disk / Uptime / Netz
|
||||
screenshot Bildschirmfoto (X11/Wayland, wenn grafische Session da ist)
|
||||
|
||||
Sicherheit: reagiert nur auf den eigenen RVS-Raum (Token) und nur, wenn
|
||||
CONTROL_ENABLED=true. Alles wird geloggt. Keine offenen Ports.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import websockets
|
||||
|
||||
# ─── Plattform-Weichen (Linux / macOS / Windows) ────────────────────
|
||||
IS_WINDOWS = os.name == "nt"
|
||||
IS_MAC = sys.platform == "darwin"
|
||||
|
||||
|
||||
def _is_admin() -> bool:
|
||||
"""root (Unix) bzw. Administrator (Windows)."""
|
||||
try:
|
||||
return os.geteuid() == 0 # Unix (Linux/macOS)
|
||||
except AttributeError:
|
||||
try:
|
||||
import ctypes
|
||||
return ctypes.windll.shell32.IsUserAnAdmin() != 0 # Windows
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [host-agent] %(levelname)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("host-agent")
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""Laedt eine .env neben der Binary/dem Script (oder im CWD) in os.environ.
|
||||
Bereits gesetzte Werte gewinnen. Kein python-dotenv noetig."""
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
# PyInstaller-onefile: __file__ liegt im Temp-Extract-Dir, NICHT beim .exe/
|
||||
# Binary — deshalb zusaetzlich sys.executable-Ordner (echter Binary-Ort) und
|
||||
# das CWD (z.B. der ProgramData-Ordner, den der Windows-Dienst als AppDir nutzt).
|
||||
exe_dir = os.path.dirname(os.path.abspath(sys.executable))
|
||||
seen = set()
|
||||
candidates = [os.path.join(d, ".env") for d in (exe_dir, here, os.getcwd())]
|
||||
for path in [p for p in candidates if not (p in seen or seen.add(p))]:
|
||||
if not os.path.isfile(path):
|
||||
continue
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
key = key.strip()
|
||||
if key.startswith("export "):
|
||||
key = key[len("export "):].strip()
|
||||
val = val.strip()
|
||||
if val[:1] in ("'", '"'):
|
||||
q = val[0]
|
||||
end = val.find(q, 1)
|
||||
val = val[1:end] if end != -1 else val[1:]
|
||||
else:
|
||||
m = re.search(r"\s+#", val)
|
||||
if m:
|
||||
val = val[:m.start()]
|
||||
val = val.strip()
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = val
|
||||
except Exception as exc:
|
||||
logger.warning(".env laden fehlgeschlagen (%s): %s", path, exc)
|
||||
break
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
|
||||
# ─── Konfiguration ──────────────────────────────────────────────────
|
||||
|
||||
def _env_bool(name: str, default: bool) -> bool:
|
||||
v = os.environ.get(name)
|
||||
if v is None:
|
||||
return default
|
||||
return v.strip().lower() in ("1", "true", "yes", "on", "ja")
|
||||
|
||||
|
||||
def _default_id() -> str:
|
||||
host = socket.gethostname() or "host"
|
||||
slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", host).strip("-").lower()
|
||||
return slug or "host"
|
||||
|
||||
|
||||
RVS_HOST = os.environ.get("RVS_HOST", "")
|
||||
RVS_PORT = int(os.environ.get("RVS_PORT", "443") or "443")
|
||||
RVS_TLS = _env_bool("RVS_TLS", True)
|
||||
# Bei TLS-Fehlschlag einmal auf ws:// zurueckfallen (wie die Compute-Bridges).
|
||||
# Hilft nur, wenn der RVS plaintext erreichbar ist; gegen Caddy-TLS bleibt wss.
|
||||
RVS_TLS_FALLBACK = _env_bool("RVS_TLS_FALLBACK", True)
|
||||
RVS_TOKEN = os.environ.get("RVS_TOKEN", "")
|
||||
# TLS-Hostname (SNI + Zertifikatspruefung), falls RVS_HOST eine IP ist — z.B. der
|
||||
# Agent laeuft im selben Netz wie der RVS und verbindet direkt auf die interne IP,
|
||||
# das Caddy-Zertifikat gilt aber fuer den Namen. Dann: RVS_HOST=<interne-ip>,
|
||||
# RVS_SNI=<zert-name>. Leer = SNI = RVS_HOST (Normalfall).
|
||||
RVS_SNI = os.environ.get("RVS_SNI", "").strip()
|
||||
|
||||
# In-Process-DNS-Override: wenn RVS_SNI gesetzt ist, verbindet die URI ueber den
|
||||
# HOSTNAMEN (Host-Header + SNI + Cert stimmen), waehrend getaddrinfo den Namen auf
|
||||
# die echte IP in RVS_HOST aufloest. Versionsunabhaengig — host=/port= kollidiert
|
||||
# in der Legacy-websockets-API mit dem aus der URI abgeleiteten Host.
|
||||
if RVS_TLS and RVS_SNI:
|
||||
import socket as _socket
|
||||
_orig_getaddrinfo = _socket.getaddrinfo
|
||||
def _sni_getaddrinfo(host, *a, **k):
|
||||
return _orig_getaddrinfo(RVS_HOST if host == RVS_SNI else host, *a, **k)
|
||||
_socket.getaddrinfo = _sni_getaddrinfo
|
||||
|
||||
|
||||
HOST_ID = (os.environ.get("HOST_ID") or _default_id()).strip()
|
||||
HOST_NAME = (os.environ.get("HOST_NAME") or HOST_ID).strip()
|
||||
|
||||
# Steuerung ist der Sinn des Agents — aber bewusst opt-in (Sicherheit).
|
||||
CONTROL_ENABLED = _env_bool("CONTROL_ENABLED", False)
|
||||
|
||||
# sudo: 1) Agent laeuft als root -> direkt. 2) SUDO_PASSWORD gesetzt -> sudo -S.
|
||||
# 3) SUDO_NOPASSWD=true (Live-ISO / NOPASSWD-sudoers) -> sudo -n. 4) sonst Fehler.
|
||||
SUDO_PASSWORD = os.environ.get("SUDO_PASSWORD", "")
|
||||
SUDO_NOPASSWD = _env_bool("SUDO_NOPASSWD", False)
|
||||
|
||||
EXEC_TIMEOUT = float(os.environ.get("EXEC_TIMEOUT", "60") or "60")
|
||||
# Ausgabe-Fenster (wie beim Satelliten): grosse stdout klein halten fuers RVS.
|
||||
OUT_MAX_CHARS = int(os.environ.get("OUT_MAX_CHARS", "20000") or "20000")
|
||||
OUT_MAX_CHARS_HARD = int(os.environ.get("OUT_MAX_CHARS_HARD", "200000") or "200000")
|
||||
# Datei-Transfer-Limit (Base64 durchs RVS).
|
||||
FILE_MAX_BYTES = int(os.environ.get("FILE_MAX_BYTES", str(10 * 1024 * 1024)) or str(10 * 1024 * 1024))
|
||||
|
||||
# Version (wird von release_agent.sh beim Release gesetzt).
|
||||
AGENT_VERSION = "0.0.0.4"
|
||||
|
||||
HEARTBEAT_SEC = 25
|
||||
CAPS = ["exec", "read", "write", "info", "screenshot"]
|
||||
|
||||
|
||||
# ─── Text-/Zahl-Helfer ──────────────────────────────────────────────
|
||||
|
||||
def _to_int(s):
|
||||
try:
|
||||
return int(str(s).strip())
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _to_float(s):
|
||||
try:
|
||||
return float(str(s).strip())
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _window_text(text: str, params: dict) -> dict:
|
||||
"""contains-Zeilenfilter + offset/max_chars-Fenster. Gibt body + Metadaten."""
|
||||
total = len(text)
|
||||
contains = params.get("contains")
|
||||
if contains:
|
||||
terms = [contains] if isinstance(contains, str) else list(contains)
|
||||
terms = [str(t).lower() for t in terms if str(t).strip()]
|
||||
if terms:
|
||||
text = "\n".join(ln for ln in text.splitlines()
|
||||
if any(t in ln.lower() for t in terms))
|
||||
offset = max(0, _to_int(params.get("offset")) or 0)
|
||||
max_chars = _to_int(params.get("max_chars")) or OUT_MAX_CHARS
|
||||
max_chars = max(1, min(max_chars, OUT_MAX_CHARS_HARD))
|
||||
body = text[offset:offset + max_chars]
|
||||
return {"body": body, "total_chars": total, "filtered": bool(contains),
|
||||
"offset": offset, "returned_chars": len(body),
|
||||
"truncated": offset + len(body) < len(text)}
|
||||
|
||||
|
||||
# ─── Aktionen ───────────────────────────────────────────────────────
|
||||
|
||||
def _wrap_sudo(cmd: str, use_sudo: bool):
|
||||
"""Baut die Argv (OS-abhaengige Shell) + optional Root/Admin-Rechte.
|
||||
Gibt (argv, stdin_data) oder (None, fehlertext)."""
|
||||
if IS_WINDOWS:
|
||||
# PowerShell; kein sudo. Fuer Admin-Rechte muss der Agent SELBST als
|
||||
# Administrator laufen (UAC) — dann hat 'sudo:true' bereits volle Rechte.
|
||||
if use_sudo and not _is_admin():
|
||||
return None, ("Windows kennt kein sudo. Starte den Agent als "
|
||||
"Administrator ('Als Administrator ausfuehren'), dann "
|
||||
"laufen Kommandos mit vollen Rechten.")
|
||||
return ["powershell", "-NoProfile", "-NonInteractive", "-Command", cmd], None
|
||||
# Unix: Linux + macOS (bash vorhanden; macOS-sudo verhaelt sich wie Linux)
|
||||
if not use_sudo or _is_admin():
|
||||
return ["bash", "-lc", cmd], None
|
||||
if SUDO_PASSWORD:
|
||||
return ["sudo", "-S", "-p", "", "bash", "-lc", cmd], SUDO_PASSWORD + "\n"
|
||||
if SUDO_NOPASSWD:
|
||||
return ["sudo", "-n", "bash", "-lc", cmd], None
|
||||
return None, ("sudo verlangt ein Passwort. Setze SUDO_PASSWORD in der .env, "
|
||||
"oder SUDO_NOPASSWD=true (Live-ISO / passwortloses sudo), oder "
|
||||
"starte den Agent als root.")
|
||||
|
||||
|
||||
def _do_exec(params: dict) -> dict:
|
||||
cmd = params.get("cmd") or params.get("command") or ""
|
||||
if not cmd:
|
||||
return {"ok": False, "error": "cmd (Kommando) erforderlich."}
|
||||
argv, stdin_data = _wrap_sudo(cmd, bool(params.get("sudo")))
|
||||
if argv is None:
|
||||
return {"ok": False, "error": stdin_data}
|
||||
timeout = _to_float(params.get("timeout")) or EXEC_TIMEOUT
|
||||
try:
|
||||
r = subprocess.run(argv, input=stdin_data, capture_output=True,
|
||||
text=True, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"ok": False, "error": f"Timeout nach {timeout:.0f}s."}
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": f"exec fehlgeschlagen: {exc}"}
|
||||
win = _window_text(r.stdout, params)
|
||||
return {"ok": True, "result": {"exit_code": r.returncode,
|
||||
"stderr": (r.stderr or "")[:4000], **win}}
|
||||
|
||||
|
||||
def _do_read(params: dict) -> dict:
|
||||
path = params.get("path") or ""
|
||||
if not path:
|
||||
return {"ok": False, "error": "path erforderlich."}
|
||||
p = Path(path).expanduser()
|
||||
if not p.is_file():
|
||||
return {"ok": False, "error": f"Datei nicht gefunden: {path}"}
|
||||
size = p.stat().st_size
|
||||
offset = max(0, _to_int(params.get("offset")) or 0)
|
||||
max_bytes = _to_int(params.get("max_bytes")) or FILE_MAX_BYTES
|
||||
max_bytes = max(1, min(max_bytes, FILE_MAX_BYTES))
|
||||
try:
|
||||
with p.open("rb") as f:
|
||||
f.seek(offset)
|
||||
data = f.read(max_bytes)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": f"Lesen fehlgeschlagen: {exc}"}
|
||||
return {"ok": True, "result": {
|
||||
"path": str(p), "size": size, "offset": offset,
|
||||
"returned_bytes": len(data), "truncated": offset + len(data) < size,
|
||||
"base64": base64.b64encode(data).decode("ascii"),
|
||||
}}
|
||||
|
||||
|
||||
def _do_write(params: dict) -> dict:
|
||||
path = params.get("path") or ""
|
||||
if not path:
|
||||
return {"ok": False, "error": "path erforderlich."}
|
||||
b64 = params.get("base64")
|
||||
text = params.get("text")
|
||||
if b64 is None and text is None:
|
||||
return {"ok": False, "error": "base64 ODER text erforderlich."}
|
||||
try:
|
||||
data = base64.b64decode(b64) if b64 is not None else str(text).encode("utf-8")
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": f"base64 ungueltig: {exc}"}
|
||||
p = Path(path).expanduser()
|
||||
try:
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
mode = "ab" if params.get("append") else "wb"
|
||||
with p.open(mode) as f:
|
||||
f.write(data)
|
||||
if params.get("chmod"):
|
||||
os.chmod(p, int(str(params["chmod"]), 8))
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": f"Schreiben fehlgeschlagen: {exc}"}
|
||||
return {"ok": True, "result": {"path": str(p), "bytes": len(data)}}
|
||||
|
||||
|
||||
def _do_info(params: dict) -> dict:
|
||||
info = {
|
||||
"host": HOST_NAME, "hostname": socket.gethostname(),
|
||||
"agent_version": AGENT_VERSION,
|
||||
"os": platform.platform(), "kernel": platform.release(),
|
||||
"arch": platform.machine(), "python": platform.python_version(),
|
||||
"user": os.environ.get("USER") or os.environ.get("USERNAME") or "",
|
||||
"is_root": _is_admin(),
|
||||
}
|
||||
try:
|
||||
import psutil
|
||||
info["cpu_percent"] = psutil.cpu_percent(interval=0.3)
|
||||
info["cpu_count"] = psutil.cpu_count()
|
||||
vm = psutil.virtual_memory()
|
||||
info["ram_used_mb"] = round(vm.used / 1024 / 1024)
|
||||
info["ram_total_mb"] = round(vm.total / 1024 / 1024)
|
||||
info["ram_percent"] = vm.percent
|
||||
du = psutil.disk_usage("/")
|
||||
info["disk_used_gb"] = round(du.used / 1024 / 1024 / 1024, 1)
|
||||
info["disk_total_gb"] = round(du.total / 1024 / 1024 / 1024, 1)
|
||||
info["disk_percent"] = du.percent
|
||||
info["uptime_s"] = round(time.time() - psutil.boot_time())
|
||||
info["load_avg"] = list(os.getloadavg()) if hasattr(os, "getloadavg") else None
|
||||
except Exception:
|
||||
# Fallback ohne psutil: das Noetigste aus os/shutil.
|
||||
try:
|
||||
info["load_avg"] = list(os.getloadavg())
|
||||
except Exception:
|
||||
info["load_avg"] = None
|
||||
try:
|
||||
total, used, free = shutil.disk_usage("/")
|
||||
info["disk_used_gb"] = round(used / 1024 ** 3, 1)
|
||||
info["disk_total_gb"] = round(total / 1024 ** 3, 1)
|
||||
except Exception:
|
||||
pass
|
||||
# Primaere IP (best effort).
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("8.8.8.8", 80))
|
||||
info["primary_ip"] = s.getsockname()[0]
|
||||
s.close()
|
||||
except Exception:
|
||||
info["primary_ip"] = ""
|
||||
return {"ok": True, "result": info}
|
||||
|
||||
|
||||
def _do_screenshot(params: dict) -> dict:
|
||||
"""Bildschirmfoto — OS-abhaengig. Windows: PowerShell/System.Drawing;
|
||||
macOS: screencapture; Linux: grim (Wayland) / scrot/maim/import (X11).
|
||||
Braucht eine aktive grafische Session."""
|
||||
import tempfile
|
||||
tmp = os.path.join(tempfile.gettempdir(), f"aria_shot_{int(time.time())}.png")
|
||||
candidates = []
|
||||
if IS_WINDOWS:
|
||||
ps = ("Add-Type -AssemblyName System.Windows.Forms,System.Drawing;"
|
||||
"$b=[System.Windows.Forms.SystemInformation]::VirtualScreen;"
|
||||
"$bmp=New-Object System.Drawing.Bitmap $b.Width,$b.Height;"
|
||||
"$g=[System.Drawing.Graphics]::FromImage($bmp);"
|
||||
"$g.CopyFromScreen($b.Location,[System.Drawing.Point]::Empty,$b.Size);"
|
||||
f"$bmp.Save('{tmp}');$g.Dispose();$bmp.Dispose()")
|
||||
candidates.append(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps])
|
||||
elif IS_MAC:
|
||||
candidates.append(["screencapture", "-x", tmp]) # -x = ohne Ton
|
||||
else:
|
||||
if os.environ.get("WAYLAND_DISPLAY") and shutil.which("grim"):
|
||||
candidates.append(["grim", tmp])
|
||||
for tool, argv in (("scrot", ["scrot", "-o", tmp]),
|
||||
("maim", ["maim", tmp]),
|
||||
("gnome-screenshot", ["gnome-screenshot", "-f", tmp]),
|
||||
("import", ["import", "-window", "root", tmp])):
|
||||
if shutil.which(tool):
|
||||
candidates.append(argv)
|
||||
if not candidates:
|
||||
return {"ok": False, "error":
|
||||
"Kein Screenshot-Tool gefunden. Linux: grim (Wayland) oder "
|
||||
"scrot/maim (X11) installieren. (Windows/macOS nutzen Bordmittel.)"}
|
||||
last_err = ""
|
||||
for argv in candidates:
|
||||
try:
|
||||
r = subprocess.run(argv, capture_output=True, text=True, timeout=15)
|
||||
if r.returncode == 0 and os.path.isfile(tmp) and os.path.getsize(tmp) > 0:
|
||||
with open(tmp, "rb") as f:
|
||||
b = f.read()
|
||||
os.remove(tmp)
|
||||
return {"ok": True, "result": {"format": "png", "bytes": len(b),
|
||||
"base64": base64.b64encode(b).decode("ascii")}}
|
||||
last_err = (r.stderr or r.stdout or "").strip()[:200]
|
||||
except Exception as exc:
|
||||
last_err = str(exc)[:200]
|
||||
return {"ok": False, "error": f"Screenshot fehlgeschlagen ({last_err}). "
|
||||
"Laeuft der Agent in derselben grafischen Session?"}
|
||||
|
||||
|
||||
ACTIONS = {
|
||||
"exec": _do_exec, "read": _do_read, "write": _do_write,
|
||||
"info": _do_info, "screenshot": _do_screenshot,
|
||||
}
|
||||
|
||||
|
||||
# ─── RVS-Client ─────────────────────────────────────────────────────
|
||||
|
||||
class HostAgent:
|
||||
def __init__(self) -> None:
|
||||
self.ws = None
|
||||
|
||||
def _for_me(self, payload: dict) -> bool:
|
||||
"""Command gilt uns, wenn kein host-Feld gesetzt ist (Broadcast) oder es
|
||||
auf unsere ID/Name passt."""
|
||||
target = (payload.get("host") or payload.get("hostId") or "").strip()
|
||||
if not target:
|
||||
return True
|
||||
return target.lower() in (HOST_ID.lower(), HOST_NAME.lower())
|
||||
|
||||
async def _send(self, message: dict) -> None:
|
||||
if self.ws is None:
|
||||
return
|
||||
try:
|
||||
await self.ws.send(json.dumps(message))
|
||||
except Exception as exc:
|
||||
logger.warning("Senden fehlgeschlagen: %s", exc)
|
||||
|
||||
async def _hello(self, log: bool = False) -> None:
|
||||
if log:
|
||||
logger.info("host_hello: id=%s name=%s caps=%s control=%s",
|
||||
HOST_ID, HOST_NAME, ",".join(CAPS), CONTROL_ENABLED)
|
||||
await self._send({"type": "host_hello", "payload": {
|
||||
"hostId": HOST_ID, "name": HOST_NAME, "os": platform.platform(),
|
||||
"version": AGENT_VERSION, "caps": CAPS, "control": CONTROL_ENABLED,
|
||||
}, "timestamp": int(time.time() * 1000)})
|
||||
|
||||
async def _heartbeat(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(HEARTBEAT_SEC)
|
||||
await self._send({"type": "host_ping", "payload": {"hostId": HOST_ID},
|
||||
"timestamp": int(time.time() * 1000)})
|
||||
await self._hello()
|
||||
|
||||
async def _handle(self, raw: str) -> None:
|
||||
try:
|
||||
msg = json.loads(raw)
|
||||
except Exception:
|
||||
return
|
||||
if msg.get("type") != "host_command":
|
||||
return
|
||||
payload = msg.get("payload") or {}
|
||||
if not self._for_me(payload):
|
||||
return
|
||||
req_id = payload.get("requestId", "")
|
||||
action = (payload.get("action") or "").strip()
|
||||
params = payload.get("params") or {}
|
||||
if not CONTROL_ENABLED:
|
||||
result = {"ok": False, "error": "Steuerung ist deaktiviert (CONTROL_ENABLED=false)."}
|
||||
elif action not in ACTIONS:
|
||||
result = {"ok": False, "error": f"Aktion '{action}' unbekannt (bekannt: {', '.join(ACTIONS)})."}
|
||||
else:
|
||||
logger.info("[cmd] %s params=%s", action,
|
||||
{k: str(v)[:60] for k, v in params.items() if k not in ("base64",)})
|
||||
loop = asyncio.get_event_loop()
|
||||
try:
|
||||
result = await loop.run_in_executor(None, ACTIONS[action], params)
|
||||
except Exception as exc:
|
||||
result = {"ok": False, "error": f"{action} fehlgeschlagen: {exc}"}
|
||||
await self._send({"type": "host_result",
|
||||
"payload": {"requestId": req_id, "hostId": HOST_ID,
|
||||
"action": action, **result},
|
||||
"timestamp": int(time.time() * 1000)})
|
||||
|
||||
async def run(self) -> None:
|
||||
if not RVS_HOST or not RVS_TOKEN:
|
||||
logger.error("RVS_HOST und RVS_TOKEN sind Pflicht (siehe .env.example).")
|
||||
return
|
||||
backoff = 1
|
||||
# use_tls kann bei Fehlschlag einmal auf ws:// fallen (RVS_TLS_FALLBACK),
|
||||
# danach wieder zurueck auf RVS_TLS (kein Sticky-Fallback).
|
||||
use_tls = RVS_TLS
|
||||
tls_fallback_tried = False
|
||||
connect_kwargs = {"max_size": 16 * 1024 * 1024,
|
||||
"ping_interval": 20, "ping_timeout": 20}
|
||||
while True:
|
||||
proto = "wss" if use_tls else "ws"
|
||||
# Bei TLS + RVS_SNI: URI nutzt den HOSTNAMEN (Host-Header/SNI/Cert),
|
||||
# getaddrinfo mappt ihn auf die IP in RVS_HOST. Bei ws:// direkt die IP.
|
||||
uri_host = RVS_SNI if (use_tls and RVS_SNI) else RVS_HOST
|
||||
url = f"{proto}://{uri_host}:{RVS_PORT}?token={RVS_TOKEN}"
|
||||
fallback = False
|
||||
try:
|
||||
logger.info("Verbinde mit RVS %s://%s:%s%s …", proto, uri_host, RVS_PORT,
|
||||
f" (TCP {RVS_HOST})" if (use_tls and RVS_SNI) else "")
|
||||
async with websockets.connect(url, **connect_kwargs) as ws:
|
||||
self.ws = ws
|
||||
backoff = 1
|
||||
tls_fallback_tried = False
|
||||
await self._hello(log=True)
|
||||
hb = asyncio.create_task(self._heartbeat())
|
||||
try:
|
||||
async for raw in ws:
|
||||
await self._handle(raw)
|
||||
finally:
|
||||
hb.cancel()
|
||||
except Exception as exc:
|
||||
logger.warning("RVS-Verbindung verloren: %s", exc)
|
||||
if use_tls and RVS_TLS_FALLBACK and not tls_fallback_tried:
|
||||
logger.info("TLS fehlgeschlagen — Fallback auf ws://")
|
||||
use_tls = False
|
||||
tls_fallback_tried = True
|
||||
fallback = True
|
||||
finally:
|
||||
self.ws = None
|
||||
if fallback:
|
||||
continue # sofort erneut mit ws://
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 2, 30)
|
||||
use_tls = RVS_TLS # kein Sticky-Fallback
|
||||
tls_fallback_tried = False
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logger.info("ARIA Host-Agent startet — id=%s name=%s control=%s root=%s",
|
||||
HOST_ID, HOST_NAME, CONTROL_ENABLED, _is_admin())
|
||||
try:
|
||||
asyncio.run(HostAgent().run())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env bash
|
||||
# ARIA Host-Agent — Service-Installer (systemd).
|
||||
#
|
||||
# Installiert die Binary nach /usr/local/bin, die .env nach /etc/aria-host-agent
|
||||
# und richtet den systemd-Dienst ein (enable + start).
|
||||
#
|
||||
# Nutzung:
|
||||
# sudo ./install-service.sh /pfad/zur/.env # .env-Pfad direkt uebergeben
|
||||
# sudo ./install-service.sh # ncurses-Dateidialog (dialog)
|
||||
#
|
||||
# Die Binary wird unter ./dist/aria-host-agent oder ./aria-host-agent erwartet
|
||||
# (vorher ./build.sh oder ./build-native.sh ausfuehren), oder als 2. Argument.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
BIN_DST="/usr/local/bin/aria-host-agent"
|
||||
ETC_DIR="/etc/aria-host-agent"
|
||||
UNIT_DST="/etc/systemd/system/aria-host-agent.service"
|
||||
|
||||
die() { echo "FEHLER: $*" >&2; exit 1; }
|
||||
|
||||
[ "$(id -u)" -eq 0 ] || die "Bitte mit sudo/root ausfuehren: sudo $0 $*"
|
||||
|
||||
# ── Binary finden (Arg 2 > dist/ > ./) ──────────────────────────────
|
||||
BIN_SRC="${2:-}"
|
||||
if [ -z "$BIN_SRC" ]; then
|
||||
if [ -x "$SCRIPT_DIR/dist/aria-host-agent" ]; then BIN_SRC="$SCRIPT_DIR/dist/aria-host-agent"
|
||||
elif [ -x "$SCRIPT_DIR/aria-host-agent" ]; then BIN_SRC="$SCRIPT_DIR/aria-host-agent"
|
||||
fi
|
||||
fi
|
||||
[ -n "$BIN_SRC" ] && [ -f "$BIN_SRC" ] || die "Binary nicht gefunden. Erst bauen (./build.sh) oder als 2. Argument uebergeben."
|
||||
|
||||
# ── .env bestimmen: Arg 1, sonst ncurses-Dateidialog ────────────────
|
||||
ENV_SRC="${1:-}"
|
||||
if [ -z "$ENV_SRC" ]; then
|
||||
if ! command -v dialog >/dev/null 2>&1; then
|
||||
echo "Kein .env-Pfad uebergeben und 'dialog' ist nicht installiert."
|
||||
read -r -p "dialog jetzt installieren (apt)? [j/N] " a
|
||||
case "$a" in
|
||||
j|J|y|Y) (apt-get update && apt-get install -y dialog) || die "dialog-Installation fehlgeschlagen — .env-Pfad bitte als Argument uebergeben." ;;
|
||||
*) die "Ohne dialog bitte den .env-Pfad als Argument uebergeben: sudo $0 /pfad/zur/.env" ;;
|
||||
esac
|
||||
fi
|
||||
# dialog --fselect: Dateibrowser; --stdout gibt die Auswahl auf stdout.
|
||||
START_DIR="${SUDO_USER:+/home/$SUDO_USER/}"
|
||||
[ -d "$START_DIR" ] || START_DIR="$SCRIPT_DIR/"
|
||||
ENV_SRC="$(dialog --stdout --title 'ARIA Host-Agent — .env auswaehlen' \
|
||||
--fselect "$START_DIR" 14 72)" || true
|
||||
clear
|
||||
[ -n "$ENV_SRC" ] || die "Abgebrochen — keine .env ausgewaehlt."
|
||||
fi
|
||||
[ -f "$ENV_SRC" ] || die ".env nicht gefunden: $ENV_SRC"
|
||||
|
||||
echo "Binary : $BIN_SRC"
|
||||
echo ".env : $ENV_SRC"
|
||||
|
||||
# ── Installieren ────────────────────────────────────────────────────
|
||||
install -m 0755 "$BIN_SRC" "$BIN_DST"
|
||||
install -d -m 0755 "$ETC_DIR"
|
||||
install -m 0600 "$ENV_SRC" "$ETC_DIR/.env" # 0600: enthaelt Token/Passwoerter
|
||||
|
||||
if [ -f "$SCRIPT_DIR/aria-host-agent.service" ]; then
|
||||
install -m 0644 "$SCRIPT_DIR/aria-host-agent.service" "$UNIT_DST"
|
||||
else
|
||||
die "aria-host-agent.service nicht gefunden neben dem Installer."
|
||||
fi
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now aria-host-agent
|
||||
|
||||
echo
|
||||
echo "✓ Installiert & gestartet."
|
||||
echo " Status: systemctl status aria-host-agent"
|
||||
echo " Log: journalctl -u aria-host-agent -f"
|
||||
echo " .env: $ETC_DIR/.env (aendern -> systemctl restart aria-host-agent)"
|
||||
Executable
+150
@@ -0,0 +1,150 @@
|
||||
#!/bin/bash
|
||||
# ════════════════════════════════════════════════════════════════════
|
||||
# ARIA Host-Agent — Release Script
|
||||
# Baut die auf Linux+Docker moeglichen Artefakte und haengt sie als
|
||||
# Gitea-Release-Assets an einen Tag. NICHTS wandert in den Git-Tree —
|
||||
# Binaries leben nur unter "Releases" (blaeht clone/History nicht auf).
|
||||
#
|
||||
# Verwendung: ./release_agent.sh <version> (z.B. ./release_agent.sh 0.2.0)
|
||||
#
|
||||
# Artefakte:
|
||||
# - Linux-x64-Binary (Docker, PyInstaller) -> immer
|
||||
# - Android-APK (Docker, Gradle) -> immer
|
||||
# - macOS / Windows (falls in dist/ vorgebaut) -> optional
|
||||
# (mac/win koennen auf Linux nicht cross-gebaut werden -> build-native.*
|
||||
# auf dem jeweiligen OS laufen lassen, Ergebnis nach host-agent/dist/ legen)
|
||||
#
|
||||
# Eigener Tag-Namespace agent-v<version> (kollidiert NICHT mit den
|
||||
# App-Tags v<version>).
|
||||
#
|
||||
# Gitea-Zugang (GITEA_URL, GITEA_REPO, GITEA_USER) wird aus der Umgebung
|
||||
# oder aus host-agent/.env bzw. der Repo-Wurzel-.env gelesen; das Kennwort
|
||||
# wird interaktiv abgefragt.
|
||||
# ════════════════════════════════════════════════════════════════════
|
||||
|
||||
set -e
|
||||
cd "$(dirname "$0")" # host-agent/
|
||||
SCRIPT_DIR="$(pwd)"
|
||||
ROOT_DIR="$(cd .. && pwd)"
|
||||
|
||||
# ── Farben ───────────────────────────────────────────────────────────
|
||||
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
|
||||
|
||||
# ── Parameter ────────────────────────────────────────────────────────
|
||||
VERSION=${1:?"Usage: ./release_agent.sh <version> (z.B. 0.2.0)"}
|
||||
TAG="agent-v$VERSION"
|
||||
|
||||
# ── Gitea-Konfiguration (env > host-agent/.env > Repo-Wurzel-.env) ────
|
||||
[ -f "$SCRIPT_DIR/.env" ] && source "$SCRIPT_DIR/.env"
|
||||
[ -f "$ROOT_DIR/.env" ] && source "$ROOT_DIR/.env"
|
||||
|
||||
GITEA_URL="${GITEA_URL:?"GITEA_URL nicht gesetzt (in .env oder als Umgebungsvariable)"}"
|
||||
GITEA_REPO="${GITEA_REPO:?"GITEA_REPO nicht gesetzt (z.B. stefan/aria-agent)"}"
|
||||
GITEA_USER="${GITEA_USER:-$(echo "$GITEA_REPO" | cut -d'/' -f1)}"
|
||||
|
||||
echo -e "${CYAN}╔═══════════════════════════════════════════╗${NC}"
|
||||
echo -e "${CYAN}║ ARIA Host-Agent Release — ${TAG}$(printf '%*s' $((14 - ${#TAG})) '')║${NC}"
|
||||
echo -e "${CYAN}╚═══════════════════════════════════════════╝${NC}\n"
|
||||
|
||||
# ── Kennwort ─────────────────────────────────────────────────────────
|
||||
echo -e "${YELLOW}Gitea-Login: ${GITEA_USER}${NC}"
|
||||
read -s -p "Gitea-Kennwort: " GITEA_PASS; echo ""
|
||||
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -u "${GITEA_USER}:${GITEA_PASS}" "$GITEA_URL/api/v1/user")
|
||||
if [ "$HTTP_CODE" != "200" ]; then
|
||||
echo -e "${RED}Login fehlgeschlagen (HTTP $HTTP_CODE). Kennwort korrekt?${NC}"; exit 1
|
||||
fi
|
||||
echo -e " ${GREEN}✓${NC} Login erfolgreich\n"
|
||||
|
||||
# ── Versionsnummern setzen ───────────────────────────────────────────
|
||||
echo -e "${GREEN}[1/5] Version auf $VERSION setzen...${NC}"
|
||||
# Desktop-Agent
|
||||
sed -i "s/^AGENT_VERSION = \"[^\"]*\"/AGENT_VERSION = \"$VERSION\"/" host_agent.py
|
||||
echo -e " ${GREEN}✓${NC} host_agent.py → AGENT_VERSION $VERSION"
|
||||
# Android: versionName + versionCode (aus Version berechnen; 3- oder 4-stellig)
|
||||
IFS='.' read -ra VP <<< "$VERSION"
|
||||
V1=${VP[0]:-0}; V2=${VP[1]:-0}; V3=${VP[2]:-0}; V4=${VP[3]:-0}
|
||||
VERSION_CODE=$((V1 * 1000000 + V2 * 10000 + V3 * 100 + V4)); [ "$VERSION_CODE" -lt 1 ] && VERSION_CODE=1
|
||||
sed -i "s/versionName '[^']*'/versionName '$VERSION'/" android/app/build.gradle
|
||||
sed -i "s/versionCode [0-9]*/versionCode $VERSION_CODE/" android/app/build.gradle
|
||||
echo -e " ${GREEN}✓${NC} android/app/build.gradle → versionName $VERSION, versionCode $VERSION_CODE\n"
|
||||
|
||||
# ── Bauen (Docker) ───────────────────────────────────────────────────
|
||||
echo -e "${GREEN}[2/5] Linux-Binary + Android-APK bauen (Docker)...${NC}"
|
||||
./build.sh >/dev/null
|
||||
LINUX_BIN="$SCRIPT_DIR/dist/aria-host-agent"
|
||||
[ -f "$LINUX_BIN" ] || { echo -e "${RED}Linux-Binary fehlt: $LINUX_BIN${NC}"; exit 1; }
|
||||
echo -e " ${GREEN}✓${NC} Linux-Binary ($(du -h "$LINUX_BIN" | cut -f1))"
|
||||
|
||||
( cd android && ./build.sh >/dev/null )
|
||||
APK="$SCRIPT_DIR/android/dist/aria-android-agent.apk"
|
||||
[ -f "$APK" ] || { echo -e "${RED}APK fehlt: $APK${NC}"; exit 1; }
|
||||
echo -e " ${GREEN}✓${NC} Android-APK ($(du -h "$APK" | cut -f1))"
|
||||
|
||||
# Windows (.exe + setup.exe) via Wine im Docker. Dauert (pywine-Image ~1-2 GB) —
|
||||
# mit SKIP_WINDOWS=1 ./release_agent.sh <v> ueberspringbar.
|
||||
if [ "${SKIP_WINDOWS:-0}" = "1" ]; then
|
||||
echo -e " ${YELLOW}Windows-Build uebersprungen (SKIP_WINDOWS=1)${NC}"
|
||||
else
|
||||
echo -e " ${CYAN}…${NC} Windows-.exe + setup.exe bauen (Wine, kann dauern)"
|
||||
if ./build-win.sh "$VERSION" >/dev/null 2>&1; then
|
||||
echo -e " ${GREEN}✓${NC} Windows-.exe + setup.exe"
|
||||
else
|
||||
echo -e " ${YELLOW}Windows-Build fehlgeschlagen — Release laeuft ohne Windows weiter.${NC}"
|
||||
echo -e " ${YELLOW}(Einzeln testen: ./build-win.sh $VERSION)${NC}"
|
||||
fi
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Asset-Liste aufbauen: "lokaler_pfad::asset-name"
|
||||
ASSETS=(
|
||||
"$LINUX_BIN::aria-host-agent-linux-x64"
|
||||
"$APK::aria-host-agent-android-$TAG.apk"
|
||||
)
|
||||
# Native Artefakte (nur wenn vorhanden): Windows aus build-win.sh, macOS
|
||||
# vorgebaut (build-native.sh auf einem Mac -> dist/aria-host-agent-macos legen).
|
||||
[ -f "$SCRIPT_DIR/dist/aria-host-agent-macos" ] && ASSETS+=("$SCRIPT_DIR/dist/aria-host-agent-macos::aria-host-agent-macos")
|
||||
[ -f "$SCRIPT_DIR/dist/aria-host-agent.exe" ] && ASSETS+=("$SCRIPT_DIR/dist/aria-host-agent.exe::aria-host-agent-windows.exe")
|
||||
[ -f "$SCRIPT_DIR/dist/aria-host-agent-setup.exe" ] && ASSETS+=("$SCRIPT_DIR/dist/aria-host-agent-setup.exe::aria-host-agent-windows-setup.exe")
|
||||
|
||||
# ── Git-Tag ──────────────────────────────────────────────────────────
|
||||
echo -e "${GREEN}[3/5] Git-Tag $TAG...${NC}"
|
||||
git add host_agent.py android/app/build.gradle
|
||||
git commit -m "release(agent): bump to $VERSION" 2>/dev/null || echo -e " ${YELLOW}Keine Aenderungen zum Committen${NC}"
|
||||
if git rev-parse "$TAG" &>/dev/null; then
|
||||
echo -e " ${YELLOW}Tag $TAG existiert bereits — überspringe${NC}"
|
||||
else
|
||||
git tag "$TAG"; echo -e " ${GREEN}✓${NC} Tag $TAG erstellt"
|
||||
fi
|
||||
git push origin main "$TAG"
|
||||
echo -e " ${GREEN}✓${NC} Tag gepusht\n"
|
||||
|
||||
# ── Gitea-Release ────────────────────────────────────────────────────
|
||||
echo -e "${GREEN}[4/5] Gitea-Release anlegen...${NC}"
|
||||
BODY=$(printf 'ARIA Host-Agent %s\n\nDesktop (Linux) + Android-APK. Auf das Zielgeraet kopieren, siehe README.' "$TAG")
|
||||
BODY_JSON=$(printf '%s' "$BODY" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read()))' 2>/dev/null || printf '"%s"' "$BODY")
|
||||
RESP=$(curl -s -X POST "$GITEA_URL/api/v1/repos/$GITEA_REPO/releases" \
|
||||
-u "${GITEA_USER}:${GITEA_PASS}" -H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"Host-Agent $TAG\",\"body\":$BODY_JSON,\"draft\":false,\"prerelease\":false}")
|
||||
RELEASE_ID=$(echo "$RESP" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
|
||||
if [ -z "$RELEASE_ID" ]; then echo -e "${RED}Release fehlgeschlagen:${NC}\n$RESP"; exit 1; fi
|
||||
echo -e " ${GREEN}✓${NC} Release #$RELEASE_ID erstellt\n"
|
||||
|
||||
# ── Assets hochladen ─────────────────────────────────────────────────
|
||||
echo -e "${GREEN}[5/5] Assets hochladen (${#ASSETS[@]})...${NC}"
|
||||
for entry in "${ASSETS[@]}"; do
|
||||
path="${entry%%::*}"; name="${entry##*::}"
|
||||
UP=$(curl -s -X POST \
|
||||
"$GITEA_URL/api/v1/repos/$GITEA_REPO/releases/$RELEASE_ID/assets?name=$name" \
|
||||
-u "${GITEA_USER}:${GITEA_PASS}" -F "attachment=@${path}")
|
||||
if echo "$UP" | grep -q '"name"'; then
|
||||
echo -e " ${GREEN}✓${NC} $name"
|
||||
else
|
||||
echo -e " ${RED}✗ $name fehlgeschlagen:${NC} $UP"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}╔═══════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${GREEN}║ Host-Agent $TAG ist live!${NC}"
|
||||
echo -e "${GREEN}║${NC} $GITEA_URL/$GITEA_REPO/releases/tag/$TAG"
|
||||
echo -e "${GREEN}╚═══════════════════════════════════════════════════╝${NC}"
|
||||
@@ -0,0 +1,2 @@
|
||||
websockets>=12.0
|
||||
psutil>=5.9 # System-Info (CPU/RAM/Disk/Uptime) fuer host_info
|
||||
@@ -0,0 +1,83 @@
|
||||
; ARIA Host-Agent — Windows-Installer (NSIS, auf Linux mit makensis gebaut).
|
||||
;
|
||||
; Installiert die Agent-.exe nach %ProgramFiles%\ARIA Host-Agent, legt eine .env
|
||||
; in %ProgramData%\ARIA-Host-Agent an (nur falls noch keine da ist — User-Config
|
||||
; bleibt erhalten) und richtet einen automatisch startenden Windows-Dienst via
|
||||
; nssm ein. Der Dienst laeuft mit AppDirectory = ProgramData-Ordner, damit der
|
||||
; Agent die .env von dort (aus dem CWD) liest.
|
||||
|
||||
!ifndef VERSION
|
||||
!define VERSION "0.0.0"
|
||||
!endif
|
||||
!define SVC "ARIAHostAgent"
|
||||
|
||||
Name "ARIA Host-Agent ${VERSION}"
|
||||
OutFile "aria-host-agent-setup.exe"
|
||||
InstallDir "$PROGRAMFILES64\ARIA Host-Agent"
|
||||
RequestExecutionLevel admin
|
||||
Unicode true
|
||||
ShowInstDetails show
|
||||
ShowUninstDetails show
|
||||
|
||||
Var DataDir
|
||||
|
||||
Page directory
|
||||
Page instfiles
|
||||
UninstPage uninstConfirm
|
||||
UninstPage instfiles
|
||||
|
||||
Section "Install"
|
||||
SetOutPath "$INSTDIR"
|
||||
File "aria-host-agent.exe"
|
||||
File "nssm.exe"
|
||||
|
||||
; ProgramData-Ordner fuer die .env bestimmen
|
||||
ReadEnvStr $0 "ProgramData"
|
||||
StrCmp $0 "" 0 +2
|
||||
StrCpy $0 "$PROFILE" ; Fallback, falls %ProgramData% fehlt
|
||||
StrCpy $DataDir "$0\ARIA-Host-Agent"
|
||||
CreateDirectory "$DataDir"
|
||||
|
||||
; .env nur schreiben, wenn noch keine existiert (User-Config nicht ueberschreiben)
|
||||
IfFileExists "$DataDir\.env" env_done 0
|
||||
FileOpen $1 "$DataDir\.env" w
|
||||
FileWrite $1 "# ARIA Host-Agent — Konfiguration (dieser Windows-Dienst liest diese Datei).$\r$\n"
|
||||
FileWrite $1 "# Nach dem Aendern den Dienst neu starten: services.msc -> ARIA Host-Agent.$\r$\n"
|
||||
FileWrite $1 "RVS_HOST=rvs.example.de$\r$\n"
|
||||
FileWrite $1 "RVS_PORT=443$\r$\n"
|
||||
FileWrite $1 "RVS_TLS=true$\r$\n"
|
||||
FileWrite $1 "RVS_TLS_FALLBACK=true$\r$\n"
|
||||
FileWrite $1 "RVS_TOKEN=$\r$\n"
|
||||
FileWrite $1 "RVS_SNI=$\r$\n"
|
||||
FileWrite $1 "HOST_NAME=$\r$\n"
|
||||
FileWrite $1 "CONTROL_ENABLED=true$\r$\n"
|
||||
FileClose $1
|
||||
env_done:
|
||||
|
||||
; Dienst (neu) einrichten — evtl. alten sauber entfernen, dann installieren
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" stop ${SVC}'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" remove ${SVC} confirm'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" install ${SVC} "$INSTDIR\aria-host-agent.exe"'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" set ${SVC} AppDirectory "$DataDir"'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" set ${SVC} DisplayName "ARIA Host-Agent"'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" set ${SVC} Description "ARIA-Fernsteuerung dieses Rechners (RVS-Agent)."'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" set ${SVC} Start SERVICE_AUTO_START'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" start ${SVC}'
|
||||
|
||||
; Uninstaller + Eintrag unter "Apps & Features"
|
||||
WriteUninstaller "$INSTDIR\uninstall.exe"
|
||||
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\ARIAHostAgent" "DisplayName" "ARIA Host-Agent"
|
||||
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\ARIAHostAgent" "DisplayVersion" "${VERSION}"
|
||||
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\ARIAHostAgent" "UninstallString" '"$INSTDIR\uninstall.exe"'
|
||||
SectionEnd
|
||||
|
||||
Section "Uninstall"
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" stop ${SVC}'
|
||||
nsExec::ExecToLog '"$INSTDIR\nssm.exe" remove ${SVC} confirm'
|
||||
Delete "$INSTDIR\aria-host-agent.exe"
|
||||
Delete "$INSTDIR\nssm.exe"
|
||||
Delete "$INSTDIR\uninstall.exe"
|
||||
RMDir "$INSTDIR"
|
||||
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\ARIAHostAgent"
|
||||
; Die .env in %ProgramData%\ARIA-Host-Agent bleibt bewusst erhalten (User-Config).
|
||||
SectionEnd
|
||||
Executable
+219
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# aria-vm — ARIAs QEMU-VM-Verwaltung fuer alle Architekturen (laeuft auf dem
|
||||
# Host). ARIA ruft das per SSH (aria-wohnung) ueber den qemu-vm-Skill auf.
|
||||
#
|
||||
# Unterkommandos:
|
||||
# aria-vm create <name> <arch> [size] Disk anlegen (qcow2)
|
||||
# aria-vm boot <name> [optionen] VM starten (VNC 127.0.0.1:<display>)
|
||||
# aria-vm screenshot <name> PNG-Screenshot → Shared-Uploads
|
||||
# aria-vm list laufende/vorhandene VMs
|
||||
# aria-vm stop <name> VM beenden
|
||||
# aria-vm rm <name> VM + Disk loeschen
|
||||
#
|
||||
# boot-Optionen:
|
||||
# --iso <pfad> Boot-ISO (setzt Boot-Reihenfolge auf CD)
|
||||
# --disk-boot von der Festplatte booten (Default nach Installation)
|
||||
# --vnc-display <N> VNC-Display (Port = 5900+N, Default 1)
|
||||
# --mem <MB> RAM (Default 1024)
|
||||
# --machine <typ> QEMU-Maschine ueberschreiben
|
||||
#
|
||||
# VNC bindet immer nur an 127.0.0.1 — von aussen erreichbar ausschliesslich
|
||||
# ueber den RVS-Tunnel der Bridge (host.docker.internal:<port>).
|
||||
set -euo pipefail
|
||||
|
||||
VM_ROOT="${ARIA_VM_ROOT:-/var/lib/aria-vms}"
|
||||
# Wohin Screenshots geschrieben werden — Host-Pfad des /shared-Volumes, damit
|
||||
# Bridge/App sie sehen. Ueberschreibbar via ARIA_VM_SHOT_DIR.
|
||||
SHOT_DIR="${ARIA_VM_SHOT_DIR:-/root/ARIA-AGENT/aria-shared/uploads}"
|
||||
|
||||
die() { echo "aria-vm: $*" >&2; exit 1; }
|
||||
|
||||
qemu_bin_for() {
|
||||
case "$1" in
|
||||
x86_64|amd64) echo qemu-system-x86_64 ;;
|
||||
i386|i686|x86) echo qemu-system-i386 ;;
|
||||
arm|armv7) echo qemu-system-arm ;;
|
||||
aarch64|arm64) echo qemu-system-aarch64 ;;
|
||||
mips) echo qemu-system-mips ;;
|
||||
mipsel) echo qemu-system-mipsel ;;
|
||||
mips64) echo qemu-system-mips64 ;;
|
||||
ppc) echo qemu-system-ppc ;;
|
||||
ppc64) echo qemu-system-ppc64 ;;
|
||||
riscv64) echo qemu-system-riscv64 ;;
|
||||
sparc) echo qemu-system-sparc ;;
|
||||
*) echo "" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
vm_dir() { echo "${VM_ROOT}/$1"; }
|
||||
vm_pid() { local d; d="$(vm_dir "$1")"; [[ -f "${d}/pid" ]] && cat "${d}/pid" || echo ""; }
|
||||
vm_running() {
|
||||
local p; p="$(vm_pid "$1")"
|
||||
[[ -n "${p}" ]] && kill -0 "${p}" 2>/dev/null
|
||||
}
|
||||
|
||||
cmd_create() {
|
||||
local name="${1:?name}" arch="${2:?arch}" size="${3:-10G}"
|
||||
local bin; bin="$(qemu_bin_for "${arch}")"
|
||||
[[ -n "${bin}" ]] || die "unbekannte Architektur: ${arch}"
|
||||
command -v "${bin}" >/dev/null || die "${bin} nicht installiert (qemu-setup.sh?)"
|
||||
local d; d="$(vm_dir "${name}")"
|
||||
[[ -f "${d}/arch" ]] && die "VM '${name}' existiert schon"
|
||||
mkdir -p "${d}"
|
||||
echo "${arch}" > "${d}/arch"
|
||||
# size='none' oder '0' → keine Festplatte (VM bootet von --iso/--floppy,
|
||||
# z.B. OS-Entwicklung von Diskette). Sonst eine qcow2-Disk anlegen.
|
||||
if [[ "${size}" == "none" || "${size}" == "0" ]]; then
|
||||
echo "VM '${name}' angelegt (${arch}, ohne Disk — bootet von ISO/Diskette)."
|
||||
else
|
||||
qemu-img create -f qcow2 "${d}/disk.qcow2" "${size}" >/dev/null
|
||||
echo "VM '${name}' angelegt (${arch}, ${size})."
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_boot() {
|
||||
local name="${1:?name}"; shift || true
|
||||
local d; d="$(vm_dir "${name}")"
|
||||
[[ -f "${d}/arch" || -f "${d}/disk.qcow2" ]] || die "VM '${name}' nicht gefunden (erst 'create')"
|
||||
vm_running "${name}" && die "VM '${name}' laeuft bereits"
|
||||
local arch; arch="$(cat "${d}/arch" 2>/dev/null || echo x86_64)"
|
||||
local bin; bin="$(qemu_bin_for "${arch}")"
|
||||
|
||||
local iso="" floppy="" disk="" bootdev="" display=1 mem=1024 machine=""
|
||||
# VNC bindet an 127.0.0.1 (Loopback) — von aussen nur ueber den RVS-Tunnel der
|
||||
# Bridge erreichbar. Die Bridge (Container) kann Loopback aber NICHT erreichen;
|
||||
# der Brain gibt deshalb per --vnc-bind die Docker-Gateway-IP mit (container-
|
||||
# intern, NICHT im LAN/Internet). Default bleibt Loopback.
|
||||
local vncbind="${ARIA_VM_VNC_BIND:-127.0.0.1}"
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--iso) iso="${2:?}"; shift 2 ;;
|
||||
--floppy) floppy="${2:?}"; shift 2 ;; # -fda (Disketten-Boot, OS-Dev)
|
||||
--disk) disk="${2:?}"; shift 2 ;; # explizite qcow2 statt Auto
|
||||
--boot) bootdev="${2:?}"; shift 2 ;; # Boot-Reihenfolge (a/c/d)
|
||||
--disk-boot) bootdev="c"; shift ;;
|
||||
--vnc-display) display="${2:?}"; shift 2 ;;
|
||||
--vnc-bind) vncbind="${2:?}"; shift 2 ;; # Bind-Adresse fuer -vnc
|
||||
--mem) mem="${2:?}"; shift 2 ;;
|
||||
--machine) machine="${2:?}"; shift 2 ;;
|
||||
*) die "unbekannte Option: $1" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Auto-Erkennung der Medien im VM-Ordner, falls nicht explizit angegeben.
|
||||
[[ -z "${disk}" && -f "${d}/disk.qcow2" ]] && disk="${d}/disk.qcow2"
|
||||
[[ -z "${floppy}" && -f "${d}/floppy.img" ]] && floppy="${d}/floppy.img"
|
||||
[[ -z "${iso}" && -f "${d}/cdrom.iso" ]] && iso="${d}/cdrom.iso"
|
||||
[[ -n "${disk}${floppy}${iso}" ]] || \
|
||||
die "Keine Boot-Medien fuer '${name}' (disk.qcow2 / --iso / --floppy). Erst 'create <name> <arch> <groesse>' oder ein Medium angeben."
|
||||
|
||||
local args=(-name "${name}" -m "${mem}"
|
||||
-vnc "${vncbind}:${display}"
|
||||
-monitor "unix:${d}/monitor.sock,server,nowait"
|
||||
-pidfile "${d}/pid" -daemonize)
|
||||
[[ -n "${disk}" ]] && args+=(-drive "file=${disk},format=qcow2")
|
||||
[[ -n "${floppy}" ]] && args+=(-fda "${floppy}")
|
||||
[[ -n "${iso}" ]] && args+=(-cdrom "${iso}")
|
||||
|
||||
# KVM nur fuer x86 auf x86-Host.
|
||||
case "${arch}" in
|
||||
x86_64|amd64|i386|i686|x86)
|
||||
[[ -e /dev/kvm ]] && args+=(-enable-kvm) ;;
|
||||
esac
|
||||
# ARM/AArch64 brauchen eine Maschine (kein Default).
|
||||
if [[ -z "${machine}" ]]; then
|
||||
case "${arch}" in
|
||||
arm|armv7|aarch64|arm64) machine="virt" ;;
|
||||
esac
|
||||
fi
|
||||
[[ -n "${machine}" ]] && args+=(-M "${machine}")
|
||||
|
||||
# Boot-Reihenfolge: explizit, sonst automatisch (ISO→d, nur Diskette→a, sonst c).
|
||||
if [[ -z "${bootdev}" ]]; then
|
||||
if [[ -n "${iso}" ]]; then bootdev="d"
|
||||
elif [[ -n "${floppy}" && -z "${disk}" ]]; then bootdev="a"
|
||||
else bootdev="c"; fi
|
||||
fi
|
||||
args+=(-boot "${bootdev}")
|
||||
|
||||
"${bin}" "${args[@]}"
|
||||
echo "VM '${name}' gestartet (${arch}) — VNC ${vncbind}:${display} (Port $((5900+display)))."
|
||||
echo "vnc_display=${display} vnc_port=$((5900+display))"
|
||||
}
|
||||
|
||||
cmd_screenshot() {
|
||||
local name="${1:?name}"
|
||||
local d; d="$(vm_dir "${name}")"
|
||||
vm_running "${name}" || die "VM '${name}' laeuft nicht"
|
||||
command -v socat >/dev/null || die "socat fehlt (qemu-setup.sh?)"
|
||||
# Standard: ins VM-Verzeichnis schreiben (dem aria-User gehoerend) — NICHT
|
||||
# nach /root/... (da kommt der aria-User nicht hin). Der Brain holt das PNG
|
||||
# danach per SSH (base64). Ueberschreibbar via ARIA_VM_SHOT_DIR.
|
||||
local out_dir="${ARIA_VM_SHOT_DIR:-${d}}"
|
||||
mkdir -p "${out_dir}"
|
||||
local ts; ts="$(date +%s)"
|
||||
local ppm="${d}/shot-${ts}.ppm"
|
||||
printf 'screendump %s\n' "${ppm}" | socat - "unix-connect:${d}/monitor.sock" >/dev/null
|
||||
sleep 0.3
|
||||
local out="${out_dir}/${name}-${ts}.png"
|
||||
if command -v convert >/dev/null; then
|
||||
convert "${ppm}" "${out}" && rm -f "${ppm}"
|
||||
else
|
||||
out="${out_dir}/${name}-${ts}.ppm"; mv "${ppm}" "${out}"
|
||||
fi
|
||||
echo "screenshot=${out}"
|
||||
}
|
||||
|
||||
cmd_list() {
|
||||
[[ -d "${VM_ROOT}" ]] || { echo "(keine VMs)"; return; }
|
||||
local any=0
|
||||
for d in "${VM_ROOT}"/*/; do
|
||||
[[ -d "${d}" ]] || continue
|
||||
any=1
|
||||
local name arch state
|
||||
name="$(basename "${d}")"
|
||||
arch="$(cat "${d}/arch" 2>/dev/null || echo '?')"
|
||||
if vm_running "${name}"; then state="laeuft (pid $(vm_pid "${name}"))"; else state="gestoppt"; fi
|
||||
echo "${name} [${arch}] ${state}"
|
||||
done
|
||||
[[ "${any}" -eq 1 ]] || echo "(keine VMs)"
|
||||
}
|
||||
|
||||
cmd_stop() {
|
||||
local name="${1:?name}"
|
||||
local d; d="$(vm_dir "${name}")"
|
||||
if vm_running "${name}"; then
|
||||
printf 'quit\n' | socat - "unix-connect:${d}/monitor.sock" >/dev/null 2>&1 || true
|
||||
sleep 0.5
|
||||
vm_running "${name}" && kill "$(vm_pid "${name}")" 2>/dev/null || true
|
||||
echo "VM '${name}' gestoppt."
|
||||
else
|
||||
echo "VM '${name}' lief nicht."
|
||||
fi
|
||||
rm -f "${d}/pid" "${d}/monitor.sock"
|
||||
}
|
||||
|
||||
cmd_rm() {
|
||||
local name="${1:?name}"
|
||||
vm_running "${name}" && cmd_stop "${name}"
|
||||
rm -rf "$(vm_dir "${name}")"
|
||||
echo "VM '${name}' geloescht."
|
||||
}
|
||||
|
||||
main() {
|
||||
local sub="${1:-}"; shift || true
|
||||
case "${sub}" in
|
||||
create) cmd_create "$@" ;;
|
||||
boot) cmd_boot "$@" ;;
|
||||
screenshot) cmd_screenshot "$@" ;;
|
||||
list) cmd_list "$@" ;;
|
||||
stop) cmd_stop "$@" ;;
|
||||
rm) cmd_rm "$@" ;;
|
||||
""|-h|--help)
|
||||
sed -n '2,40p' "$0" | sed 's/^# \{0,1\}//' ;;
|
||||
*) die "unbekanntes Kommando: ${sub} (siehe --help)" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# qemu-setup.sh — installiert QEMU fuer ALLE Architekturen auf dem ARIA-Host
|
||||
# (10.0.0.1) plus den aria-vm-Helper. Einmalig als root ausfuehren.
|
||||
#
|
||||
# sudo bash host-provisioning/qemu-setup.sh
|
||||
#
|
||||
# KVM-Beschleunigung gibt es nur fuer x86-Gaeste auf einem x86-Host; ARM/MIPS/
|
||||
# PPC/RISC-V laufen unter TCG (voll emuliert, langsamer, aber alle Architekturen
|
||||
# baubar). websockify/noVNC werden NICHT installiert — der VNC-Stream wird als
|
||||
# RFB-Bytes durch die Bridge/RVS getunnelt (siehe aria_bridge.py VNC-Bruecke).
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "${EUID}" -ne 0 ]]; then
|
||||
echo "Bitte als root ausfuehren (sudo)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[qemu-setup] apt update ..."
|
||||
apt-get update -qq
|
||||
|
||||
echo "[qemu-setup] Installiere QEMU (alle Architekturen) + Werkzeuge ..."
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
qemu-system \
|
||||
qemu-system-x86 \
|
||||
qemu-system-arm \
|
||||
qemu-system-mips \
|
||||
qemu-system-ppc \
|
||||
qemu-system-sparc \
|
||||
qemu-system-misc \
|
||||
qemu-utils \
|
||||
seabios \
|
||||
ovmf \
|
||||
ipxe-qemu \
|
||||
socat \
|
||||
imagemagick
|
||||
|
||||
echo "[qemu-setup] KVM-Status:"
|
||||
if [[ -e /dev/kvm ]]; then
|
||||
echo " /dev/kvm vorhanden → x86-Gaeste mit KVM-Beschleunigung."
|
||||
else
|
||||
echo " /dev/kvm FEHLT → alle Gaeste laufen unter TCG (emuliert, langsamer)."
|
||||
fi
|
||||
|
||||
# aria-vm-Helper installieren (liegt neben diesem Skript).
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
install -m 0755 "${SCRIPT_DIR}/aria-vm" /usr/local/bin/aria-vm
|
||||
echo "[qemu-setup] /usr/local/bin/aria-vm installiert."
|
||||
|
||||
mkdir -p /var/lib/aria-vms
|
||||
echo "[qemu-setup] VM-Verzeichnis: /var/lib/aria-vms"
|
||||
|
||||
echo "[qemu-setup] Fertig. Test: aria-vm list"
|
||||
@@ -183,9 +183,9 @@ Wichtige Mechanismen:
|
||||
- [x] Decimal-zu-Worte fuer TTS (0.1 → null komma eins, mit IP-Schutz-Lookahead)
|
||||
- [x] Generic Acronym-Buchstabieren (XTTS → X T T S, USB → U S B, ueber expliziter Liste)
|
||||
- [x] voice_preload/voice_ready: Stille Mini-Render bei Voice-Wechsel + Toast/Status "bereit"
|
||||
- [x] Whisper STT auf die Gamebox ausgelagert (faster-whisper CUDA, float16) — neuer aria-whisper-bridge Container
|
||||
- [x] aria-bridge: STT primaer remote (Gamebox), Fallback lokal nach 45s Timeout
|
||||
- [x] Whisper-Modell hot-swap auf Gamebox via config-Broadcast aus Diagnostic
|
||||
- [x] Whisper STT auf die AI-Box ausgelagert (faster-whisper CUDA, float16) — neuer aria-whisper-bridge Container
|
||||
- [x] aria-bridge: STT primaer remote (AI-Box), Fallback lokal nach 45s Timeout
|
||||
- [x] Whisper-Modell hot-swap auf AI-Box via config-Broadcast aus Diagnostic
|
||||
- [x] **F5-TTS ersetzt XTTS komplett** — neuer aria-f5tts-bridge Container, Voice Cloning, satzweises Streaming
|
||||
- [x] Voice-Upload mit Whisper-Auto-Transkription — User muss keinen Referenz-Text eintippen
|
||||
- [x] Audio-Pause statt Ducking: Spotify/YouTube pausieren komplett waehrend TTS (TRANSIENT statt MAY_DUCK)
|
||||
@@ -334,7 +334,7 @@ Skills mit Tool-Use.
|
||||
|
||||
- [x] Datei-Manager (Diagnostic + App-Modal): /shared/uploads/ verwalten, Multi-Select + Select-All + Bulk-Download als ZIP + Bulk-Delete
|
||||
- [x] Wipe-All-Button (Memory + Stimmen + Settings)
|
||||
- [x] Voice Export/Import pro Stimme (Diagnostic + XTTS-Bridge auf Gamebox)
|
||||
- [x] Voice Export/Import pro Stimme (Diagnostic + XTTS-Bridge auf AI-Box)
|
||||
- [x] F5/Whisper-Settings als JSON-Bundle Export/Import
|
||||
- [x] App Chat-Suche umgebaut: Highlight + Next/Prev statt Filter
|
||||
- [x] App Pinch-Zoom in Bildern rewriten (Multi-Touch-Race-Bugs)
|
||||
@@ -399,7 +399,7 @@ Skills mit Tool-Use.
|
||||
### Architektur
|
||||
- [ ] Diagnostic: System-Info Tab (Container-Status, Disk, RAM, CPU)
|
||||
- [ ] RVS Zombie-Connections endgueltig loesen
|
||||
- [ ] Gamebox: kleine Web-Oberflaeche fuer Credentials/Server-Config oder zentral aus Diagnostic per RVS push
|
||||
- [ ] AI-Box: kleine Web-Oberflaeche fuer Credentials/Server-Config oder zentral aus Diagnostic per RVS push
|
||||
- [ ] Erste Skills bauen lassen (yt-dlp, pdf-extract, image-resize, etc.) — durch normale Anfragen, ARIA legt sie selbst an
|
||||
- [ ] Heartbeat (periodische Selbst-Checks)
|
||||
- [ ] Lokales LLM als Waechter (Triage vor Claude-Call)
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Claude Code CLI Subprocess Manager — ARIA-Patch
|
||||
*
|
||||
* Basis: claude-max-api-proxy dist/subprocess/manager.js, plus die bisher per
|
||||
* sed in docker-compose.yml eingespielten Anpassungen (dangerously-skip-
|
||||
* permissions, system-prompt, 24h-Timeout, Prompt via stdin) — hier fest im
|
||||
* File, damit der groessere Zwischenruf-Umbau nicht per sed gefrickelt werden
|
||||
* muss. Wird per `cp` ueber die npm-Version gelegt (siehe docker-compose.yml).
|
||||
*
|
||||
* ZWISCHENRUF (interject): Statt den Prompt als Text zu schreiben und stdin
|
||||
* sofort zu schliessen (--print/text), laeuft claude jetzt im
|
||||
* `--input-format stream-json`-Modus. Der initiale Prompt geht als
|
||||
* stream-json User-Message rein, stdin bleibt OFFEN — so kann waehrend des
|
||||
* laufenden Turns per sendMessage() eine weitere User-Message reingeschoben
|
||||
* werden, die claude an der naechsten Tool-Grenze aufgreift (kein Abbruch).
|
||||
* Bei 'result' (Turn fertig) wird stdin geschlossen, damit claude sauber
|
||||
* beendet und die HTTP-Response (in routes.js an 'close' gebunden) rausgeht.
|
||||
*/
|
||||
import { spawn } from "child_process";
|
||||
import { EventEmitter } from "events";
|
||||
import { isAssistantMessage, isResultMessage, isContentDelta } from "../types/claude-cli.js";
|
||||
const DEFAULT_TIMEOUT = 86400000; // 24h — lange Agent-Loops (Pentests etc.)
|
||||
export class ClaudeSubprocess extends EventEmitter {
|
||||
process = null;
|
||||
buffer = "";
|
||||
timeoutId = null;
|
||||
isKilled = false;
|
||||
_stdinClosed = false;
|
||||
/**
|
||||
* Start the Claude CLI subprocess with the given prompt
|
||||
*/
|
||||
async start(prompt, options) {
|
||||
const args = this.buildArgs(prompt, options);
|
||||
const timeout = options.timeout || DEFAULT_TIMEOUT;
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// Use spawn() for security - no shell interpretation
|
||||
this.process = spawn("claude", args, {
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: { ...process.env },
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
// Set timeout
|
||||
this.timeoutId = setTimeout(() => {
|
||||
if (!this.isKilled) {
|
||||
this.isKilled = true;
|
||||
this.process?.kill("SIGTERM");
|
||||
this.emit("error", new Error(`Request timed out after ${timeout}ms`));
|
||||
}
|
||||
}, timeout);
|
||||
// Handle spawn errors (e.g., claude not found)
|
||||
this.process.on("error", (err) => {
|
||||
this.clearTimeout();
|
||||
if (err.message.includes("ENOENT")) {
|
||||
reject(new Error("Claude CLI not found. Install with: npm install -g @anthropic-ai/claude-code"));
|
||||
}
|
||||
else {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
// stdin BLEIBT OFFEN: initialen Prompt als stream-json User-
|
||||
// Message schreiben; spaetere Zwischenrufe kommen via
|
||||
// sendMessage(). Geschlossen wird bei 'result' (s. processBuffer).
|
||||
this._writeUserMessage(prompt);
|
||||
// Falls stdin (z.B. EPIPE) frueh stirbt: nicht crashen.
|
||||
this.process.stdin?.on("error", () => {});
|
||||
console.error(`[Subprocess] Process spawned with PID: ${this.process.pid}`);
|
||||
// Parse JSON stream from stdout
|
||||
this.process.stdout?.on("data", (chunk) => {
|
||||
const data = chunk.toString();
|
||||
console.error(`[Subprocess] Received ${data.length} bytes of stdout`);
|
||||
this.buffer += data;
|
||||
this.processBuffer();
|
||||
});
|
||||
// Capture stderr for debugging
|
||||
this.process.stderr?.on("data", (chunk) => {
|
||||
const errorText = chunk.toString().trim();
|
||||
if (errorText) {
|
||||
// Don't emit as error unless it's actually an error
|
||||
// Claude CLI may write debug info to stderr
|
||||
console.error("[Subprocess stderr]:", errorText.slice(0, 200));
|
||||
}
|
||||
});
|
||||
// Handle process close
|
||||
this.process.on("close", (code) => {
|
||||
console.error(`[Subprocess] Process closed with code: ${code}`);
|
||||
this.clearTimeout();
|
||||
// Process any remaining buffer
|
||||
if (this.buffer.trim()) {
|
||||
this.processBuffer();
|
||||
}
|
||||
this.emit("close", code);
|
||||
});
|
||||
// Resolve immediately since we're streaming
|
||||
resolve();
|
||||
}
|
||||
catch (err) {
|
||||
this.clearTimeout();
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Build CLI arguments array
|
||||
*/
|
||||
buildArgs(prompt, options) {
|
||||
const args = [
|
||||
"--print", // Non-interactive mode
|
||||
"--output-format",
|
||||
"stream-json", // JSON streaming output
|
||||
"--verbose", // Required for stream-json
|
||||
"--include-partial-messages", // Enable streaming chunks
|
||||
"--input-format",
|
||||
"stream-json", // ARIA: User-Messages via stdin (Zwischenruf)
|
||||
"--model",
|
||||
options.model, // Model alias (opus/sonnet/haiku)
|
||||
"--no-session-persistence", "--dangerously-skip-permissions", "--system-prompt", options.systemPrompt, "--safe-mode",
|
||||
];
|
||||
if (options.sessionId) {
|
||||
args.push("--session-id", options.sessionId);
|
||||
}
|
||||
return args;
|
||||
}
|
||||
/**
|
||||
* Eine User-Message im stream-json-Input-Format an stdin schreiben.
|
||||
* Genutzt fuer den initialen Prompt UND fuer Zwischenrufe (sendMessage).
|
||||
*/
|
||||
_writeUserMessage(text) {
|
||||
const p = this.process;
|
||||
if (!p || !p.stdin || p.stdin.destroyed || this._stdinClosed)
|
||||
return false;
|
||||
try {
|
||||
p.stdin.write(JSON.stringify({ type: "user", message: { role: "user", content: String(text) } }) + "\n");
|
||||
return true;
|
||||
}
|
||||
catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Zwischenruf: waehrend eines laufenden Turns eine weitere User-Message
|
||||
* reinschieben. claude greift sie an der naechsten Tool-Grenze auf, ohne
|
||||
* den Turn abzubrechen. Kein Effekt, wenn stdin schon geschlossen ist
|
||||
* (Turn praktisch fertig) — dann ist der Zwischenruf schlicht zu spaet.
|
||||
*/
|
||||
sendMessage(text) {
|
||||
return this._writeUserMessage(text);
|
||||
}
|
||||
/**
|
||||
* stdin schliessen → claude beendet den stream-json-Input und exit't.
|
||||
*/
|
||||
_closeStdin() {
|
||||
if (this._stdinClosed)
|
||||
return;
|
||||
this._stdinClosed = true;
|
||||
try {
|
||||
this.process?.stdin?.end();
|
||||
}
|
||||
catch (_) { }
|
||||
}
|
||||
/**
|
||||
* Process the buffer and emit parsed messages
|
||||
*/
|
||||
processBuffer() {
|
||||
const lines = this.buffer.split("\n");
|
||||
this.buffer = lines.pop() || ""; // Keep incomplete line
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed)
|
||||
continue;
|
||||
try {
|
||||
const message = JSON.parse(trimmed);
|
||||
this.emit("message", message);
|
||||
if (isContentDelta(message)) {
|
||||
// Emit content delta for streaming
|
||||
this.emit("content_delta", message);
|
||||
}
|
||||
else if (isAssistantMessage(message)) {
|
||||
this.emit("assistant", message);
|
||||
}
|
||||
else if (isResultMessage(message)) {
|
||||
this.emit("result", message);
|
||||
// Turn fertig → stdin schliessen, sonst wartet claude im
|
||||
// stream-json-Input auf weitere Messages und der Prozess
|
||||
// (und damit die HTTP-Response) haengt fuer immer.
|
||||
this._closeStdin();
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// Non-JSON output, emit as raw
|
||||
this.emit("raw", trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clear the timeout timer
|
||||
*/
|
||||
clearTimeout() {
|
||||
if (this.timeoutId) {
|
||||
clearTimeout(this.timeoutId);
|
||||
this.timeoutId = null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Kill the subprocess
|
||||
*/
|
||||
kill(signal = "SIGTERM") {
|
||||
if (!this.isKilled && this.process) {
|
||||
this.isKilled = true;
|
||||
this.clearTimeout();
|
||||
this.process.kill(signal);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Check if the process is still running
|
||||
*/
|
||||
isRunning() {
|
||||
return this.process !== null && !this.isKilled && this.process.exitCode === null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Verify that Claude CLI is installed and accessible
|
||||
*/
|
||||
export async function verifyClaude() {
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn("claude", ["--version"], { stdio: "pipe" });
|
||||
let output = "";
|
||||
proc.stdout?.on("data", (chunk) => {
|
||||
output += chunk.toString();
|
||||
});
|
||||
proc.on("error", () => {
|
||||
resolve({
|
||||
ok: false,
|
||||
error: "Claude CLI not found. Install with: npm install -g @anthropic-ai/claude-code",
|
||||
});
|
||||
});
|
||||
proc.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ ok: true, version: output.trim() });
|
||||
}
|
||||
else {
|
||||
resolve({
|
||||
ok: false,
|
||||
error: "Claude CLI returned non-zero exit code",
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check if Claude CLI is authenticated
|
||||
*/
|
||||
export async function verifyAuth() {
|
||||
return { ok: true };
|
||||
}
|
||||
//# sourceMappingURL=manager.js.map
|
||||
@@ -25,6 +25,13 @@ const MODEL_MAP = {
|
||||
"opus": "opus",
|
||||
"sonnet": "sonnet",
|
||||
"haiku": "haiku",
|
||||
"fable": "fable",
|
||||
"claude-fable-5": "fable",
|
||||
"claude-code-cli/fable": "fable",
|
||||
// Volle aktuelle IDs (falls die App/Diagnostic sie mal direkt setzt)
|
||||
"claude-opus-5": "opus",
|
||||
"claude-sonnet-5": "sonnet",
|
||||
"claude-haiku-4-5": "haiku",
|
||||
};
|
||||
|
||||
export function extractModel(model) {
|
||||
|
||||
+95
-4
@@ -28,6 +28,43 @@ const TOOL_HOOK_URL = process.env.ARIA_TOOL_HOOK_URL
|
||||
|| "http://aria-bridge:8090/internal/agent-activity";
|
||||
const STREAM_HOOK_URL = process.env.ARIA_STREAM_HOOK_URL
|
||||
|| "http://aria-bridge:8090/internal/agent-stream";
|
||||
const CODE_FILE_HOOK_URL = process.env.ARIA_CODE_FILE_HOOK_URL
|
||||
|| "http://aria-bridge:8090/internal/code-file";
|
||||
|
||||
// Code-Projekte leben unter /shared/projects/<projectId>/ (Volume in proxy +
|
||||
// bridge + brain gemountet). Schreibt/aendert ARIA hier eine Datei, spiegeln
|
||||
// wir den Volltext live in den Code-Editor der App. Nur Dateien unter diesem
|
||||
// Praefix — ARIAs sonstige Datei-Ops (Skills, Configs) bleiben unberuehrt.
|
||||
const PROJECTS_ROOT = "/shared/projects/";
|
||||
const CODE_FILE_MAX_BYTES = 512 * 1024;
|
||||
|
||||
/** Zerlegt einen absoluten Pfad unter /shared/projects/<pid>/<rel> → {pid, rel}
|
||||
* oder null wenn er nicht darunter liegt. */
|
||||
function _parseProjectPath(filePath) {
|
||||
if (typeof filePath !== "string" || !filePath.startsWith(PROJECTS_ROOT)) return null;
|
||||
const rest = filePath.slice(PROJECTS_ROOT.length);
|
||||
const slash = rest.indexOf("/");
|
||||
if (slash <= 0) return null;
|
||||
return { pid: rest.slice(0, slash), rel: rest.slice(slash + 1) };
|
||||
}
|
||||
|
||||
/** Liest die (frisch geschriebene) Datei und pusht sie als code_file an die
|
||||
* Bridge. Fire-and-forget, fail-open. */
|
||||
function _emitCodeFile(filePath) {
|
||||
try {
|
||||
const parsed = _parseProjectPath(filePath);
|
||||
if (!parsed || !parsed.rel) return;
|
||||
const st = fs.statSync(filePath);
|
||||
if (!st.isFile() || st.size > CODE_FILE_MAX_BYTES) return;
|
||||
const content = fs.readFileSync(filePath, "utf8");
|
||||
_postJson(CODE_FILE_HOOK_URL, {
|
||||
projectId: parsed.pid,
|
||||
path: parsed.rel,
|
||||
content,
|
||||
version: Date.now(),
|
||||
});
|
||||
} catch (_) { /* fail-open */ }
|
||||
}
|
||||
|
||||
// Tool-Output kann sehr lang werden (git log -p, find /). Wir truncaten
|
||||
// hart auf 4 KB pro Event — der User sieht weiterhin den Anfang und einen
|
||||
@@ -153,6 +190,9 @@ function _attachIdleWatchdog(subprocess, requestId) {
|
||||
* - Neu-API: voller Stream (text/tool_use/tool_result) an /internal/agent-stream
|
||||
*/
|
||||
function _attachToolHook(subprocess, requestId, projectId) {
|
||||
// tool_use_id → file_path fuer Write/Edit, damit wir beim (erfolgreichen)
|
||||
// tool_result die frisch geschriebene Datei aus /shared lesen koennen.
|
||||
const _pendingFileWrites = new Map();
|
||||
subprocess.on("assistant", (message) => {
|
||||
try {
|
||||
const blocks = message?.message?.content || [];
|
||||
@@ -160,6 +200,10 @@ function _attachToolHook(subprocess, requestId, projectId) {
|
||||
if (!b) continue;
|
||||
if (b.type === "tool_use") {
|
||||
if (b.name) _emitToolEvent(b.name, projectId);
|
||||
if ((b.name === "Write" || b.name === "Edit" || b.name === "MultiEdit")
|
||||
&& b.id && b.input && typeof b.input.file_path === "string") {
|
||||
_pendingFileWrites.set(b.id, b.input.file_path);
|
||||
}
|
||||
const inputStr = b.input ? JSON.stringify(b.input) : "";
|
||||
const inp = _truncate(inputStr, TOOL_INPUT_MAX_CHARS);
|
||||
_emitStreamEvent(requestId, "tool_use", {
|
||||
@@ -203,6 +247,11 @@ function _attachToolHook(subprocess, requestId, projectId) {
|
||||
truncatedBytes: out.truncatedBytes,
|
||||
isError: b.is_error === true,
|
||||
});
|
||||
// Write/Edit erfolgreich → Datei live in den Code-Editor spiegeln.
|
||||
if (b.tool_use_id && b.is_error !== true && _pendingFileWrites.has(b.tool_use_id)) {
|
||||
_emitCodeFile(_pendingFileWrites.get(b.tool_use_id));
|
||||
_pendingFileWrites.delete(b.tool_use_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) { /* fail-open */ }
|
||||
@@ -465,12 +514,18 @@ async function handleNonStreamingResponse(res, subprocess, cliInput, requestId)
|
||||
// Datei, greifen die eingebauten Defaults; die Datei wird dann einmalig mit
|
||||
// diesen Defaults angelegt, damit es was zu editieren gibt.
|
||||
const MODELS_FILE = process.env.ARIA_MODELS_FILE || "/shared/config/models.json";
|
||||
// Tier-Aliase als id (opus/sonnet/haiku/fable) — die CLI loest sie automatisch
|
||||
// auf die AKTUELLE Version des Tiers auf (Stand 2026-07: fable→Fable 5,
|
||||
// opus→Opus 5, sonnet→Sonnet 5, haiku→Haiku 4.5). So bleibt die Liste
|
||||
// versions-robust; die display_name-Texte nur bei Tier-Wechsel anpassen.
|
||||
const DEFAULT_MODELS = [
|
||||
{ id: "claude-sonnet-4", tier: "sonnet", display_name: "Sonnet (aktuell: Sonnet 5)",
|
||||
{ id: "fable", tier: "fable", display_name: "Fable (aktuell: Fable 5)",
|
||||
description: "Staerkstes Modell — fuer die haertesten Aufgaben (Software-Entwicklung, lange Agent-Laeufe)." },
|
||||
{ id: "opus", tier: "opus", display_name: "Opus (aktuell: Opus 5)",
|
||||
description: "Sehr schlau, schneller als Fable — fuer schwere/lange Aufgaben." },
|
||||
{ id: "sonnet", tier: "sonnet", display_name: "Sonnet (aktuell: Sonnet 5)",
|
||||
description: "Schnell & gut — Standard fuer den Alltag." },
|
||||
{ id: "claude-opus-4", tier: "opus", display_name: "Opus (aktuell: Opus 4.8)",
|
||||
description: "Langsamer, aber am schlausten — fuer schwere/lange Aufgaben." },
|
||||
{ id: "claude-haiku-4", tier: "haiku", display_name: "Haiku (aktuell: Haiku 4.5)",
|
||||
{ id: "haiku", tier: "haiku", display_name: "Haiku (aktuell: Haiku 4.5)",
|
||||
description: "Sehr schnell & guenstig, kleinerer Kontext — fuer einfache Tasks." },
|
||||
];
|
||||
|
||||
@@ -572,6 +627,28 @@ function _cancelByProject(projectId) {
|
||||
return { killed, requestIds: ids, projectId: pid };
|
||||
}
|
||||
|
||||
// Zwischenruf: schiebt eine User-Message in den/die laufenden Subprozess(e)
|
||||
// eines Kontexts, OHNE sie zu killen. claude greift sie an der naechsten Tool-
|
||||
// Grenze auf (stream-json-Input, s. manager.js). Kein Treffer / stdin schon
|
||||
// zu (Turn quasi fertig) → delivered=0.
|
||||
function _interjectByProject(projectId, text) {
|
||||
const pid = String(projectId || "");
|
||||
const ids = [];
|
||||
let delivered = 0;
|
||||
for (const [id, entry] of Array.from(_activeSubprocesses)) {
|
||||
if (entry.projectId !== pid) continue;
|
||||
try {
|
||||
if (typeof entry.subprocess.sendMessage === "function" && entry.subprocess.sendMessage(text)) {
|
||||
delivered++;
|
||||
ids.push(id);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[aria-interject] sendMessage failed for", id, e?.message);
|
||||
}
|
||||
}
|
||||
return { delivered, requestIds: ids, projectId: pid };
|
||||
}
|
||||
|
||||
try {
|
||||
const internalServer = http.createServer((req, res) => {
|
||||
if (req.method === "POST" && req.url === "/cancel-all") {
|
||||
@@ -596,6 +673,20 @@ try {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST" && req.url === "/interject") {
|
||||
// Body: {projectId, text}. Zwischenruf in den laufenden Turn.
|
||||
let raw = "";
|
||||
req.on("data", (c) => { raw += c; if (raw.length > 65536) req.destroy(); });
|
||||
req.on("end", () => {
|
||||
let projectId = "", text = "";
|
||||
try { const b = JSON.parse(raw || "{}"); projectId = String(b.projectId || ""); text = String(b.text || ""); } catch (_) {}
|
||||
const result = text ? _interjectByProject(projectId, text) : { delivered: 0, requestIds: [], projectId };
|
||||
console.warn("[aria-interject] /interject project=%s — delivered %d", projectId || "(main)", result.delivered);
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, ...result }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/health") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, active: _activeSubprocesses.size }));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user