feat(matrix): MAS migration helpers + 2 flows + 15 issues + capability group
Helper functions (matrix-mas capability group): - mas_client_register_bash_infra: register/sync OAuth clients via mas-cli - mas_syn2mas_migration_bash_infra: dry-run + apply user migration to MAS - synapse_msc3861_enable_go_infra: edit homeserver.yaml MSC3861 block (with diff) - wellknown_oidc_patch_go_infra: patch well-known JSON with msc2965.authentication - synapse_login_flows_check_go_infra: health-check post-migration login flows Flows + issues for custom Matrix clients (PC + Android): - 0010 matrix-client-pc: Wails + React+Mantine (issues 0147-0153) - 0011 matrix-client-android: Kotlin + Compose (issues 0154-0161) - 0162 enable MAS as auth provider (Synapse delegate) — EXECUTED on VPS - 0163 custom admin panel propio (sustituye synapse-admin) Production state (organic-machine.com): - Synapse migrated SQLite -> Postgres - MSC3861 active, password_config disabled - 21 users + 41 access_tokens migrated via syn2mas - 4 MAS clients registered (element, matrix_pc, matrix_android, admin_panel) - synapse-admin container removed + Coolify route deleted - well-known patched with org.matrix.msc2965.authentication Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
---
|
||||
name: matrix-client-pc
|
||||
id: 0010
|
||||
status: pending
|
||||
created: 2026-05-24
|
||||
updated: 2026-05-24
|
||||
priority: high
|
||||
risk: medium
|
||||
related_issues: [0147, 0148, 0149, 0150, 0151, 0152, 0153, 0162, 0163]
|
||||
related_flows: [0009, 0011]
|
||||
apps: [matrix_client_pc]
|
||||
projects: [element_agents]
|
||||
vaults: []
|
||||
capability_groups: [matrix-client, livekit-calls, e2ee, widgets]
|
||||
trigger: manual
|
||||
schedule: ""
|
||||
expected_runtime_s: 0
|
||||
tags: [matrix, element, wails, react, mantine, livekit, e2ee, widgets, agents]
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Cliente Matrix propio para PC (Win/Linux/macOS) construido con Wails (Go backend) + React+Mantine+`@fn_library` frontend. Replica capacidades actuales de Element Web (chat, E2EE, calls LiveKit) y se abre a mejoras propias: mini-webapps embebidas en conversaciones gestionadas por agentes del project `element_agents`, paneles especiales para llamadas, integracion directa con `agents_and_robots` + `agents_dashboard` + `device_agent` + futuro mesh WireGuard (flow 0009).
|
||||
|
||||
## Pre-requisitos
|
||||
|
||||
- Synapse + MAS + LiveKit funcionando en `organic-machine.com` (app `element_matrix_chat` ya desplegada, 5+ semanas uptime).
|
||||
- `livekit-jwt` container vivo para generar tokens (ver `docker-compose.livekit.yml`).
|
||||
- Sygnal push gateway (Synapse) — TBD si no existe, anadir container para push notifs PC + Android.
|
||||
- Cuenta Matrix de test (`@dev-pc:matrix-af2f3d.organic-machine.com`) registrada via MAS.
|
||||
- Go 1.22+ + Wails CLI v2 instalado (`go install github.com/wailsapp/wails/v2/cmd/wails@latest`).
|
||||
- pnpm + Node 20+ (ya en el repo para `frontend/`).
|
||||
|
||||
## Funciones del registry recomendadas
|
||||
|
||||
| Rol | Funcion candidata | Estado |
|
||||
|---|---|---|
|
||||
| Matrix client init (Go) | `matrix_client_init_go_infra` | FALTA: wrapper sobre `mautrix-go` (login MAS OIDC, sync, store SQLite) |
|
||||
| LiveKit token gen (Go) | `livekit_token_gen_go_infra` | FALTA: JWT con `livekit-server-sdk-go` |
|
||||
| Matrix room subscribe SSE (Go) | `matrix_room_subscribe_go_infra` | FALTA: stream eventos Synapse -> frontend Wails via SSE/IPC |
|
||||
| Matrix message send (Go) | `matrix_message_send_go_infra` | FALTA: text + markdown + reply + edit + reaction |
|
||||
| Matrix E2EE bootstrap (Go) | `matrix_e2ee_bootstrap_go_infra` | FALTA: cross-signing keys, recovery passphrase |
|
||||
| Matrix device verify (Go) | `matrix_device_verify_go_infra` | FALTA: SAS verification flow |
|
||||
| LiveKit room hook (TS) | `livekit_room_ts_ui` | FALTA: hook React wrapper sobre `livekit-client` |
|
||||
| Widget host iframe (TS) | `widget_host_ts_ui` | FALTA: iframe sandbox + postMessage Matrix Widget API v2 |
|
||||
| Matrix timeline hook (TS) | `useMatrixTimeline_ts_ui` | FALTA: hook React con pagination, dedupe, optimistic UI |
|
||||
| Markdown render (TS) | reuse existing `markdown_render_ts_ui` si existe, sino crear | check |
|
||||
| HTTP client (Go) | `http_json_client_go_infra` | OK (reusar) |
|
||||
| SQLite open (Go) | `sqlite_open_go_infra` | OK (reusar) |
|
||||
| HTTP server SSE | `http_sse_server_go_infra` | OK (reusar) |
|
||||
| Notify (impure) | `notify_desktop_go_infra` | FALTA: Win/Linux/mac notifications nativas |
|
||||
|
||||
## Apps tocadas
|
||||
|
||||
- `projects/element_agents/apps/matrix_client_pc` (nueva — Wails + React).
|
||||
- `projects/element_agents/apps/element_matrix_chat` (backend ya activo; quiza anadir sygnal container).
|
||||
- `projects/element_agents/apps/agents_and_robots` (consumidor — el cliente PC dialoga con agentes via rooms Matrix).
|
||||
- `projects/element_agents/apps/agents_dashboard` (referencia UI — algunos paneles se reusan).
|
||||
|
||||
## Projects relacionados
|
||||
|
||||
- `element_agents` (root project — agrupa todo).
|
||||
|
||||
## Vaults / storage
|
||||
|
||||
- Local del PC: `~/.matrix_client_pc/store.db` (sync state + crypto store SQLite).
|
||||
- Cache media: `~/.matrix_client_pc/media/`.
|
||||
|
||||
## Capability groups consultados
|
||||
|
||||
- `matrix-client` (a crear: documenta wrappers `mautrix-go`).
|
||||
- `livekit-calls` (a crear: token gen + room join + UI calls).
|
||||
- `e2ee` (a crear: bootstrap + verification + recovery).
|
||||
- `widgets` (a crear: Matrix Widget API v2 host + sandbox + permisos).
|
||||
|
||||
## Flow
|
||||
|
||||
Pasos numerados. Cada paso = issue propio (ver `related_issues`).
|
||||
|
||||
1. **0147 — Scaffold Wails + login MAS.** Crear app `matrix_client_pc/` con Wails init, conectar a Synapse via MAS OIDC, mostrar perfil del usuario logueado. Persistencia tokens en `pass` o keychain del SO.
|
||||
2. **0148 — Rooms list + timeline.** Sidebar con rooms (DMs + spaces + grupos), panel central timeline con pagination scroll-up, dedupe, optimistic UI. Reusar layout `AppShell` Mantine.
|
||||
3. **0149 — Composer + interacciones.** Composer markdown, replies, edits, reactions, threads, upload media (imagenes, files, voice msg). Drag&drop. Slash commands placeholder.
|
||||
4. **0150 — E2EE.** `mautrix-go` con crypto store SQLite. Cross-signing setup, recovery passphrase, SAS verification de devices, key backup. UI para verificar otros usuarios.
|
||||
5. **0151 — Calls LiveKit.** Boton call en room -> token JWT desde Go backend -> join LiveKit room -> UI con tiles participantes, mute/cam/screen/hangup. 1:1 + grupales hasta 16 (limite actual del config).
|
||||
6. **0152 — Mini-webapps embebidas.** Implementar Matrix Widget API v2: iframe sandbox + postMessage handshake + permisos (capabilities `m.always_on_screen`, `org.matrix.msc2762.send.event`, etc.). Lanzar webapps desde slash command `/widget <url>` o desde state event `m.widget`. Agentes pueden publicar widgets en su room (ej. dashboard de telemetria, formulario, kanban inline).
|
||||
7. **0153 — Agent integration.** Paneles especiales para rooms operados por agentes de `agents_and_robots`: timeline + panel lateral con estado del agente (uptime, cola de tasks, last_error). Reusar SSE del `agents_dashboard`.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] App Wails compila y arranca en Win+Linux con binario standalone.
|
||||
- [ ] Login MAS OIDC completo, token persistido entre arranques.
|
||||
- [ ] Sync incremental con Synapse funciona; reconexion automatica tras red caida.
|
||||
- [ ] E2EE: enviar/recibir mensajes cifrados con otro cliente (Element Web o Android).
|
||||
- [ ] Call 1:1 con video+audio funcional via LiveKit.
|
||||
- [ ] Widget de prueba (HTML estatico servido por `agents_and_robots`) se carga en iframe sandbox y postMessage handshake completa.
|
||||
|
||||
## Definition of Done
|
||||
|
||||
### Mecanica (pre-requisito)
|
||||
|
||||
- `go build -tags wails` verde para Win + Linux.
|
||||
- `pnpm build` frontend verde.
|
||||
- `fn doctor cpp-apps` no aplica; `fn doctor services` confirma backend Matrix sano.
|
||||
- `app.md` con `uses_functions` declarando todas las dependencias del registry.
|
||||
|
||||
### Cobertura de comportamiento
|
||||
|
||||
| Escenario | Tipo | Comando / evidencia | Resultado esperado |
|
||||
|---|---|---|---|
|
||||
| Golden: login + recibir mensaje E2EE | e2e | `e2e/test_login_and_receive.sh` | mensaje aparece en timeline en <2s, descifrado OK |
|
||||
| Edge: red cae 30s, vuelve | e2e | `e2e/test_reconnect.sh` | sync se reanuda sin perder mensajes |
|
||||
| Edge: 2000 mensajes en 1 room | e2e | `e2e/test_perf_timeline.sh` | scroll a 60fps, memoria <500MB |
|
||||
| Edge: device nuevo no verificado envia msg | e2e | `e2e/test_unverified_device.sh` | warning visible en UI, msg cifra a este device solo si user confirma |
|
||||
| Error: token MAS expira | e2e | `e2e/test_token_refresh.sh` | refresh automatico, sin logout visible |
|
||||
| Error: LiveKit SFU caido | e2e | `e2e/test_livekit_down.sh` | error claro en UI, no crash de la app |
|
||||
|
||||
### Vida util validada (>=7 dias uso real)
|
||||
|
||||
| Metrica | Umbral | Donde se observa | Ventana |
|
||||
|---|---|---|---|
|
||||
| Crashes proceso PC | `0` | `journalctl --user -u matrix_client_pc` (Linux) / Event Viewer (Win) | 7 dias |
|
||||
| Latencia send msg | `p95 < 500ms` | panel propio de la app + `call_monitor` | 7 dias |
|
||||
| Calls fallidas | `< 5%` | counter en app + logs LiveKit | 7 dias |
|
||||
| Uso real diario | `>= 4 dias/semana` | `last_active_at` en store local | 7 dias |
|
||||
| Onboarding nuevo usuario | `< 5min hasta primer msg E2EE` | screencast operador | 1 sesion |
|
||||
|
||||
### Anti-criterios
|
||||
|
||||
- NO marcar done si E2EE se silent-falla (mensajes no se descifran y la UI no lo dice).
|
||||
- NO marcar done si la app solo funciona en `home-wsl` y peta en `aurgi-pc`.
|
||||
- NO marcar done si widget host carga `javascript:` URLs (XSS).
|
||||
- NO marcar done si calls grupales >3 participantes lagean con audio cortado.
|
||||
|
||||
## Notas
|
||||
|
||||
**Onboarding rapido:**
|
||||
1. `cd projects/element_agents/apps/matrix_client_pc`
|
||||
2. `wails dev` para desarrollo con hot-reload.
|
||||
3. `wails build -platform linux/amd64,windows/amd64` para release.
|
||||
4. Tokens MAS guardados via `keyring` (Go bindings al keychain del SO).
|
||||
5. Para probar E2EE: crear segundo usuario en Synapse Admin, abrir Element Web como segundo cliente, intercambiar verifications.
|
||||
|
||||
**Camino futuro (post-DoD):**
|
||||
- Push notifs nativas via `sygnal` + APNs/FCM-equivalent desktop (Win Action Center, Linux notify-send).
|
||||
- Mini-webapp catalog: registry de widgets internos (`projects/element_agents/widgets/`) publicables a rooms con un comando.
|
||||
- Threads UI mejorado (vs Element que es plano).
|
||||
- Integracion `agents_and_robots`: panel embebido que muestra logs del agente del room actual.
|
||||
- Cuando flow 0009 (mesh wireguard) este vivo: este cliente PC habla con `device_agent` de cada PC del mesh via su room Matrix.
|
||||
|
||||
**Decisiones clave (justificacion en hilo Claude 2026-05-24):**
|
||||
- Wails > Tauri: Go es stack principal del registry, reusa funciones existentes, `mautrix-go` es el SDK Matrix mas maduro en Go.
|
||||
- React+Vite+Mantine+`@fn_library`: defaults del proyecto, ver `frontend_theming.md`.
|
||||
- 2 codebases (PC Wails + Android Kotlin nativo): tradeoff aceptado por calidad nativa Android + reuso Go en PC. Contrato compartido en `docs/client_contract.md` (TBD).
|
||||
|
||||
## Capability growth log
|
||||
|
||||
- v0.1.0 (2026-05-24) — baseline (flow creado).
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: matrix-client-android
|
||||
id: 0011
|
||||
status: pending
|
||||
created: 2026-05-24
|
||||
updated: 2026-05-24
|
||||
priority: high
|
||||
risk: medium
|
||||
related_issues: [0154, 0155, 0156, 0157, 0158, 0159, 0160, 0161, 0162, 0163]
|
||||
related_flows: [0009, 0010]
|
||||
apps: [matrix_client_android]
|
||||
projects: [element_agents]
|
||||
vaults: []
|
||||
capability_groups: [matrix-client, livekit-calls, e2ee, widgets, android-native]
|
||||
trigger: manual
|
||||
schedule: ""
|
||||
expected_runtime_s: 0
|
||||
tags: [matrix, element, android, kotlin, compose, livekit, e2ee, widgets, agents, fcm, push]
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Cliente Matrix Android nativo (Kotlin + Jetpack Compose) que comparte contrato con el cliente PC (flow 0010) pero usa SDKs nativos para calidad superior: `matrix-rust-sdk` Kotlin bindings (E2EE rust, mejor), `livekit-android` (codecs HW, audio focus, AEC), FCM push directo via `sygnal`, foreground service para calls en background. Replica capacidades de Element Android + abre mini-webapps embebidas (Matrix Widget API v2 dentro de WebView) gestionadas por agentes del project `element_agents`.
|
||||
|
||||
## Pre-requisitos
|
||||
|
||||
- Stack Synapse + MAS + LiveKit ya activo en `organic-machine.com` (flow 0010 compartido).
|
||||
- Container `sygnal` corriendo en VPS (anadir si no existe — issue 0159 lo cubre).
|
||||
- Firebase project con FCM activado + service account JSON. Hosting gratuito.
|
||||
- Android Studio Iguana+, NDK r26+, Kotlin 1.9+.
|
||||
- `init_kotlin_app_bash_pipelines` (ya existe, ver issues 0073/0074/0075/0078 completados) para scaffold inicial.
|
||||
- Device fisico o emulator Android 9+ (API 28+) para test.
|
||||
- Capability del usuario operador: instalar APK debug + microphone/camera/notification grants.
|
||||
|
||||
## Funciones del registry recomendadas
|
||||
|
||||
| Rol | Funcion candidata | Estado |
|
||||
|---|---|---|
|
||||
| Kotlin app scaffold | `init_kotlin_app_bash_pipelines` | OK (reusar) |
|
||||
| Matrix rust-sdk wrapper (Kotlin) | `matrix_client_kotlin_infra` | FALTA: facade sobre `matrix-rust-sdk` Kotlin bindings |
|
||||
| LiveKit Android wrapper | `livekit_call_kotlin_infra` | FALTA: wrapper `io.livekit:livekit-android` |
|
||||
| FCM token register | `fcm_register_kotlin_infra` | FALTA: registrar device en sygnal via Synapse pusher API |
|
||||
| Sygnal pusher add | `sygnal_pusher_add_go_infra` | FALTA: Go helper para configurar push gateway |
|
||||
| Compose Room list | `RoomListScreen_kotlin_ui` | FALTA |
|
||||
| Compose Timeline | `TimelineScreen_kotlin_ui` | FALTA |
|
||||
| Compose Composer | `Composer_kotlin_ui` | FALTA |
|
||||
| Compose CallScreen | `CallScreen_kotlin_ui` | FALTA |
|
||||
| Compose WidgetHost | `WidgetHost_kotlin_ui` | FALTA: WebView + JS bridge Widget API |
|
||||
| Foreground service call | `CallForegroundService_kotlin_infra` | FALTA |
|
||||
| ICE permissions helper | `permissions_request_kotlin_core` | FALTA: mic/cam/notif/foreground service grants |
|
||||
| Local DB Room | reusar `androidx.room` directo | OK |
|
||||
|
||||
## Apps tocadas
|
||||
|
||||
- `projects/element_agents/apps/matrix_client_android` (nueva — Kotlin+Compose).
|
||||
- `projects/element_agents/apps/element_matrix_chat` (anadir sygnal container — issue 0159).
|
||||
- `projects/element_agents/apps/agents_and_robots` (consumidor agent panels).
|
||||
|
||||
## Projects relacionados
|
||||
|
||||
- `element_agents`.
|
||||
|
||||
## Vaults / storage
|
||||
|
||||
- Local Android: `/data/data/com.fnregistry.matrix_client_android/databases/` (room DB encriptada via SQLCipher).
|
||||
- Crypto store de matrix-rust-sdk: gestionado por el SDK en `files/matrix/<userId>/`.
|
||||
|
||||
## Capability groups consultados
|
||||
|
||||
- `matrix-client` (compartido con flow 0010).
|
||||
- `livekit-calls` (compartido).
|
||||
- `e2ee` (compartido).
|
||||
- `widgets` (compartido — contrato Widget API igual).
|
||||
- `android-native` (a crear: foreground service, FCM, MediaSession para calls).
|
||||
|
||||
## Flow
|
||||
|
||||
1. **0154 — Scaffold Kotlin + Compose + login MAS.** App `matrix_client_android/` con `init_kotlin_app`, Material 3 + tema propio acorde a `frontend_theming.md` (paleta equivalente). Login MAS OIDC via Chrome Custom Tabs. Tokens persistidos en EncryptedSharedPreferences.
|
||||
2. **0155 — Rooms list + Timeline.** Compose UI con `LazyColumn` virtualizado, sync via `matrix-rust-sdk` (corrutinas). Pagination, optimistic UI, swipe-to-react.
|
||||
3. **0156 — Composer.** Markdown, replies, edits, reactions, media (camara + galeria + voice msg con `MediaRecorder` opus).
|
||||
4. **0157 — E2EE rust-sdk.** Cross-signing setup, SAS verification (emoji), recovery passphrase, key backup. UI dialog verificacion.
|
||||
5. **0158 — Calls LiveKit Android nativo.** `livekit-android` SDK con codecs HW (H.264/VP9 hardware decoder), audio focus, echo cancellation, noise suppression. PiP mode Android nativo.
|
||||
6. **0159 — Push FCM via sygnal.** Anadir container `sygnal` al stack `element_matrix_chat`. Registrar FCM token via Synapse Pusher API. Handle push payload -> open room / wake up para incoming call.
|
||||
7. **0160 — Mini-webapps en WebView.** `WebView` con `WebViewClient` + JS bridge implementando Matrix Widget API v2. Sandbox via `setAllowFileAccess(false)`, `setAllowContentAccess(false)`, CSP estricta. Mismo contrato widgets que cliente PC.
|
||||
8. **0161 — Foreground service para calls + lifecycle.** `CallForegroundService` con notification ongoing, audio routing (speaker/earpiece/bluetooth), MediaSession para controls en lockscreen, wakelock controlado.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] APK debug instala + arranca en Android 9+ (API 28).
|
||||
- [ ] Login MAS via Chrome Custom Tabs, token persistido en EncryptedSharedPreferences.
|
||||
- [ ] Sync incremental funciona; reconexion automatica tras avion mode toggle.
|
||||
- [ ] E2EE: mensaje enviado desde PC (Wails) se descifra en Android (y al reves).
|
||||
- [ ] Call 1:1 con video+audio nativos, calidad superior a WebView.
|
||||
- [ ] Push FCM despierta app para incoming msg / call.
|
||||
- [ ] Widget de prueba se carga en WebView sandbox con bridge funcional.
|
||||
- [ ] Foreground service mantiene call viva con app en background + pantalla bloqueada.
|
||||
|
||||
## Definition of Done
|
||||
|
||||
### Mecanica (pre-requisito)
|
||||
|
||||
- `./gradlew assembleDebug` verde.
|
||||
- `./gradlew test` verde.
|
||||
- `./gradlew connectedAndroidTest` verde en emulator API 31+ (instrumented).
|
||||
- `app.md` con `uses_functions` declarando dependencias del registry.
|
||||
|
||||
### Cobertura de comportamiento
|
||||
|
||||
| Escenario | Tipo | Comando / evidencia | Resultado esperado |
|
||||
|---|---|---|---|
|
||||
| Golden: login + E2EE msg | instrumented | `./gradlew connectedAndroidTest --tests *LoginE2EE*` | msg descifrado en <2s, shield green |
|
||||
| Edge: avion mode 30s | instrumented | `./gradlew connectedAndroidTest --tests *Reconnect*` | sync resume, sin perder msgs |
|
||||
| Edge: 1000 msgs en room | benchmark | `./gradlew :app:benchmark` | scroll a 60fps, RAM <300MB |
|
||||
| Edge: incoming call, pantalla apagada | manual + screencast | apagar pantalla + recibir call desde PC | notif full-screen + ring, accept funciona |
|
||||
| Error: FCM token rotation | instrumented | `./gradlew connectedAndroidTest --tests *FCMRotation*` | re-register automatico en sygnal |
|
||||
| Error: WebView widget malicioso | instrumented | `./gradlew connectedAndroidTest --tests *WidgetSandbox*` | bloqueado, no escape |
|
||||
| Battery: call 30min | manual + dumpsys batterystats | call 30min | drain <15%, sin OOM |
|
||||
|
||||
### Vida util validada (>=7 dias uso real)
|
||||
|
||||
| Metrica | Umbral | Donde se observa | Ventana |
|
||||
|---|---|---|---|
|
||||
| Crashes (ANRs/forced close) | `0` | `adb logcat -e FATAL` + Play Console (si publicado) | 7 dias |
|
||||
| Push latency (msg enviado -> notif visible) | `p95 < 3s` | log custom en app + sygnal | 7 dias |
|
||||
| Call drops in-pocket (lockscreen) | `< 5%` | counter app | 7 dias |
|
||||
| Battery drain idle | `< 2%/h` | dumpsys batterystats | 7 dias |
|
||||
| Uso real diario | `>= 5 dias/semana` | last_active en local DB | 7 dias |
|
||||
|
||||
### Anti-criterios
|
||||
|
||||
- NO marcar done si E2EE silent-falla.
|
||||
- NO marcar done si call con pantalla bloqueada se corta a los <5min (battery optimization mata el service).
|
||||
- NO marcar done si WebView de widget permite acceso a `file://` o cookies del browser host.
|
||||
- NO marcar done si la app solo funciona en el device del operador y peta en Android < 11.
|
||||
- NO marcar done sin probar en Android 9 (legacy, muchos dispositivos antiguos siguen vivos).
|
||||
|
||||
## Notas
|
||||
|
||||
**Onboarding rapido:**
|
||||
1. `cd projects/element_agents/apps/matrix_client_android`
|
||||
2. `./gradlew assembleDebug && adb install -r app/build/outputs/apk/debug/app-debug.apk`
|
||||
3. Para hot-reload UI: `./gradlew :app:installDebug` + Android Studio Compose preview.
|
||||
4. Para test push: enviar msg desde Element Web a la cuenta del Android; debe llegar notif via FCM en <3s.
|
||||
|
||||
**Decisiones clave:**
|
||||
- `matrix-rust-sdk` Kotlin bindings > matrix-android-sdk2 (deprecated). Rust-sdk es el futuro oficial de matrix.org.
|
||||
- `livekit-android` nativo > WebRTC.org directo. SDK oficial mantiene mejor performance + features.
|
||||
- Jetpack Compose > XML views. Encaja mejor con reactive model + menos boilerplate.
|
||||
- EncryptedSharedPreferences para tokens MAS. NO usar SharedPreferences plain.
|
||||
- Material 3 con tema propio (paleta similar a Mantine accent del cliente PC para coherencia visual).
|
||||
|
||||
**Camino futuro (post-DoD):**
|
||||
- Wear OS companion app (notifs + quick reply).
|
||||
- Android Auto integration (read msgs voice + reply voice).
|
||||
- Conversation shortcuts API (Android 11+) para que cada room aparezca en share sheet.
|
||||
- Bubble notifications (Android 11+) para conversaciones favoritas.
|
||||
|
||||
**Compartido con flow 0010:**
|
||||
- Contrato `m.widget` y Widget API v2 IDENTICO. Mismo widget html funciona en ambos.
|
||||
- Contrato `m.agent.metadata` para detectar rooms de agentes IDENTICO.
|
||||
- Cuando flow 0009 (mesh) este vivo, ambos clientes hablan a `device_agent` igual.
|
||||
|
||||
## Capability growth log
|
||||
|
||||
- v0.1.0 (2026-05-24) — baseline.
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
id: "0147"
|
||||
title: "matrix-client-pc scaffold: Wails + React+Mantine + login MAS"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010"]
|
||||
related_issues: ["0148", "0162"]
|
||||
dependencies: ["0162"]
|
||||
tags: [matrix, wails, react, mantine, mas, oidc, scaffold]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Crear el esqueleto de la app `projects/element_agents/apps/matrix_client_pc/` con Wails v2 (Go) + React+Vite+Mantine+`@fn_library` y dejar funcionando el login MAS OIDC contra `mas-...organic-machine.com`. Resultado: arrancar binario -> redirect navegador a MAS -> volver con token -> mostrar perfil del usuario.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. `wails init -n matrix_client_pc -t react-ts` dentro de `projects/element_agents/apps/`.
|
||||
2. Sub-repo Gitea: `git init -b master` + crear repo `dataforge/matrix_client_pc` + push inicial.
|
||||
3. `app.md` con frontmatter (lang=go, framework=wails, tags incluyen `matrix` + `service`? — NO, es app cliente, sin tag service).
|
||||
4. `go.mod` con deps: `wails/v2`, `mautrix-go`, `keyring`.
|
||||
5. Reemplazar template frontend por React+Mantine+`@fn_library`. Symlink `frontend/src/fn_library` -> `../../../../../frontend/functions/ui/` (o copia si symlink no funciona en build).
|
||||
6. Backend Go (`backend/`):
|
||||
- `wails.json` con `bindings` para `MatrixService`.
|
||||
- `MatrixService.Login() -> URL` (devuelve URL MAS OIDC).
|
||||
- `MatrixService.HandleCallback(code) -> User`.
|
||||
- `MatrixService.GetSession() -> *Session` (lee de keyring).
|
||||
- `MatrixService.Logout()`.
|
||||
7. Frontend React: layout `AppShell` Mantine, pagina `Login.tsx` con boton "Sign in with Matrix" -> abre URL MAS en navegador del SO.
|
||||
8. Persistencia tokens en keyring SO (`github.com/zalando/go-keyring`).
|
||||
9. Loopback HTTP local (`127.0.0.1:0`, puerto libre aleatorio) para recibir callback OIDC.
|
||||
10. Test e2e basico: arrancar app, login con `@dev-pc:matrix-af2f3d.organic-machine.com`, ver perfil.
|
||||
|
||||
## Funciones del registry a crear (delegar a fn-constructor)
|
||||
|
||||
- `matrix_client_init_go_infra` — `mautrix.NewClient(homeserver, userID, accessToken) -> *Client, error`. Wrapper que configura SQLite store + crypto store.
|
||||
- `mas_oidc_flow_go_infra` — `StartFlow(masURL) -> authURL, codeVerifier, state`. `ExchangeCode(code, codeVerifier) -> *Token`.
|
||||
- `keyring_save_token_go_infra` / `keyring_load_token_go_infra` — wrappers `go-keyring`.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Binario Wails compila para linux/amd64 + windows/amd64.
|
||||
- [ ] `wails dev` arranca con hot-reload.
|
||||
- [ ] Login MAS OIDC end-to-end: boton -> navegador -> consent -> callback -> perfil visible.
|
||||
- [ ] Token persistido entre re-arranques (no re-login si token vigente).
|
||||
- [ ] `app.md` con `uses_functions` que apunta a las 3 funciones nuevas.
|
||||
- [ ] Sub-repo `dataforge/matrix_client_pc` creado con commit inicial.
|
||||
|
||||
## Notas
|
||||
|
||||
- MAS URL: leerla de `.well-known/matrix/client` del homeserver para no hardcodear.
|
||||
- Refresh token: MAS usa OAuth 2.0 estandar — implementar refresh proactivo (~5min antes de expiry).
|
||||
- Gotcha: en Windows, `wails dev` requiere WebView2 instalado.
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
id: "0148"
|
||||
title: "matrix-client-pc rooms list + timeline con sync incremental"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010"]
|
||||
related_issues: ["0147", "0149"]
|
||||
dependencies: ["0147"]
|
||||
tags: [matrix, sync, timeline, rooms, react, mantine, sse]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Sidebar con rooms (DMs + spaces + grupos) + panel central con timeline del room activo. Sync incremental con Synapse via long-poll `/sync`. Stream eventos backend -> frontend via SSE (`http_sse_server_go_infra`). Pagination scroll-up (cargar mensajes anteriores). Optimistic UI al enviar.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend Go:
|
||||
- `MatrixService.StartSync()` — long-poll `/sync` con since token persistido.
|
||||
- `MatrixService.SubscribeEvents() -> chan Event` — broadcaster events a frontend.
|
||||
- SSE endpoint `http://127.0.0.1:<puerto>/events` (autenticado con cookie session local).
|
||||
- Persistir state en SQLite (`store.db`): rooms, members, last_event_id por room.
|
||||
2. Frontend React:
|
||||
- Hook `useMatrixRooms()` — devuelve `Room[]` ordenadas por last_activity.
|
||||
- Hook `useMatrixTimeline(roomId, limit=50)` — devuelve eventos + `loadMore()`.
|
||||
- Componente `RoomList` (sidebar con avatar, nombre, last_msg preview, unread badge).
|
||||
- Componente `Timeline` con `react-virtuoso` para scroll perf con miles de msgs.
|
||||
- Componente `EventBubble` (text, image, file, redacted, reaction agregada).
|
||||
- Reconnect automatico si SSE/sync cae (exponential backoff).
|
||||
3. Tests:
|
||||
- `e2e/test_sync_basic.sh` — login + verificar que 3 rooms aparecen en sidebar.
|
||||
- `e2e/test_pagination.sh` — scroll-up carga mensajes anteriores sin gap.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_room_subscribe_go_infra` — SSE wrapper: subscribe events de Synapse y push a clientes.
|
||||
- `useMatrixTimeline_ts_ui` — hook React con dedupe + pagination + optimistic.
|
||||
- `useMatrixRooms_ts_ui` — hook React rooms list.
|
||||
- `RoomList_ts_ui` — componente sidebar Mantine.
|
||||
- `EventBubble_ts_ui` — componente burbuja msg.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Sidebar lista rooms del usuario test, ordenados por actividad.
|
||||
- [ ] Click en room muestra timeline ultimos 50 msgs.
|
||||
- [ ] Scroll arriba carga msgs anteriores sin duplicar.
|
||||
- [ ] Mensaje enviado desde Element Web aparece en <2s en la timeline.
|
||||
- [ ] Cerrar app + abrir: state restaurado desde SQLite, no re-sync completo.
|
||||
- [ ] Network kill + restore: sync se reanuda sin perder mensajes.
|
||||
|
||||
## Notas
|
||||
|
||||
- DMs vs rooms grupales: detectar via `m.direct` account data.
|
||||
- Spaces (`m.space`): mostrar como grupos colapsables en sidebar.
|
||||
- Edits + redactions: aplicar in-place, no duplicar bubble.
|
||||
- Read receipts: TBD en otro issue, no bloquea este.
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
id: "0149"
|
||||
title: "matrix-client-pc composer: markdown, reply, edit, reactions, media"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010"]
|
||||
related_issues: ["0148", "0150"]
|
||||
dependencies: ["0148"]
|
||||
tags: [matrix, composer, markdown, media, reactions, threads]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Composer del room: markdown rendering, replies con quote, edits, reactions emoji, threads (Matrix MSC3440), upload de media (imagenes, files, voice msg). Drag&drop archivos. Slash commands placeholder (`/me`, `/shrug`, `/widget` — este ultimo para issue 0152).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend Go:
|
||||
- `MatrixService.SendMessage(roomID, body, format)` — text + markdown -> HTML via `goldmark`.
|
||||
- `MatrixService.SendReply(roomID, parentEventID, body)`.
|
||||
- `MatrixService.EditMessage(roomID, eventID, newBody)`.
|
||||
- `MatrixService.SendReaction(roomID, eventID, key)`.
|
||||
- `MatrixService.UploadMedia(roomID, filePath) -> mxc://`.
|
||||
- `MatrixService.SendThreadReply(roomID, threadRootID, body)`.
|
||||
2. Frontend React:
|
||||
- Componente `Composer` con Mantine `Textarea` + toolbar markdown.
|
||||
- Hotkeys: Cmd+B/I/K, Cmd+Enter para enviar, Esc cancel edit.
|
||||
- Drag&drop zone over Composer + paste image desde clipboard.
|
||||
- `EmojiPicker` (reusar `@emoji-mart/react` o componente propio `@fn_library`).
|
||||
- `ReactionBar` debajo de EventBubble con aggregates.
|
||||
- Thread panel lateral (abrir click en evento "X replies").
|
||||
- Voice messages: graba con `MediaRecorder` (opus codec), upload + send con `org.matrix.msc3245.voice` flag.
|
||||
3. Tests:
|
||||
- `e2e/test_send_markdown.sh` — `**bold**` aparece negrita en otro cliente.
|
||||
- `e2e/test_edit_message.sh` — edicion aparece in-place en Element Web.
|
||||
- `e2e/test_reaction.sh` — reaccion emoji propagada bidireccional.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `markdown_to_matrix_html_go_core` — `goldmark` con sanitizer Matrix-compatible.
|
||||
- `Composer_ts_ui` — componente Mantine + dropzone.
|
||||
- `EmojiPicker_ts_ui` — wrapper picker emoji.
|
||||
- `ReactionBar_ts_ui` — componente reactions aggregadas.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Mensaje markdown `**negrita** _cursiva_` se ve formateado en Element Web.
|
||||
- [ ] Reply quote aparece referenciando el msg padre.
|
||||
- [ ] Edit cambia el msg in-place en ambos clientes.
|
||||
- [ ] Reaccion emoji con click aparece como counter agregado.
|
||||
- [ ] Upload imagen (PNG 2MB) se ve thumbnail + click abre full.
|
||||
- [ ] Voice msg grabado 5s reproduce OK en Element Web.
|
||||
- [ ] Thread: 5 replies anidados se muestran en panel lateral.
|
||||
|
||||
## Notas
|
||||
|
||||
- Sanitizer HTML: usar allowlist Matrix (b, i, em, strong, a[href], code, pre, blockquote, ul, ol, li, br, p, h1-h6). NO permitir `<script>`, `<iframe>`, event handlers.
|
||||
- mxc:// uploads: validar size limit (Synapse default 50MB).
|
||||
- Voice msg: encode opus 32kbps, max 5min.
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: "0150"
|
||||
title: "matrix-client-pc E2EE: cross-signing, SAS verification, recovery"
|
||||
status: pending
|
||||
priority: critical
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010"]
|
||||
related_issues: ["0149", "0151"]
|
||||
dependencies: ["0149"]
|
||||
tags: [matrix, e2ee, olm, megolm, cross-signing, recovery, security]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Encriptacion end-to-end con `mautrix-go` (Olm/Megolm). Cross-signing keys (master/self-signing/user-signing), SAS verification de devices (emoji + decimal), recovery passphrase + key backup en Synapse, manejo de devices no verificados con warning visible. Mensajes en rooms encriptados se envian y descifran correctamente.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend Go:
|
||||
- `MatrixService.BootstrapCrossSigning(passphrase)` — genera master/self/user keys, sube a Synapse cifradas con passphrase-derived key.
|
||||
- `MatrixService.RecoverFromPassphrase(passphrase)` — descarga keys de Synapse y descifra.
|
||||
- `MatrixService.StartVerification(userID, deviceID) -> *VerificationSession`.
|
||||
- `MatrixService.VerifyEmoji(sessionID, accepted bool)`.
|
||||
- `MatrixService.ListDevices() -> []Device` (con verified flag).
|
||||
- `MatrixService.BackupMegolmKeys()` — key backup server-side.
|
||||
- Crypto store SQLite separado del state store (mejor para integridad).
|
||||
2. Frontend React:
|
||||
- Wizard onboarding E2EE: pasos (1) generar passphrase, (2) backup, (3) verificar device.
|
||||
- Panel `Settings > Security & Privacy`:
|
||||
- Lista devices propios con verified state.
|
||||
- Boton "Verify new device" + dialog SAS con emoji grid.
|
||||
- "Reset cross-signing" (destructive, requiere confirmacion).
|
||||
- "Restore from passphrase" (login en device nuevo).
|
||||
- `EventBubble` muestra shield: green (verified), amber (encrypted, device unverified), red (decryption failed).
|
||||
- Banner room: "X devices are not verified" si algun miembro tiene devices unverified.
|
||||
3. Tests:
|
||||
- `e2e/test_e2ee_send_receive.sh` — msg enviado en room encriptado se descifra en Element Web.
|
||||
- `e2e/test_cross_signing.sh` — bootstrap + verificar device desde Element Web.
|
||||
- `e2e/test_recovery.sh` — login en device nuevo + recover keys con passphrase.
|
||||
- `e2e/test_unverified_warning.sh` — device nuevo aparece como warning en otros clientes.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_e2ee_bootstrap_go_infra` — wrapper cross-signing bootstrap.
|
||||
- `matrix_device_verify_go_infra` — SAS verification flow.
|
||||
- `matrix_key_backup_go_infra` — server-side key backup wrapper.
|
||||
- `passphrase_derive_key_go_infra` — PBKDF2/scrypt para derivar key de passphrase.
|
||||
- `VerificationDialog_ts_ui` — componente emoji grid SAS.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Bootstrap cross-signing crea 3 keys + las sube a Synapse cifradas.
|
||||
- [ ] Msg enviado a room encriptado se descifra en Element Web (y al reves).
|
||||
- [ ] SAS verification con emoji grid funciona contra Element Web (ambos lados muestran 7 emojis iguales).
|
||||
- [ ] Login en device nuevo + restore con passphrase recupera msgs historicos.
|
||||
- [ ] Device no verificado dispara shield amber en EventBubble.
|
||||
- [ ] Decryption failure (key no disponible) muestra shield rojo + boton "Request key".
|
||||
|
||||
## Notas
|
||||
|
||||
**Critico — anti-criterio:**
|
||||
- NO marcar done si E2EE silent-falla (msg muestra "** Unable to decrypt **" sin shield rojo claro).
|
||||
- NO marcar done si recovery passphrase queda en plain text en disco (debe vivir solo en keyring/memoria).
|
||||
|
||||
**Decisiones:**
|
||||
- Olm/Megolm via `mautrix-go/crypto` (Go port estable de libolm).
|
||||
- Alternativa rust-crypto via CGo: descartada, mantiene complejidad build.
|
||||
- Passphrase format: 4 palabras Diceware o 12-byte base32. Usuario elige al bootstrap.
|
||||
|
||||
**Gotchas:**
|
||||
- Key rotation: rooms encriptados rotan megolm cada 1 semana o 100 msgs (default). Manejar refresh.
|
||||
- Olm sessions max 100 mensajes: rotar prekey bundles automaticamente.
|
||||
- Cuando arrancas device nuevo sin passphrase, los msgs pre-existentes NO se descifran — UI debe ser clara.
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: "0151"
|
||||
title: "matrix-client-pc calls LiveKit: 1:1 + grupales, mic/cam/screen"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010"]
|
||||
related_issues: ["0150", "0152"]
|
||||
dependencies: ["0150"]
|
||||
tags: [matrix, livekit, calls, webrtc, video, audio, screen-share]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Llamadas via LiveKit SFU (ya activo en `organic-machine.com:7880-7882`). Backend Go genera JWT con `livekit-server-sdk-go`. Frontend React usa `livekit-client` JS para join room, manejar tracks (mic/cam/screen), UI con tiles participantes, controles. Soporta 1:1 + grupales hasta 16 (limite config actual).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend Go:
|
||||
- `MatrixService.RequestCallToken(matrixRoomID) -> (token, livekitRoomURL)`.
|
||||
- Mapea Matrix roomID -> LiveKit room name (hash determinista).
|
||||
- Genera JWT con claim `room`, `identity` (matrix userID), `ttl 30min`.
|
||||
- Permisos: `canPublish=true, canSubscribe=true, canPublishData=true`.
|
||||
- Publicar event Matrix `m.call.member` para sincronizar quien esta en call (MSC3401).
|
||||
2. Frontend React:
|
||||
- Hook `useLiveKitCall(matrixRoomID)`:
|
||||
- Pide token al backend.
|
||||
- Conecta `Room` de `livekit-client`.
|
||||
- Expone participants, tracks, localTracks, state.
|
||||
- Auto-publish microfono on connect (mute default).
|
||||
- Componente `CallPanel`:
|
||||
- Grid tiles participantes (1, 2, 4, 9, 16 layout).
|
||||
- Tile principal con speaker activo (active-speaker detection del SDK).
|
||||
- Controles bottom: mic, cam, screen share, raise hand, leave.
|
||||
- PiP mode: cuando minimizado, tile flotante en esquina.
|
||||
- Boton "Start call" en header del room (icono telefono).
|
||||
- Boton "Join call" si hay call activa (segun `m.call.member` events).
|
||||
- Notifs ring incoming call: audio + desktop notif.
|
||||
3. Backend ICE/TURN:
|
||||
- Verificar LiveKit config tiene TURN configurado (NAT traversal). Si no, anadir coturn container.
|
||||
4. Tests:
|
||||
- `e2e/test_call_1to1.sh` — 2 clientes (Wails + Element Web), 30s call, audio+video flow.
|
||||
- `e2e/test_call_screen_share.sh` — compartir pantalla, otro cliente ve el track.
|
||||
- `e2e/test_call_4_participants.sh` — 4 clientes simultaneos, no crash.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `livekit_token_gen_go_infra` — JWT generator con `livekit-server-sdk-go`.
|
||||
- `matrix_call_member_go_infra` — wrapper para publicar/leer `m.call.member` state events.
|
||||
- `useLiveKitCall_ts_ui` — hook React.
|
||||
- `CallPanel_ts_ui` — componente UI completo de call.
|
||||
- `CallTile_ts_ui` — tile individual con video + nombre + speaker indicator.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Boton "Start call" en room DM con otro user.
|
||||
- [ ] Otro cliente (Element Web) ve ring + acepta -> 2 tiles con video+audio.
|
||||
- [ ] Mute mic + apagar cam funciona y se refleja en el otro lado.
|
||||
- [ ] Screen share: tile separado aparece para todos los participantes.
|
||||
- [ ] 4 participantes simultaneos sin crash ni audio cortado.
|
||||
- [ ] Hangup limpia recursos (no tracks fantasma, no peer connections abiertas).
|
||||
|
||||
## Notas
|
||||
|
||||
- LiveKit room name: `sha256(matrix_room_id + secret)` truncado a 32 chars. Asi cualquier cliente que conozca el matrix_room_id puede computar el room name (no es secret).
|
||||
- Token TTL 30min, refresh proactivo a los 25min.
|
||||
- Codecs: H.264 + VP8 fallback para compatibilidad navegadores. Audio: Opus 32kbps.
|
||||
- E2EE en calls: LiveKit soporta E2EE simetrico (insertable streams API). TBD para version posterior — flow inicial usa SRTP only (cifrado SFU<->client, no e2e).
|
||||
- Sygnal push para incoming calls: enviar VoIP push con TTL bajo para wake-up moviles (relevante para issue 0158 Android).
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
id: "0152"
|
||||
title: "matrix-client-pc mini-webapps embebidas: Matrix Widget API v2"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010"]
|
||||
related_issues: ["0151", "0153"]
|
||||
dependencies: ["0151"]
|
||||
tags: [matrix, widgets, webapps, iframe, sandbox, agents, postmessage]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Implementar host de widgets segun Matrix Widget API v2 (MSC2762, MSC2871, MSC2974). Cada room puede tener widgets activos publicados como state events `m.widget`. Los widgets son URLs cargadas en iframes sandboxed con bridge postMessage que da capabilities controladas (leer eventos del room, enviar eventos, mostrar UI overlay, etc.). Agentes de `agents_and_robots` pueden publicar widgets en sus rooms (ej. dashboard telemetria, formulario, kanban inline, panel de control del agente).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend Go:
|
||||
- `MatrixService.ListWidgets(roomID) -> []Widget` — lee state events `m.widget` del room.
|
||||
- `MatrixService.AddWidget(roomID, widget Widget)` — publica state event.
|
||||
- `MatrixService.RemoveWidget(roomID, widgetID)`.
|
||||
- `MatrixService.GenerateWidgetURL(widget Widget, userID) -> string` — substituye `$matrix_user_id`, `$matrix_room_id`, `$matrix_display_name`, `$matrix_avatar_url`, `$matrix_widget_id`, `$theme` en la URL del widget.
|
||||
- Slash command `/widget <url>` handler en composer (issue 0149) que crea state event con widget temporal.
|
||||
- `MatrixService.MintWidgetScopedToken(widgetID, userID) -> string` — token efimero con scope reducido (solo el room donde esta el widget).
|
||||
2. Frontend React:
|
||||
- Hook `useWidgets(roomID)` — lista widgets activos.
|
||||
- Componente `WidgetPanel`:
|
||||
- Tabs por widget activo + boton "+" para anadir.
|
||||
- Cada widget en iframe con `sandbox="allow-scripts allow-same-origin allow-forms allow-popups-to-escape-sandbox"`.
|
||||
- `iframe.referrerpolicy="no-referrer"`.
|
||||
- CSP: `frame-src https: data: blob:`.
|
||||
- `WidgetBridge` — clase JS que escucha `postMessage` del iframe e implementa Widget API v2:
|
||||
- `capabilities` handshake: el widget declara que necesita, el host pide consentimiento usuario (dialog Mantine).
|
||||
- `read_events`, `send_event`, `send_to_device`, `get_openid`, `m.always_on_screen`, etc.
|
||||
- Whitelist estricta de capabilities concedidas. Audit log de mensajes en `store.db`.
|
||||
- Layout: widgets se abren en panel lateral derecho (toggleable) o en modal fullscreen.
|
||||
3. Widgets internos primer batch (proof of concept):
|
||||
- `widget-jitsi-fallback` — si LiveKit falla, fallback a Jitsi via widget (URL config).
|
||||
- `widget-agent-panel` — panel de control de agente: estado, ultima ejecucion, restart, view logs. Servido por `agents_and_robots` HTTP API (issue 0113 ya creando agent runner API).
|
||||
- `widget-kanban` — kanban inline embebido para tasks del room. Reusa `apps/kanban` (Go) servido en LAN.
|
||||
- `widget-issue-tracker` — widget que abre issue API (`0109m`).
|
||||
4. Tests:
|
||||
- `e2e/test_widget_capabilities.sh` — widget pide capability, dialog aparece, deniega/acepta funciona.
|
||||
- `e2e/test_widget_send_event.sh` — widget con capability `send_event` envia msg al room.
|
||||
- `e2e/test_widget_sandbox.sh` — widget malicioso (intenta `top.location =`) es bloqueado por sandbox.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_widget_state_go_infra` — CRUD state events `m.widget`.
|
||||
- `widget_url_template_go_core` — substituye placeholders en URL.
|
||||
- `widget_token_mint_go_infra` — token scoped a un widget+room+user.
|
||||
- `WidgetBridge_ts_ui` — clase postMessage bridge Widget API v2 completa.
|
||||
- `WidgetPanel_ts_ui` — UI tabs + iframes + permisos.
|
||||
- `CapabilityConsentDialog_ts_ui` — dialog Mantine para consentimiento.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] `/widget https://my.app` crea state event y abre iframe.
|
||||
- [ ] Widget declara capability `m.send_event` -> dialog Mantine pide consentimiento.
|
||||
- [ ] Widget concedido envia msg al room que aparece en timeline.
|
||||
- [ ] Widget malicioso `<script>top.location='evil.com'</script>` bloqueado por sandbox.
|
||||
- [ ] `agents_and_robots` publica widget panel y se ve embebido en el room del agente.
|
||||
- [ ] Widget kanban inline funciona: drag&drop card persiste en DB del kanban.
|
||||
|
||||
## Notas
|
||||
|
||||
**Anti-criterios:**
|
||||
- NO permitir `javascript:` ni `data:text/html` URLs (XSS).
|
||||
- NO conceder capabilities sin consentimiento explicito del usuario (auditable).
|
||||
- NO compartir el access_token Matrix del usuario al widget — usar siempre tokens scoped efimeros.
|
||||
|
||||
**Decisiones:**
|
||||
- Widget API v2 (no v1) — soporta capabilities + tokens scoped.
|
||||
- iframe sandbox sin `allow-top-navigation` (previene escape).
|
||||
- CSP `frame-src https:` + permitir `data:`/`blob:` solo para widgets internos firmados.
|
||||
|
||||
**Roadmap post-DoD:**
|
||||
- Widget marketplace interno: `widget-catalog` en `agents_and_robots` con widgets internos descubribles.
|
||||
- Widget templates: un agente publica un widget HTML estatico subido al room (`mxc://`) y el cliente lo renderiza desde la URL `mxc -> http`.
|
||||
- Cross-room widgets: widget que persiste entre rooms (TBD, requiere MSC propio).
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
id: "0153"
|
||||
title: "matrix-client-pc agent integration: paneles para rooms operados por agentes"
|
||||
status: pending
|
||||
priority: medium
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010", "0009"]
|
||||
related_issues: ["0152"]
|
||||
dependencies: ["0152"]
|
||||
tags: [matrix, agents, agents_and_robots, dashboard, sse, device_agent]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Integracion nativa con `agents_and_robots` + `agents_dashboard` + futuro `device_agent` (flow 0009 mesh). Detectar que un room esta operado por un agente Matrix conocido (via state event custom `m.agent.metadata`) y mostrar panel lateral con info del agente: uptime, ultima ejecucion, cola de tasks, last_error, boton restart, view logs en vivo (SSE). Atajos: enviar slash commands del agente (`/agent restart`, `/agent skill <name>`).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend Go:
|
||||
- `MatrixService.GetAgentMetadata(roomID) -> *AgentMetadata` — lee state event `m.agent.metadata` que el agente publica al arrancar.
|
||||
- `MatrixService.SubscribeAgentLogs(agentID) -> chan LogLine` — SSE proxy al endpoint `agents_and_robots /api/agents/<id>/logs` ya existente (issue 0113).
|
||||
- Llamadas REST proxy a `agents_and_robots`: `RestartAgent(agentID)`, `ListSkills(agentID)`, `TriggerSkill(agentID, skill, args)`.
|
||||
2. Frontend React:
|
||||
- Hook `useAgentMetadata(roomID)` — devuelve `null` si no es room de agente.
|
||||
- Componente `AgentPanel` (panel lateral colapsable, solo visible si hay agentMetadata):
|
||||
- Card con avatar, nombre, version, uptime, status (running/stopped/error).
|
||||
- Tabs: "Logs" (live SSE), "Skills" (lista de skills disponibles + boton trigger), "Config" (read-only del config.yaml del agente).
|
||||
- Boton restart con confirmacion.
|
||||
- Componente `LogStream` — termtinal-like log viewer con auto-scroll + filtro grep.
|
||||
- Slash commands custom: `/agent restart`, `/agent skill <name> <args>`, `/agent logs`.
|
||||
3. Cuando flow 0009 (mesh) este vivo:
|
||||
- Detectar `device_agent` rooms (state event `m.device.metadata` con tipo `device_agent`).
|
||||
- Panel especifico `DevicePanel`: hostname, OS, kernel, IP mesh WG, capabilities firmadas, ultimo heartbeat.
|
||||
- Slash commands: `/device shell <cmd>` (si capability permite), `/device fs ls <path>`, `/device camera capture`.
|
||||
4. Tests:
|
||||
- `e2e/test_agent_panel_basic.sh` — entrar a room de `welcome-bot`, panel agente visible con info correcta.
|
||||
- `e2e/test_agent_logs_live.sh` — boton "view logs" stream logs en tiempo real (5s).
|
||||
- `e2e/test_agent_restart.sh` — restart desde panel + verificar agente vuelve online.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_agent_metadata_go_infra` — leer/publicar state event `m.agent.metadata`.
|
||||
- `agents_and_robots_client_go_infra` — wrapper REST + SSE del API de `agents_and_robots`.
|
||||
- `AgentPanel_ts_ui` — panel lateral Mantine con tabs.
|
||||
- `LogStream_ts_ui` — viewer logs SSE.
|
||||
- `DevicePanel_ts_ui` — panel device_agent (cuando flow 0009 vivo).
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Room operado por agente conocido muestra `AgentPanel` automatico.
|
||||
- [ ] Logs en vivo del agente aparecen en panel (SSE).
|
||||
- [ ] Restart desde panel funciona end-to-end.
|
||||
- [ ] Slash `/agent skill greet` ejecuta skill remota y respuesta llega como msg al room.
|
||||
- [ ] Room NO operado por agente: panel oculto (no clutter).
|
||||
|
||||
## Notas
|
||||
|
||||
- State event `m.agent.metadata` format: `{ agent_id, version, capabilities[], owner, repo_url }`. Documentar en `projects/element_agents/docs/agent_metadata.md`.
|
||||
- SSE proxy: el cliente PC habla a `agents_and_robots` via su DNS publica (`agents.organic-machine.com`) con auth Bearer (token del usuario Matrix + scope `agent_panel`).
|
||||
- Permisos: solo el `owner` declarado en el agente puede ejecutar restart/trigger. Otros users del room solo leen.
|
||||
- Gotcha: si el agente se rebuilds y cambia `agent_id`, el state event queda obsoleto — necesita TTL o heartbeat.
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: "0154"
|
||||
title: "matrix-client-android scaffold: Kotlin + Compose + login MAS"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0155", "0162"]
|
||||
dependencies: ["0162"]
|
||||
tags: [matrix, android, kotlin, compose, mas, oidc, scaffold]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Crear `projects/element_agents/apps/matrix_client_android/` con `init_kotlin_app` (pipeline ya existente del registry). Configurar Compose + Material 3 + tema propio. Implementar login MAS OIDC via Chrome Custom Tabs. Tokens persistidos en EncryptedSharedPreferences. Resultado: APK debug que abre Custom Tab al MAS, retorna con token y muestra perfil del usuario.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. `./fn run init_kotlin_app matrix_client_android` — usa pipeline existente del registry (ver issues completados 0073-0078).
|
||||
2. Sub-repo Gitea: `git init -b master` + crear `dataforge/matrix_client_android` + push inicial. **Antes** de salir del worktree (ver `apps_subrepo.md`).
|
||||
3. `app.md` con frontmatter:
|
||||
- `lang: kotlin`, `framework: jetpack-compose`, `dir_path: projects/element_agents/apps/matrix_client_android`.
|
||||
- `tags: [matrix, android, kotlin, compose]`.
|
||||
- `uses_functions: []` (irlo rellenando issue a issue).
|
||||
4. `build.gradle.kts`:
|
||||
- `compileSdk = 34`, `minSdk = 28`, `targetSdk = 34`.
|
||||
- Compose BOM `2024.x`.
|
||||
- `matrix-rust-sdk` Kotlin bindings (`org.matrix.rustcomponents:sdk-android:0.x`).
|
||||
- `androidx.security:security-crypto` para EncryptedSharedPreferences.
|
||||
- `androidx.browser:browser` para Chrome Custom Tabs.
|
||||
5. Login MAS:
|
||||
- `LoginActivity` con boton "Sign in with Matrix".
|
||||
- Generar PKCE code_verifier + state.
|
||||
- Abrir Chrome Custom Tab a `<mas_url>/oauth/authorize?...`.
|
||||
- `MainActivity` con intent-filter para `matrix-client-android://callback` redirect.
|
||||
- Intercambiar code -> access_token + refresh_token.
|
||||
- Guardar en EncryptedSharedPreferences (`SecurityCryptoUserPrefs`).
|
||||
6. `HomeScreen` Compose con `Text("Hola @<userId>")` + boton Logout.
|
||||
7. Tema Material 3 propio (paleta accent acorde a flow 0010 cliente PC para coherencia).
|
||||
8. Test instrumented: `LoginInstrumentedTest` que mocka MAS y verifica flow callback -> token saved.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_client_kotlin_infra` — facade sobre `matrix-rust-sdk` (init, login, sync, logout).
|
||||
- `mas_oidc_kotlin_infra` — Chrome Custom Tabs + PKCE + callback handler.
|
||||
- `encrypted_prefs_kotlin_core` — wrapper EncryptedSharedPreferences (idempotente, generic put/get).
|
||||
- `LoginScreen_kotlin_ui` — Compose screen Material 3.
|
||||
- `HomeScreen_kotlin_ui` — Compose screen perfil + logout.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] `./gradlew assembleDebug` produce APK valido.
|
||||
- [ ] APK instala en Android 9+ y arranca.
|
||||
- [ ] Login: boton -> Custom Tab MAS -> consent -> callback -> perfil visible.
|
||||
- [ ] Token persiste entre re-aperturas (no re-login si vigente).
|
||||
- [ ] `app.md` con frontmatter completo + 5 `uses_functions`.
|
||||
- [ ] Sub-repo `dataforge/matrix_client_android` con commit inicial.
|
||||
- [ ] Test instrumented `LoginInstrumentedTest` pasa en emulator API 31.
|
||||
|
||||
## Notas
|
||||
|
||||
- Chrome Custom Tabs > WebView para OAuth (security: comparte cookies con browser principal del user, mejor UX).
|
||||
- Refresh token: implementar refresh proactivo 5min antes de expiry (corutina + WorkManager periodic).
|
||||
- Gotcha conocido (ver issue 0074): `local.properties` con `sdk.dir` obligatorio en setup nuevo. El scaffolder lo crea.
|
||||
- Gotcha (issue 0075): Material 3 sin AppCompat — usar `MaterialTheme` directamente, no `Theme.AppCompat.*`.
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
id: "0155"
|
||||
title: "matrix-client-android rooms list + timeline Compose"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0154", "0156"]
|
||||
dependencies: ["0154"]
|
||||
tags: [matrix, android, compose, sync, timeline, rooms]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
UI Compose con `Scaffold` que muestre sidebar drawer con rooms y panel principal con timeline. Sync via `matrix-rust-sdk` (corrutinas + Flow). `LazyColumn` virtualizado para timeline (perf con miles de mensajes). Swipe-to-react en mensajes. Optimistic UI al enviar (en issue 0156).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. ViewModels:
|
||||
- `RoomsViewModel(matrixClient)` — expone `StateFlow<List<RoomSummary>>`. Ordenado por `lastActivity`.
|
||||
- `TimelineViewModel(matrixClient, roomId)` — expone `StateFlow<List<TimelineEvent>>` + `loadMore()`.
|
||||
- Persistencia local con Room DB (`androidx.room`) — store rooms + last sync token.
|
||||
2. Compose:
|
||||
- `MainScreen` con `ModalNavigationDrawer`:
|
||||
- Drawer: `RoomList` (LazyColumn con `RoomItem`: avatar, name, last preview, unread badge).
|
||||
- Content: `TimelineScreen(roomId)`.
|
||||
- `TimelineScreen`:
|
||||
- `LazyColumn` con `reverseLayout = true` (mensajes recientes abajo).
|
||||
- `key = { it.eventId }` para evitar re-composiciones.
|
||||
- `LaunchedEffect` con `LazyListState` -> al llegar al top, `viewModel.loadMore()`.
|
||||
- `EventBubble` composables segun tipo (text, image, file, redacted).
|
||||
- `Avatar` composable reusable con cache de imagenes (`Coil`).
|
||||
3. Sync engine:
|
||||
- `MatrixSyncService` (corrutina supervisor scope) que mantiene `client.syncStream()`.
|
||||
- Si pasa a background sin call activa, sync se pausa hasta que vuelve foreground (lifecycle-aware).
|
||||
- Errores de red: backoff exponencial (1s, 2s, 4s ... 60s max).
|
||||
4. Tests:
|
||||
- Instrumented `RoomsListTest` — 3 rooms aparecen en drawer.
|
||||
- Instrumented `TimelinePaginationTest` — scroll-up carga 50 msgs anteriores.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_room_summary_kotlin_infra` — extract `RoomSummary` de matrix-rust-sdk.
|
||||
- `matrix_timeline_kotlin_infra` — Flow de eventos paginados.
|
||||
- `RoomListScreen_kotlin_ui` — Compose drawer rooms.
|
||||
- `TimelineScreen_kotlin_ui` — Compose timeline virtualizado.
|
||||
- `EventBubble_kotlin_ui` — composable burbuja msg.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Drawer lista rooms del usuario test.
|
||||
- [ ] Click en room muestra timeline ultimos 50 msgs.
|
||||
- [ ] Swipe arriba carga msgs anteriores sin gap.
|
||||
- [ ] Msg enviado desde PC (Wails) aparece en Android en <2s.
|
||||
- [ ] Avion mode + restore: sync resume, no msgs perdidos.
|
||||
- [ ] Cerrar app + reopen: state restaurado desde Room DB, no full re-sync.
|
||||
|
||||
## Notas
|
||||
|
||||
- `matrix-rust-sdk` ya gestiona persistencia interna (SQLite + crypto store). Room DB local solo para datos UI-rapidos (room summaries, unread counters).
|
||||
- Read receipts: TBD otro issue.
|
||||
- DMs detectados via `m.direct` account data.
|
||||
- Spaces: `RoomItem` con icono diferente, colapsable.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: "0156"
|
||||
title: "matrix-client-android composer: markdown, replies, edits, reactions, media"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0155", "0157"]
|
||||
dependencies: ["0155"]
|
||||
tags: [matrix, android, compose, composer, markdown, media, voice]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Composer Compose con markdown shortcuts, replies, edits, reactions emoji, threads, upload media (camara nativa, galeria, voice msg con `MediaRecorder` opus). Drag&drop archivos compartidos via share sheet Android.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. ViewModel:
|
||||
- `ComposerViewModel(matrixClient, roomId)` — methods `sendText`, `sendReply`, `editMessage`, `sendReaction`, `uploadMedia`, `recordVoice`.
|
||||
2. Compose:
|
||||
- `Composer` con `OutlinedTextField` + toolbar (markdown shortcuts B/I/code).
|
||||
- Hotkeys soft keyboard: Send action en IME.
|
||||
- `AttachmentMenu`: botones camara, galeria, file, voice.
|
||||
- `EmojiPicker` overlay (reusar libreria existente o componente propio).
|
||||
- `ReactionBar` debajo de `EventBubble` con aggregates.
|
||||
- `ThreadScreen` — nueva pantalla full para thread (no panel lateral como en PC, por screen real estate movil).
|
||||
- Voice recording UI: hold-to-record con waveform preview + cancelar al deslizar.
|
||||
3. Backend:
|
||||
- Upload media: comprimir imagenes si >2MB antes de upload (`androidx.exifinterface` para preservar orientacion).
|
||||
- Voice: `MediaRecorder` con OPUS, 32kbps, ogg container.
|
||||
- Markdown -> HTML local con `markwon` library (lightweight, no Goldmark equivalente).
|
||||
4. Share intent:
|
||||
- `IntentFilter` para `android.intent.action.SEND` + tipos image/video/text/file -> abre composer del room seleccionado.
|
||||
5. Tests:
|
||||
- Instrumented `SendMarkdownTest` — `**bold**` formateado en Element Web.
|
||||
- Instrumented `EditMessageTest` — edicion in-place propagada.
|
||||
- Instrumented `VoiceMsgTest` — graba 5s + upload + play en Element Web.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `markdown_to_matrix_html_kotlin_core` — wrapper markwon con sanitizer.
|
||||
- `image_compress_kotlin_core` — resize + recompress JPEG.
|
||||
- `voice_record_kotlin_infra` — MediaRecorder opus wrapper.
|
||||
- `Composer_kotlin_ui` — Compose composer + toolbar + attachment menu.
|
||||
- `ReactionBar_kotlin_ui` — composable reactions.
|
||||
- `ThreadScreen_kotlin_ui` — pantalla thread.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Mensaje markdown se ve formateado en Element Web.
|
||||
- [ ] Reply con quote del msg padre.
|
||||
- [ ] Edit in-place propagado en ambos clientes.
|
||||
- [ ] Reaccion emoji bidireccional.
|
||||
- [ ] Upload imagen 5MB -> compresion a ~1MB -> envio + thumbnail OK.
|
||||
- [ ] Voice msg 5s reproducible en Element Web.
|
||||
- [ ] Share intent desde galeria abre composer con imagen pre-cargada.
|
||||
|
||||
## Notas
|
||||
|
||||
- Sanitizer HTML server-side delegado a matrix-rust-sdk (mismo allowlist que cliente PC).
|
||||
- Voice msg: encode opus 32kbps, max 5min.
|
||||
- Markwon vs goldmark: ambos cumplen el rol equivalente en su stack. Salida HTML compatible Matrix.
|
||||
- Drag&drop: en Android = share sheet o picker, no drag&drop nativo como en PC.
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: "0157"
|
||||
title: "matrix-client-android E2EE rust-sdk: cross-signing, SAS, recovery"
|
||||
status: pending
|
||||
priority: critical
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0156", "0158"]
|
||||
dependencies: ["0156"]
|
||||
tags: [matrix, android, e2ee, rust-sdk, cross-signing, sas, security]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Encriptacion end-to-end con `matrix-rust-sdk` Kotlin bindings (mejor impl Olm/Megolm disponible). Cross-signing keys, SAS verification con emoji, recovery passphrase, key backup server-side. UI para verificar otros usuarios + manejar devices propios.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. ViewModel:
|
||||
- `SecurityViewModel(matrixClient)`:
|
||||
- `bootstrapCrossSigning(passphrase)`.
|
||||
- `recoverFromPassphrase(passphrase)`.
|
||||
- `startVerification(userId, deviceId) -> VerificationSession`.
|
||||
- `verifyEmoji(sessionId, accepted)`.
|
||||
- `listOwnDevices() -> Flow<List<Device>>`.
|
||||
- `backupMegolmKeys()`.
|
||||
2. Compose:
|
||||
- `OnboardingE2EEScreen` — wizard 3 pasos: generar passphrase, backup, verify primer device.
|
||||
- `SettingsSecurityScreen`:
|
||||
- Lista devices propios con badge verified/unverified.
|
||||
- Dialog SAS con emoji grid 7x1 cuando hay verificacion en curso.
|
||||
- Boton "Reset cross-signing" (destructive, requiere typing "RESET").
|
||||
- Boton "Restore from passphrase".
|
||||
- `EventBubble` con icono shield (green/amber/red).
|
||||
- Banner room con "X devices not verified" si aplica.
|
||||
3. Crypto store:
|
||||
- `matrix-rust-sdk` gestiona internamente. Solo asegurar que `applicationContext.filesDir` es persistente entre upgrades.
|
||||
- Backup local del store (export encriptado) antes de uninstall: feature opcional via "Export to file" en settings.
|
||||
4. Tests:
|
||||
- Instrumented `BootstrapCrossSigningTest`.
|
||||
- Instrumented `VerificationSASTest` con mock peer.
|
||||
- Instrumented `RecoveryFromPassphraseTest`.
|
||||
- E2E manual con Element Web: enviar/recibir msg E2EE, verificar device cross-platform.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `matrix_e2ee_kotlin_infra` — wrapper rust-sdk encryption module.
|
||||
- `passphrase_derive_key_kotlin_core` — PBKDF2 wrapper.
|
||||
- `VerificationDialog_kotlin_ui` — Compose emoji grid SAS.
|
||||
- `OnboardingE2EEScreen_kotlin_ui` — wizard.
|
||||
- `SettingsSecurityScreen_kotlin_ui` — devices + verification UI.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Bootstrap crea cross-signing keys + sube cifradas.
|
||||
- [ ] Msg enviado en room E2EE se descifra en Element Web + cliente PC Wails (y al reves).
|
||||
- [ ] SAS verification con emoji grid vs Element Web: ambos 7 emojis iguales, accept funciona.
|
||||
- [ ] Login device nuevo + restore passphrase recupera msgs historicos.
|
||||
- [ ] Device no verificado dispara shield amber en EventBubble.
|
||||
- [ ] Decryption failure muestra shield rojo + boton "Request key".
|
||||
|
||||
## Notas
|
||||
|
||||
**Anti-criterios:**
|
||||
- NO marcar done si E2EE silent-falla (mensaje no descifrado pero sin warning visible).
|
||||
- NO marcar done si passphrase queda en plain text en disco.
|
||||
- NO marcar done si cross-signing no funciona contra cliente PC Wails (interop critica).
|
||||
|
||||
**Decisiones:**
|
||||
- `matrix-rust-sdk` >> matrix-android-sdk2 (deprecated). Olm/Megolm en Rust = mejor perf + sin memory leaks.
|
||||
- Passphrase format igual que cliente PC (4 palabras Diceware o 12-byte base32).
|
||||
|
||||
**Gotchas:**
|
||||
- Key rotation Megolm: rust-sdk lo gestiona, pero monitorizar logs en primera semana de uso real.
|
||||
- Olm sessions max: rust-sdk auto-rotate, no accion manual.
|
||||
- Devices nuevos sin passphrase: msgs pre-existentes NO se descifran. UI debe ser clara.
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: "0158"
|
||||
title: "matrix-client-android calls LiveKit nativo: mic/cam/screen + PiP"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0157", "0159", "0161"]
|
||||
dependencies: ["0157"]
|
||||
tags: [matrix, android, livekit, calls, webrtc, pip, audio-focus]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Llamadas nativas via `io.livekit:livekit-android` SDK oficial. Codecs HW (H.264/VP9 hardware decoder), audio focus + AEC/NS nativos, MediaSession para controls en lockscreen, Picture-in-Picture mode Android nativo. Soporta 1:1 + grupales (limite 16 del LiveKit config actual).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Backend (compartido con cliente PC):
|
||||
- Reusar `livekit_token_gen_go_infra` que esta en flow 0010.
|
||||
- Cliente Android pide token al mismo endpoint `/api/call/token` que el cliente PC.
|
||||
2. ViewModel:
|
||||
- `CallViewModel(matrixClient, roomId)`:
|
||||
- `joinCall()` — pide token + conecta `Room.connect()`.
|
||||
- `toggleMic()`, `toggleCamera()`, `toggleScreenShare()`.
|
||||
- `hangup()`.
|
||||
- `Flow<CallState>` con participants, tracks, connection state.
|
||||
3. Compose:
|
||||
- `CallScreen` fullscreen:
|
||||
- Grid tiles participantes (`Flow` layout responsive 1/2/4/9/16).
|
||||
- Tile principal: active speaker (track audio level del SDK).
|
||||
- Controles bottom: mic, cam, screen, raise hand, hangup.
|
||||
- `IncomingCallScreen` fullscreen con accept/decline (system overlay activity).
|
||||
- `CallTile` composable con `VideoView` (SurfaceViewRenderer del SDK).
|
||||
4. PiP (Picture-in-Picture):
|
||||
- `Activity` con `setPictureInPictureParams()`.
|
||||
- Auto-enter PiP al minimizar la app durante call.
|
||||
- PiP tile: video remoto + boton hangup.
|
||||
5. Audio routing:
|
||||
- `AudioFocusRequest` (Android 8+) — focus exclusivo durante call.
|
||||
- Switch speaker/earpiece/bluetooth via `AudioManager.setSpeakerphoneOn()` + connection state listeners para audifonos BT.
|
||||
- Echo cancellation + noise suppression: SDK los habilita por defecto, verificar.
|
||||
6. ICE/TURN: igual que cliente PC, depende del LiveKit config server-side.
|
||||
7. Tests:
|
||||
- Instrumented `Call1to1Test` con emulator + segundo cliente (PC) — connect, video, hangup.
|
||||
- Manual `ScreenShareTest` con device fisico.
|
||||
- Manual `4ParticipantsTest`.
|
||||
- Manual `PiPTest` — call activa + Home button -> PiP aparece.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `livekit_call_kotlin_infra` — wrapper `Room` SDK + permission helpers.
|
||||
- `audio_routing_kotlin_infra` — speaker/earpiece/BT switching.
|
||||
- `CallScreen_kotlin_ui` — fullscreen call UI.
|
||||
- `CallTile_kotlin_ui` — tile con VideoView.
|
||||
- `IncomingCallScreen_kotlin_ui` — accept/decline overlay activity.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Start call desde Android -> PC Wails recibe y conecta.
|
||||
- [ ] 30s call con video+audio nativo (verificar HW codec via `adb shell dumpsys media.codec`).
|
||||
- [ ] Mute mic + apagar cam refleja en otro cliente.
|
||||
- [ ] Screen share desde Android (con `MediaProjection`) visible en PC.
|
||||
- [ ] PiP: minimizar app durante call -> tile flotante con video remoto.
|
||||
- [ ] Bluetooth headphones: cambio automatico al conectar/desconectar.
|
||||
- [ ] Battery: call 30min con AC + WiFi <15% drain.
|
||||
|
||||
## Notas
|
||||
|
||||
- Permissions runtime: `RECORD_AUDIO`, `CAMERA`, `POST_NOTIFICATIONS` (Android 13+), `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_MEDIA_PROJECTION` (Android 14+).
|
||||
- Foreground service requerido para mantener call con app en background (issue 0161).
|
||||
- E2EE en call (insertable streams): TBD post-DoD, igual que en cliente PC.
|
||||
- Connection service Android (sistema): TBD, opcional. Permite integracion con dialer system + Bluetooth Car. Valorar coste/beneficio.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: "0159"
|
||||
title: "matrix-client-android push FCM via sygnal + Firebase setup"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0158", "0160"]
|
||||
dependencies: ["0154"]
|
||||
tags: [matrix, android, push, fcm, firebase, sygnal, infra]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Notificaciones push moviles via FCM (Firebase Cloud Messaging) usando `sygnal` (push gateway oficial de Matrix). Sygnal recibe push events de Synapse, traduce a payload FCM, enviado a Firebase, entregado al device. La app despierta para mostrar notificacion del mensaje, o trigger ringer para incoming calls. App en background o muerta tambien recibe.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. Infra (modifica `element_matrix_chat` app):
|
||||
- Anadir container `sygnal` al `docker-compose.yml`. Config en `configs/sygnal.yaml`.
|
||||
- Service account JSON de Firebase en `configs/firebase-sa.json` (gitignored, instalado en VPS via secrets).
|
||||
- Synapse config: pushers habilitados (ya por defecto).
|
||||
- Reverse proxy: `https://push-<hash>.organic-machine.com/_matrix/push/v1/notify` -> sygnal:5000.
|
||||
- Documentar setup en `projects/element_agents/apps/element_matrix_chat/docs/sygnal_setup.md`.
|
||||
2. Firebase:
|
||||
- Crear proyecto `fn-registry-matrix-push` en Firebase console.
|
||||
- Habilitar Cloud Messaging.
|
||||
- Generar service account JSON.
|
||||
- Anadir `google-services.json` al modulo Android (`app/google-services.json`).
|
||||
3. Android app:
|
||||
- `build.gradle`: `com.google.gms:google-services`, `com.google.firebase:firebase-messaging`.
|
||||
- `FirebaseMessagingService` subclass:
|
||||
- `onNewToken(token)` -> registrar en sygnal via Synapse Pusher API `POST /_matrix/client/v3/pushers/set`.
|
||||
- `onMessageReceived(message)` -> parse data payload + mostrar notif.
|
||||
- Notification channels (Android 8+):
|
||||
- `messages` — IMPORTANCE_HIGH, sonido.
|
||||
- `calls` — IMPORTANCE_HIGH, full-screen intent (despertar pantalla).
|
||||
- `silent` — IMPORTANCE_LOW.
|
||||
- VoIP push para calls: payload con `prio=high`, `event_id_only=false` (incluir event para mostrar caller info sin sync completo).
|
||||
4. Tests:
|
||||
- Instrumented `FCMTokenRegistrationTest` — mock Firebase, verificar pusher creado en Synapse.
|
||||
- Manual `PushDeliveryTest` — enviar msg desde Element Web a Android offline -> push aparece <3s.
|
||||
- Manual `PushCallTest` — start call desde PC -> Android offline despierta + ring.
|
||||
- Manual `PushBatterySaverTest` — Android en battery saver + Doze mode + push sigue llegando.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `sygnal_setup_bash_infra` — script setup container sygnal en VPS.
|
||||
- `sygnal_config_template_go_infra` — generador `sygnal.yaml` con Firebase SA.
|
||||
- `fcm_register_kotlin_infra` — onNewToken + register en Synapse Pusher API.
|
||||
- `synapse_pusher_set_go_infra` — Go helper REST `POST /pushers/set` (reutilizable PC + Android).
|
||||
- `NotificationBuilder_kotlin_ui` — helper notification channels + actions.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Container `sygnal` activo en VPS, health check `:5000/_matrix/push/v1/notify` HEAD 200.
|
||||
- [ ] Firebase project creado + SA JSON instalada en VPS.
|
||||
- [ ] App Android registra FCM token + crea pusher en Synapse al primer login.
|
||||
- [ ] Msg desde Element Web a Android (app cerrada por user) -> push notif en <3s.
|
||||
- [ ] Start call desde cliente PC -> Android offline despierta + ring 30s.
|
||||
- [ ] Battery saver activo: push sigue llegando (FCM high priority bypasses Doze).
|
||||
- [ ] Multiple users: pusher por device, no se cruzan.
|
||||
|
||||
## Notas
|
||||
|
||||
**Gotcha critico:** FCM no entrega push si:
|
||||
- App ha sido force-stopped por user (system requirement).
|
||||
- Device tiene "Restricted background usage" en battery settings.
|
||||
- Account Google no esta sincronizada en el device.
|
||||
Documentar en onboarding para que el user lo entienda.
|
||||
|
||||
**Privacy:** payload FCM no debe contener contenido del msg en claro (Synapse E2EE). Solo: `room_id`, `event_id`, `unread_count`, `prio`. App hace sync interno al recibir push para obtener msg cifrado y descifrar local.
|
||||
|
||||
**Coste:** FCM gratis para hosting Firebase. Sygnal CPU/RAM despreciable (<50MB).
|
||||
|
||||
**Alternativas exploradas:**
|
||||
- UnifiedPush + ntfy: open-source, sin Google. Pro: privacy. Con: requiere infraestructura propia + onboarding mas duro. Post-DoD considerar como segunda opcion para users sin Google Play.
|
||||
|
||||
**Decisiones futuras (post-DoD):**
|
||||
- iOS equivalent: APNs via sygnal mismo gateway. Cuando llegue cliente iOS.
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: "0160"
|
||||
title: "matrix-client-android mini-webapps: WebView + Widget API v2 bridge"
|
||||
status: pending
|
||||
priority: medium
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0159", "0161"]
|
||||
dependencies: ["0159"]
|
||||
tags: [matrix, android, webview, widgets, agents, sandbox]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Host de widgets en Android equivalente al cliente PC (issue 0152). Mismo contrato Widget API v2. WebView con sandbox estricto + bridge JS-Kotlin implementa capabilities API. Widgets de los rooms operados por agentes (`agents_and_robots`) se ven embebidos: dashboard, formulario, kanban inline, control del agente.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. ViewModel:
|
||||
- `WidgetsViewModel(matrixClient, roomId)`:
|
||||
- `Flow<List<Widget>>` desde state events `m.widget` del room.
|
||||
- `addWidget(widget)`, `removeWidget(widgetId)`.
|
||||
- `generateUrl(widget) -> String` — substituye placeholders Matrix Widget API.
|
||||
- `mintScopedToken(widgetId) -> String` — token efimero scope room+widget.
|
||||
2. Compose:
|
||||
- `WidgetsPanel` (drawer lateral o bottom sheet en movil):
|
||||
- Tabs con widgets activos del room.
|
||||
- Cada tab = `WidgetView` que envuelve un `WebView`.
|
||||
- `WidgetView` composable:
|
||||
- `WebView` configurado:
|
||||
- `settings.javaScriptEnabled = true`.
|
||||
- `settings.allowFileAccess = false`.
|
||||
- `settings.allowContentAccess = false`.
|
||||
- `settings.allowFileAccessFromFileURLs = false`.
|
||||
- `settings.allowUniversalAccessFromFileURLs = false`.
|
||||
- `settings.mixedContentMode = MIXED_CONTENT_NEVER_ALLOW`.
|
||||
- `webViewClient` con CSP injection + URL allowlist.
|
||||
- `addJavascriptInterface(WidgetBridge, "MatrixWidgetBridge")` — bridge expone Widget API v2.
|
||||
- `CapabilityConsentDialog` Compose — pide consentimiento usuario para capabilities.
|
||||
3. WidgetBridge (Kotlin):
|
||||
- Implementa capabilities handshake postMessage (igual contrato que cliente PC):
|
||||
- `read_events`, `send_event`, `send_to_device`, `get_openid`, `m.always_on_screen`.
|
||||
- Audit log mensajes JS<->Kotlin en local DB.
|
||||
- Whitelist estricta de capabilities concedidas.
|
||||
4. Widgets internos primer batch (compartidos con cliente PC):
|
||||
- `widget-agent-panel` — control del agente.
|
||||
- `widget-kanban` — kanban inline.
|
||||
- `widget-issue-tracker`.
|
||||
5. Tests:
|
||||
- Instrumented `WidgetCapabilitiesTest` — dialog aparece + accept/decline funciona.
|
||||
- Instrumented `WidgetSandboxTest` — widget malicioso (intenta `window.location='file:///etc/passwd'`) bloqueado.
|
||||
- Instrumented `WidgetSendEventTest` — widget con capability envia msg.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `WidgetView_kotlin_ui` — Compose WebView wrapper sandboxed.
|
||||
- `widget_bridge_kotlin_infra` — JavascriptInterface implementando Widget API v2.
|
||||
- `widget_url_template_kotlin_core` — substituyente placeholders (puede compartirse logica con la Go version del PC, contrato identico).
|
||||
- `CapabilityConsentDialog_kotlin_ui` — Compose dialog.
|
||||
- `widget_audit_log_kotlin_infra` — append-only audit log en Room DB.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Widget publicado desde cliente PC se ve embebido en Android (mismo room).
|
||||
- [ ] Capability handshake: widget pide `send_event` -> dialog Compose -> accept -> widget envia msg.
|
||||
- [ ] Sandbox: widget intenta `XMLHttpRequest` a `file:///` -> bloqueado.
|
||||
- [ ] Widget agent-panel funcional: muestra logs en vivo del agente + boton restart.
|
||||
- [ ] Audit log persiste en Room DB con timestamp + capability + accept/deny.
|
||||
|
||||
## Notas
|
||||
|
||||
**Critico:**
|
||||
- Mismo contrato Widget API v2 que cliente PC. Widget HTML escrito una vez funciona en ambos.
|
||||
- WebView Android moderno (Chromium 100+) soporta WebRTC + WebGL + service workers. Suficiente para widgets ricos.
|
||||
|
||||
**Gotcha:**
|
||||
- `WebView.addJavascriptInterface` solo seguro en Android 4.2+ (API 17+, ya minSdk=28). Pero validar todo input desde JS — nunca confiar.
|
||||
- `setAllowFileAccessFromFileURLs(false)` solo aplica si la URL del widget es `file://`. Nuestros widgets son `https://` -> hardcode CSP estricta.
|
||||
- Memory: WebView por tab + 5 widgets activos = ~200MB facil. Limitar a max 3 widgets simultaneos activos.
|
||||
|
||||
**Roadmap post-DoD:**
|
||||
- Widget marketplace catalog accesible via menu.
|
||||
- "Add to home screen" PWA mode para widgets favoritos (Android shortcut + launcher icon dedicado).
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
id: "0161"
|
||||
title: "matrix-client-android foreground service: calls + lifecycle + lockscreen"
|
||||
status: pending
|
||||
priority: high
|
||||
created: 2026-05-24
|
||||
related_flows: ["0011"]
|
||||
related_issues: ["0158", "0160"]
|
||||
dependencies: ["0158"]
|
||||
tags: [matrix, android, foreground-service, lifecycle, mediasession, wakelock]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
`CallForegroundService` que mantiene call activa con app en background o pantalla bloqueada. Notification ongoing visible mientras dura la call. `MediaSession` para integrar con lockscreen controls + Bluetooth Car (mute, hangup desde audio device). Wakelock controlado para evitar drain excesivo. Notificaciones full-screen intent para incoming calls (despiertan pantalla).
|
||||
|
||||
## Tareas
|
||||
|
||||
1. `CallForegroundService` (`android.app.Service`):
|
||||
- `START_FOREGROUND_SERVICE` con type `MEDIA_PROJECTION` o `PHONE_CALL` (Android 14+ requiere type explicito).
|
||||
- `Notification.Builder` channel `calls` con:
|
||||
- Custom view con caller name, duration, mute/hangup buttons.
|
||||
- `setOngoing(true)`.
|
||||
- `setCategory(CATEGORY_CALL)`.
|
||||
- Lifecycle: `START_STICKY` para reiniciar si OS lo mata (raro con foreground).
|
||||
2. `MediaSession` integration:
|
||||
- `MediaSessionCompat` con play/pause/stop actions mapeados a mute/unmute/hangup.
|
||||
- Bluetooth Car media controls.
|
||||
- Lockscreen controls visibles si dispositivo lo soporta.
|
||||
3. Wakelock:
|
||||
- `PowerManager.PARTIAL_WAKE_LOCK` durante call activa.
|
||||
- `WAKE_LOCK_KEY = "matrix_client:call"` para audit en `dumpsys power`.
|
||||
- Liberar inmediato al hangup.
|
||||
- Proximity wakelock (`PROXIMITY_SCREEN_OFF_WAKE_LOCK`) si call solo audio + telefono pegado a oreja.
|
||||
4. Incoming call full-screen intent:
|
||||
- `Notification` con `setFullScreenIntent(pendingIntent, true)`.
|
||||
- Activity `IncomingCallActivity` con `showWhenLocked(true)` + `turnScreenOn(true)`.
|
||||
- Compose UI fullscreen con accept/decline.
|
||||
5. Doze mode handling:
|
||||
- `ACTION_IGNORE_BATTERY_OPTIMIZATIONS` solicitar al user en onboarding (no obligatorio, solo para calls fiables).
|
||||
- Documentar tradeoff en pantalla onboarding.
|
||||
6. Battery monitoring:
|
||||
- Log custom: call duration + battery_drain_pct al hangup.
|
||||
- Visible en `Settings > Diagnostics` para debug.
|
||||
7. Tests:
|
||||
- Manual `CallBackgroundTest` — start call + Home button -> notif visible + audio sigue.
|
||||
- Manual `CallLockscreenTest` — call + power button -> pantalla apaga + audio sigue + lockscreen controls visibles.
|
||||
- Manual `IncomingFullScreenTest` — device en lockscreen + incoming call -> pantalla despierta + UI accept/decline.
|
||||
- Manual `BluetoothCarTest` — Bluetooth Car connected + call active + mute desde steering wheel funciona.
|
||||
- Manual `BatteryTest` — call 30min en background + WiFi + AC -> drain <15%.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `CallForegroundService_kotlin_infra` — service completo.
|
||||
- `media_session_kotlin_infra` — wrapper MediaSessionCompat.
|
||||
- `wakelock_manager_kotlin_infra` — adquirir/liberar wakelocks de forma idempotente.
|
||||
- `IncomingCallActivity_kotlin_ui` — Compose fullscreen activity.
|
||||
- `battery_monitor_kotlin_infra` — log drain por session.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] Call activa + Home -> notif ongoing visible + audio sigue 30s.
|
||||
- [ ] Call + power button -> lockscreen muestra controls + audio sigue.
|
||||
- [ ] Incoming call con pantalla apagada -> despierta + UI accept/decline.
|
||||
- [ ] Bluetooth Car: mute/hangup desde steering wheel funciona.
|
||||
- [ ] Hangup libera wakelocks (verificar con `dumpsys power | grep matrix_client`).
|
||||
- [ ] Battery saver activo: call no se corta (foreground service exempt).
|
||||
- [ ] Call 30min background: drain <15% con WiFi+AC.
|
||||
|
||||
## Notas
|
||||
|
||||
**Anti-criterios:**
|
||||
- NO marcar done si call se corta a los 5min en background (battery optimization kill).
|
||||
- NO marcar done si wakelock queda colgado tras hangup (battery leak).
|
||||
- NO marcar done si lockscreen no muestra controls (UX critico para calls largas).
|
||||
|
||||
**Gotchas Android 14+:**
|
||||
- Foreground service type DEBE declararse en manifest + runtime: `phoneCall|mediaProjection`.
|
||||
- `POST_NOTIFICATIONS` runtime permission (Android 13+).
|
||||
- `USE_FULL_SCREEN_INTENT` runtime permission (Android 14+) — pedir explicito.
|
||||
|
||||
**Decisiones:**
|
||||
- Telecom framework (ConnectionService): NO en esta iteracion. Pro: integracion dialer nativo. Con: bug-prone, requiere CALL_PHONE permission con justificacion Play Store. Post-DoD considerar.
|
||||
- Audio focus exclusivo durante call (issue 0158 ya lo cubre).
|
||||
|
||||
**Battery optimization onboarding:**
|
||||
- Pantalla en primer launch: explicar por que pedimos exempt battery optimization (calls fiables).
|
||||
- Boton "Open settings" -> `Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`.
|
||||
- Si user declina: app funciona pero documentar que calls largas pueden cortarse.
|
||||
@@ -0,0 +1,197 @@
|
||||
---
|
||||
id: "0162"
|
||||
title: "Matrix: migrar Synapse a MAS como unico auth provider (MSC3861)"
|
||||
status: pending
|
||||
priority: critical
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010", "0011"]
|
||||
related_issues: ["0147", "0154", "0163"]
|
||||
dependencies: []
|
||||
tags: [matrix, mas, synapse, msc3861, auth, oidc, migration, infra]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Activar `matrix_authentication_service` en Synapse para que TODO login pase por MAS (Matrix Authentication Service) via MSC3861. Estado actual: MAS corre 6 semanas pero esta en pie sin clients registrados. Synapse usa login password legacy + application_service. Element Web, Synapse-Admin y clientes nuevos (flows 0010 + 0011) deben autenticarse exclusivamente contra MAS via OIDC.
|
||||
|
||||
Bloquea flows 0010 (matrix-client-pc) + 0011 (matrix-client-android) porque ambos asumen MAS funcional.
|
||||
|
||||
## Estado actual
|
||||
|
||||
```yaml
|
||||
# synapse_data/homeserver.yaml — comentado, NO activo:
|
||||
# matrix_authentication_service:
|
||||
# enabled: true
|
||||
# endpoint: "http://mas:8080/"
|
||||
# secret: "<shared_secret>"
|
||||
|
||||
experimental_features:
|
||||
msc3266_enabled: true
|
||||
msc4222_enabled: true
|
||||
msc4354_enabled: true
|
||||
# msc4108_delegation_endpoint: "https://auth-af2f3d.organic-machine.com/_matrix/client/unstable/org.matrix.msc4108/rendezvous"
|
||||
```
|
||||
|
||||
```yaml
|
||||
# mas/config.yaml
|
||||
clients: [] # vacio
|
||||
public_base: https://auth-af2f3d.organic-machine.com/
|
||||
```
|
||||
|
||||
```
|
||||
GET /_matrix/client/v3/login -> {"flows":[{"type":"m.login.password"},{"type":"m.login.application_service"}]}
|
||||
GET /.well-known/matrix/client -> sin org.matrix.msc2965.authentication
|
||||
```
|
||||
|
||||
## Tareas
|
||||
|
||||
1. **Pre-migracion: backup completo**
|
||||
- Snapshot postgres Synapse: `docker exec element_matrix_chat-postgres-1 pg_dump -U synapse synapse > /backup/synapse_$(date +%Y%m%d).sql`.
|
||||
- Snapshot postgres MAS: idem `mas-postgres`.
|
||||
- Snapshot `synapse_data/` + `mas/config.yaml`.
|
||||
- Guardar backups en VPS local + descargar copia a PC.
|
||||
|
||||
2. **Registrar clients en MAS** (`mas/config.yaml`):
|
||||
- Cliente para Synapse (admin/internal): `client_id` + `client_secret` o `client_auth_method: client_secret_basic`.
|
||||
- Cliente para Element Web: `redirect_uris: [https://element-a05ae4.organic-machine.com/]`.
|
||||
- Cliente para nuevo admin panel (issue 0163): `redirect_uris: [<admin_panel_url>]`.
|
||||
- Cliente para matrix_client_pc (flow 0010): `redirect_uris: [http://127.0.0.1:*]` (loopback dinamico).
|
||||
- Cliente para matrix_client_android (flow 0011): `redirect_uris: [matrix-client-android://callback]`.
|
||||
- Aplicar: `docker exec element_matrix_chat-mas-1 mas-cli config sync`.
|
||||
|
||||
3. **Activar MSC3861 en Synapse**:
|
||||
- Editar `synapse_data/homeserver.yaml`:
|
||||
```yaml
|
||||
matrix_authentication_service:
|
||||
enabled: true
|
||||
endpoint: "http://mas:8080/"
|
||||
secret: "<shared_secret_matching_mas_config>"
|
||||
experimental_features:
|
||||
msc3861:
|
||||
enabled: true
|
||||
msc3266_enabled: true
|
||||
msc4222_enabled: true
|
||||
msc4354_enabled: true
|
||||
msc4108_delegation_endpoint: "https://auth-af2f3d.organic-machine.com/_matrix/client/unstable/org.matrix.msc4108/rendezvous"
|
||||
# Disable legacy password login:
|
||||
password_config:
|
||||
enabled: false
|
||||
```
|
||||
|
||||
4. **Migrar usuarios existentes Synapse -> MAS**:
|
||||
- `docker exec element_matrix_chat-mas-1 mas-cli syn2mas --synapse-config /data/homeserver.yaml --dry-run` primero.
|
||||
- Revisar log (conflictos, usuarios huerfanos).
|
||||
- Ejecutar real: `mas-cli syn2mas --synapse-config /data/homeserver.yaml`.
|
||||
- Verificar: contar usuarios `mas-postgres` vs `synapse-postgres`, deben coincidir.
|
||||
|
||||
5. **Actualizar well-known** (`/.well-known/matrix/client`):
|
||||
- Servido por `element_matrix_chat-wellknown-1` (nginx).
|
||||
- Anadir:
|
||||
```json
|
||||
"org.matrix.msc2965.authentication": {
|
||||
"issuer": "https://auth-af2f3d.organic-machine.com/",
|
||||
"account": "https://auth-af2f3d.organic-machine.com/account"
|
||||
}
|
||||
```
|
||||
- Reload nginx.
|
||||
|
||||
6. **Restart ordenado**:
|
||||
- `docker compose restart mas` -> verificar logs sin errores 30s.
|
||||
- `docker compose restart synapse` -> verificar `_matrix/client/v3/login` ahora devuelve `m.login.sso` con `identity_providers` apuntando a MAS.
|
||||
- `docker compose restart element` (recarga config).
|
||||
|
||||
7. **Reconfigurar Element Web** (`element-config.json`):
|
||||
- Activar `oidc_native_flow: true` (Element Web soporta MSC3861 desde v1.11.50+).
|
||||
- Verificar version Element Web (`docker exec element_matrix_chat-element-1 cat /etc/nginx/conf.d/element.json | head` o image tag) >= v1.11.50.
|
||||
- Si version vieja: bump container image.
|
||||
|
||||
8. **Verificar end-to-end**:
|
||||
- Logout completo navegador.
|
||||
- Abrir Element Web -> debe redirigir a MAS para login.
|
||||
- Login con cuenta existente migrada -> redirect back a Element -> sesion activa.
|
||||
- Comprobar rooms historicos siguen visibles + msgs E2EE descifrados (las cross-signing keys NO se re-bootstrappean si la migracion va bien).
|
||||
|
||||
9. **Plan rollback** (escribir en `docs/mas_migration_rollback.md`):
|
||||
- Restaurar postgres Synapse desde dump.
|
||||
- Comentar bloque `matrix_authentication_service:` en homeserver.yaml.
|
||||
- `password_config.enabled: true`.
|
||||
- Restart Synapse.
|
||||
- MAS sigue vivo idle (no destruir).
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `mas_client_register_bash_infra` — `mas-cli config sync` wrapper + validacion idempotente.
|
||||
- `synapse_msc3861_enable_go_infra` — edita `homeserver.yaml` con bloque MAS + experimental_features.
|
||||
- `mas_syn2mas_migration_bash_infra` — wrapper migracion con dry-run obligatorio + log archive.
|
||||
- `wellknown_oidc_patch_go_infra` — anade `org.matrix.msc2965.authentication` al well-known JSON servido por nginx.
|
||||
- `synapse_login_flows_check_go_infra` — health-check post-migracion (espera ver `m.login.sso` en flows).
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] `GET /_matrix/client/v3/login` devuelve `m.login.sso` con identity provider MAS.
|
||||
- [ ] `GET /.well-known/matrix/client` contiene `org.matrix.msc2965.authentication.issuer`.
|
||||
- [ ] Element Web redirige a MAS para login (no muestra form propio).
|
||||
- [ ] Login con cuenta existente funciona post-migracion.
|
||||
- [ ] Rooms historicos + msgs E2EE siguen visibles tras re-login.
|
||||
- [ ] `password_config.enabled: false` no rompe nada (todo va por MAS).
|
||||
- [ ] Backup pre-migracion subido + documentado.
|
||||
- [ ] `docs/mas_migration_rollback.md` escrito + probado en staging (ver Notas).
|
||||
|
||||
## Definition of Done
|
||||
|
||||
### Mecanica
|
||||
- `docker compose ps` muestra todos los containers healthy.
|
||||
- `mas-cli config check` exit 0.
|
||||
- `synapse curl /health` 200.
|
||||
- Tests humo: login + send msg + recibe msg propagado a otra cuenta.
|
||||
|
||||
### Cobertura
|
||||
|
||||
| Escenario | Comando / evidencia | Resultado |
|
||||
|---|---|---|
|
||||
| Golden: login Element Web via MAS | navegador Incognito -> ` element-a05ae4.organic-machine.com` | redirect MAS -> login -> sesion activa |
|
||||
| Edge: usuario migrado con E2EE setup previo | post-login en Element Web | rooms cifrados se descifran sin re-bootstrap |
|
||||
| Edge: app servicio (bot) usa application_service token | bot envia msg | sigue funcionando (AS no pasa por MAS) |
|
||||
| Edge: device verification cross-platform | Element Web verifica device PC Wails (post flow 0010) | OK |
|
||||
| Error: token MAS expira mid-session | esperar TTL (default 5min refresh) | refresh automatico, no logout |
|
||||
| Error: MAS cae (kill container) | matar `mas-1` 60s | Synapse rechaza nuevos logins; sessiones activas siguen (access_token cached); restart MAS -> recovery |
|
||||
|
||||
### Vida util validada (7 dias post-migracion)
|
||||
|
||||
| Metrica | Umbral | Donde | Ventana |
|
||||
|---|---|---|---|
|
||||
| Login failures (causa MAS) | `< 1%` | `mas` logs + sentry-like | 7 dias |
|
||||
| Latency `/oauth2/token` | `p95 < 500ms` | nginx access log VPS | 7 dias |
|
||||
| Crashes MAS / Synapse | `0` | `docker logs --since` | 7 dias |
|
||||
| Users migrados activos | `>= 95%` | `mas-cli admin user list` vs sesiones activas | 7 dias |
|
||||
|
||||
### Anti-criterios
|
||||
- NO marcar done si algun usuario migrado pierde acceso a rooms cifrados.
|
||||
- NO marcar done si Element Web sigue mostrando form de password (legacy flow).
|
||||
- NO marcar done si rollback documentado no se ha probado al menos una vez en staging.
|
||||
|
||||
## Notas
|
||||
|
||||
**Staging recomendado:** levantar stack identico en VPS test o WSL local con docker-compose + datos fake antes de tocar prod. organic-machine.com lleva 6 semanas viva.
|
||||
|
||||
**Element Call (LiveKit):** ya usa OIDC del homeserver para tokens via `livekit-jwt` container -> migracion debe verificar que tokens siguen emitiendose contra el MAS auth.
|
||||
|
||||
**Synapse-Admin compat:** synapse-admin v0.10+ soporta MSC3861. Verificar version corriendo. Si vieja, bump O reemplazar por panel propio (issue 0163).
|
||||
|
||||
**Gotcha critico — shared_secret:**
|
||||
- `mas/config.yaml` tiene `matrix.secret` que debe matchear `homeserver.yaml.matrix_authentication_service.secret`.
|
||||
- Generar con `openssl rand -hex 32` si no existe.
|
||||
- Si no matchean: Synapse rechaza requests MAS con 401.
|
||||
|
||||
**Gotcha — application_service tokens:**
|
||||
- Los AS (bridges, bots) NO pasan por MAS. Siguen usando `as_token`/`hs_token` de su registration.
|
||||
- `agents_and_robots` usa application_service? Verificar antes — si SI, no afecta. Si usa password login normal, tendra que pasar por MAS (re-config).
|
||||
|
||||
**Roadmap post-DoD:**
|
||||
- Habilitar `device_code` grant en MAS para login CLI futuro.
|
||||
- Habilitar QR-code login (MSC4108) ya pre-config con `msc4108_delegation_endpoint`.
|
||||
- Multi-factor (TOTP) en MAS — config available.
|
||||
|
||||
## Capability growth log
|
||||
|
||||
- v0.1.0 (2026-05-24) — issue creada.
|
||||
@@ -0,0 +1,189 @@
|
||||
---
|
||||
id: "0163"
|
||||
title: "Matrix admin panel propio: users, rooms, devices, sessions (sustituye synapse-admin)"
|
||||
status: pending
|
||||
priority: medium
|
||||
created: 2026-05-24
|
||||
related_flows: ["0010", "0011"]
|
||||
related_issues: ["0162", "0147"]
|
||||
dependencies: ["0162"]
|
||||
tags: [matrix, admin, panel, react, mantine, mas, synapse, infra]
|
||||
---
|
||||
|
||||
## Objetivo
|
||||
|
||||
Panel admin propio que reemplaza `https://admin-0cc4d3.organic-machine.com/#/users` (synapse-admin actual). Funciones equivalentes: gestionar usuarios (crear, deactivate, reset password, list devices, list rooms), gestionar rooms (list, members, kick, force-leave, delete), ver sesiones activas + revoke, ver media (storage usage por user). Auth via MAS OIDC con scope admin. Stack: React+Vite+Mantine+`@fn_library` (consistente con flows 0010/0011 + resto del registry).
|
||||
|
||||
## Por que reemplazar synapse-admin
|
||||
|
||||
- **Auth legacy**: synapse-admin usa admin token + password admin directo. Tras issue 0162 (MAS obligatorio) esto chirria. Mejor consume MAS OIDC + Synapse Admin API.
|
||||
- **UI ajena**: stack distinto al resto del registry. Sin theming propio, sin `@fn_library`, sin coherencia visual con cliente PC (flow 0010).
|
||||
- **Sin agentes**: no podemos integrar paneles especiales para `agents_and_robots`, devices del mesh (flow 0009), policies de widgets.
|
||||
- **No extensible**: anadir "ver telemetria de calls LiveKit" o "audit log MAS" requiere fork pesado.
|
||||
|
||||
## Tareas
|
||||
|
||||
1. **Scaffold app**:
|
||||
- `projects/element_agents/apps/matrix_admin_panel/`.
|
||||
- Stack: React+Vite+TS+Mantine+`@fn_library`+`@tabler/icons-react`.
|
||||
- Backend: Go con `mautrix-go` admin client + MAS OIDC client + `livekit-server-sdk-go` (para sesiones de call).
|
||||
- Empaquetado: backend Go sirve frontend estatico embebido (`embed.FS`).
|
||||
- Deploy: container Docker en `element_matrix_chat` stack o como service standalone via `deploy_server`.
|
||||
|
||||
2. **Auth flow MAS**:
|
||||
- Cliente registrado en MAS (issue 0162 paso 2) con scope `urn:synapse:admin:*`.
|
||||
- Login Web: OIDC redirect a MAS.
|
||||
- Token guardado en httpOnly cookie + CSRF token.
|
||||
|
||||
3. **Modulos UI**:
|
||||
- **Users**:
|
||||
- Tabla virtualizada con `data-table` (cuando exista TS equivalente) o `mantine-react-table`.
|
||||
- Columnas: localpart, displayname, avatar, admin, deactivated, last_seen, device_count.
|
||||
- Acciones por row: view detail, deactivate/reactivate, reset password (force MAS link), list devices.
|
||||
- Filtros: deactivated, admin, search.
|
||||
- **User detail**:
|
||||
- Sub-tabs: Profile, Devices (list + revoke individual), Rooms (membership list), Media (uploads + size), Sessions (MAS active sessions + revoke), Audit log (MAS).
|
||||
- **Rooms**:
|
||||
- Tabla: room_id, name, alias, members_count, encrypted, public, federated, state_events.
|
||||
- Acciones: view detail, force-leave usuarios, delete room (purge), shutdown notif.
|
||||
- **Room detail**:
|
||||
- Members + roles, state events viewer (read-only JSON), media in room, widgets activos (interop con flow 0010 widget API).
|
||||
- **Sessions** (MAS):
|
||||
- Lista sesiones activas global.
|
||||
- Filtro por user, IP, device, last_used.
|
||||
- Revoke individual o bulk.
|
||||
- **Federation**:
|
||||
- Estado federation (Synapse `federation_handler`).
|
||||
- Allowlist/blocklist servers.
|
||||
- **Stats**:
|
||||
- Resumen: users count, rooms count, mensajes/dia (ultima semana), media storage, calls activas (via LiveKit `RoomService.ListRooms`).
|
||||
- Graficas con `@mantine/charts` o `recharts`.
|
||||
|
||||
4. **Capability groups en panel**:
|
||||
- Reusa `AgentPanel` (flow 0010 issue 0153) para mostrar info de agentes registrados.
|
||||
- Reusa `DevicePanel` (cuando flow 0009 vivo) para devices del mesh.
|
||||
- Slot "Widgets policy": ver/aprobar capabilities concedidas globalmente, audit log.
|
||||
|
||||
5. **API endpoints backend Go**:
|
||||
- `GET /api/users` -> proxy a Synapse `/_synapse/admin/v2/users` con auth MAS.
|
||||
- `POST /api/users/<id>/deactivate`.
|
||||
- `GET /api/rooms`, `POST /api/rooms/<id>/delete`.
|
||||
- `GET /api/mas/sessions`, `POST /api/mas/sessions/<id>/revoke` (MAS admin API).
|
||||
- `GET /api/livekit/rooms` (active calls).
|
||||
- `GET /api/stats/summary`.
|
||||
|
||||
6. **Permisos**:
|
||||
- Solo users con flag `admin: true` (Synapse) o scope MAS admin claim.
|
||||
- Backend valida claim/flag en cada request.
|
||||
- UI muestra "Access denied" si user logueado no es admin.
|
||||
|
||||
7. **Deploy**:
|
||||
- Anadir container al `docker-compose.yml` de `element_matrix_chat`.
|
||||
- O bien standalone via `deploy_server` (registry function existente).
|
||||
- URL: `admin-af2f3d.organic-machine.com` o reusar `admin-0cc4d3.organic-machine.com` cuando se retire synapse-admin.
|
||||
|
||||
8. **Migracion synapse-admin -> panel propio**:
|
||||
- Coexistencia 2 semanas: ambos vivos, MAS audita uso de cada uno.
|
||||
- Cuando uso de synapse-admin = 0 durante 7 dias seguidos: detener container.
|
||||
- Documentar en `docs/admin_panel_migration.md`.
|
||||
|
||||
9. **Tests**:
|
||||
- `e2e/test_admin_login.sh` — MAS OIDC + scope admin valido -> acceso.
|
||||
- `e2e/test_admin_login_denied.sh` — user no-admin recibe 403.
|
||||
- `e2e/test_user_deactivate.sh` — flow completo deactivate + verify can't login.
|
||||
- `e2e/test_room_purge.sh` — purge room + verify gone en Synapse.
|
||||
- `e2e/test_session_revoke.sh` — revoke sesion MAS + user perdiendo acceso en <30s.
|
||||
|
||||
## Funciones del registry a crear
|
||||
|
||||
- `synapse_admin_client_go_infra` — wrapper Synapse Admin API.
|
||||
- `mas_admin_client_go_infra` — wrapper MAS admin API (`/api/admin/v1/...`).
|
||||
- `livekit_admin_client_go_infra` — `RoomService.ListRooms`, kick participant, etc.
|
||||
- `oidc_admin_middleware_go_infra` — middleware Go que valida scope admin en cookie/Bearer.
|
||||
- `UsersTable_ts_ui` — componente Mantine con virtualization + filtros.
|
||||
- `RoomDetail_ts_ui` — componente con tabs Members/State/Media/Widgets.
|
||||
- `SessionsList_ts_ui` — lista sesiones + revoke action.
|
||||
- `StatsSummary_ts_ui` — componente con `@mantine/charts`.
|
||||
- `FederationStatusPanel_ts_ui` — componente federation diag.
|
||||
|
||||
## Acceptance
|
||||
|
||||
- [ ] App compila + arranca como container Docker.
|
||||
- [ ] Login via MAS OIDC con scope admin funciona.
|
||||
- [ ] User no-admin recibe 403 al intentar entrar.
|
||||
- [ ] Tabla users con 50+ rows + filtros + actions.
|
||||
- [ ] Deactivate user end-to-end (verify cannot login despues).
|
||||
- [ ] Room detail muestra members + state events JSON.
|
||||
- [ ] Sessions MAS listadas + revoke individual.
|
||||
- [ ] Stats: counts + media usage + active calls visibles.
|
||||
- [ ] Tema visual coherente con cliente PC (flow 0010).
|
||||
|
||||
## Definition of Done
|
||||
|
||||
### Mecanica
|
||||
- `go build` + `pnpm build` verde.
|
||||
- Container Docker `<150MB` (Alpine + binary + static).
|
||||
- Health endpoint `/health` 200.
|
||||
- E2E suite pasa.
|
||||
|
||||
### Cobertura
|
||||
|
||||
| Escenario | Evidencia | Resultado |
|
||||
|---|---|---|
|
||||
| Golden: admin login + ver users | `e2e/test_admin_full_flow.sh` | tabla con users reales, actions visibles |
|
||||
| Edge: 5000 users en tabla | benchmark scroll | 60fps, <300MB RAM |
|
||||
| Edge: user sin admin entra | request directo | 403 + audit log |
|
||||
| Edge: room con 200 members | view detail | render < 1s, paginacion OK |
|
||||
| Error: Synapse Admin API caida | mock 500 | UI muestra error claro, no crash |
|
||||
| Error: MAS session revoke fails | mock 500 | retry + toast error |
|
||||
|
||||
### Vida util (>=7 dias)
|
||||
|
||||
| Metrica | Umbral | Donde | Ventana |
|
||||
|---|---|---|---|
|
||||
| Crashes container | `0` | docker logs | 7 dias |
|
||||
| Uso real | `>= 2 sesiones/semana` (operador) | nginx access log | 7 dias |
|
||||
| Latency p95 endpoint /api/users | `< 800ms` (Synapse Admin paginado) | metrics | 7 dias |
|
||||
| Acciones destructivas auditadas | `100%` (cada delete/revoke con audit row) | local audit DB | continuo |
|
||||
|
||||
### Anti-criterios
|
||||
- NO marcar done si admin panel acepta token sin claim/flag admin.
|
||||
- NO marcar done si delete room no purga media en DB Synapse.
|
||||
- NO marcar done si UI deja al operador sin confirmacion en acciones destructivas (deactivate, purge, revoke).
|
||||
- NO marcar done si lookalike de synapse-admin sin features propias (mejor mantener synapse-admin entonces).
|
||||
|
||||
## Notas
|
||||
|
||||
**Ventajas reales sobre synapse-admin:**
|
||||
1. Coherencia visual + Mantine + theme propio.
|
||||
2. Integracion con `agents_and_robots` (panel agente embedded).
|
||||
3. Integracion con widgets policy (audit + override capabilities).
|
||||
4. Integracion con LiveKit calls (ver rooms activos, force-end).
|
||||
5. Audit log local SQLite con todas las acciones admin (synapse-admin no lo tiene).
|
||||
6. Extensible — anadir tabs para mesh devices (flow 0009), telemetria, etc.
|
||||
|
||||
**Onboarding:**
|
||||
1. `cd projects/element_agents/apps/matrix_admin_panel`.
|
||||
2. `make dev` (Go backend + Vite frontend hot reload).
|
||||
3. Visitar `http://127.0.0.1:8090` -> login MAS dev.
|
||||
4. Deploy prod: ver `deploy/README.md`.
|
||||
|
||||
**Decisiones:**
|
||||
- Backend Go > Python/Node: alinea con `mautrix-go` + reusa funciones del registry. Binario pequeno, deploy facil.
|
||||
- Embedded static (Go `embed.FS`): un binario, sin docker multi-stage compleja.
|
||||
- Audit log local SQLite > Postgres: panel admin no necesita HA, suficiente con SQLite local + backup periodico.
|
||||
|
||||
**Gotchas:**
|
||||
- Synapse Admin API requiere `Bearer <admin_token>` — el panel intercambia OIDC token + admin claim por admin_token (con MAS admin API o con cuenta admin shared).
|
||||
- MAS admin API esta en `/api/admin/v1/` — version unstable, monitorizar breaking changes.
|
||||
- Federation tab: si federation deshabilitada (caso actual, ver `homeserver.yaml`), tab muestra "disabled" en vez de error.
|
||||
|
||||
**Roadmap post-DoD:**
|
||||
- Bulk actions (mass deactivate, mass invite).
|
||||
- Export reports CSV.
|
||||
- Slack/email alerts en eventos criticos (server cae, MAS down, federation block).
|
||||
- Multi-tenancy si llegan mas homeservers.
|
||||
|
||||
## Capability growth log
|
||||
|
||||
- v0.1.0 (2026-05-24) — issue creada.
|
||||
Reference in New Issue
Block a user