Compare commits

..
9 Commits
Author SHA1 Message Date
myxeliumandCursor d3d22846e7 fix: Bug - User login status showing as both logged in and logged out
Stop treating transient auth_required as home-session expiry, keep auth scope
consistent across login redirect and server-rail joins, and leave /login when
the in-memory user is still authenticated.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-14 01:54:01 +02:00
myxelium 59dfd2de85 perf: performance improvements 1 2026-07-14 01:34:33 +02:00
myxelium edc4d935d8 chore: Fix app 2026-07-14 00:41:05 +02:00
myxeliumandCursor 3e090933fd fix: Bug - User receiving direct call doesn't get notified (identity aliases)
Match incoming direct-call events against every local identity alias - home
id, entity id, peer id, and each provisioned signal-server actor id - instead
of only oderId||id. A caller who met the callee through a room on the
caller's signal server addresses the ring by the callee's provisioned actor
id, so the old admission check silently dropped it: the caller went "In
Voice" while the callee saw no modal, no ring audio, and no rail entry.
Incoming self aliases are normalized onto the canonical local id
(normalizeDirectCallPayloadSelfAliases) so they never appear as a phantom
third participant, and remoteParticipantIds / the DM-header peer lookup skip
all self aliases.

Adds a DM-header call ring e2e including the cross-signal topology (callee
homed on a secondary signal server) that fails on the old code.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-13 20:18:37 +02:00
myxeliumandCursor 590e487250 fix: Bug - Sending files between users doesn't really work (chunk-time size re-gate)
Remove the leftover MAX_AUTO_SAVE_SIZE_BYTES guard from handleFileChunk's
in-memory path. The request gate (canReceiveAttachment) already admits 10-50 MB
generic files for in-memory receive on stores without disk streaming (browser),
but the chunk handler silently dropped every chunk of such files: no ack was
sent, the sender's waitForAck timed out, and the receiver's GUI never changed.
Receive admission is now decided once, at request time.

Adds a two-browser regression e2e that sends an 11 MB generic file and asserts
Request -> progress -> Download.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-13 18:48:30 +02:00
myxeliumandCursor 497033aff0 fix: Bug - Sending files and attachment issues (cross-transport auto-download race)
Re-queue attachment auto-downloads when the chat message arrives, since
file-announce (WebRTC) can beat chat-message (websocket) and the announce-time
pass gives up on an unknown room. Gate stalled-download resets on chunk-progress
staleness so an active transfer is never cancelled mid-stream, which deadlocked
the retry against the sender's active-transfer dedupe.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 21:26:59 +02:00
myxeliumandCursor 0078c320a5 fix: Bug - Sending files and attachment issues
Normalize attachment MIME types from filenames, hydrate playable media and
gallery tiles from disk without redundant peer requests, reset stalled partial
downloads, and improve gallery retry/hydration UX across chat and DMs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-14 13:30:13 +02:00
myxeliumandCursor b13f71d2d3 fix: Bug - Sending files and attachment issues (gallery load and speed)
Route small images through in-memory receive instead of serialized disk
chunk-acks, and improve gallery hydration for local copies and pending
downloads so thumbnails display without minutes-long progress stalls.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-14 13:19:12 +02:00
myxeliumandCursor fa45052432 fix: Bug - Sending files and attachment issues
Hydrate playable media after disk receive, relay file-announce to sibling
devices via account_sync, bind DM attachments to pre-allocated message ids,
and improve gallery retry/cancel UX with bounded parallel auto-downloads.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-14 13:05:23 +02:00
170 changed files with 6258 additions and 438 deletions
+15 -2
View File
@@ -9,14 +9,27 @@ It must stay accurate as new features are introduced, renamed, merged, or remove
## Feature list (alphabetical) ## Feature list (alphabetical)
- [App i18n](features/app-i18n.md) — `@ngx-translate/core` localization for the product client; English-only catalog today, same stack as the marketing website. - [App i18n](features/app-i18n.md) — `@ngx-translate/core` localization for the product client; English-only catalog today, same stack as the marketing website.
- [Attachments](features/attachments.md) — P2P chunked file transfer over WebRTC data channels with Electron/Capacitor disk persistence.
- [Authentication](features/authentication.md) — signaling-server session tokens, protected REST/WebSocket identity, and client bearer storage. - [Authentication](features/authentication.md) — signaling-server session tokens, protected REST/WebSocket identity, and client bearer storage.
- [Custom Emoji](features/custom-emoji.md) — peer-synced user-created emoji assets, chat reaction shortcuts, and composer emoji insertion. - [Custom Emoji](features/custom-emoji.md) — peer-synced user-created emoji assets, chat reaction shortcuts, and composer emoji insertion.
- [Desktop Local API](features/desktop-local-api.md) — Electron localhost HTTP read API, auth proxy, and offline Docusaurus docs.
- [Direct Messaging](features/direct-messaging.md) — index entry; full contract in [Messaging](features/messaging.md).
- [Game Activity](features/game-activity.md) — RAWG game matching, Electron process detection, and P2P now-playing sync.
- [Invites & Join Requests](features/invites-join-requests.md) — invite links, HTML landing pages, and moderated join approval.
- [Klipy GIFs](features/klipy-gifs.md) — server-proxied GIF search for chat and DM composers.
- [Link Preview & Media Proxy](features/link-preview-media-proxy.md) — SSRF-guarded link unfurling and image proxy on the signaling server.
- [Message Integrity](features/message-integrity.md) — signed P2P message revision chains, inventory `headHash` convergence, and Ed25519 signing-key registration on the signaling server. - [Message Integrity](features/message-integrity.md) — signed P2P message revision chains, inventory `headHash` convergence, and Ed25519 signing-key registration on the signaling server.
- [Messaging](features/messaging.md) — server-channel chat, direct messages, inventory sync, and DM delivery state machine.
- [Mobile Capacitor](features/mobile-capacitor.md) — Capacitor native shell, mobile infrastructure facades, and phone-specific call/chat/media integrations. - [Mobile Capacitor](features/mobile-capacitor.md) — Capacitor native shell, mobile infrastructure facades, and phone-specific call/chat/media integrations.
- [Server Discovery](features/server-discovery.md) — featured/trending public-server REST endpoints (server) consumed by the `/dashboard` and `/servers` client pages. - [Plugins](features/plugins.md) — client plugin runtime, server metadata API, Electron plugin data, and P2P message bus.
- [Push Notifications](features/push-notifications.md) — FCM/APNs device tokens on the server and Capacitor registration.
- [Server Directory](features/server-directory.md) — multi-endpoint catalog, REST CRUD/join/moderation, and room signal affinity.
- [Server Discovery](features/server-discovery.md) — featured/trending public-server REST endpoints consumed by `/dashboard` and `/servers`.
- [Signaling](features/signaling.md) — canonical WebSocket envelope catalog, ordering invariants, and relay rules.
- [Signal Server Tag](features/signal-server-tag.md) — configurable signal-server display tag shown on profile cards for a user's registration server. - [Signal Server Tag](features/signal-server-tag.md) — configurable signal-server display tag shown on profile cards for a user's registration server.
- [Voice & WebRTC](features/voice-webrtc.md) — voice/camera/screen-share WebRTC with signaling relay and multi-device ownership.
The product client already documents its bounded contexts at `toju-app/src/app/domains/<name>/README.md` (Access Control, Attachment, Authentication, Chat, Direct Call, Direct Message, Experimental Media, Game Activity, Notifications, Plugins, Profile Avatar, Screen Share, Server Directory, Theme, Voice Connection, Voice Session). Those domain READMEs cover internal product-client behavior. The product client also documents its bounded contexts at `toju-app/src/app/domains/<name>/README.md` (Access Control, Attachment, Authentication, Chat, Custom Emoji, Direct Call, Direct Message, Experimental Media, Game Activity, Notifications, Plugins, Profile Avatar, Screen Share, Server Directory, Theme, Voice Connection, Voice Session). Those domain READMEs cover internal product-client behavior.
`agents-docs/features/<slug>.md` is for **cross-context** contracts and feature areas that span more than one subdomain — WebSocket envelopes, IPC channels, plugin manifests, end-to-end flows that touch client + server + Electron together. Add an entry here the first time you write one. `agents-docs/features/<slug>.md` is for **cross-context** contracts and feature areas that span more than one subdomain — WebSocket envelopes, IPC channels, plugin manifests, end-to-end flows that touch client + server + Electron together. Add an entry here the first time you write one.
+28
View File
@@ -25,6 +25,34 @@ Durable rules for AI agents working on this project. Read this file at session s
## Lessons ## Lessons
### Run `npm run i18n:sync` after editing any `public/i18n/catalog/*.json` file [i18n] [testing]
- **Trigger:** Added new `call.errors.*` keys to `toju-app/public/i18n/catalog/call.json` and used them in code; the full test run failed in `app-i18n-catalog.rules.spec.ts` with "Missing i18n keys" even though the keys existed in the catalog file.
- **Rule:** The runtime and the catalog spec read the merged `toju-app/public/i18n/en.json`, not the per-area `catalog/*.json` files — after any catalog edit, run `npm run i18n:sync` (root script, `tools/sync-app-i18n-catalog.mjs`) and commit the regenerated `en.json` alongside the catalog change.
- **Why:** without the sync the new strings silently fall back to raw keys at runtime and the catalog spec fails, but only in the full suite — targeted spec runs of the feature under change pass, so the failure surfaces late.
- **Example:** `npm run i18n:sync && npm run test` after adding `call.errors.microphonePermissionDenied` to `catalog/call.json`.
### Match direct-call recipients against every local identity alias, exactly like DMs already do [direct-call] [identity]
- **Trigger:** "User receiving direct call doesn't get notified" — a caller who met the callee through a room on the caller's signal server addressed the ring by the callee's *provisioned actor id*; `handleIncomingCallEvent` admitted only `payload.participantIds.includes(oderId || id)`, so the ring was silently dropped, the caller sat "In Voice", and the callee saw nothing. DMs had the identical bug fixed earlier (`baa350e`), but the fix stopped at `DirectMessageService` and never reached `DirectCallService`.
- **Rule:** every self check on a cross-user event (admission, sender-echo filter, remote-participant filtering, DM-header peer lookup) must span all local aliases — home id, entity id, peer id, plus each `SignalServerCredentialStoreService.listValidCredentials()` actor id — and incoming aliases must be normalized onto the canonical local id before session state is keyed (`normalizeDirectCallPayloadSelfAliases`).
- **Why:** the failure only reproduces when caller and callee have different home signal servers, which no same-server e2e covers; and when one identity-alias bug is fixed in a domain, grep for the same `=== currentUserId` pattern in sibling domains that share the transport — the direct-call domain reused `PeerDeliveryService` but kept the naive check for another month.
- **Example:** `direct-call-participant-identity.rules.ts#directCallPayloadIncludesAnyId` / `normalizeDirectCallPayloadSelfAliases`; regression e2e `e2e/tests/voice/dm-header-call-ring.spec.ts` registers Bob on a secondary signal server, meets in a primary-signal room, and asserts the DM-header call rings Bob's incoming-call modal (fails on old code, passes after).
### Decide attachment receive admission once at request time; never re-gate size in the chunk handler [attachments]
- **Trigger:** "Sending files between users doesn't really work" — a browser user clicked Request on a 1050 MB generic file, the request gate (`canReceiveAttachment`) admitted it for in-memory receive, the sender streamed chunks, but `handleFileChunk` still had a leftover hard `size > MAX_AUTO_SAVE_SIZE_BYTES` rejection on the in-memory path, so every chunk was dropped, no ack was ever sent, the sender's `waitForAck` timed out, and the GUI never changed.
- **Rule:** `canReceiveAttachment` (request time) is the single admission decision; the chunk handler may only route between disk-streaming and in-memory assembly — any stricter size check there silently drops chunks the request gate already admitted.
- **Why:** the failure is invisible in logs-from-the-outside: the sender's per-chunk sends look like a working transfer ("packages with size 32kb") until the ack timeout, and the receiver sets `requestError` only into memory that a re-request immediately clears — the user just sees a dead Request button.
- **Example:** removed the `MAX_AUTO_SAVE_SIZE_BYTES` guard in `attachment-transfer.service.ts#handleFileChunk`; regression e2e `e2e/tests/chat/large-generic-file-transfer.spec.ts` sends an 11 MB `.bin` between two browser clients and asserts Request → progress → Download (fails on the old code, passes after).
### Re-queue attachment auto-downloads on every message/room binding event; never trust one transport's ordering [attachments] [realtime]
- **Trigger:** cross-user attachment sync e2e (`chat-message-features.spec.ts`) flaked ~50%: `file-announce` (WebRTC data channel) beat `chat-message` (signaling websocket) to the receiver, so the announce-time auto-download resolved `roomId=null`, silently gave up, and nothing ever retried — the receiver showed "Waiting for image source..." forever. A related bug: the stalled-download reset keyed only on "receivedBytes>0 && no pending request", but the pending-request marker is deleted on the *first* chunk, so any auto-download pass during an active transfer cancelled it mid-stream and the retry deadlocked against the sender's active-transfer dedupe.
- **Rule:** events that complete the `messageId -> roomId` binding (`chat-message` in `messages-incoming.handlers.ts`) must call `queueAutoDownloadsForMessage` again — never assume `file-announce` arrives after the message, they ride different transports; and stall detection must gate on chunk-progress staleness (`lastUpdateMs` older than `ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS`), never on the absence of a pending-request marker alone.
- **Why:** both halves fail silently (no error, no requestError set), so the UI just sits at 0 bytes; the flake is timing-dependent and invisible in single-client tests — only the two-client e2e with `--repeat-each` exposed it deterministically enough to fix.
- **Example:** `handleChatMessage` now calls `attachments.queueAutoDownloadsForMessage(message.id)` after `rememberMessageRoom`; `shouldResetStalledAttachmentDownload(attachment, hasPendingRequest, nowMs)` in `attachment-autodownload.rules.ts`. Verified with `npx playwright test -g "syncs image and file attachments|syncs multi-chunk" --repeat-each=4` (8/8 after, ~50% before).
### Scope per-user UI state by user id, not by the client database [persistence] [multi-user] [custom-emoji] ### Scope per-user UI state by user id, not by the client database [persistence] [multi-user] [custom-emoji]
- **Trigger:** custom emoji "saved library" membership was a single `savedByUser` flag on the shared emoji row plus a long-lived singleton (`CustomEmojiService`) that merged state across logins — so a second account on the same client (and the Electron shared SQLite DB) inherited the first user's picker. - **Trigger:** custom emoji "saved library" membership was a single `savedByUser` flag on the shared emoji row plus a long-lived singleton (`CustomEmojiService`) that merged state across logins — so a second account on the same client (and the Electron shared SQLite DB) inherited the first user's picker.
+18
View File
@@ -1,7 +1,14 @@
# App i18n # App i18n
> **Status:** Active
> **Last updated:** 2026-07-05
Client-side UI string localization for the product client (`toju-app`), using the same `@ngx-translate/core` stack as the marketing website. Client-side UI string localization for the product client (`toju-app`), using the same `@ngx-translate/core` stack as the marketing website.
## Migration status
Only **English** ships today (`SUPPORTED_APP_LOCALES = ['en']`). The catalog workflow and `translate` pipe are in place, but many components still use hardcoded strings — new user-visible copy should use i18n keys; migrate adjacent strings when touching a component. There is no locale preference UI yet.
## Responsibilities ## Responsibilities
- Bundle locale JSON under `toju-app/public/i18n/`. - Bundle locale JSON under `toju-app/public/i18n/`.
@@ -60,3 +67,14 @@ The sync script also extracts `theme.registry.*` labels/descriptions from `theme
- `toju-app/src/app/core/i18n/app-i18n.rules.spec.ts` - `toju-app/src/app/core/i18n/app-i18n.rules.spec.ts`
- `toju-app/src/app/core/i18n/app-i18n.service.spec.ts` - `toju-app/src/app/core/i18n/app-i18n.service.spec.ts`
- `toju-app/src/app/core/i18n/app-i18n.testing.ts``provideAppI18nForTests()` / `initializeAppI18nForTests()` for Vitest injectors - `toju-app/src/app/core/i18n/app-i18n.testing.ts``provideAppI18nForTests()` / `initializeAppI18nForTests()` for Vitest injectors
## Related
- `toju-app/AGENTS.md` — i18n usage rules for agents
- Marketing site i18n is separate: `website/public/i18n/`
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Documented partial migration status and locale UI gap |
+125
View File
@@ -0,0 +1,125 @@
# Attachments
> **Area:** attachments
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Attachments move file bytes peer-to-peer over the WebRTC ordered data channel using a announce → request → chunk protocol. Chat and DMs attach metadata to messages; the signaling server does not store or relay file payloads. Sibling devices learn attachment **metadata** via `account_sync` `chat-sync-batch` but must still download bytes from a peer that has them.
Domain internals: [`toju-app/src/app/domains/attachment/README.md`](../../toju-app/src/app/domains/attachment/README.md).
## Responsibilities
- Chunked P2P transfer with flow control and cancel semantics.
- Auto-download when policy allows; disk streaming on Electron/Capacitor.
- Ownership vs "shared from your device" UI rules.
- Persist attachment rows + filesystem paths on desktop/mobile.
This area does **not** own:
- Message envelopes or delivery states → [messaging.md](messaging.md).
- WebRTC negotiation → [voice-webrtc.md](voice-webrtc.md).
## Key concepts
- **Announce** — sender advertises `fileId`, name, size, mime without sending bytes.
- **Mirror host** — peer that holds a complete copy and can serve chunks.
- **Buffered send** — waits for data-channel back-pressure (4 MB high / 1 MB low water marks on chat channel).
---
## P2P protocol
| type | Purpose |
|------|---------|
| `file-announce` | Metadata only |
| `file-request` | Receiver starts download |
| `file-chunk` | Base64 chunk (`index`, `total`, `data`) |
| `file-chunk-ack` | Per-chunk flow control |
| `file-cancel` | Abort in flight |
| `file-not-found` | Host lacks bytes |
**Chunk size:** `FILE_CHUNK_SIZE_BYTES` = **64 KB** (`attachment-transfer.constants.ts`).
**Electron send path:** reads one chunk at a time from disk via IPC (`append-file-bytes` / read chunk) to avoid loading whole files into renderer memory.
---
## Persistence
| Runtime | Metadata | Bytes |
|---------|----------|-------|
| Browser | In-memory / optional save | Below **10 MB** auto-save cap (`MAX_AUTO_SAVE_SIZE_BYTES`) |
| Electron | SQLite `attachments` + CQRS | `user/<username>/…` via `AttachmentStorageService` / IPC |
| Capacitor | SQLite | App-private attachment directory — [mobile-capacitor.md](mobile-capacitor.md) |
---
## Download / export to user location
`AttachmentDownloadService.downloadToUserLocation` picks the runtime-appropriate export path:
| Runtime | Behavior |
|---------|----------|
| Electron | `saveExistingFileAs` (disk-backed) or `saveFileAs` (blob) native save dialog |
| Browser | Anchor `download` click on the object URL |
| Capacitor | `CapacitorAttachmentExportService.exportToDevice`: copies the disk file from `Directory.Data` into `Directory.Documents` (or fetches the object URL and writes base64) using `buildAttachmentExportFileName` (timestamp suffix so exports never collide — Android 11+ rejects overwrites of files the app did not create). Anchor downloads do nothing in the Android WebView. |
## Multi-device
`chat-sync-batch` in `account_sync` carries an `attachments` map (local paths stripped). Sibling devices discover files exist; P2P `file-request` still required for bytes.
---
## Business rules and invariants
- Transfers are between connected peers only (no server CDN).
- Receive strategy is decided once at request time by `canReceiveAttachment` (`attachment.logic.ts`): ≤ 10 MB assembles in memory everywhere; > 10 MB streams to disk on Electron/Capacitor, assembles in memory on the browser up to its 50 MB persist cap, and is rejected with a visible `fileTooLarge` error beyond that. `handleFileChunk` must accept whatever the request gate admitted — a stricter chunk-time size cap silently drops chunks and stalls the transfer.
- Visibility-based blob lifecycle on desktop: revoke `blob:` URLs when messages scroll off-screen if disk can rehydrate.
- Display-blob memory invariants (added 2026-07-14, RAM investigation):
- Inline hydration (`chat-message-item` effect) only runs for messages that are visible or within the `IntersectionObserver` root margin — gated by `attachment-hydration-visibility.rules.ts`. Off-screen rows never load blobs.
- Disk-hydrated blobs are **not** duplicated into `AttachmentRuntimeStore.originalFiles`; peer requests are served from the disk path (`streamRequestedFile` prefers `resolveExistingPath`). `originalFiles` only holds uploads/downloads that have no disk copy yet.
- `revokeAttachmentDisplayBlob` also drops the `originalFiles` entry when `savedPath` exists, so revocation actually frees the bytes.
- Message rows always revoke their display blobs on destroy (pins are respected), not only when they were visible.
- Room switch sweeps display blobs of all other rooms (`releaseDisplayBlobsForInactiveRooms`, driven by `collectMessageIdsForInactiveRoomBlobRelease`). Messages with unknown room mapping are left alone.
- "Shared from your device" badge only when bytes are local to the viewing user.
---
## Technical implementation
- Facade: `AttachmentFacade``AttachmentManagerService`
- Protocol: `AttachmentTransferService` + `AttachmentTransferTransportService`
- Electron IPC: `read-file-chunk`, `append-file-bytes`, `write-file`, `delete-file`, etc.
---
## Testing
- Domain logic specs under `attachment/`
- E2E: `e2e/tests/chat/chat-message-features.spec.ts`, `local-attachment-persistence.spec.ts`, `multi-device-attachment-sharing.spec.ts`, `large-generic-file-transfer.spec.ts` (browser receiver, generic file above the 10 MB auto-save cap)
---
## Security considerations
- No server-side virus scanning; peers trust senders they are connected to.
- Files stay in user data directories (Electron path jail).
---
## Related features
- [messaging.md](messaging.md) — message + attachment metadata coupling
- [authentication.md](authentication.md) — `account_sync` batches
- [mobile-capacitor.md](mobile-capacitor.md) — mobile storage
## Changelog
| Date | Change |
|------|--------|
| 2026-07-14 | Blob-memory invariants: visibility-gated hydration, no `originalFiles` duplication for disk-backed blobs, revoke-on-destroy, inactive-room blob sweep |
| 2026-07-13 | Capacitor download/export to public `Documents` via `CapacitorAttachmentExportService` |
| 2026-07-05 | Expanded to full contract style |
+100 -10
View File
@@ -1,6 +1,14 @@
# Authentication # Authentication
Session-token authentication for the signaling server and product client. > **Area:** authentication
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Session-token authentication binds REST mutations and WebSocket `identify` to a user identity on each signaling server. The product client may hold **multiple** server credentials (home + foreign auto-provisioned accounts) while keeping one local user profile. Multi-device tabs share one identity via separate `clientInstanceId` values and `account_sync` relay.
WebSocket details: [signaling.md](signaling.md). Local API tokens: [desktop-local-api.md](desktop-local-api.md).
## Trust boundaries ## Trust boundaries
@@ -8,8 +16,8 @@ Session-token authentication for the signaling server and product client.
|---|---|---| |---|---|---|
| Signaling server REST (mutations) | `Authorization: Bearer <token>` | Actor user IDs in request bodies are ignored; server derives `authUserId` from the token | | Signaling server REST (mutations) | `Authorization: Bearer <token>` | Actor user IDs in request bodies are ignored; server derives `authUserId` from the token |
| Signaling server REST (discovery) | None | `GET /api/servers`, featured/trending/search remain public | | Signaling server REST (discovery) | None | `GET /api/servers`, featured/trending/search remain public |
| Signaling server WebSocket | `identify.token` | Connections must identify before any other message type | | Signaling server WebSocket | `identify.token` | Connections must identify before any other message type — see [signaling.md](signaling.md) |
| Electron Local API | Separate in-memory bearer tokens | Proxies login to allowed signaling servers only | | Electron Local API | Separate in-memory bearer tokens | Proxies login to allowed signaling servers only — see [desktop-local-api.md](desktop-local-api.md) |
| Product client local DB | OS user account | SQLite and attachments are plaintext at rest | | Product client local DB | OS user account | SQLite and attachments are plaintext at rest |
## Client logout ## Client logout
@@ -36,13 +44,81 @@ Session-token authentication for the signaling server and product client.
## Protected REST routes ## Protected REST routes
Require `Authorization: Bearer`: Require `Authorization: Bearer` (`requireAuth` middleware). Public routes are listed for contrast.
- `PUT/POST/DELETE` under `/api/servers/*` (except public `GET`) ### Users (`/api/users`)
- `PUT /api/requests/:id`
- Plugin-support mutations under `/api/servers/:serverId/plugins/*` | Method | Path | Auth |
- `/api/users/device-tokens/*` |--------|------|------|
- `POST /api/users/logout` | POST | `/register` | Public |
| POST | `/login` | Public |
| GET | `/:id/signing-public-key` | Public |
| PUT | `/me/signing-key` | Bearer |
| POST | `/logout` | Bearer |
### Device tokens (`/api/users/device-tokens`)
All routes require bearer; `userId` in body or path must equal `authUserId` (`403` otherwise).
| Method | Path |
|--------|------|
| POST | `/` |
| GET | `/:userId` |
| POST | `/:userId/dispatch` |
### Servers (`/api/servers`)
| Method | Path | Auth |
|--------|------|------|
| GET | `/`, `/featured`, `/trending`, `/:id` | Public |
| POST | `/` | Bearer |
| PUT | `/:id` | Bearer |
| DELETE | `/:id` | Bearer |
| POST | `/:id/join` | Bearer |
| POST | `/:id/leave` | Bearer |
| POST | `/:id/heartbeat` | Bearer |
| POST | `/:id/invites` | Bearer |
| GET | `/:id/requests` | Bearer |
| POST | `/:id/moderation/kick` | Bearer |
| POST | `/:id/moderation/ban` | Bearer |
| POST | `/:id/moderation/unban` | Bearer |
### Join requests (`/api/requests`)
| Method | Path | Auth |
|--------|------|------|
| PUT | `/:id` | Bearer (approve/deny) |
### Plugin support (`/api/servers/:serverId/plugins`)
| Method | Path | Auth |
|--------|------|------|
| GET | `/` | Public (metadata read) |
| PUT | `/:pluginId/requirement` | Bearer |
| DELETE | `/:pluginId/requirement` | Bearer |
| PUT | `/:pluginId/events/:eventName` | Bearer |
| DELETE | `/:pluginId/events/:eventName` | Bearer |
| GET/PUT/DELETE | `/:pluginId/data/*` | **410 Gone** (server plugin data disabled) |
### Public (no bearer)
- `GET /api/health`, `/api/time`
- `GET /api/link-metadata`, `/api/image-proxy`
- `GET /api/klipy/config`, `/api/klipy/gifs`
- `POST /api/games/match`
- `GET /api/invites/:id`
- `GET /invite/:id` (HTML invite page)
- OpenAPI docs routes (`/api/openapi.json`, `/api/docs`, …) — gated by server config, not session auth
Full server-directory semantics: [server-directory.md](server-directory.md).
## Message signing key registration
Ed25519 signing keys for [message-integrity.md](message-integrity.md) register via `PUT /api/users/me/signing-key` with `{ publicKeyJwk }`.
- **When registered:** `AuthenticationService` calls `MessageSigningService.registerSigningPublicKeyIfNeeded()` after successful **home** `POST /login` and `POST /register` only (`authentication.service.ts`).
- **Scope:** registration uses the **active** signaling server's API base (`ServerDirectoryFacade.activeServer()`). Foreign-server auto-provision (`authorizeSignalServer` / `SignalServerProvisionerService`) does **not** currently call signing-key registration — message integrity on foreign servers depends on a later login path or manual registration when that server becomes active.
- **Storage:** private key in `localStorage` (`metoyou.messageSigningKeyPair`); public key directory on server SQLite only.
## WebSocket identify contract ## WebSocket identify contract
@@ -119,7 +195,7 @@ A per-install **provision secret** enables silent account creation on newly adde
| Foreign login/register | `authorizeSignalServer` | Upserts credential for that URL only; home session unchanged | | Foreign login/register | `authorizeSignalServer` | Upserts credential for that URL only; home session unchanged |
| Auto-provision | `SignalServerProvisionerService` | Registers or logs in on foreign server using provision secret; on username collision tries suffixed username (`alice-<homeUserIdPrefix>`) and prefixes the display name with `#<homeUserIdPrefix> #<signalServerTag>` so same-name accounts stay distinguishable | | Auto-provision | `SignalServerProvisionerService` | Registers or logs in on foreign server using provision secret; on username collision tries suffixed username (`alice-<homeUserIdPrefix>`) and prefixes the display name with `#<homeUserIdPrefix> #<signalServerTag>` so same-name accounts stay distinguishable |
| Create/join on foreign server | `RoomsEffects.createRoom$`, invite/join flows | `ensureCredentialForServerUrl` provisions (or reuses) the per-server session token first; REST/WebSocket calls use the **actor user id** for that signal URL, not the home registration id | | Create/join on foreign server | `RoomsEffects.createRoom$`, invite/join flows | `ensureCredentialForServerUrl` provisions (or reuses) the per-server session token first; REST/WebSocket calls use the **actor user id** for that signal URL, not the home registration id |
| Foreign auth failure | `signalServerAuthFailed` | Clears that URL's credential and re-provisions when home token is still valid; global logout only when home server rejects auth | | Foreign auth failure | `signalServerAuthFailed` | `auth_required` (message raced ahead of identify) re-identifies or is ignored while a valid local credential exists; `auth_error` (token rejected) clears that URL's credential and re-provisions on foreign servers or expires the home session |
Unreachable or offline signal servers must **not** open `/login?mode=authorize`. `ensureEndpointVersionCompatibility()` treats only `online` endpoints as connectable, and `ensureCredentialForServerUrl()` skips authorize navigation when health checks report the server offline (or provisioning fails over the network). Unreachable or offline signal servers must **not** open `/login?mode=authorize`. `ensureEndpointVersionCompatibility()` treats only `online` endpoints as connectable, and `ensureCredentialForServerUrl()` skips authorize navigation when health checks report the server offline (or provisioning fails over the network).
@@ -135,3 +211,17 @@ Startup routing for signed-out visitors is decided by `resolveUnauthenticatedSta
- CORS allowlist: optional `corsAllowlist` in `server/data/variables.json` or `CORS_ALLOWLIST` env (comma-separated). Empty allowlist keeps permissive CORS for local development. - CORS allowlist: optional `corsAllowlist` in `server/data/variables.json` or `CORS_ALLOWLIST` env (comma-separated). Empty allowlist keeps permissive CORS for local development.
- Push-token routes require bearer auth and user-id match. - Push-token routes require bearer auth and user-id match.
- RTC relay: direct-message/direct-call types always relay; server-icon types require shared server membership; WebRTC offer/answer/ice remain open for cross-server DM WebRTC. - RTC relay: direct-message/direct-call types always relay; server-icon types require shared server membership; WebRTC offer/answer/ice remain open for cross-server DM WebRTC.
## Related
- [signaling.md](signaling.md) — WebSocket `identify`, `account_sync`, ordering invariants
- [desktop-local-api.md](desktop-local-api.md) — Electron Local API bearer tokens
- [message-integrity.md](message-integrity.md) — signing keys and revision chains
- [server-directory.md](server-directory.md) — protected server REST mutations
## Changelog
| Date | Change |
|------|--------|
| 2026-07-14 | Distinguish `auth_required` vs `auth_error` on `signalServerAuthFailed`; stop false home-session expiry; leave `/login` when in-memory user still authenticated |
| 2026-07-05 | Expanded protected-route inventory; clarified signing-key registration scope; cross-links |
+101 -40
View File
@@ -2,64 +2,125 @@
> **Area:** custom-emoji > **Area:** custom-emoji
> **Status:** Active > **Status:** Active
> **Last updated:** 2026-06-05 > **Last updated:** 2026-07-05
## Overview ## Overview
Custom emoji lets users upload small image emoji, use them in chat messages and reactions, and sync emoji assets needed for rendering to connected peers over the existing data-channel mesh. Custom emoji lets users upload small image emoji, use them in chat messages and reactions, and sync the image bytes to connected peers over the WebRTC data channel (and to sibling devices via `account_sync`). The signaling server never stores emoji assets.
Internal UI and NgRx wiring: [`toju-app/src/app/domains/custom-emoji/README.md`](../../toju-app/src/app/domains/custom-emoji/README.md). Chat composer integration: [`toju-app/src/app/domains/chat/README.md`](../../toju-app/src/app/domains/chat/README.md).
## Responsibilities ## Responsibilities
- Own custom emoji asset validation, local persistence, user-saved library membership, shortcut ranking, and peer-to-peer asset sync. - Validate uploads (size, MIME), persist image assets locally, and track per-user **saved library** membership.
- Expose a shared picker consumed by chat message reactions and the chat composer. - Rank shortcuts by local usage (not synced across devices).
- Keep usage ranking local to the current user; usage counts are not synced. - Sync assets P2P (`custom-emoji-*` envelopes) and proactively push referenced emoji when sending messages.
- Does not store custom emoji on the signaling server. - Relay the same envelopes on `account_sync` for multi-device library convergence.
- Expose `CustomEmojiPickerComponent` for composer and reactions.
## Key Concepts This area does **not** own:
- **Custom emoji asset**: A user-created image stored as a data URL with id, name, mime, size, hash, creator, timestamps, and optional saved-library membership. - Message send/edit transport → [messaging.md](messaging.md).
- **Known custom emoji**: A synced asset available for message rendering and forwarding, but not shown in the current user's picker unless saved. - Profile avatar bytes → `toju-app/src/app/domains/profile-avatar/README.md`.
- **Saved custom emoji**: A known asset the current user added to their library; saved emoji appear in the picker and shortcut ranking. Library membership is **user-bound, not client-bound** — it is tracked per signed-in user (keyed by user id), so a second account on the same device never inherits the first account's library. - Server-side storage (none).
- **Emoji shortcut row**: The seven most-used emoji entries for the current user plus an eighth control that opens the full selector.
- **Custom emoji token**: The stable message/reaction representation `:emoji[id](name)`, resolved locally to the synced image asset when rendering.
- **Composer emoji alias**: The readable inline draft representation `:name:`. The composer rewrites known aliases to stable custom emoji tokens only when sending.
## Peer Envelope Contract ## Key concepts
Custom emoji uses `ChatEvent` data-channel envelopes: - **Custom emoji asset** — image with `id`, `name`, `mime`, `size`, `hash`, `creatorUserId`, `dataUrl` (or reconstructed from chunks).
- **Known emoji** — synced for rendering; not necessarily in the picker.
- **Saved emoji** — in the active user's library (`metoyou_custom_emoji_saved:<userId>`); shown in picker and shortcut row.
- **Token** — stable wire form `:emoji[id](name)` in message/reaction bodies.
- **Composer alias** — draft form `:name:` rewritten to a token on send when the name is known.
- **Shortcut row** — seven most-used saved entries plus opener for full picker.
- `custom-emoji-summary`: `{ customEmojiSummaries: [{ id, hash, updatedAt }] }` ---
- `custom-emoji-request`: `{ ids: string[] }`
- `custom-emoji-full`: `{ customEmojiTransfer: Omit<CustomEmoji, 'dataUrl'>, total: number }`
- `custom-emoji-chunk`: `{ customEmojiId, index, total, data }`
When a peer connects, each side sends a summary of known assets. The receiver requests missing or stale emoji by id, and the owner replies with a small manifest followed by bounded base64 chunks using buffered peer sends. Creating a new emoji also streams that manifest and chunk sequence to every currently connected peer. Outgoing room chat messages, edits, reactions, and direct messages proactively push every referenced custom emoji asset to connected peers in parallel with the message event, so receivers do not wait for a request round-trip. Small assets that fit under `CUSTOM_EMOJI_INLINE_MAX_JSON_BYTES` travel inline in one `custom-emoji-full` event; larger assets use manifest plus chunks. Incoming chat messages and chat-sync batches still scan for `:emoji[id](name)` tokens and request any missing assets from the sender as a repair path. Full inline `customEmoji` payloads remain accepted for backward compatibility. ## Peer envelope contract (P2P)
## Business Rules | type | Payload |
|------|---------|
| `custom-emoji-summary` | `{ customEmojiSummaries: [{ id, hash, updatedAt }] }` |
| `custom-emoji-request` | `{ ids: string[] }` |
| `custom-emoji-full` | manifest (`customEmojiTransfer`) ± inline bytes |
| `custom-emoji-chunk` | `{ customEmojiId, index, total, data }` base64 |
- Uploads are capped at 1 MB. **Handshake:** on peer connect both sides send summaries; receiver requests stale/missing ids; owner sends manifest then chunked payloads via buffered sends.
- Accepted image types match profile avatars: WebP, GIF, JPG, and JPEG.
- Local shortcut ranking is keyed by the active user and includes Unicode emoji plus saved custom emoji only.
- Saved-library membership is bound to the user, not the client: `CustomEmojiService` tracks the set of saved emoji ids per user id in `localStorage` (`metoyou_custom_emoji_saved:<userId>`, mirroring the per-user usage ranking). The picker shows only emoji in the active user's saved set, so signing in as a different account on the same client never exposes the previous account's library. On first load after this change the set is seeded from legacy `savedByUser` rows the user actually created (`creatorUserId === userId`), so creators keep their library while other local accounts stay empty.
- Message rendering reserves inline emoji space with a transparent placeholder image while a referenced custom emoji asset is not yet available; deferred markdown placeholders rewrite tokens to readable `:name:` aliases so raw `:emoji[id](name)` text never flashes in chat.
- Seen custom emoji are not added to the picker automatically; right-click a rendered custom emoji in chat or on a custom emoji reaction and choose **Add to emoji library** from the app context menu (`NativeContextMenuComponent`).
- Saved custom emoji can be removed from the picker library by right-clicking them inside the emoji picker and choosing **Remove from emoji library**; the asset stays available for rendering messages that already reference it.
- Emoji hosts are marked with `data-custom-emoji` / `data-custom-emoji-library` plus `data-custom-emoji-id` so the global context menu can distinguish them from regular images and suppress the default **Copy Image** action.
- The full emoji picker includes a search field that filters built-in Unicode emoji by common terms and saved custom emoji by name.
- Custom emoji data-channel chunks are capped below typical SCTP message limits; back-pressure alone is not enough because a single oversized send can fire `RTCDataChannel.onerror`.
- Completed transfers are persisted only when the reconstructed data URL matches the manifest size and hash; corrupt local rows are dropped before summaries are advertised.
## Data Access **Proactive push:** outgoing chat/DM messages scan for tokens and push assets to connected peers in parallel with the message event.
- Browser runtime stores custom emoji image assets in IndexedDB store `customEmojis` (per-user database scope). **Inline threshold:** assets ≤ `CUSTOM_EMOJI_INLINE_MAX_JSON_BYTES` (48 KiB) ship in one `custom-emoji-full`; larger assets use manifest + chunks.
- Electron runtime stores custom emoji image assets in SQLite table `custom_emojis`, created by migration `1000000000011-AddCustomEmojis` (a single shared desktop database).
- Renderer access goes through `DatabaseService` methods `saveCustomEmoji`, `getCustomEmojis`, and `deleteCustomEmoji`. These persist the image **assets** only; they are not scoped per user (the Electron table is shared across local accounts). Per-user **library membership** lives separately in `localStorage` (`metoyou_custom_emoji_saved:<userId>`), which is what keeps the picker user-bound even on a shared client database. **Repair path:** incoming messages and `chat-sync-batch` scan for tokens and request missing assets from the sender.
### Multi-device (`account_sync`)
Relayable types (`account-sync.rules.ts`): `custom-emoji-summary`, `custom-emoji-request`, `custom-emoji-full`, `custom-emoji-chunk`. See [signaling.md](signaling.md) and [authentication.md](authentication.md).
---
## Business rules and invariants
- Max upload **1 MB**; MIME: WebP, GIF, JPEG/JPG (same set as profile avatars).
- Library membership is **per user id**, not per device — second account on same machine does not inherit another user's saved set.
- Seeing an emoji in chat does **not** add it to the library; user must **Add to emoji library** from context menu.
- Remove from library hides picker entry but keeps asset for messages that already reference it.
- Chunks stay below SCTP-safe sizes; oversized single sends can trigger `RTCDataChannel.onerror` even when back-pressure is idle.
- Persist only when reconstructed `dataUrl` matches manifest **size and hash**; corrupt rows are dropped before advertising summaries.
- Placeholder rendering avoids flashing raw tokens while assets are in flight.
---
## Storage
| Runtime | Asset bytes | Library membership |
|---------|-------------|-------------------|
| Browser | IndexedDB `customEmojis` (per-user DB scope) | `localStorage` `metoyou_custom_emoji_saved:<userId>` |
| Electron | SQLite `custom_emojis` (shared desktop DB) | same localStorage key |
| Capacitor | SQLite `custom_emojis` in `metoyou__<userId>` | same localStorage key |
API: `DatabaseService.saveCustomEmoji` / `getCustomEmojis` / `deleteCustomEmoji`.
---
## Technical implementation
- Rules: `domains/custom-emoji/domain/custom-emoji.rules.ts`
- Service: `CustomEmojiService`; effects: `CustomEmojiSyncEffects`
- Picker: `feature/custom-emoji-picker/`
- Context menu: `data-custom-emoji` / `data-custom-emoji-library` attributes on rendered hosts
---
## Testing ## Testing
- Unit tests cover upload size validation, shortcut selection, picker search filtering, custom emoji token generation, data-channel chunk splitting, readable composer alias rewriting, transfer integrity, saved-library membership, and add/remove library context-menu actions. - `custom-emoji.rules.spec.ts`, `custom-emoji.service.spec.ts`, `custom-emoji-picker.component.spec.ts`
- `account-sync.rules.spec.ts` (relayable types)
- E2E: `e2e/tests/chat/custom-emoji-user-binding.spec.ts`
## Security Considerations ---
- Emoji payloads are image-only and size-limited before persistence or broadcast. ## Security considerations
- Assets sync only to already connected peers; the signaling server does not persist or proxy emoji images.
- Image-only, size-capped payloads before persist or broadcast.
- Assets reach only connected peers (or same-account devices via `account_sync`); server never proxies bytes.
---
## Known limitations
- Usage counts and shortcut ranking are **local only**.
- Electron asset table is **shared across OS users** on one desktop install; library keys remain per MetoYou user id.
---
## Related features
- [messaging.md](messaging.md) — tokens in message bodies, proactive push on send
- [signaling.md](signaling.md) — `account_sync`
- [mobile-capacitor.md](mobile-capacitor.md) — Capacitor SQLite path
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Restructured to match messaging doc style; fixed duplicate sections; Capacitor + account_sync |
+53
View File
@@ -0,0 +1,53 @@
# Desktop Local API
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Electron hosts an optional **localhost HTTP API** that exposes read-only access to the local SQLite database, proxies login to allowed signaling servers, and serves bundled Docusaurus documentation offline.
## Responsibilities
| Layer | Owns |
|-------|------|
| Electron `api/router.ts` | HTTP routes, bearer token store, CQRS query dispatch |
| Desktop settings | Enable/disable Local API, port, allowed signal servers |
| `docs-site` build | Static bundle mounted at `/docusaurus/*` |
## Trust boundary
Separate **in-memory bearer tokens** from signaling-server session tokens. Login via Local API issues a local token; read routes require `Authorization: Bearer`. See [authentication.md](authentication.md).
## Routes (summary)
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| GET | `/api/health` | No | Local API liveness |
| GET | `/api/openapi.json`, `/docs`, `/scalar/api-reference.js` | No | API docs (Scalar) |
| GET | `/docusaurus/*` | No | In-app documentation site |
| POST | `/api/auth/login` | No | Proxy to configured signaling server; returns local bearer |
| POST | `/api/auth/logout` | Bearer | Revoke local token |
| GET | `/api/profile` | Bearer | Current user profile |
| GET | `/api/rooms`, `/api/rooms/{roomId}`, `.../users`, `.../messages`, `.../bans` | Bearer | Read-only room data |
| GET | `/api/messages/{messageId}`, `.../reactions`, `.../attachments` | Bearer | Message graph |
| GET | `/api/users/{userId}`, `/api/attachments`, `/api/plugin-data` | Bearer | User + plugin data reads |
| GET | `/api/meta/{key}` | Bearer | Meta key lookup |
Database routes return **503** when SQLite is not initialised.
## IPC
- `get-local-api-status`, `open-local-api-docs`, `open-docusaurus-docs`
## Related
- [authentication.md](authentication.md) — trust table
- `electron/CONTEXT.md` — Local API vocabulary
- `docs-site/CONTEXT.md` — documentation bundle
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial Local API route catalog |
+29
View File
@@ -0,0 +1,29 @@
# Direct Messaging
> **Area:** messaging
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Direct messaging (1:1 and group PMs) is documented in full in **[messaging.md](messaging.md)** — transports, delivery state machine, sync protocol, storage, and security. This file remains as an index entry in [FEATURES.md](../FEATURES.md).
## Quick reference
- **Domain:** `toju-app/src/app/domains/direct-message/`
- **Entry points:** `DirectMessageService`, `PeerDeliveryService`, `FriendService`
- **Persistence:** `metoyou_direct_message_*` (per-user local storage)
- **P2P types:** `direct-message`, `direct-message-status`, `direct-message-mutation`, `direct-message-typing`, `direct-message-sync-request`, `direct-message-sync`
- **Calls:** `direct-call` shares `PeerDeliveryService` → [voice-webrtc.md](voice-webrtc.md)
## Related
- [messaging.md](messaging.md) — full cross-context contract
- [signaling.md](signaling.md) — WebSocket relay
- Domain README: [`toju-app/src/app/domains/direct-message/README.md`](../../toju-app/src/app/domains/direct-message/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Slimmed to index; comprehensive content moved to messaging.md |
+54
View File
@@ -0,0 +1,54 @@
# Game Activity
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
"Now playing" game detection: Electron foreground-window/process heuristics, RAWG metadata match via signaling server, and P2P `game-activity` broadcast to peers. Shown on profile cards and room sidebars.
## Responsibilities
| Layer | Owns |
|-------|------|
| `game-activity` domain | Scan loop, confidence scoring, P2P broadcast, user store updates |
| Electron IPC | `get-running-process-names`, `get-active-game-candidate` |
| Signaling server | `POST /api/games/match` (RAWG proxy + miss cache) |
| P2P | `game-activity` data-channel event |
## Server API
### `POST /api/games/match`
- **Auth:** Public
- **Body:** `{ processNames: string[], candidates?: { processName, score }[] }` (bounded list sizes)
- **Response:** `{ game: MatchedGame | null }` — RAWG-backed title, cover art, store links
Misses cached in server SQLite (`GameMatchMiss`) to limit API calls.
## Client detection
- Periodic scan (default 10 s, configurable 560 s in localStorage `metoyou_game_scan_interval_ms`).
- Ignores launcher/helper processes via `IGNORED_PROCESS_NAMES` and regex patterns.
- **Electron:** suppresses scan when MetoYou window is focused; prefers foreground-window candidate from `get-active-game-candidate`.
- **Browser/Capacitor:** no process scan — activity only from P2P peers.
## P2P event
```json
{ "type": "game-activity", "activity": { "game", "startedAt", "processName", ... } }
```
Peers merge into `User.gameActivity` in NgRx store.
## Related
- [signaling.md](signaling.md) — not WS-relayed
- [server-directory.md](server-directory.md) — API base URL for match endpoint
- Domain README: [`toju-app/src/app/domains/game-activity/README.md`](../../toju-app/src/app/domains/game-activity/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial cross-context game-activity contract |
@@ -0,0 +1,65 @@
# Invites & Join Requests
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Invite links and join-request approval let users join private or moderated chat-servers without public listing. Spans signaling **server** REST + HTML invite pages and the product **client** `server-directory` invite feature.
## Responsibilities
- Server: create time-limited invites, resolve invite metadata, record join requests, notify requesters on moderation decisions.
- Client: create/copy invite links, render invite landing UX, call join API with invite codes/passwords.
- It does NOT own: WebSocket room membership (`join_server` after REST join succeeds).
## Key concepts
- **Invite:** opaque id mapping to a server; may expire.
- **Join request:** pending membership when server requires approval.
- **request_update:** server-pushed WebSocket notification when a moderator approves/denies.
## REST API
### Invites
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| POST | `/api/servers/:id/invites` | Bearer | Create invite (moderator) |
| GET | `/api/invites/:id` | Public | Resolve invite metadata + server card |
| GET | `/invite/:id` | Public | HTML invite landing page (browser) |
### Join
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| POST | `/api/servers/:id/join` | Bearer | Join with password, invite id, or public access; may create join request |
### Join requests (moderation)
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| GET | `/api/servers/:id/requests` | Bearer (`manageServer`) | List pending requests |
| PUT | `/api/requests/:id` | Bearer (`manageServer`) | Approve or deny; body `{ status }` |
`PUT /api/requests/:id` validates optional `ownerId` matches authenticated user, checks `manageServer` permission, updates status, and sends `notifyUser(request.userId, { type: 'request_update', request })`.
## Client flow
1. Moderator creates invite via `ServerDirectoryFacade.createInvite()`.
2. Recipient opens `/invite/:id` or deep link; client resolves `GET /api/invites/:id`.
3. Authenticated user calls `POST /api/servers/:id/join` with invite payload.
4. On approval-required servers, user waits for `request_update` or polls requests list (moderator UI).
## Related
- [server-directory.md](server-directory.md) — join/leave REST
- [authentication.md](authentication.md) — bearer on mutations
- [signaling.md](signaling.md) — `join_server` after join
- Domain README: [`toju-app/src/app/domains/server-directory/README.md`](../../toju-app/src/app/domains/server-directory/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial cross-context invite/join-request contract |
+44
View File
@@ -0,0 +1,44 @@
# Klipy GIFs
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
GIF search in chat and DM composers via a **Klipy API proxy** on the signaling server. API keys stay server-side; clients call same-origin routes on the active signal server.
## Responsibilities
- Server: proxy/search Klipy API (`variables.json` `klipyApiKey`).
- Client `chat` domain: `KlipyService`, composer picker; DMs reuse the same integration.
## API
### `GET /api/klipy/config`
- **Auth:** Public
- **Response:** `{ enabled: boolean }``enabled` when server has a configured API key
### `GET /api/klipy/gifs`
- **Auth:** Public
- **Query:** `q` (search), `page`, `per_page` (default 24, max 50)
- **Response:** Normalised `{ gifs: [{ id, slug, title, url, previewUrl, width, height }], hasNext }`
- **Upstream:** `https://api.klipy.com/api/v1` with 8 s timeout
## Client behavior
- GIF picker visibility is resolved against the **current chat-server's** signal server (not a global offline endpoint) so KLIPY availability matches the room's backend.
- Selected GIFs send as markdown image messages; rendering uses [link-preview-media-proxy.md](link-preview-media-proxy.md) image proxy when needed.
## Related
- [server-directory.md](server-directory.md) — per-room signal server for config
- [direct-messaging.md](direct-messaging.md) — DM composer reuse
- Domain README: [`toju-app/src/app/domains/chat/README.md`](../../toju-app/src/app/domains/chat/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial Klipy proxy contract |
@@ -0,0 +1,46 @@
# Link Preview & Media Proxy
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
The signaling server fetches untrusted URLs on behalf of clients for **link embed previews** and **image proxying**, with SSRF guards. Chat and DM composers render embeds using these endpoints.
## Responsibilities
- Server: outbound fetch with host validation, caching, size limits.
- Client `chat` domain: request metadata when messages contain URLs; render cards in message list.
- It does NOT store embeds long-term on the server beyond in-memory cache.
## API
### `GET /api/link-metadata`
- **Auth:** Public
- **Query:** `url` (http/https)
- **Response:** `{ title?, description?, imageUrl?, siteName? }`
- **Guards:** `resolveAndValidateHost` + `safeFetch`; 8 s timeout; HTML capped at 512 KB; in-memory cache sized by `variables.json` link-preview config
### `GET /api/image-proxy`
- **Auth:** Public
- **Query:** `url` (http/https)
- **Response:** Raw image bytes (`Content-Type` from origin)
- **Limits:** image/* only; max 8 MB; 8 s timeout; SSRF validation
- **Cache:** `Cache-Control: public, max-age=3600`
## Client usage
Message markdown / link-embed pipeline calls link-metadata for unfurling; proxied images load through `/api/image-proxy` when direct fetch would fail (CORS, mixed content).
## Related
- [server-directory.md](server-directory.md) — requests use active server's API base
- Domain README: [`toju-app/src/app/domains/chat/README.md`](../../toju-app/src/app/domains/chat/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial link preview / image proxy contract |
+27 -3
View File
@@ -1,6 +1,14 @@
# Message Integrity # Message Integrity
Signed, append-only **message revisions** give P2P chat a verifiable history without central message storage. The materialized `Message` row in local SQLite/IDB is a cache; peers converge via inventory snapshots and revision events. > **Area:** messaging
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Signed, append-only **message revisions** give P2P chat a verifiable history without central message storage. The materialized `Message` row in local SQLite/IDB is a cache; peers converge via inventory snapshots (`revision`, `headHash`) and `message-revision` events.
Parent transport and sync context: [messaging.md](messaging.md).
## Responsibilities ## Responsibilities
@@ -15,7 +23,7 @@ Signed, append-only **message revisions** give P2P chat a verifiable history wit
| --- | --- | | --- | --- |
| Product client (`toju-app`) | Revision construction, merge, verification, P2P broadcast, local persistence | | Product client (`toju-app`) | Revision construction, merge, verification, P2P broadcast, local persistence |
| Signaling server (`server`) | `PUT /api/users/me/signing-key`, `GET /api/users/:id/signing-public-key` — key directory only, no message storage | | Signaling server (`server`) | `PUT /api/users/me/signing-key`, `GET /api/users/:id/signing-public-key` — key directory only, no message storage |
| Electron / mobile persistence | `revision` + `headHash` on message rows; revision audit log (IDB store / SQLite meta) | | Electron / mobile persistence | `revision` + `headHash` on message rows; revision audit log in IDB store (browser), SQLite `meta` table (Electron **and Capacitor** — keys `message-revision:<messageId>:<revision>`) |
Plugin API messages may emit unsigned revisions (`plugin-edit` / `plugin-delete`) when the actor is a synthetic plugin user. Plugin API messages may emit unsigned revisions (`plugin-edit` / `plugin-delete`) when the actor is a synthetic plugin user.
@@ -47,7 +55,23 @@ Plugin API messages may emit unsigned revisions (`plugin-edit` / `plugin-delete`
| `PUT` | `/api/users/me/signing-key` | Bearer | `{ publicKeyJwk }` — stores Ed25519 public JWK on the user row | | `PUT` | `/api/users/me/signing-key` | Bearer | `{ publicKeyJwk }` — stores Ed25519 public JWK on the user row |
| `GET` | `/api/users/:id/signing-public-key` | Public | `{ publicKeyJwk }` — used by peers to verify signatures | | `GET` | `/api/users/:id/signing-public-key` | Public | `{ publicKeyJwk }` — used by peers to verify signatures |
Registration runs automatically after login/register via `AuthenticationService`. Registration runs automatically after **home** login/register via `AuthenticationService` — see [authentication.md](authentication.md) for foreign-server scope.
## Multi-device relay (`account_sync`)
`message-revision` chat events are relayable to sibling connections via WebSocket `account_sync` (alongside legacy `chat-message` paths documented in [authentication.md](authentication.md)). Inventory convergence still prefers P2P data-channel sync when peers are connected.
## Related
- [authentication.md](authentication.md) — signing-key registration, `account_sync` chat batches
- [signaling.md](signaling.md) — `account_sync` envelope
- [mobile-capacitor.md](mobile-capacitor.md) — Capacitor `meta` revision keys
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Capacitor meta persistence; account_sync cross-ref; signing registration scope |
## Degraded-mode behavior ## Degraded-mode behavior
+211
View File
@@ -0,0 +1,211 @@
# Messaging
> **Area:** messaging
> **Status:** Active
> **Last updated:** 2026-07-13
## Overview
Messaging in MetoYou covers two transports that share inventory-sync concepts and (for DMs) a monotonic delivery state machine. **Server-channel chat** is broadcast by the signaling server over WebSocket (`chat_message`) as a narrow fallback when P2P data channels are down — the server does not persist message bodies. **Direct messages** (1:1 and group DMs) are primarily peer-to-peer over the WebRTC ordered data channel, with WebSocket signaling relay when no channel is open and an offline queue when neither path succeeds.
On both transports the client maintains local history (Electron SQLite / browser IndexedDB for server channels; user-scoped `localStorage` for DMs) and a **chunked inventory-sync protocol** so peers reconcile missing rows without flooding the link.
This document is the cross-context contract: envelope names, sync protocol, delivery states, edit/delete rules, and storage boundaries. Internal NgRx orchestration lives in [`toju-app/src/app/domains/chat/README.md`](../../toju-app/src/app/domains/chat/README.md) and [`toju-app/src/app/domains/direct-message/README.md`](../../toju-app/src/app/domains/direct-message/README.md). WebSocket relay rules: [signaling.md](signaling.md). Signed revision chains: [message-integrity.md](message-integrity.md).
## Responsibilities
- Send server-channel chat over WebSocket fallback (`chat_message`) and primarily over P2P (`chat-message`, `edit-message`, `delete-message`, `message-revision`).
- Send, edit, delete, and react in direct messages over the data channel with signaling fallback.
- Carry typing indicators: server channels (`typing``user_typing`) and DMs (`direct-message-typing`).
- Reconcile peer history via the inventory protocol (`chat-inventory` / `chat-sync-batch`; DM `direct-message-sync`).
- Drive a monotonic DM delivery state machine: `QUEUED → SENT → DELIVERED → ACKNOWLEDGED`.
- Relay multi-device chat via `account_sync` (`chat-message`, `message-revision`, `chat-sync-batch`).
This area does **not** own:
- Attachment payloads or chunked file transfer → [attachments.md](attachments.md).
- WebRTC session setup and data-channel lifecycle → [voice-webrtc.md](voice-webrtc.md).
- Write permission resolution (`writeMessages`, `manageMessages`, bans) → `toju-app/src/app/domains/access-control/README.md`.
- Full WebSocket envelope catalog (identity, voice, plugins) → [signaling.md](signaling.md).
## Key concepts
- **Server-channel message** — room-scoped text in a saved chat-server. Primary path: P2P `chat-message` on the data channel. Fallback: server broadcasts `chat_message` to other connections in the room.
- **Direct message** — 1:1 or group PM. Persisted per user under `metoyou_direct_message_*` keys (domain-owned storage, not the global messages CQRS table).
- **Conversation** — DM thread (`direct` or `group`). Upgrading a 1:1 call to a group creates a **new** group conversation; the original 1:1 history is not copied.
- **Inventory event**`chat-inventory` (P2P): sender announces message ids plus integrity fields (`ts`, `rc`, `ac`, `revision`, `headHash`); receiver requests missing or stale ids.
- **Sync batch**`chat-sync-batch`: chunked response, **200 messages per envelope** (`CHUNK_SIZE` in `message-sync.rules.ts`).
- **Delivery state** — DM-only enum: `QUEUED (0) → SENT (1) → DELIVERED (2) → ACKNOWLEDGED (3)`. Advanced only via `advanceDirectMessageStatus` (never backwards).
- **Peer delivery**`PeerDeliveryService` tries data channel, then signaling forward, then offline queue.
---
## Transports
### Server-channel chat
**P2P (primary):** `chat-message`, `edit-message`, `delete-message`, `message-revision`, reactions, and inventory events on the ordered data channel. See [message-integrity.md](message-integrity.md) for dual-emit revision behavior.
**WebSocket (fallback):** Client sends `chat_message`; `handleChatMessage` (`server/src/websocket/handler.ts`) broadcasts to other connections in the room. The server does **not** handle `edit_message` or `delete_message` on the wire — edits and deletes are P2P (and `account_sync` for sibling devices).
**Typing:** Client sends `typing`; server broadcasts `user_typing` (transient, no persistence).
**Multi-device:** Sibling tabs receive live chat via `account_sync` payloads (`chat-message`, `message-revision`, `chat-sync-batch`). See [authentication.md](authentication.md).
### Direct messages
**P2P (primary):** Events on the shared ordered data channel (same peer connections as voice/chat).
**WebSocket (fallback):** `PeerDeliveryService.sendViaSignaling` forwards these types to `targetUserId` without requiring shared server membership:
| type | Purpose |
|------|---------|
| `direct-message` | New message |
| `direct-message-status` | Delivery / ack |
| `direct-message-mutation` | Edit, delete, reactions |
| `direct-message-typing` | Typing indicator |
| `direct-message-sync-request` | Request snapshot |
| `direct-message-sync` | Bounded history merge |
**Offline queue:** When both paths fail, `OfflineMessageQueueService` retains message ids; replay runs on `peerConnected$` / `networkRestored$` (no scheduled retry timer).
### Storage
| Data | Where |
|------|--------|
| Server-channel messages | `DatabaseService` → Electron SQLite or browser IndexedDB (`messages` store) |
| Direct messages | `metoyou_direct_message_*` via direct-message repositories |
| Signaling server | **No message bytes** — broadcast/relay only |
---
## Inventory / sync protocol
Shared shapes in `toju-app/src/app/shared-kernel/chat-events.ts`:
| Event | Role |
|-------|------|
| `chat-inventory-request` | Ask peer for inventory |
| `chat-inventory` | Announce ids + integrity snapshots |
| `chat-sync-request` | Request specific missing ids |
| `chat-sync-batch` | Up to **200** messages per envelope |
| `direct-message-sync-request` / `direct-message-sync` | DM-scoped snapshot merge |
Rules (`message-sync.rules.ts`, `message-integrity.rules.ts`):
- Merges are **additive** — sparser peers never wipe richer local history.
- `findMissingIds` compares remote inventory to local `revision` / `headHash` (and legacy `ts` / `rc` / `ac`).
- `INVENTORY_LIMIT` = `FULL_SYNC_LIMIT` = **20_000** (2026-07-14, RAM investigation; previously 1_000_000). Building an inventory or full-sync batch loads full message rows into memory, so the ceiling must stay bounded. Only the most recent 20k messages per room are reconciled peer-to-peer; older messages stay local-only. `ACCOUNT_SYNC_MESSAGE_LIMIT` follows `FULL_SYNC_LIMIT`.
- Sync polling: 10 s when catching up, 15 min after a clean cycle (`SYNC_POLL_FAST_MS` / `SYNC_POLL_SLOW_MS`).
- NgRx store retention: on room switch, inactive rooms are pruned to the most recent `CACHED_INACTIVE_ROOM_MESSAGE_LIMIT` = **100** messages each (`messages.reducer.ts`), keeping return-visit rendering instant while bounding store growth across many rooms. The active room is never pruned; the local DB keeps full history.
---
## Delivery state machine (DMs only)
| Value | Numeric | Meaning |
|-------|---------|---------|
| `QUEUED` | 0 | Composed locally; no successful send yet |
| `SENT` | 1 | Data channel or signaling forward accepted the payload |
| `DELIVERED` | 2 | At least one recipient acknowledged receipt |
| `ACKNOWLEDGED` | 3 | Full recipient set acknowledged (1:1: the peer; group: every participant) |
`advanceDirectMessageStatus` only moves forward (`direct-message.logic.ts`). Server-channel messages have no application-level delivery enum; the UI treats them as sent once the transport accepts the event.
---
## Edit and delete
**Server channels:** Outgoing edits check `canEditMessage(message, userId)` before broadcast. Incoming P2P `edit-message` / `delete-message` merge via NgRx handlers; signed paths prefer `message-revision` when integrity is enabled.
**DMs:** `direct-message-mutation` with types `edit`, `delete`, `reaction-add`, `reaction-remove`. `applyMutation` in `DirectMessageService` updates by `messageId` but **does not verify** the mutator is the original author — a non-cooperating peer could mutate another user's row. Server chat enforces authorship on **outgoing** edits only.
Deletes keep tombstone semantics (`isDeleted`, empty `content`) so inventory sync can converge.
---
## Business rules and invariants
- The signaling server is **not authoritative** for message content — it relays `chat_message` and DM types opaquely.
- DM events are **ignored** unless the local user is in `recipients` / `participants` or already has the conversation locally.
- Recipient matching (DM **and** `direct-call`) must accept **every local identity alias** — home id, entity id, peer id, and each provisioned signal-server actor id from `SignalServerCredentialStoreService` — because senders who met the recipient on a foreign signal server address them by the provisioned actor id (`direct-message-identity.rules.ts`, `direct-call-participant-identity.rules.ts`).
- DM status transitions are **monotonic**.
- Inventory merges never downgrade a row with a newer `revision` / `headHash`.
- 1:1 → group upgrade **does not copy** private history into the new group thread.
- Unread counts are **idempotent by message id** — re-sync does not double-increment.
- Incoming DMs raise a system notification via `NotificationsFacade.handleIncomingDirectMessage` (title = sender name; `shouldDeliverDirectMessageNotification` suppresses only when the conversation is on screen in an active window, notifications are disabled, or the user is busy). System messages (e.g. call-started) and deletions never notify. On Capacitor this flows through the same `DesktopNotificationService` → LocalNotifications routing as server chat.
---
## Technical implementation
### Server
- `server/src/websocket/handler.ts``handleChatMessage`, `handleTyping`, DM forward via `forwardRtcMessage` / `DIRECT_SIGNALING_TYPES`.
- No message CQRS or entities on the server.
### Product client
| Area | Location |
|------|----------|
| Server chat effects / handlers | `store/messages/`, `domains/chat/` |
| DM service / queue | `domains/direct-message/application/services/` |
| Sync rules | `domains/chat/domain/rules/message-sync.rules.ts` |
| Wire types | `shared-kernel/chat-events.ts`, `direct-message-contracts.ts` |
| Account sync relay | `infrastructure/realtime/account-sync/` |
### Electron
- Server-channel rows: TypeORM `Message` entity + CQRS `save-message` / `delete-message`.
- DMs: renderer `localStorage` repositories (not the main message table).
---
## Testing
- Unit: `message-sync.rules.spec.ts`, `message-integrity.rules.spec.ts`, `message.rules.spec.ts`, `direct-message.service.spec.ts`, `direct-message.logic` specs, `messages-incoming.handlers.spec.ts`, `account-sync-chat.helper.spec.ts`.
- E2E: `e2e/tests/chat/chat-message-features.spec.ts`, `multi-client-chat-sync.spec.ts`, `dm-flow.spec.ts`, `multi-device-attachment-sharing.spec.ts`, `e2e/tests/voice/dm-header-call-ring.spec.ts` (DM-header call ring, incl. cross-signal actor-id addressing).
---
## Performance considerations
- Sync batches: **200 messages per `chat-sync-batch` envelope**.
- `chat_message` broadcast is O(connections in room) per send.
- Group DMs: O(recipients) transport attempts per message.
---
## Security considerations
- **No end-to-end encryption** for message bodies. WebRTC data channels use DTLS; signaling fallback is TLS WebSocket; local DBs store plaintext.
- **DM `applyMutation` does not verify authorship** on incoming mutations.
- **No server-side rate limit** on `chat_message` volume.
---
## Known issues and limitations
- **No server-side chat log** — late joiners depend on peers with local history or `account_sync` from a sibling device.
- **DM mutation authorship** not verified on receive.
- **Offline queue** replays only on peer connect / network restore events.
---
## Related features
- [signaling.md](signaling.md) — WebSocket relay and ordering invariants
- [message-integrity.md](message-integrity.md) — signed revision chains
- [attachments.md](attachments.md) — file payloads alongside chat events
- [voice-webrtc.md](voice-webrtc.md) — data channel transport
- [authentication.md](authentication.md) — `account_sync` multi-device relay
- [direct-messaging.md](direct-messaging.md) — short index (defers here)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-14 | RAM bounds: `INVENTORY_LIMIT`/`FULL_SYNC_LIMIT` lowered to 20k (most recent messages reconcile); NgRx prunes inactive rooms to 100 cached messages on room switch |
| 2026-07-13 | Incoming DMs raise system notifications through the notifications domain (previously unread-badge only) |
| 2026-07-13 | Recipient matching for DM and `direct-call` events must span all local identity aliases (provisioned actor ids included) |
| 2026-07-05 | Initial comprehensive messaging contract (replaces thin direct-messaging summary) |
+29 -12
View File
@@ -31,10 +31,6 @@ npm run cap:sync
npm run cap:open:android npm run cap:open:android
npm run cap:open:ios npm run cap:open:ios
### Linux: Android Studio path
Capacitor defaults to `/usr/local/android-studio/bin/studio.sh`. If Android Studio is installed elsewhere (common with **Flatpak** from Flathub), `npm run cap:open:android` uses `tools/resolve-android-studio-path.js` to locate `studio.sh` (Flatpak `active` symlink, Toolbox, snap, `/opt`, etc.). Override anytime with `CAPACITOR_ANDROID_STUDIO_PATH`.
# Convenience (build + sync + open) # Convenience (build + sync + open)
npm run cap:build:android npm run cap:build:android
npm run cap:build:ios npm run cap:build:ios
@@ -44,6 +40,10 @@ npm run cap:apk:android
# → toju-app/android/app/build/outputs/apk/debug/app-debug.apk # → toju-app/android/app/build/outputs/apk/debug/app-debug.apk
``` ```
### Linux: Android Studio path
Capacitor defaults to `/usr/local/android-studio/bin/studio.sh`. If Android Studio is installed elsewhere (common with **Flatpak** from Flathub), `npm run cap:open:android` uses `tools/resolve-android-studio-path.js` to locate `studio.sh` (Flatpak `active` symlink, Toolbox, snap, `/opt`, etc.). Override anytime with `CAPACITOR_ANDROID_STUDIO_PATH`.
Config: `toju-app/capacitor.config.ts` (`webDir: ../dist/client/browser`). Config: `toju-app/capacitor.config.ts` (`webDir: ../dist/client/browser`).
### CI (Gitea) ### CI (Gitea)
@@ -85,13 +85,15 @@ Re-run `npm run cap:assets:android` whenever `images/icon-new-rounded.png` chang
| Feature | Status | Notes | | Feature | Status | Notes |
|---------|--------|-------| |---------|--------|-------|
| Push/local notifications | **Working (partial)** | Local notifications always available; remote push (FCM/APNs) registers only when Firebase/APNs is configured — app starts normally without `google-services.json` | | Push/local notifications | **Working (partial)** | Local notifications always available; remote push (FCM/APNs) registers only when Firebase/APNs is configured — app starts normally without `google-services.json` |
| Chat message notifications | **Working** | `DesktopNotificationService` routes to `MobileNotificationsService.showMessage()` on Capacitor (LocalNotifications channel `toju-messages`); web `Notification` API is never used on native shells |
| Server push dispatch | **Working (configured)** | Tokens persist in server SQLite; outbound FCM/APNs via env credentials | | Server push dispatch | **Working (configured)** | Tokens persist in server SQLite; outbound FCM/APNs via env credentials |
| In-call notifications | **Working (Capacitor)** | Persistent notification with answer/mute/hang-up actions | | In-call notifications | **Working (Capacitor)** | Persistent notification with answer/mute/hang-up actions |
| Stream pop-out (PiP) | **Working (partial)** | Document PiP when WebView supports it; Android native PiP fallback via `MetoyouMobile` plugin | | Stream pop-out (PiP) | **Working (partial)** | Document PiP when WebView supports it; Android native PiP fallback via `MetoyouMobile` plugin |
| Background voice | **Working (partial)** | Android foreground service; iOS `UIBackgroundModes` audio + CallKit active-call bridge | | Background voice | **Working (partial)** | Android foreground service; iOS `UIBackgroundModes` audio + CallKit active-call bridge |
| iOS CallKit | **Working (partial)** | `MetoyouMobile.startCallKitSession` reports active calls; requires Xcode target wiring after `cap:sync` | | iOS CallKit | **Working (partial)** | `MetoyouMobile.startCallKitSession` reports active calls; requires Xcode target wiring after `cap:sync` |
| Screensharing | **Limited** | Disabled on iOS WebView; Android `getDisplayMedia` may work | | Screensharing | **Hidden on native mobile** | `getDisplayMedia` is unavailable in mobile WebViews; all screen-share buttons (private call, voice controls, floating controls, voice workspace) are gated behind `!viewport.isMobile() && !MobilePlatformService.isNativeMobile()` |
| Composer attachments | **Working** | Mobile attachment button + hidden file input | | Composer attachments | **Working** | Mobile attachment button + hidden file input |
| Attachment download/export | **Working** | `AttachmentDownloadService` delegates to `CapacitorAttachmentExportService` on native shells: copies disk-backed files (or fetches the object URL) into the public `Documents` directory with a timestamped name; anchor `download` links do nothing in the Android WebView |
| Camera sharing | **Working** | Existing `getUserMedia` camera path in WebRTC stack | | Camera sharing | **Working** | Existing `getUserMedia` camera path in WebRTC stack |
| Speakerphone | **Working (partial)** | Android `AudioManager` via `MetoyouMobile`; iOS `@capgo/capacitor-audio-session`; direct-call speaker toggle on native mobile | | Speakerphone | **Working (partial)** | Android `AudioManager` via `MetoyouMobile`; iOS `@capgo/capacitor-audio-session`; direct-call speaker toggle on native mobile |
| Local DB (SQLite) | **Working** | `DatabaseService` routes Capacitor shells to `CapacitorDatabaseService` (native SQLite CRUD) | | Local DB (SQLite) | **Working** | `DatabaseService` routes Capacitor shells to `CapacitorDatabaseService` (native SQLite CRUD) |
@@ -103,7 +105,7 @@ Re-run `npm run cap:assets:android` whenever `images/icon-new-rounded.png` chang
- **iOS CallKit:** Plugin Swift source ships in `ios/App/App/MetoyouMobilePlugin.swift`; add it to the Xcode target if not auto-linked. Incoming-call UI is not fully bridged to WebRTC answer/hang-up yet. - **iOS CallKit:** Plugin Swift source ships in `ios/App/App/MetoyouMobilePlugin.swift`; add it to the Xcode target if not auto-linked. Incoming-call UI is not fully bridged to WebRTC answer/hang-up yet.
- **iOS screenshare:** `getDisplayMedia` is not available in WKWebView. - **iOS screenshare:** `getDisplayMedia` is not available in WKWebView.
- **Android PiP:** Native PiP enters activity-level PiP; WebView video may not always render inside PiP on all OEM WebViews. - **Android PiP:** Native PiP enters activity-level PiP; WebView video may not always render inside PiP on all OEM WebViews.
- **Production discovery:** `signal.toju.app` may not expose `/api/servers/featured` or `/trending`; client skips those calls for known hosts. - **Legacy discovery endpoints:** Older signal servers may not expose `/api/servers/featured` or `/trending` (they resolve as `/servers/:id` and return 404). The client still calls those routes on every online endpoint and **falls back per-endpoint to `GET /api/servers`** when 404 is returned — see [server-discovery.md](server-discovery.md).
- **Push delivery:** Requires FCM service account and APNs key configuration on the signaling server. - **Push delivery:** Requires FCM service account and APNs key configuration on the signaling server.
## Push notification setup (FCM / APNs) ## Push notification setup (FCM / APNs)
@@ -133,8 +135,11 @@ Declared in `toju-app/android/app/src/main/AndroidManifest.xml`:
| `BLUETOOTH_CONNECT` | Bluetooth headset routing during calls (Android 12+) | | `BLUETOOTH_CONNECT` | Bluetooth headset routing during calls (Android 12+) |
| `POST_NOTIFICATIONS` | Incoming/active call notifications | | `POST_NOTIFICATIONS` | Incoming/active call notifications |
| `FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_MICROPHONE` | Background voice session | | `FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_MICROPHONE` | Background voice session |
| `READ_EXTERNAL_STORAGE` (maxSdk 32) / `WRITE_EXTERNAL_STORAGE` (maxSdk 29) | Attachment export to public `Documents` on Android 10 and below |
Before WebRTC capture, the client calls `MobileMediaService.ensureVoiceCapturePermissions()` / `ensureCameraCapturePermissions()`, which delegate to `MetoyouMobile.requestVoiceCapturePermissions()` / `requestCameraCapturePermissions()` on Capacitor shells. If the native plugin is unavailable or the bridge call fails, capture preflight defers to the WebView `getUserMedia` permission flow instead of aborting voice/camera joins. Before WebRTC capture, the client calls `MobileMediaService.ensureVoiceCapturePermissions()` / `ensureCameraCapturePermissions()`, which delegate to `MetoyouMobile.requestVoiceCapturePermissions()` / `requestCameraCapturePermissions()` on Capacitor shells. If the native plugin is unavailable or the bridge call fails, capture preflight defers to the WebView `getUserMedia` permission flow instead of aborting voice/camera joins. Preflight only blocks capture on an explicit native `denied` state (`mobile-media-permission.rules.ts`); a `prompt` state is deferred to the WebView so the user still gets the permission dialog.
Join and capture failures are surfaced in the UI instead of failing silently: `DirectCallService.joinCall` sets a `joinError` signal (`call.errors.*` i18n keys for signaling, capture-unsupported, mic permission, and mic unavailable cases), and the private-call and voice-controls components surface camera errors the same way.
On Capacitor startup, `MobileRuntimePermissionsService` (via `MobileAppLifecycleService.initialize()`) proactively prompts for microphone, camera, local-notification, and push-notification runtime permissions so Android 13+ shells do not keep every permission in the "Not allowed" state until the user joins voice or receives a call. On Capacitor startup, `MobileRuntimePermissionsService` (via `MobileAppLifecycleService.initialize()`) proactively prompts for microphone, camera, local-notification, and push-notification runtime permissions so Android 13+ shells do not keep every permission in the "Not allowed" state until the user joins voice or receives a call.
@@ -165,16 +170,19 @@ Tokens persist in server SQLite (`device_tokens` table). Outbound push uses repo
| `APNS_BUNDLE_ID` | Defaults to `com.metoyou.app` | | `APNS_BUNDLE_ID` | Defaults to `com.metoyou.app` |
| `APNS_USE_SANDBOX` | `true` for development builds | | `APNS_USE_SANDBOX` | `true` for development builds |
Manual dispatch (ops/testing): Manual dispatch (ops/testing). Requires `Authorization: Bearer`; `:userId` in the path **must match** the authenticated user (`403` otherwise):
```http ```http
POST /api/users/device-tokens/:userId/dispatch POST /api/users/device-tokens/:userId/dispatch
Authorization: Bearer <token>
{ "title": "Incoming call", "body": "Alice is calling" } { "title": "Incoming call", "body": "Alice is calling" }
``` ```
`POST /api/users/device-tokens` and `GET /api/users/device-tokens/:userId` apply the same rule: body/param `userId` must equal the bearer identity.
## Android foreground service ## Android foreground service
`VoiceCallForegroundService` starts when `MobileCallSessionService` begins an active call. Required manifest permissions: `VoiceCallForegroundService` starts when `MobileCallSessionService` begins an active call. The voice-channel path also starts/stops it directly: `MediaManager.enableVoice()` / `disableVoice()` call `startMobileVoiceForegroundSession()` / `stopMobileVoiceForegroundSession()` (`infrastructure/mobile/logic/mobile-voice-foreground-session.ts`) so channel voice keeps the mic alive when the app backgrounds. Required manifest permissions:
- `FOREGROUND_SERVICE` - `FOREGROUND_SERVICE`
- `FOREGROUND_SERVICE_MICROPHONE` - `FOREGROUND_SERVICE_MICROPHONE`
@@ -193,10 +201,13 @@ The service shows a low-importance ongoing notification while a call is active.
- Routing: `infrastructure/persistence/database-backend.rules.ts` — Capacitor uses SQLite, not IndexedDB. - Routing: `infrastructure/persistence/database-backend.rules.ts` — Capacitor uses SQLite, not IndexedDB.
- Per-user database files: `metoyou__<userId>` via `mobile-sqlite-database-name.rules.ts`. - Per-user database files: `metoyou__<userId>` via `mobile-sqlite-database-name.rules.ts`.
- First launch runs DDL migrations stored in the `meta` table. Schema init failures are cached per database file so the client does not retry in a loop. - First launch runs DDL migrations stored in the `meta` table. Schema init failures are cached per database file so the client does not retry in a loop.
- **Custom emoji assets** persist in the `custom_emojis` table (`CapacitorDatabaseService.saveCustomEmoji` / `getCustomEmojis` / `deleteCustomEmoji`).
- **Message revisions** persist in `meta` under keys `message-revision:<messageId>:<revision>` (JSON payload). See [message-integrity.md](message-integrity.md) and [custom-emoji.md](custom-emoji.md).
## Capacitor plugin loading ## Capacitor plugin loading
- `infrastructure/mobile/adapters/capacitor/capacitor-plugin-loader.ts` uses **static** `@capacitor/*` imports and `Capacitor.isPluginAvailable()` before returning a plugin. Do not `import()` plugin modules dynamically or `await` plugin objects (Capacitor proxies expose a throwing `.then()` stub). - `infrastructure/mobile/adapters/capacitor/capacitor-plugin-loader.ts` loads `@capacitor/*` modules via **dynamic `import()`** only when `isCapacitorNativeRuntime()` is true, and checks `Capacitor.isPluginAvailable()` before returning a plugin. Electron and browser shells never evaluate these imports at startup.
- Do not `await` a Capacitor plugin proxy object directly — Capacitor proxies expose a throwing `.then()` stub; always call methods on the resolved plugin instance.
- After adding or upgrading Capacitor plugins, run `npm run build:prod && npm run cap:sync` so Android/iOS native projects register `App`, `AppUpdate`, `LocalNotifications`, push, and SQLite. - After adding or upgrading Capacitor plugins, run `npm run build:prod && npm run cap:sync` so Android/iOS native projects register `App`, `AppUpdate`, `LocalNotifications`, push, and SQLite.
## Safe area (Android) ## Safe area (Android)
@@ -267,10 +278,16 @@ Phase 3 delivered:
3. iOS CallKit bridge (partial) via `MetoyouMobile` plugin and `MobileCallKitService`. 3. iOS CallKit bridge (partial) via `MetoyouMobile` plugin and `MobileCallKitService`.
4. Android Firebase Gradle wiring with `google-services.json.example` (real file gitignored). 4. Android Firebase Gradle wiring with `google-services.json.example` (real file gitignored).
5. Capacitor plugin availability checks to avoid hard failures when plugins are missing pre-sync. 5. Capacitor plugin availability checks to avoid hard failures when plugins are missing pre-sync.
6. Discovery endpoint skip for production signal hosts without featured/trending routes. 6. Discovery 404 fallback to public server listing on legacy signal hosts (see [server-discovery.md](server-discovery.md)).
Remaining work: Remaining work:
- Wire CallKit answer/end actions back into `DirectCallService`. - Wire CallKit answer/end actions back into `DirectCallService`.
- Migrate legacy IndexedDB mobile data into SQLite where needed. - Migrate legacy IndexedDB mobile data into SQLite where needed.
- Deploy featured/trending routes to production signal servers or add capability negotiation in health checks.
## Changelog
| Date | Change |
|------|--------|
| 2026-07-13 | Chat notifications routed to LocalNotifications (`toju-messages` channel + `ic_stat_metoyou` status icon); capture preflight blocks only on native `denied`; call join/camera errors surfaced via `call.errors.*`; voice channels start the foreground service; screen share hidden on native mobile; attachment export to `Documents`; full-screen overlays use `metoyou-fixed-safe-viewport` |
| 2026-07-05 | Corrected discovery fallback (not host skip), plugin-loader dynamic imports, markdown fence; added Capacitor custom-emoji/revision persistence and dispatch auth rules |
+70
View File
@@ -0,0 +1,70 @@
# Plugins
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Client-only plugin runtime with server-stored **metadata** (install requirements, event definitions) and Electron-local **plugin data** persistence. Plugins extend chat slash commands, toolbar actions, DOM mounts, and a P2P message bus — they never execute on the signaling server.
## Responsibilities
| Layer | Owns |
|-------|------|
| Product client (`plugins` domain) | Manifest validation, load order, `PluginHostService`, UI registry, store installs |
| Electron | Local manifest discovery (`plugins/`, `plugin-bundles/`), `plugin_data` CQRS table, path jail |
| Signaling server | Requirement/event metadata REST + `plugin_event` WebSocket broadcast; **no** plugin code execution |
| P2P data channel | `plugin-message-bus` events (ignored by chat reducers) |
Server plugin **data** HTTP routes return **410 Gone** (`PLUGIN_DATA_DISABLED`).
## Server REST (`/api/servers/:serverId/plugins`)
| Method | Path | Auth |
|--------|------|------|
| GET | `/` | Public (metadata snapshot) |
| PUT | `/:pluginId/requirement` | Bearer |
| DELETE | `/:pluginId/requirement` | Bearer |
| PUT | `/:pluginId/events/:eventName` | Bearer |
| DELETE | `/:pluginId/events/:eventName` | Bearer |
| GET/PUT/DELETE | `/:pluginId/data/*` | 410 (disabled) |
## WebSocket
| type | Direction | Purpose |
|------|-----------|---------|
| `plugin_requirements` | Server → client | Snapshot after `join_server` / `view_server` |
| `plugin_event` | Client → server → room | Validated broadcast of plugin events |
| `plugin_error` | Server → client | Validation failure |
See [signaling.md](signaling.md).
## Manifest scopes
- `scope: "client"` — global desktop/browser plugins (Settings → Client plugins).
- `scope: "server"` — per chat-server plugins; join may block until user consents to required plugins.
Store source manifests support HTTPS `bundle`/`bundleUrl` with optional SHA-256 `integrity` verification before `import()`.
## Electron IPC / storage
- `list-local-plugin-manifests`, `get-local-plugins-path`, `grant-plugin-read-root`
- Plugin preferences and `api.clientData` / `api.serverData``plugin_data` table (user-scoped)
- Cached bundles: `plugin-bundles/<plugin-id>/<version>/main.js`
## Client API surface (summary)
Plugins receive `TojuClientPluginApi`: `commands`, `ui.mountElement`, `ui.registerToolbarAction`, `messageBus`, `messages.setTyping`, `context.getCurrent()`, `clientData`/`serverData` async storage.
## Related
- [signaling.md](signaling.md) — `plugin_event`, `plugin_requirements`
- [server-directory.md](server-directory.md) — server-scoped install on join
- [authentication.md](authentication.md) — bearer on metadata mutations
- Domain README: [`toju-app/src/app/domains/plugins/README.md`](../../toju-app/src/app/domains/plugins/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial cross-context plugin contract |
@@ -0,0 +1,53 @@
# Push Notifications
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Mobile remote push (FCM/APNs) and server-side device token storage. Desktop uses local/Electron notifications via the `notifications` domain.
## Responsibilities
| Layer | Owns |
|-------|------|
| Signaling server | `device_tokens` SQLite table; FCM/APNs dispatch |
| Capacitor client | Token registration via `MobilePushRegistrationService` |
| Server env | FCM service account + APNs key configuration |
## REST API (`/api/users/device-tokens`)
All routes require bearer; `userId` must match authenticated identity.
| Method | Path | Purpose |
|--------|------|---------|
| POST | `/` | Upsert `{ userId, platform: "android"\|"ios", token }` |
| GET | `/:userId` | List tokens for user |
| POST | `/:userId/dispatch` | Manual push `{ title, body, data? }` (ops/testing) |
## Server configuration
Repository-root `.env`:
| Variable | Purpose |
|----------|---------|
| `FCM_SERVICE_ACCOUNT_PATH` or `FCM_SERVICE_ACCOUNT_JSON` | Android FCM HTTP v1 |
| `APNS_KEY_PATH`, `APNS_KEY_ID`, `APNS_TEAM_ID` | iOS APNs HTTP/2 |
| `APNS_BUNDLE_ID` | Default `com.metoyou.app` |
| `APNS_USE_SANDBOX` | Development builds |
## Mobile client
- Optional Firebase: app starts without `google-services.json`; registration skipped when remote push not configured.
- See [mobile-capacitor.md](mobile-capacitor.md) for FCM/APNs setup, permissions, and in-call local notifications.
## Related
- [authentication.md](authentication.md) — bearer + userId match rules
- [mobile-capacitor.md](mobile-capacitor.md) — client registration and foreground service
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial push notification contract |
+96
View File
@@ -0,0 +1,96 @@
# Server Directory
> **Area:** server-directory
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Server directory is the cross-context contract for **which signaling servers exist**, how clients health-check and route to them, and how public/private chat-servers are created, joined, updated, moderated, and discovered over REST. It spans the signaling **server** (`server/src/routes/servers.ts`, CQRS handlers) and the product **client** (`server-directory` domain + `ServerDirectoryFacade`).
Curated browse lists (featured/trending) are documented separately in [server-discovery.md](server-discovery.md). WebSocket membership (`join_server`, presence) is in [signaling.md](signaling.md).
## Responsibilities
- Server: persist public server records, memberships, channels, roles, bans, invites, join requests; expose REST CRUD and access checks.
- Client: maintain configured endpoint list, health/compatibility probes, canonical endpoint dedup by `serverInstanceId`, room `sourceId`/`sourceUrl` affinity, and HTTP orchestration for all server operations.
- It does NOT own: P2P chat transport, voice WebRTC, or local Electron room/message persistence (except mirroring server metadata into local DB after join).
## Key concepts
- **ServerEndpoint:** configured signaling base URL with health status, latency, and version compatibility.
- **ServerInfo:** public server card shape returned by search/discovery/GET — includes `sourceId`, `sourceName`, `sourceUrl` filled by the client API layer.
- **Room signal affinity:** each saved room records which endpoint registered it; reconnect prefers that URL before fallback endpoints.
- **serverInstanceId:** stable id from `GET /api/health` used to collapse alias URLs to one canonical endpoint.
## Public REST (no bearer)
| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/health` | Liveness, `serverVersion`, `serverInstanceId`, optional `serverTag` |
| GET | `/api/servers` | Free-text search / public listing (`q`, `limit`) |
| GET | `/api/servers/featured` | Curated popular list — [server-discovery.md](server-discovery.md) |
| GET | `/api/servers/trending` | Curated active list — [server-discovery.md](server-discovery.md) |
| GET | `/api/servers/:id` | Single server metadata |
## Protected REST (bearer required)
All mutations derive the actor from the session token; body user ids are not trusted.
| Method | Path | Purpose |
|--------|------|---------|
| POST | `/api/servers` | Register a new public server |
| PUT | `/api/servers/:id` | Update name, description, channels, icon metadata, access settings |
| DELETE | `/api/servers/:id` | Unregister server (owner) |
| POST | `/api/servers/:id/join` | Join or request access (password, invite, public) |
| POST | `/api/servers/:id/leave` | Leave membership |
| POST | `/api/servers/:id/heartbeat` | Refresh `lastSeen` for trending ranking |
| POST | `/api/servers/:id/invites` | Create invite link — [invites-join-requests.md](invites-join-requests.md) |
| GET | `/api/servers/:id/requests` | List pending join requests (moderators) |
| POST | `/api/servers/:id/moderation/kick` | Remove member |
| POST | `/api/servers/:id/moderation/ban` | Ban member (optional expiry) |
| POST | `/api/servers/:id/moderation/unban` | Lift ban |
Join-request approval: `PUT /api/requests/:id` — [invites-join-requests.md](invites-join-requests.md).
Plugin metadata under `/api/servers/:serverId/plugins` — [plugins.md](plugins.md).
## Client endpoint lifecycle
1. Load endpoints from `localStorage` (`metoyou_server_endpoints`); reconcile with environment defaults.
2. `testAllServers()` probes `GET /api/health` (5 s timeout); on failure falls back to `GET /api/servers`.
3. Mark incompatible when `serverVersion` fails semantic compatibility check.
4. `resolveCanonicalEndpoint()` collapses aliases sharing the same `serverInstanceId`.
5. Cold-start room reconnect waits for the initial health sweep before opening WebSockets.
## Multi-endpoint behavior
| Operation | Fan-out |
|-----------|---------|
| Search (`searchServers` with `searchAllServers`) | All online endpoints, dedupe by server id |
| Discovery (featured/trending) | All online endpoints + 404→public list fallback |
| Room CRUD/join | Authoritative room `sourceUrl` first; temporary fallback to other compatible endpoints on outage |
Only `status === 'incompatible'` stops fallback with an update-required message. Network errors and Cloudflare 521/522 must continue to the next endpoint.
## Server-owned channel metadata
`PUT /api/servers/:id` persists the server's `channels` array (text + voice). The client round-trips channel create/rename/delete through this API — local-only channel state is not authoritative. Server-side normalisation deduplicates names within each channel type.
## WebSocket complement
After REST join, the client sends `join_server` on the room's signaling URL. Presence (`server_users`, `user_joined`, `user_left`) is room-scoped on the WebSocket — see [signaling.md](signaling.md).
## Related
- [server-discovery.md](server-discovery.md) — featured/trending ranking and browse UI
- [authentication.md](authentication.md) — bearer tokens for mutations
- [invites-join-requests.md](invites-join-requests.md) — invite links and approval workflow
- [signal-server-tag.md](signal-server-tag.md) — `serverTag` on health + profile cards
- Product-client domain README: [`toju-app/src/app/domains/server-directory/README.md`](../../toju-app/src/app/domains/server-directory/README.md)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial cross-context server-directory REST contract |
+13 -2
View File
@@ -2,7 +2,7 @@
> **Area:** server-directory > **Area:** server-directory
> **Status:** Active > **Status:** Active
> **Last updated:** 2025-02-14 > **Last updated:** 2026-07-05
## Overview ## Overview
@@ -67,13 +67,24 @@ Both endpoints live in `server/src/routes/servers.ts` and **must be registered b
## Client internals ## Client internals
- `ServerDirectoryApiService.getFeaturedServers()` / `getTrendingServers()` call the routes through a shared private `getDiscoveryServers(path)` helper and normalise into `ServerInfo[]`. - `ServerDirectoryApiService.getFeaturedServers()` / `getTrendingServers()` call the routes through a shared private `getDiscoveryServers(path)` helper and normalise into `ServerInfo[]`.
- **Multi-endpoint fan-out:** discovery queries **every online endpoint** (`getSearchableEndpoints()` + `forkJoin`), deduplicated by server ID — mirroring free-text search. Querying only the active endpoint made the default `/servers` view appear empty when populated servers lived on other endpoints.
- **Legacy 404 fallback:** when `GET /api/servers/featured` or `/trending` returns **404** (older signal servers resolve those paths as `/servers/:id`), `fetchDiscoveryFromEndpoint` falls back per-endpoint to the public `GET /api/servers` listing (`fetchPublicServerListForDiscovery`) instead of returning `[]`. Verified in `server-directory-api.service.spec.ts` (including production hosts like `signal.toju.app`).
- `ServerDirectoryService``ServerDirectoryFacade` expose `getFeaturedServers()` / `getTrendingServers()` as the domain boundary. - `ServerDirectoryService``ServerDirectoryFacade` expose `getFeaturedServers()` / `getTrendingServers()` as the domain boundary.
- `FindServersComponent` (`/servers`) composes **Recently active** (the user's saved rooms, capped at 6), **Featured**, and **Trending** sections, all rendered through `app-server-browser` with `[showMyServers]="true"`. - `FindServersComponent` (`/servers`) composes **Recently active** (the user's saved rooms, capped at 6), **Featured**, and **Trending** sections, all rendered through `app-server-browser` with `[showMyServers]="true"`.
- `DashboardComponent` (`/dashboard`) is a single-column landing page (max-width centered, no in-page sidebars): a header greeting (no emoji), a global search with `Ctrl+K` focus and localStorage-backed **Recent Searches** chips shown beneath it, three primary action cards (Find People → `/people`, Find Servers → `/servers`, Create Server → `/create-server` — one link each), and discovery panels **People you might know**, **Popular Servers**, **Your Friends**, and **Recently Active Servers**. Each list is capped at 5 (`DISCOVERY_LIMIT`). It loads `popularServers` on init from `getFeaturedServers(5)`, falling back to `getTrendingServers(5)` when featured is empty; reuses `app-friend-button` for Add and `app-user-avatar` for people rows. `peopleYouMightKnow` excludes existing friends (via `FriendService.friendIds()`); `friends` lists discovered people who are friends. "See all" header links route to the matching `/people` or `/servers` page (no duplicated footer links). Recent searches are recorded on Enter (deduped, most-recent-first, capped at 8) and persisted under `metoyou_dashboard_recent_searches`. - `DashboardComponent` (`/dashboard`) is a single-column landing page (max-width centered, no in-page sidebars): a header greeting (no emoji), a global search with `Ctrl+K` focus and localStorage-backed **Recent Searches** chips shown beneath it, three primary action cards (Find People → `/people`, Find Servers → `/servers`, Create Server → `/create-server` — one link each), and discovery panels **People you might know**, **Popular Servers**, **Your Friends**, and **Recently Active Servers**. Each list is capped at 5 (`DISCOVERY_LIMIT`). It loads `popularServers` on init from `getFeaturedServers(5)`, falling back to `getTrendingServers(5)` when featured is empty; reuses `app-friend-button` for Add and `app-user-avatar` for people rows. `peopleYouMightKnow` excludes existing friends (via `FriendService.friendIds()`); `friends` lists discovered people who are friends. "See all" header links route to the matching `/people` or `/servers` page (no duplicated footer links). Recent searches are recorded on Enter (deduped, most-recent-first, capped at 8) and persisted under `metoyou_dashboard_recent_searches`.
- The servers-rail top button (`servers-rail.component`) is the **Dashboard** button (`lucideLayoutDashboard`, `title="Dashboard"`); its `goToDashboard()` handler deselects any active voice server and navigates to `/dashboard`. A **Create a server** button (`lucidePlus`, `data-testid="server-rail-create"`) sits below the saved-server icons and opens `app-create-server-dialog` (a Toju modal on desktop / bottom sheet on mobile) which dispatches `RoomsActions.createRoom` directly; the dashboard / `/create-server` route remains as an alternative entry point. Rail icons (`h-12 w-12`, `md:h-11 w-11`) animate their corner radius on hover and `:active` for a Discord-style squircle effect. - The servers-rail top button (`servers-rail.component`) is the **Dashboard** button (`lucideLayoutDashboard`, `title="Dashboard"`); its `goToDashboard()` handler deselects any active voice server and navigates to `/dashboard`. A **Create a server** button (`lucidePlus`, `data-testid="server-rail-create"`) sits below the saved-server icons and opens `app-create-server-dialog` (a Toju modal on desktop / bottom sheet on mobile) which dispatches `RoomsActions.createRoom` directly; the dashboard / `/create-server` route remains as an alternative entry point. Rail icons (`h-12 w-12`, `md:h-11 w-11`) animate their corner radius on hover and `:active` for a Discord-style squircle effect.
- On mobile (`ViewportService.isMobile()`), `DashboardComponent`, `FindPeopleComponent` (`/people`), and `FindServersComponent` (`/servers`) each mount their page body inside a single `<swiper-container>` slide next to `app-servers-rail` (rail `shrink-0`, content `flex-1` with a left border), mirroring the chat-room / DM-workspace mobile layout so the primary navigation rail stays reachable. The page body is shared between the desktop and mobile branches via an `<ng-template #pageContent>` + `[ngTemplateOutlet]`, and each component declares `schemas: [CUSTOM_ELEMENTS_SCHEMA]` for the Swiper custom elements. - On mobile (`ViewportService.isMobile()`), discovery routes (`/dashboard`, `/people`, `/servers`) render their page body full-width via `<ng-template #pageContent>` + `[ngTemplateOutlet]`. The **servers rail is global** in `app.html` (`shouldShowMobileAppServersRail` in `core/platform/mobile-shell-layout.rules.ts`) — discovery pages must **not** embed a second `<app-servers-rail>` or Swiper stack. Chat-room and DM-workspace routes keep their own embedded rail inside Swiper and hide the global shell rail (see `toju-app/AGENTS.md`).
## Related ## Related
- Product-client domain README: `toju-app/src/app/domains/server-directory/README.md` - Product-client domain README: `toju-app/src/app/domains/server-directory/README.md`
- Full server-directory REST contract (CRUD, join, moderation): [server-directory.md](server-directory.md)
- People discovery (`/people`): `toju-app/src/app/domains/direct-message/README.md` - People discovery (`/people`): `toju-app/src/app/domains/direct-message/README.md`
- Mobile shell: [mobile-capacitor.md](mobile-capacitor.md)
## Changelog
| Date | Change |
| ---------- | -------------------------------------------------------------------------------------------------------------- |
| 2026-07-05 | Added multi-endpoint fan-out and 404 fallback; corrected mobile shell layout (global rail, no per-page Swiper) |
| 2025-02-14 | Initial documentation |
+28 -4
View File
@@ -1,10 +1,18 @@
# Signal Server Tag # Signal Server Tag
> **Status:** Active
> **Last updated:** 2026-07-05
Users registered on a signal server can show that server's display tag on their profile card (opened by clicking their name or avatar). Users registered on a signal server can show that server's display tag on their profile card (opened by clicking their name or avatar).
## Responsibilities
- Server: expose a human-readable tag per **endpoint** (not per user identity).
- Client: resolve tag for a user's **home** signaling server (`homeSignalServerUrl`) and render on profile cards.
## Server configuration ## Server configuration
`server/data/variables.json` accepts an optional `serverTag` string. When omitted, the server falls back to its public URL built from `serverProtocol`, `serverHost`, and `serverPort`. `server/data/variables.json` accepts an optional `serverTag` string. When omitted, the server falls back to its public URL built from `serverProtocol`, `serverHost`, and `serverPort` (`server/src/config/variables.ts`).
## Health API ## Health API
@@ -12,11 +20,27 @@ Users registered on a signal server can show that server's display tag on their
## WebSocket presence ## WebSocket presence
The client sends `homeSignalServerUrl` in `identify` messages. The signaling server echoes that value in `server_users` and `user_joined` payloads so other clients can resolve the correct tag. The client sends `homeSignalServerUrl` in `identify` messages. The signaling server echoes that value in `server_users` and `user_joined` payloads so other clients can resolve the correct tag. See [signaling.md](signaling.md).
## Client behavior ## Client behavior
- Login and registration store `homeSignalServerUrl` on the current user. - Login and registration store `homeSignalServerUrl` on the current user.
- Profile cards show the resolved tag beside the username in muted text. - Profile cards show the resolved tag beside the username in muted text (`profile-signal-server-tag.component`).
- Configured labels render as `#tag`; URL fallbacks render as a globe icon with the URL in a tooltip. - Configured labels render as `#tag`; URL fallbacks render as a globe icon with the URL in a tooltip.
- Tag resolution prefers the endpoint's cached `serverTag` from health checks, then falls back to the stored home URL. - Tag resolution (`signal-server-tag.rules.ts`): match `homeSignalServerUrl` against configured endpoints and prefer cached health `serverTag`; otherwise show the raw URL fallback.
## Testing
- `toju-app/src/app/domains/server-directory/domain/logic/signal-server-tag.rules.spec.ts`
- `server/src/websocket/handler-status.spec.ts` (presence payload includes `homeSignalServerUrl`)
## Related
- [server-directory.md](server-directory.md) — endpoint health cache
- [authentication.md](authentication.md) — `homeSignalServerUrl` on identify
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Clarified per-endpoint tag vs per-user home URL; added test references |
+152
View File
@@ -0,0 +1,152 @@
# Signaling (WebSocket)
> **Area:** realtime
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
The signaling server exposes a single WebSocket per origin that carries identity, room membership, presence, WebRTC SDP/ICE relay, selected server-relayed chat/DM/voice fallbacks, plugin events, and multi-device `account_sync`. The product client implements the consumer in `toju-app/src/app/infrastructure/realtime/signaling/`.
**Canonical contract:** this document and [`server/src/websocket/handler.ts`](../../server/src/websocket/handler.ts). Do **not** treat `toju-app/src/app/shared-kernel/signaling-contracts.ts` as authoritative — it lists legacy types (`join`, `leave`, `chat`, `ice-candidate`) that do not match the live server.
## Responsibilities
- Authenticate connections via `identify` (session token).
- Track per-connection room membership and broadcast room-scoped presence.
- Relay WebRTC offers/answers/ICE between peers that share server membership (or DM/direct-call rules).
- Relay narrow server fallbacks when P2P data channels are unavailable (chat, DM, voice presence).
- Forward `account_sync` payloads to sibling connections for the same user identity.
- It does NOT own: P2P data-channel payloads (attachments, message inventory, custom emoji chunks, plugin message bus), local persistence, or REST server-directory APIs.
## Key concepts
- **Envelope:** JSON object with required `type` string; additional fields vary by type.
- **oderId:** user identity on the wire (legacy spelling, matches server code).
- **clientInstanceId:** per-tab/device id stored in `sessionStorage`; multiple open connections per `oderId` are allowed.
- **connectionScope:** optional string grouping connections (e.g. browser profile).
- **voiceActive:** server marks the connection that owns outbound RTC relay for a user; updated from `voice_state` payloads.
## Ordering invariants
1. **`identify` before anything else** — unauthenticated connections receive `auth_required` for all types except `identify` and `keepalive`.
2. **Per-connection serialization**`handleWebSocketMessage` chains handlers per `connectionId` so `join_server` cannot run while `identify` is still awaiting the token DB lookup.
3. **Client replay on reconnect**`SignalingManager.reIdentifyAndRejoin` sends `identify` then re-joins rooms; see [`toju-app/src/app/infrastructure/realtime/README.md`](../../toju-app/src/app/infrastructure/realtime/README.md).
## Connection lifecycle (server → client)
On connect the server assigns a `connectionId` and may emit:
| type | When |
|------|------|
| `connected` | Immediately after WebSocket open (`server/src/websocket/index.ts`) |
On disconnect, if the connection was voice-active, the server broadcasts a cleared `voice_state` via `finalizeVoiceDisconnectForConnection`.
## Inbound types (client → server)
| type | Auth | Behavior |
|------|------|----------|
| `keepalive` | Optional | Responds `keepalive_ack` with `serverTime` |
| `identify` | N/A (establishes auth) | Validates session token; sets `oderId`, profile fields; evicts stale same `(oderId, connectionScope, clientInstanceId)` sockets; emits `account_sync_peer_online` to siblings |
| `join_server` | Required | Access check; adds `serverId` to connection; sends `server_users` + `plugin_requirements`; may broadcast `user_joined` (identity-aware) |
| `view_server` | Required | Switches `viewedServerId`; refreshes `server_users` + `plugin_requirements` |
| `leave_server` | Required | Removes membership; may broadcast `user_left` with remaining `serverIds` |
| `offer`, `answer`, `ice_candidate` | Required | Relay to `targetUserId` when peers share server membership |
| `direct-message`, `direct-message-status`, `direct-message-mutation`, `direct-message-typing`, `direct-message-sync-request`, `direct-message-sync`, `direct-call` | Required | Relay to `targetUserId` (DM rules — no shared-server requirement) |
| `server_icon_peer_request`, `server_icon_peer_data` | Required | Relay when both users share `serverId` membership |
| `chat_message` | Required | Broadcast to server members (excludes sender connection) |
| `voice_state` | Required | Updates `voiceActive` / snapshot; broadcast to server members |
| `voice_client_takeover` | Required | Notifies sibling connections via `notifyOtherConnectionsForOderId` |
| `account_sync` | Required | Forwards `payload` object to other connections for same `oderId` |
| `typing` | Required | Broadcast `user_typing` to server members |
| `status_update` | Required | Broadcast `status_update` (`online` \| `away` \| `busy` \| `offline`) to joined servers |
| `server_icon_available` | Required | Records local `iconUpdatedAt` per server on the connection |
| `server_icon_sync_request` | Required | Responds `server_icon_sync_peers` with peers having newer icons |
| `plugin_event` | Required | Validates against server plugin metadata; broadcast or `plugin_error` |
Unknown inbound types are logged and ignored.
### `identify` request fields
| Field | Required | Notes |
|-------|----------|-------|
| `token` | Yes | Session token from REST login/register |
| `oderId` | No | If present, must match token user id |
| `displayName` | No | Defaults to existing or `"User"` |
| `description`, `profileUpdatedAt`, `homeSignalServerUrl` | No | Profile card fields |
| `clientInstanceId` | No | Per-tab id for multi-device and voice ownership |
| `connectionScope` | No | Eviction scope for stale sockets |
Errors: `auth_error` with `MISSING_TOKEN`, `INVALID_TOKEN`, or `USER_ID_MISMATCH`.
## Server-emitted types (server → client)
| type | Trigger |
|------|---------|
| `keepalive_ack` | Response to `keepalive` |
| `auth_required` | Message before `identify` |
| `auth_error` | Failed `identify` |
| `access_denied` | `join_server` rejected (`serverId`, `reason`) |
| `server_users` | After join/view; lists unique users in room |
| `user_joined` | New identity in server (excludes same identity's connections) |
| `user_left` | Identity fully left server (`serverIds` = remaining rooms) |
| `plugin_requirements` | Plugin install snapshot after join/view |
| `plugin_error` | Invalid plugin event |
| `server_icon_sync_peers` | Response to `server_icon_sync_request` |
| `account_sync_peer_online` | Sibling connection came online |
| `account_sync` | Relayed multi-device payload |
| `chat_message` | Relayed room chat fallback |
| `user_typing` | Typing indicator |
| `status_update` | Presence status change |
| `voice_state` | Voice roster / disconnect cleanup |
| `voice_client_takeover` | Another tab took voice ownership |
| `plugin_event` | Broadcast plugin event |
| Forwarded RTC/DM | Copies of client messages with `fromUserId` set |
## Relay rules
- **RTC (`offer` / `answer` / `ice_candidate`):** forwarded when sender and target share any server membership.
- **Direct signaling types:** forwarded to `targetUserId` without shared-server check.
- **Server icon P2P:** both users must be members of `message.serverId`.
- **Broadcasts** (`chat_message`, `voice_state`, `typing`, etc.): exclude sender **connection id** (not whole identity) so multi-device sessions still receive updates.
- **`user_joined` / `user_left`:** exclude whole **identity** so other users do not see duplicate join/leave for multiple tabs.
## P2P vs signaling split
| Transport | Carries |
|-----------|---------|
| **WebRTC data channel** | Chat events, attachments, custom emoji, message revisions/inventory, profile avatar bytes, voice/screen control, plugin message bus, game activity |
| **WebSocket signaling** | Identity, membership, presence, RTC SDP/ICE, chat/DM/voice fallbacks, `account_sync`, plugin events |
Server-relayed chat (`chat_message`) and DM types exist so users see written chat and delivery state while data channels are down. Media, attachments, and inventory sync remain peer-plane responsibilities.
## Multi-device (`account_sync`)
The client wraps relayable local changes in `account_sync` envelopes. The server forwards the inner `payload` to other open connections for the same `oderId`. When a device identifies, siblings receive `account_sync_peer_online` and push snapshots (saved servers, friends, emoji library, chat history batches, etc.). See [authentication.md](authentication.md) and domain-specific feature docs.
## Client implementation map
| Concern | Location |
|---------|----------|
| One socket per signal URL | `signaling/signaling.manager.ts` |
| Route picker | `signaling/signaling-transport-handler.ts` |
| Room affinity | `signaling/server-signaling-coordinator.ts` |
| Inbound dispatch | `signaling/signaling-message-handler.ts` |
| Constants (intervals, types) | `realtime.constants.ts` |
## Related
- [authentication.md](authentication.md) — session tokens and `identify` trust boundary
- [direct-messaging.md](direct-messaging.md) — DM envelope relay types
- [voice-webrtc.md](voice-webrtc.md) — RTC relay and `voice_state`
- [plugins.md](plugins.md) — `plugin_event` / `plugin_requirements`
- [message-integrity.md](message-integrity.md) — signed revisions (P2P; `account_sync` relay)
- Product client deep dive: [`toju-app/src/app/infrastructure/realtime/README.md`](../../toju-app/src/app/infrastructure/realtime/README.md)
- Server handler: [`server/src/websocket/handler.ts`](../../server/src/websocket/handler.ts)
## Changelog
| Date | Change |
|------|--------|
| 2026-07-05 | Initial canonical envelope catalog; deprecates `shared-kernel/signaling-contracts.ts` as wire source |
+68
View File
@@ -0,0 +1,68 @@
# Voice & WebRTC
> **Status:** Active
> **Last updated:** 2026-07-05
## Overview
Voice channels, camera, and screen-share use direct **WebRTC** peer connections between clients. The signaling server relays SDP offers/answers/ICE and **voice presence** (`voice_state`); media never flows through the server.
## Responsibilities
| Layer | Owns |
|-------|------|
| `infrastructure/realtime/` | WebRTC sessions, negotiation, data channels, RNNoise worklet |
| `voice-connection` / `voice-session` domains | Facades, workspace UI, settings, multi-device ownership |
| `screen-share` domain | Source picker, quality presets (Electron) |
| Signaling server | RTC relay + `voice_state` / `voice_client_takeover` broadcast |
## WebSocket signaling types
| type | Purpose |
|------|---------|
| `offer`, `answer`, `ice_candidate` | WebRTC negotiation relay to `targetUserId` |
| `voice_state` | Voice roster (mute/deafen/speaking, channel id); sets `voiceActive` on one connection per user |
| `voice_client_takeover` | Notify sibling tabs to yield voice ownership |
Relay rules: RTC messages require shared server membership (except DM-specific types). See [signaling.md](signaling.md).
## Multi-device voice
- Only one connection per `oderId` may be `voiceActive`; RTC offers route to that connection (fallback: any open connection).
- Other tabs show passive UI and may send `voice_client_takeover`.
- `clientInstanceId` in `identify` and voice payloads distinguishes tabs.
## Media pipeline (client)
- **Voice:** `getUserMedia` → optional RNNoise AudioWorklet → gain → same-room peer routing only.
- **Camera:** separate video track; same-room filter.
- **Screen share:** on-demand via data-channel `SCREEN_SHARE_REQUEST`; platform-specific capture (browser `getDisplayMedia`, Electron picker, Linux PulseAudio routing).
## P2P data channel
Carries voice/screen control messages, chat, attachments, and state sync — not server-relayed. Data-channel failure triggers peer renegotiation or full rebuild (see realtime README). When a failed control channel is replaced (`replaceDataChannel`), the old channel is closed first so its SCTP resources are released.
## Media memory invariants (2026-07-14, RAM investigation)
- `removePeer` / `closeAllPeers` clear **all four** remote stream maps, including `remotePeerCameraStreams` (previously leaked per departed peer).
- Video tiles (`voice-workspace-stream-tile`) pause and null `srcObject` in `ngOnDestroy` (`voice-workspace-stream-video.rules.ts`) so Chromium releases decoder/frame buffers immediately.
- `debug-network-metrics` drops a peer's entry when the peer is fully removed and caps the store at `MAX_TRACKED_DEBUG_NETWORK_PEERS` = 200 (oldest evicted).
- Electron registers `setDisplayMediaRequestHandler` once per app run (guarded in `create-window.ts`), not on every window recreation.
## Mobile / Capacitor
Background voice uses Android foreground service + iOS audio/CallKit bridges — [mobile-capacitor.md](mobile-capacitor.md). Screen share is limited on mobile WebViews.
## Related
- [signaling.md](signaling.md) — envelope catalog
- [direct-messaging.md](direct-messaging.md) — private calls share `PeerDeliveryService`
- [`toju-app/src/app/infrastructure/realtime/README.md`](../../toju-app/src/app/infrastructure/realtime/README.md) — negotiation, recovery, RNNoise
- Domain READMEs: `voice-connection`, `voice-session`, `screen-share`
## Changelog
| Date | Change |
|------|--------|
| 2026-07-14 | Media memory invariants: camera-stream map cleanup, tile `srcObject` release, debug-metrics cap, single display-media handler registration, replaced data channels closed |
| 2026-07-05 | Initial cross-context voice/WebRTC contract |
@@ -0,0 +1,114 @@
import { test, expect } from '../../fixtures/multi-client';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
/**
* Regression coverage for "Sending files between users doesn't really work":
* a generic (non-media) file above the 10 MB auto-save cap sent to a browser
* receiver. The receiver clicks Request; previously the chunk handler dropped
* every incoming chunk with a silent file-too-large error, the sender's ack
* wait timed out, and the GUI never changed.
*/
const LARGE_FILE_SIZE_BYTES = 11 * 1024 * 1024;
test.describe('Large generic file transfer', () => {
test.describe.configure({ timeout: 420_000, retries: 1 });
test('browser receiver can request and download a generic file above the auto-save cap', async ({ createClient }) => {
const suffix = uniqueName('largefile');
const serverName = `Large File Server ${suffix}`;
const fileName = `${suffix}-dataset.bin`;
const caption = `Large file upload ${suffix}`;
const alice = await createClient();
const bob = await createClient();
const aliceMessages = new ChatMessagesPage(alice.page);
const bobMessages = new ChatMessagesPage(bob.page);
await test.step('Alice and Bob register and meet in a server', async () => {
const aliceRegister = new RegisterPage(alice.page);
await aliceRegister.goto();
await aliceRegister.register(`alice_${suffix}`, 'Alice', 'TestPass123!');
await expect(alice.page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
const bobRegister = new RegisterPage(bob.page);
await bobRegister.goto();
await bobRegister.register(`bob_${suffix}`, 'Bob', 'TestPass123!');
await expect(bob.page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
const aliceSearch = new ServerSearchPage(alice.page);
await aliceSearch.createServer(serverName, { description: 'Large generic file transfer coverage' });
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 });
const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.joinServerFromSearch(serverName);
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await aliceMessages.waitForReady();
await bobMessages.waitForReady();
});
await test.step('Alice sends an 11 MB generic file', async () => {
await attachGeneratedBinaryFile(aliceMessages, fileName, LARGE_FILE_SIZE_BYTES);
await aliceMessages.sendMessage(caption);
await expect(aliceMessages.getMessageItemByText(caption)).toBeVisible({ timeout: 30_000 });
});
const bobBubble = bobMessages.getMessageItemByText(caption);
await test.step('Bob sees the attachment card with a Request button', async () => {
await expect(bobBubble).toBeVisible({ timeout: 30_000 });
await expect(bobBubble.getByText(fileName, { exact: false })).toBeVisible({ timeout: 30_000 });
await expect(bobBubble.getByRole('button', { name: /request/i })).toBeVisible({ timeout: 20_000 });
});
await test.step('Bob requests the file and it downloads to completion', async () => {
await bobBubble.getByRole('button', { name: /request/i }).click();
// The transfer must visibly progress (Cancel replaces Request) instead of
// silently stalling at 0 bytes like the original bug.
await expect(bobBubble.getByRole('button', { name: /cancel/i })).toBeVisible({ timeout: 30_000 });
await expect(bobBubble.getByRole('button', { name: /download/i })).toBeVisible({ timeout: 300_000 });
await expect(bobBubble.getByText(/too large/i)).toHaveCount(0);
});
});
});
/**
* Builds the file inside the page so the multi-megabyte payload never crosses
* the CDP protocol as a base64 string.
*/
async function attachGeneratedBinaryFile(
messages: ChatMessagesPage,
fileName: string,
sizeBytes: number
): Promise<void> {
await messages.waitForReady();
await messages.composerInput.evaluate((element, { name, size }) => {
const bytes = new Uint8Array(size);
for (let index = 0; index < size; index++) {
bytes[index] = (index * 31 + 7) & 0xff;
}
const dataTransfer = new DataTransfer();
dataTransfer.items.add(new File([bytes], name, { type: 'application/octet-stream' }));
element.dispatchEvent(new DragEvent('drop', {
bubbles: true,
cancelable: true,
dataTransfer
}));
}, { name: fileName, size: sizeBytes });
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;
}
@@ -85,6 +85,61 @@ test.describe('Multi-device attachment sharing', () => {
await expect(getButton.first()).toBeVisible({ timeout: 20_000 }); await expect(getButton.first()).toBeVisible({ timeout: 20_000 });
}); });
}); });
test('relays file-announce metadata to a sibling device that is already online during upload', async ({
createClient
}) => {
const suffix = uniqueMultiDeviceName('attach-online');
const credentials = {
username: `online_${suffix}`,
displayName: 'Multi Device User',
password: MULTI_DEVICE_PASSWORD
};
const serverName = `Attachment Online Relay ${suffix}`;
const fileName = `${suffix}-relay.bin`;
const caption = `Uploaded while device B was online ${suffix}`;
const fileAttachment = createBinaryFilePayload(fileName, 'application/octet-stream', `relay-body-${suffix}`);
const clientA = await createClient();
const clientB = await createClient();
const messagesA = new ChatMessagesPage(clientA.page);
const messagesB = new ChatMessagesPage(clientB.page);
await test.step('device A registers and creates a server', async () => {
const registerPage = new RegisterPage(clientA.page);
await registerPage.goto();
await registerPage.register(credentials.username, credentials.displayName, credentials.password);
await expect(clientA.page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
const search = new ServerSearchPage(clientA.page);
await search.createServer(serverName, { description: 'Sibling online file-announce relay coverage' });
await expect(clientA.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await messagesA.waitForReady();
});
await test.step('device B logs into the same server before the upload starts', async () => {
await loginSecondDeviceIntoServer(clientB.page, credentials, serverName);
await clientA.page.bringToFront();
await messagesA.waitForReady();
await clientB.page.bringToFront();
await messagesB.waitForReady();
});
await test.step('device A uploads while device B is already in the room', async () => {
await clientA.page.bringToFront();
await messagesA.attachFiles([fileAttachment]);
await messagesA.sendMessage(caption);
await expect(messagesA.getMessageItemByText(caption)).toBeVisible({ timeout: 30_000 });
});
await test.step('device B learns attachment metadata without a server-rail click dance', async () => {
await clientB.page.bringToFront();
await expect(messagesB.getMessageItemByText(caption)).toBeVisible({ timeout: 90_000 });
await expect(messagesB.getMessageItemByText(caption).getByText(fileName, { exact: false }))
.toBeVisible({ timeout: 90_000 });
});
});
}); });
function createBinaryFilePayload(name: string, mimeType: string, content: string): ChatDropFilePayload { function createBinaryFilePayload(name: string, mimeType: string, content: string): ChatDropFilePayload {
@@ -0,0 +1,61 @@
import { test, expect } from '../../fixtures/multi-client';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatMessagesPage, type ChatDropFilePayload } from '../../pages/chat-messages.page';
test.describe('Multi-image gallery grouping', () => {
test.describe.configure({ timeout: 180_000 });
test('groups three images in one message bubble with a visible grid', async ({ createClient }) => {
const suffix = uniqueName('gallery');
const client = await createClient();
const registerPage = new RegisterPage(client.page);
const search = new ServerSearchPage(client.page);
const messages = new ChatMessagesPage(client.page);
const serverName = `Gallery Group ${suffix}`;
const imageNames = [
`${suffix}-one.svg`,
`${suffix}-two.svg`,
`${suffix}-three.svg`
];
const images = imageNames.map((name) => createSvgFilePayload(name));
await registerPage.goto();
await registerPage.register(`gallery_${suffix}`, 'Gallery User', 'TestPass123!');
await expect(client.page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
await search.createServer(serverName, { description: 'Multi-image gallery regression server' });
await expect(client.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await messages.waitForReady();
await messages.attachFiles(images);
await messages.sendPendingAttachments();
for (const imageName of imageNames) {
await messages.expectMessageImageLoaded(imageName);
}
const messageId = await messages.getMessageIdContainingImage(imageNames[0]);
expect(messageId).toBeTruthy();
const bubble = client.page.locator(`[data-message-id="${messageId}"]`);
await expect(bubble.locator('img[alt$=".svg"]')).toHaveCount(3, { timeout: 20_000 });
await expect(bubble.locator('.chat-image-grid')).toBeVisible({ timeout: 20_000 });
});
});
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 10_000)}`;
}
function createSvgFilePayload(name: string): ChatDropFilePayload {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#4A217A"/></svg>';
return {
name,
mimeType: 'image/svg+xml',
base64: Buffer.from(svg, 'utf8').toString('base64')
};
}
+237
View File
@@ -0,0 +1,237 @@
import { expect, type Page } from '@playwright/test';
import { test } from '../../fixtures/multi-client';
import { installTestServerEndpoints } from '../../helpers/seed-test-endpoint';
import { startTestServer } from '../../helpers/test-server';
import { readSignalServerCredentialFromPage } from '../../helpers/auth-api';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
/**
* Regression coverage for "User receiving direct call doesn't get notified":
* starting a call from the DM chat header (steps: open DM of a user, click
* call) must ring the recipient - incoming-call modal, ring audio, and a
* server-rail call entry. Includes the cross-signal topology where the callee
* is addressed by a provisioned actor id instead of their home identity.
*/
const USER_PASSWORD = 'TestPass123!';
const PRIMARY_SIGNAL_ID = 'e2e-dm-ring-primary';
const SECONDARY_SIGNAL_ID = 'e2e-dm-ring-secondary';
test.describe('DM header call ring', () => {
test.describe.configure({ timeout: 240_000 });
test('callee is notified when the caller starts the call from the DM chat header', async ({ createClient }) => {
const suffix = uniqueName('dm-ring');
const serverName = `DM Ring Server ${suffix}`;
const alice = await createClient();
const bob = await createClient();
await installRingInstrumentation(bob.page);
await test.step('Alice and Bob register and meet in a server', async () => {
await registerUser(alice.page, `alice_${suffix}`, 'Alice');
await registerUser(bob.page, `bob_${suffix}`, 'Bob');
const aliceSearch = new ServerSearchPage(alice.page);
await aliceSearch.createServer(serverName, { description: 'DM header call ring regression coverage' });
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 20_000 });
await new ChatMessagesPage(alice.page).waitForReady();
const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.joinServerFromSearch(serverName);
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 20_000 });
await new ChatMessagesPage(bob.page).waitForReady();
});
await test.step('Both users open the DM view; live DM delivery confirms the transport works', async () => {
const bobUserCard = alice.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Bob' }).first();
await expect(bobUserCard).toBeVisible({ timeout: 20_000 });
await bobUserCard.getByRole('button', { name: 'Message Bob' }).click();
await expect(alice.page).toHaveURL(/\/dm\//, { timeout: 15_000 });
const aliceUserCard = bob.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Alice' }).first();
await expect(aliceUserCard).toBeVisible({ timeout: 20_000 });
await aliceUserCard.getByRole('button', { name: 'Message Alice' }).click();
await expect(bob.page).toHaveURL(/\/dm\//, { timeout: 15_000 });
// Mirrors the bug report: the users are in the DM view (not a server
// room) when the call starts. The message must arrive live so a broken
// ring cannot be blamed on a dead transport.
await alice.page.getByTestId('dm-input').fill(`hello before call ${suffix}`);
await alice.page.getByTestId('dm-input').press('Enter');
await expect(bob.page.locator('app-dm-chat').getByText(`hello before call ${suffix}`)).toBeVisible({ timeout: 20_000 });
});
await test.step('Alice starts the call from the DM chat header', async () => {
const callButton = alice.page.locator('app-dm-chat header').getByRole('button', { name: 'Call Bob' });
await expect(callButton).toBeVisible({ timeout: 20_000 });
await expect(callButton).toBeEnabled({ timeout: 20_000 });
await callButton.click();
await expect(alice.page).toHaveURL(/\/call\//, { timeout: 20_000 });
});
await test.step('Bob gets the incoming-call modal, ring audio, and rail entry', async () => {
await expect(bob.page.getByRole('dialog', { name: /is calling/ })).toBeVisible({ timeout: 20_000 });
await expect(bob.page.locator('[data-testid^="server-rail-call-"]')).toHaveCount(1, { timeout: 20_000 });
await expect
.poll(async () => await getCallAudioPlayCount(bob.page), {
timeout: 20_000,
intervals: [500, 1_000]
})
.toBeGreaterThan(0);
});
});
test('callee homed on another signal server is notified when called via their provisioned actor id', async ({ createClient, testServer }) => {
const secondaryServer = await startTestServer();
try {
const suffix = uniqueName('xsig-ring');
const serverName = `Cross Signal Ring ${suffix}`;
const alice = await createClient();
const bob = await createClient();
const endpoints = [
{
id: PRIMARY_SIGNAL_ID,
name: 'E2E Ring Signal A',
url: testServer.url,
isActive: true,
status: 'online'
},
{
id: SECONDARY_SIGNAL_ID,
name: 'E2E Ring Signal B',
url: secondaryServer.url,
isActive: true,
status: 'online'
}
];
await installTestServerEndpoints(alice.context, endpoints);
await installTestServerEndpoints(bob.context, endpoints);
await installRingInstrumentation(bob.page);
await test.step('Alice registers on the primary signal, Bob on the secondary', async () => {
const aliceRegister = new RegisterPage(alice.page);
await aliceRegister.goto();
await aliceRegister.serverSelect.selectOption(PRIMARY_SIGNAL_ID);
await aliceRegister.register(`alice_${suffix}`, 'Alice', USER_PASSWORD);
await expect(alice.page).toHaveURL(/\/dashboard/, { timeout: 20_000 });
const bobRegister = new RegisterPage(bob.page);
await bobRegister.goto();
await bobRegister.serverSelect.selectOption(SECONDARY_SIGNAL_ID);
await bobRegister.register(`bob_${suffix}`, 'Bob', USER_PASSWORD);
await expect(bob.page).toHaveURL(/\/dashboard/, { timeout: 20_000 });
});
await test.step('They meet in a room on the primary signal; Bob gets a provisioned actor identity', async () => {
const aliceSearch = new ServerSearchPage(alice.page);
await aliceSearch.createServer(serverName, {
description: 'Cross-signal DM call ring coverage',
sourceId: PRIMARY_SIGNAL_ID
});
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 20_000 });
await new ChatMessagesPage(alice.page).waitForReady();
const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.joinServerFromSearch(serverName);
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 20_000 });
await new ChatMessagesPage(bob.page).waitForReady();
await expect.poll(async () =>
await readSignalServerCredentialFromPage(bob.page, testServer.url),
{ timeout: 30_000 }
).not.toBeNull();
});
await test.step('Alice opens the DM with Bob and calls from the DM chat header', async () => {
const bobUserCard = alice.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Bob' }).first();
await expect(bobUserCard).toBeVisible({ timeout: 20_000 });
await bobUserCard.getByRole('button', { name: 'Message Bob' }).click();
await expect(alice.page).toHaveURL(/\/dm\//, { timeout: 15_000 });
const callButton = alice.page.locator('app-dm-chat header').getByRole('button', { name: 'Call Bob' });
await expect(callButton).toBeVisible({ timeout: 20_000 });
await expect(callButton).toBeEnabled({ timeout: 20_000 });
await callButton.click();
await expect(alice.page).toHaveURL(/\/call\//, { timeout: 20_000 });
});
await test.step('Bob gets the incoming-call modal and ring audio', async () => {
await expect(bob.page.getByRole('dialog', { name: /is calling/ })).toBeVisible({ timeout: 20_000 });
await expect
.poll(async () => await getCallAudioPlayCount(bob.page), {
timeout: 20_000,
intervals: [500, 1_000]
})
.toBeGreaterThan(0);
});
} finally {
await secondaryServer.stop();
}
});
});
async function registerUser(page: Page, username: string, displayName: string): Promise<void> {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(username, displayName, USER_PASSWORD);
await expect(page).toHaveURL(/\/dashboard/, { timeout: 20_000 });
}
async function installRingInstrumentation(page: Page): Promise<void> {
await page.addInitScript(() => {
const OriginalAudio = window.Audio;
const callAudioState = { playCount: 0 };
(window as Window & { __callAudioState?: typeof callAudioState }).__callAudioState = callAudioState;
function isCallAudio(audio: HTMLAudioElement): boolean {
return audio.src.includes('/assets/audio/call.wav') || audio.src.endsWith('assets/audio/call.wav');
}
(window as unknown as { Audio: typeof Audio }).Audio = function(this: HTMLAudioElement, src?: string) {
const audio = new OriginalAudio(src);
const originalPlay = audio.play.bind(audio);
audio.play = () => {
if (isCallAudio(audio)) {
callAudioState.playCount += 1;
}
return originalPlay();
};
return audio;
} as typeof Audio;
window.Audio.prototype = OriginalAudio.prototype;
Object.setPrototypeOf(window.Audio, OriginalAudio);
});
}
async function getCallAudioPlayCount(page: Page): Promise<number> {
return await page.evaluate(() => (window as Window & { __callAudioState?: { playCount: number } }).__callAudioState?.playCount ?? 0);
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;
}
+37 -25
View File
@@ -12,12 +12,14 @@ import * as path from 'path';
import { DESKTOP_APP_DISPLAY_NAME } from '../app/desktop-branding.rules'; import { DESKTOP_APP_DISPLAY_NAME } from '../app/desktop-branding.rules';
import { readDesktopSettings } from '../desktop-settings'; import { readDesktopSettings } from '../desktop-settings';
import { resolveDevelopmentClientUrl } from './dev-client-url.rules'; import { resolveDevelopmentClientUrl } from './dev-client-url.rules';
import { shouldRegisterDisplayMediaHandler } from './display-media-handler.rules';
let mainWindow: BrowserWindow | null = null; let mainWindow: BrowserWindow | null = null;
let tray: Tray | null = null; let tray: Tray | null = null;
let closeToTrayEnabled = true; let closeToTrayEnabled = true;
let appQuitting = false; let appQuitting = false;
let youtubeRequestHeadersConfigured = false; let youtubeRequestHeadersConfigured = false;
let displayMediaHandlerConfigured = false;
const WINDOW_STATE_CHANGED_CHANNEL = 'window-state-changed'; const WINDOW_STATE_CHANGED_CHANNEL = 'window-state-changed';
const YOUTUBE_EMBED_REFERRER = 'https://toju.app/'; const YOUTUBE_EMBED_REFERRER = 'https://toju.app/';
@@ -189,31 +191,12 @@ function emitWindowState(): void {
}); });
} }
export async function createWindow(): Promise<void> { function ensureDisplayMediaRequestHandler(): void {
const windowIconPath = getWindowIconPath(); if (!shouldRegisterDisplayMediaHandler(process.platform, displayMediaHandlerConfigured)) {
return;
closeToTrayEnabled = readDesktopSettings().closeToTray;
ensureTray();
ensureYoutubeEmbedRequestHeaders();
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
frame: false,
title: DESKTOP_APP_DISPLAY_NAME,
titleBarStyle: 'hidden',
backgroundColor: '#0a0a0f',
...(windowIconPath ? { icon: windowIconPath } : {}),
webPreferences: {
backgroundThrottling: false,
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, '..', 'preload.js'),
webSecurity: true
} }
});
displayMediaHandlerConfigured = true;
if (process.platform === 'linux') { if (process.platform === 'linux') {
session.defaultSession.setDisplayMediaRequestHandler( session.defaultSession.setDisplayMediaRequestHandler(
@@ -241,9 +224,10 @@ export async function createWindow(): Promise<void> {
}, },
{ useSystemPicker: true } { useSystemPicker: true }
); );
return;
} }
if (process.platform === 'win32') {
session.defaultSession.setDisplayMediaRequestHandler( session.defaultSession.setDisplayMediaRequestHandler(
async (request, respond) => { async (request, respond) => {
// On Windows the system picker (useSystemPicker: true) is preferred. // On Windows the system picker (useSystemPicker: true) is preferred.
@@ -277,6 +261,34 @@ export async function createWindow(): Promise<void> {
); );
} }
export async function createWindow(): Promise<void> {
const windowIconPath = getWindowIconPath();
closeToTrayEnabled = readDesktopSettings().closeToTray;
ensureTray();
ensureYoutubeEmbedRequestHeaders();
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
frame: false,
title: DESKTOP_APP_DISPLAY_NAME,
titleBarStyle: 'hidden',
backgroundColor: '#0a0a0f',
...(windowIconPath ? { icon: windowIconPath } : {}),
webPreferences: {
backgroundThrottling: false,
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, '..', 'preload.js'),
webSecurity: true
}
});
ensureDisplayMediaRequestHandler();
if (process.env['NODE_ENV'] === 'development') { if (process.env['NODE_ENV'] === 'development') {
await mainWindow.loadURL(resolveDevelopmentClientUrl(process.env['SSL'] === 'true')); await mainWindow.loadURL(resolveDevelopmentClientUrl(process.env['SSL'] === 'true'));
@@ -0,0 +1,22 @@
import {
describe,
expect,
it
} from 'vitest';
import { shouldRegisterDisplayMediaHandler } from './display-media-handler.rules';
describe('shouldRegisterDisplayMediaHandler', () => {
it('registers once for platforms that need a fallback picker', () => {
expect(shouldRegisterDisplayMediaHandler('linux', false)).toBe(true);
expect(shouldRegisterDisplayMediaHandler('win32', false)).toBe(true);
});
it('does not re-register on window recreation', () => {
expect(shouldRegisterDisplayMediaHandler('linux', true)).toBe(false);
expect(shouldRegisterDisplayMediaHandler('win32', true)).toBe(false);
});
it('never registers on platforms with a native picker', () => {
expect(shouldRegisterDisplayMediaHandler('darwin', false)).toBe(false);
});
});
@@ -0,0 +1,16 @@
/**
* The display-media request handler is a session-level singleton. Registering
* it inside `createWindow()` without a guard re-installed a fresh handler
* (holding fresh closures) every time the window was recreated from the tray
* or a deep link. Registration happens at most once per app run.
*/
export function shouldRegisterDisplayMediaHandler(
platform: NodeJS.Platform,
alreadyConfigured: boolean
): boolean {
if (alreadyConfigured) {
return false;
}
return platform === 'linux' || platform === 'win32';
}
@@ -59,4 +59,11 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Attachment export to public Documents needs legacy storage permissions on Android 10 and below. -->
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
</manifest> </manifest>
Binary file not shown.

After

Width:  |  Height:  |  Size: 241 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 633 B

+2 -2
View File
@@ -13,8 +13,8 @@ const config: CapacitorConfig = {
style: 'DARK' style: 'DARK'
}, },
LocalNotifications: { LocalNotifications: {
smallIcon: 'ic_stat_icon_config_sample', smallIcon: 'ic_stat_metoyou',
iconColor: '#488AFF', iconColor: '#4A217A',
sound: 'call.wav' sound: 'call.wav'
}, },
PushNotifications: { PushNotifications: {
+7 -1
View File
@@ -43,7 +43,13 @@
}, },
"errors": { "errors": {
"noRecipient": "Direct message conversation has no recipient to call.", "noRecipient": "Direct message conversation has no recipient to call.",
"noCurrentUser": "Cannot use calls without a current user." "noCurrentUser": "Cannot use calls without a current user.",
"signalingUnavailable": "Not connected to the call server. Check your connection and try again.",
"captureUnsupported": "Voice capture is not available on this device.",
"microphonePermissionDenied": "Microphone access is blocked. Allow the microphone permission in system settings to join calls.",
"microphoneUnavailable": "Could not start the microphone. Close other apps that use it and try again.",
"cameraPermissionDenied": "Camera access is blocked. Allow the camera permission in system settings to share video.",
"cameraUnavailable": "Could not start the camera. Close other apps that use it and try again."
} }
} }
} }
+1
View File
@@ -24,6 +24,7 @@
"notifications": { "notifications": {
"incomingCallsChannel": "Incoming calls", "incomingCallsChannel": "Incoming calls",
"activeCallsChannel": "Active calls", "activeCallsChannel": "Active calls",
"messagesChannel": "Messages",
"answer": "Answer", "answer": "Answer",
"decline": "Decline", "decline": "Decline",
"mute": "Mute", "mute": "Mute",
+8 -1
View File
@@ -127,7 +127,13 @@
}, },
"errors": { "errors": {
"noRecipient": "Direct message conversation has no recipient to call.", "noRecipient": "Direct message conversation has no recipient to call.",
"noCurrentUser": "Cannot use calls without a current user." "noCurrentUser": "Cannot use calls without a current user.",
"signalingUnavailable": "Not connected to the call server. Check your connection and try again.",
"captureUnsupported": "Voice capture is not available on this device.",
"microphonePermissionDenied": "Microphone access is blocked. Allow the microphone permission in system settings to join calls.",
"microphoneUnavailable": "Could not start the microphone. Close other apps that use it and try again.",
"cameraPermissionDenied": "Camera access is blocked. Allow the camera permission in system settings to share video.",
"cameraUnavailable": "Could not start the camera. Close other apps that use it and try again."
} }
}, },
"chat": { "chat": {
@@ -517,6 +523,7 @@
"notifications": { "notifications": {
"incomingCallsChannel": "Incoming calls", "incomingCallsChannel": "Incoming calls",
"activeCallsChannel": "Active calls", "activeCallsChannel": "Active calls",
"messagesChannel": "Messages",
"answer": "Answer", "answer": "Answer",
"decline": "Decline", "decline": "Decline",
"mute": "Mute", "mute": "Mute",
+6 -1
View File
@@ -29,21 +29,26 @@ infrastructure adapters and UI.
The larger domains also keep longer design notes in their own folders: The larger domains also keep longer design notes in their own folders:
- [attachment/README.md](attachment/README.md)
- [access-control/README.md](access-control/README.md) - [access-control/README.md](access-control/README.md)
- [attachment/README.md](attachment/README.md)
- [authentication/README.md](authentication/README.md) - [authentication/README.md](authentication/README.md)
- [chat/README.md](chat/README.md) - [chat/README.md](chat/README.md)
- [custom-emoji/README.md](custom-emoji/README.md)
- [direct-message/README.md](direct-message/README.md) - [direct-message/README.md](direct-message/README.md)
- [direct-call/README.md](direct-call/README.md) - [direct-call/README.md](direct-call/README.md)
- [experimental-media/README.md](experimental-media/README.md) - [experimental-media/README.md](experimental-media/README.md)
- [game-activity/README.md](game-activity/README.md)
- [notifications/README.md](notifications/README.md) - [notifications/README.md](notifications/README.md)
- [plugins/README.md](plugins/README.md) - [plugins/README.md](plugins/README.md)
- [profile-avatar/README.md](profile-avatar/README.md) - [profile-avatar/README.md](profile-avatar/README.md)
- [screen-share/README.md](screen-share/README.md) - [screen-share/README.md](screen-share/README.md)
- [server-directory/README.md](server-directory/README.md) - [server-directory/README.md](server-directory/README.md)
- [theme/README.md](theme/README.md)
- [voice-connection/README.md](voice-connection/README.md) - [voice-connection/README.md](voice-connection/README.md)
- [voice-session/README.md](voice-session/README.md) - [voice-session/README.md](voice-session/README.md)
Cross-context wire contracts live in [`agents-docs/features/`](../../agents-docs/features/) — see [`agents-docs/FEATURES.md`](../../agents-docs/FEATURES.md).
## Folder convention ## Folder convention
Every domain follows the same internal layout: Every domain follows the same internal layout:
+17 -6
View File
@@ -28,7 +28,8 @@ attachment/
├── infrastructure/ ├── infrastructure/
│ ├── services/ │ ├── services/
│ │ ── attachment-storage.service.ts Electron filesystem access (save / read / delete) │ │ ── attachment-storage.service.ts Electron filesystem access (save / read / delete)
│ │ └── capacitor-attachment-export.service.ts Capacitor "download": copy/write bytes into public Documents
│ └── util/ │ └── util/
│ └── attachment-storage.util.ts sanitizeAttachmentRoomName, resolveAttachmentStorageBucket │ └── attachment-storage.util.ts sanitizeAttachmentRoomName, resolveAttachmentStorageBucket
@@ -107,14 +108,14 @@ Concurrent triggers (file-announce, message sync, peer connect) can race to requ
- **Requester:** `requestFromAnyPeer` marks the request pending *synchronously* before any async work, so the manager's `hasPendingRequest` gate closes the double-request race window. - **Requester:** `requestFromAnyPeer` marks the request pending *synchronously* before any async work, so the manager's `hasPendingRequest` gate closes the double-request race window.
- **Sender:** `handleFileRequest` / `fulfillRequestWithFile` track active outbound streams per `(messageId, fileId, peerId)` and ignore duplicate requests while a stream is in flight. A fresh `file-request` clears any earlier `file-cancel` marker from that peer. - **Sender:** `handleFileRequest` / `fulfillRequestWithFile` track active outbound streams per `(messageId, fileId, peerId)` and ignore duplicate requests while a stream is in flight. A fresh `file-request` clears any earlier `file-cancel` marker from that peer.
- **Receiver:** chunk buffers are dense (`Array.from({ length: total })`, never sparse `new Array(total)`); a chunk index that is already buffered is ignored entirely and never counts toward `receivedBytes`; a transfer finalizes only when *every* chunk index is present — byte counters are never a substitute for chunk completeness. Assembly state is released only after the attachment is marked `available`, and chunks arriving for an already-available attachment are dropped. When the active store supports streaming (`canStreamToDisk`), **all** persistable downloads append directly to disk — metadata `filePath` does not force an in-memory assembly fallback. Disk-streamed receives decode each chunk once, append bytes through Electron IPC (`append-file-bytes`), and acknowledge the sender with `file-chunk-ack` so only one chunk is in flight at a time (preventing unbounded base64 retention in the renderer). Completed media stays on `savedPath` until inline display hydration runs on demand. - **Receiver:** chunk buffers are dense (`Array.from({ length: total })`, never sparse `new Array(total)`); a chunk index that is already buffered is ignored entirely and never counts toward `receivedBytes`; a transfer finalizes only when *every* chunk index is present — byte counters are never a substitute for chunk completeness. Assembly state is released only after the attachment is marked `available`, and chunks arriving for an already-available attachment are dropped. Files **`MAX_AUTO_SAVE_SIZE_BYTES` (10 MB)** assemble in memory (parallel chunk receive, immediate `file-chunk-ack`) and are persisted after completion via `shouldPersistDownloadedAttachment`. **Oversized** persistable downloads (`> 10 MB`) append directly to disk when the store supports streaming (`canStreamToDisk`) — metadata `filePath` does not force an in-memory fallback. On stores that cannot stream (browser), oversized files the store can still persist (≤ 50 MB) assemble in memory instead. Whether a file can be received at all is decided once, at request time, by `canReceiveAttachment``handleFileChunk` must not re-gate on a stricter size cap, or it silently drops chunks the request gate already admitted (the receiver never acks, the sender's ack wait times out, and the download stalls at 0 bytes with no error). Disk-streamed receives decode each chunk once, append bytes through Electron IPC (`append-file-bytes`), and acknowledge the sender with `file-chunk-ack` so only one chunk is in flight at a time (preventing unbounded base64 retention in the renderer). Completed **images** ≤ 10 MB get an immediate `objectUrl` blob; oversized images stay on `savedPath` until inline display hydration runs on demand. Completed **audio/video** immediately resolve a playable URL via `attachmentStorage.getFileUrl(savedPath)` (Electron/Capacitor) or `ensureInlineDisplayObjectUrl` in the browser.
- **Sender:** after each `file-chunk` the transport awaits the matching `file-chunk-ack` before sending the next chunk, in addition to data-channel bufferedAmount back-pressure. - **Sender:** after each `file-chunk` the transport awaits the matching `file-chunk-ack` before sending the next chunk, in addition to data-channel bufferedAmount back-pressure.
### Failure handling ### Failure handling
If the sender cannot find the file, it replies with `file-not-found`. The transfer service then tries the next connected peer that has announced the same attachment. Either side can send `file-cancel` to abort a transfer in progress. If the sender cannot find the file, it replies with `file-not-found`. The transfer service then tries the next connected peer that has announced the same attachment. Either side can send `file-cancel` to abort a transfer in progress.
Peers that finish downloading a file re-announce it and register themselves as mirror hosts. New download requests prefer mirror hosts over the original uploader so the sharer's device is not the only upload source. Repeat `file-announce` events for already-known attachments update the host list but do not re-trigger auto-download. Peers that finish downloading a file re-announce it and register themselves as mirror hosts. New download requests prefer mirror hosts over the original uploader so the sharer's device is not the only upload source. Repeat `file-announce` events for already-known attachments update the host list but do not re-trigger auto-download. Outgoing `file-announce` broadcasts are also relayed to sibling devices through `account_sync` (see `infrastructure/realtime/account-sync/account-sync.rules.ts`) so a second client of the same user learns attachment metadata even when it cannot P2P to itself.
```mermaid ```mermaid
sequenceDiagram sequenceDiagram
@@ -144,7 +145,11 @@ When the user navigates to a room, the manager watches the route and decides whi
The decision lives in `shouldAutoRequestWhenWatched()` which calls `isAttachmentMedia()` and checks against `MAX_AUTO_SAVE_SIZE_BYTES`. The decision lives in `shouldAutoRequestWhenWatched()` which calls `isAttachmentMedia()` and checks against `MAX_AUTO_SAVE_SIZE_BYTES`.
Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:<conversationId>`, so image/video metadata announced for the visible conversation is eligible for the same automatic request path as server-room media. Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:<conversationId>`, so image/video metadata announced for the visible conversation is eligible for the same automatic request path as server-room media. Auto-download work fans out with bounded concurrency (`ATTACHMENT_AUTO_DOWNLOAD_CONCURRENCY`, default 3 files at a time per watched room) so multiple pending files can progress in parallel without removing the per-file chunk-ack memory safety invariant. Stalled partial downloads are reset automatically before the next auto-download pass — but only when chunk progress has been quiet past `ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS` (`attachment-autodownload.rules.ts`). The pending-request marker is deleted on the first received chunk, so "no pending request" alone must never classify an in-flight transfer as stalled; resetting an active transfer cancels it on the sender and the retry deadlocks against the sender's per-peer active-transfer dedupe.
Auto-download triggers must fire from *every* event that can complete the `messageId -> roomId` binding, because `file-announce` (WebRTC data channel) and `chat-message` (signaling websocket) travel on different transports and arrive in either order. When the announce arrives first, the room is still unknown and that pass gives up; the `chat-message` handler (`messages-incoming.handlers.ts`) therefore calls `rememberMessageRoom` and re-queues `queueAutoDownloadsForMessage` for the arriving message.
Incoming and synced attachment metadata is normalized through `attachment-normalize.rules.ts` / `attachment-mime.rules.ts`: generic `application/octet-stream` (or empty) MIME types are inferred from the filename extension so images still group into galleries and small audio/video render as players instead of generic file cards. Display hydration (`needsAttachmentDisplayHydration`) rehydrates blob/file URLs from disk for both inline images and playable media without forcing a fresh peer download when local bytes already exist.
Browser chat views render audio/video larger than 50 MB with the same generic file interface as other downloads, even after the bytes are available. Attachments with audio/video MIME types that Chromium reports as unsupported also use the generic file interface instead of a broken native player. Browser chat views render audio/video larger than 50 MB with the same generic file interface as other downloads, even after the bytes are available. Attachments with audio/video MIME types that Chromium reports as unsupported also use the generic file interface instead of a broken native player.
@@ -205,8 +210,14 @@ Components read attachment state reactively through the store's signals. The sto
Image inline previews on Electron/desktop use renderer `blob:` URLs rebuilt from disk. To cap RAM in media-heavy channels: Image inline previews on Electron/desktop use renderer `blob:` URLs rebuilt from disk. To cap RAM in media-heavy channels:
- **Room restore** (`restoreLocalAttachmentsForRoom`) resolves `savedPath` for hosting only — it does not hydrate every image blob up front. - **Room restore** (`restoreLocalAttachmentsForRoom`) resolves `savedPath` for hosting only — it does not hydrate every image blob up front.
- **Visibility** (`ChatMessageItemComponent` + `IntersectionObserver` on the chat scrollport) hydrates blobs when a message enters view (with `ATTACHMENT_BLOB_VISIBILITY_ROOT_MARGIN`) and revokes them when it leaves, as long as a disk path can rehydrate later (`canRevokeAttachmentDisplayBlob`). - **Visibility** (`ChatMessageItemComponent` + `IntersectionObserver` on the chat scrollport) hydrates blobs when a message enters view (with `ATTACHMENT_BLOB_VISIBILITY_ROOT_MARGIN`) and revokes them when it leaves, as long as a disk path can rehydrate later (`canRevokeAttachmentDisplayBlob`). Hydration itself is visibility-gated (`attachment-hydration-visibility.rules.ts`) — off-screen rows never load blobs, and destroyed rows always release theirs.
- **No byte duplication:** disk-hydrated blobs are never copied into `AttachmentRuntimeStore.originalFiles` (`applyAttachmentBlob`); revocation of a disk-backed blob also drops any stale `originalFiles` entry. `originalFiles` only carries uploads/downloads that have no disk copy yet.
- **Room switch sweep:** `releaseDisplayBlobsForInactiveRooms` revokes display blobs for messages of all other rooms when navigation lands on a different room.
- **Pinned overlays** (lightbox / image gallery) call `pinDisplayBlobs` so an open full-screen view is not revoked while its message scrolls off-screen. - **Pinned overlays** (lightbox / image gallery) call `pinDisplayBlobs` so an open full-screen view is not revoked while its message scrolls off-screen.
- **Serving** is unaffected: peers still download from `savedPath` / `filePath`; blob URLs are display-only. - **Serving** is unaffected: peers still download from `savedPath` / `filePath` (`streamRequestedFile` prefers the disk path); blob URLs are display-only.
While a revoked image waits to rehydrate, chat renders the existing image-grid spinner skeleton (`isAttachmentPendingInlineHydration`). While a revoked image waits to rehydrate, chat renders the existing image-grid spinner skeleton (`isAttachmentPendingInlineHydration`).
## Cross-context feature docs
- [`agents-docs/features/attachments.md`](../../../../../agents-docs/features/attachments.md)
@@ -135,6 +135,12 @@ export class AttachmentFacade {
return this.manager.cancelRequest(...args); return this.manager.cancelRequest(...args);
} }
hasPendingRequest(
...args: Parameters<AttachmentManagerService['hasPendingRequest']>
): ReturnType<AttachmentManagerService['hasPendingRequest']> {
return this.manager.hasPendingRequest(...args);
}
handleFileCancel( handleFileCancel(
...args: Parameters<AttachmentManagerService['handleFileCancel']> ...args: Parameters<AttachmentManagerService['handleFileCancel']>
): ReturnType<AttachmentManagerService['handleFileCancel']> { ): ReturnType<AttachmentManagerService['handleFileCancel']> {
@@ -9,8 +9,15 @@ import {
import { DOCUMENT } from '@angular/common'; import { DOCUMENT } from '@angular/common';
import { Injector, runInInjectionContext } from '@angular/core'; import { Injector, runInInjectionContext } from '@angular/core';
const isCapacitorNativeRuntimeMock = vi.fn(() => false);
vi.mock('../../../../infrastructure/mobile/logic/platform-detection.rules', () => ({
isCapacitorNativeRuntime: () => isCapacitorNativeRuntimeMock()
}));
import { AttachmentDownloadService } from './attachment-download.service'; import { AttachmentDownloadService } from './attachment-download.service';
import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service'; import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service';
import { CapacitorAttachmentExportService } from '../../infrastructure/services/capacitor-attachment-export.service';
import type { Attachment } from '../../domain/models/attachment.model'; import type { Attachment } from '../../domain/models/attachment.model';
describe('AttachmentDownloadService', () => { describe('AttachmentDownloadService', () => {
@@ -21,8 +28,11 @@ describe('AttachmentDownloadService', () => {
let documentStub: Document; let documentStub: Document;
let saveExistingFileAs: ReturnType<typeof vi.fn>; let saveExistingFileAs: ReturnType<typeof vi.fn>;
let saveFileAs: ReturnType<typeof vi.fn>; let saveFileAs: ReturnType<typeof vi.fn>;
let exportToDevice: ReturnType<typeof vi.fn>;
beforeEach(() => { beforeEach(() => {
isCapacitorNativeRuntimeMock.mockReturnValue(false);
exportToDevice = vi.fn(async () => true);
saveExistingFileAs = vi.fn(async () => ({ saved: true, cancelled: false })); saveExistingFileAs = vi.fn(async () => ({ saved: true, cancelled: false }));
saveFileAs = vi.fn(async () => ({ saved: true, cancelled: false })); saveFileAs = vi.fn(async () => ({ saved: true, cancelled: false }));
@@ -53,6 +63,7 @@ describe('AttachmentDownloadService', () => {
providers: [ providers: [
AttachmentDownloadService, AttachmentDownloadService,
{ provide: ElectronBridgeService, useValue: electronBridge }, { provide: ElectronBridgeService, useValue: electronBridge },
{ provide: CapacitorAttachmentExportService, useValue: { exportToDevice } },
{ provide: DOCUMENT, useValue: documentStub } { provide: DOCUMENT, useValue: documentStub }
] ]
}); });
@@ -78,6 +89,28 @@ describe('AttachmentDownloadService', () => {
expect(saveFileAs).not.toHaveBeenCalled(); expect(saveFileAs).not.toHaveBeenCalled();
}); });
it('delegates to the Capacitor export service on a native mobile shell', async () => {
isCapacitorNativeRuntimeMock.mockReturnValue(true);
electronBridge.getApi = vi.fn(() => null);
const service = createService();
const attachment: Attachment = {
id: 'file-3',
messageId: 'message-3',
filename: 'photo.png',
mime: 'image/png',
size: 2048,
available: true,
savedPath: 'metoyou/server/room/files/photo.png'
};
await expect(service.downloadToUserLocation(attachment)).resolves.toBe(true);
expect(exportToDevice).toHaveBeenCalledWith(attachment);
expect(saveExistingFileAs).not.toHaveBeenCalled();
expect(saveFileAs).not.toHaveBeenCalled();
});
it('does nothing when the attachment is not downloadable yet', async () => { it('does nothing when the attachment is not downloadable yet', async () => {
const service = createService(); const service = createService();
const attachment: Attachment = { const attachment: Attachment = {
@@ -2,12 +2,15 @@ import { DOCUMENT } from '@angular/common';
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service'; import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service';
import { isCapacitorNativeRuntime } from '../../../../infrastructure/mobile/logic/platform-detection.rules';
import { canDownloadAttachment, resolveAttachmentDiskPath } from '../../domain/logic/attachment-download.rules'; import { canDownloadAttachment, resolveAttachmentDiskPath } from '../../domain/logic/attachment-download.rules';
import type { Attachment } from '../../domain/models/attachment.model'; import type { Attachment } from '../../domain/models/attachment.model';
import { CapacitorAttachmentExportService } from '../../infrastructure/services/capacitor-attachment-export.service';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class AttachmentDownloadService { export class AttachmentDownloadService {
private readonly electronBridge = inject(ElectronBridgeService); private readonly electronBridge = inject(ElectronBridgeService);
private readonly capacitorExport = inject(CapacitorAttachmentExportService);
private readonly document = inject(DOCUMENT); private readonly document = inject(DOCUMENT);
async downloadToUserLocation(attachment: Attachment): Promise<boolean> { async downloadToUserLocation(attachment: Attachment): Promise<boolean> {
@@ -15,6 +18,10 @@ export class AttachmentDownloadService {
return false; return false;
} }
if (isCapacitorNativeRuntime()) {
return this.capacitorExport.exportToDevice(attachment);
}
const electronApi = this.electronBridge.getApi(); const electronApi = this.electronBridge.getApi();
const diskPath = resolveAttachmentDiskPath(attachment); const diskPath = resolveAttachmentDiskPath(attachment);
@@ -10,12 +10,18 @@ import { RealtimeSessionFacade } from '../../../../core/realtime';
import { selectCurrentUserId } from '../../../../store/users/users.selectors'; import { selectCurrentUserId } from '../../../../store/users/users.selectors';
import { DatabaseService } from '../../../../infrastructure/persistence'; import { DatabaseService } from '../../../../infrastructure/persistence';
import { yieldToAttachmentHydrationLoop } from '../../domain/logic/attachment-blob.rules'; import { yieldToAttachmentHydrationLoop } from '../../domain/logic/attachment-blob.rules';
import { buildAttachmentDisplayPinKey, shouldRevokeDisplayBlobForAttachment } from '../../domain/logic/attachment-blob-eviction.rules'; import {
buildAttachmentDisplayPinKey,
collectMessageIdsForInactiveRoomBlobRelease,
shouldRevokeDisplayBlobForAttachment
} from '../../domain/logic/attachment-blob-eviction.rules';
import { import {
getWatchedAttachmentRoomIdFromUrl, getWatchedAttachmentRoomIdFromUrl,
isDirectMessageAttachmentRoomId, isDirectMessageAttachmentRoomId,
shouldAutoRequestWhenWatched shouldAutoRequestWhenWatched
} from '../../domain/logic/attachment.logic'; } from '../../domain/logic/attachment.logic';
import { ATTACHMENT_AUTO_DOWNLOAD_CONCURRENCY, runTasksWithBoundedConcurrency } from '../../domain/logic/attachment-autodownload-concurrency.rules';
import { shouldResetStalledAttachmentDownload } from '../../domain/logic/attachment-autodownload.rules';
import type { Attachment, AttachmentMeta } from '../../domain/models/attachment.model'; import type { Attachment, AttachmentMeta } from '../../domain/models/attachment.model';
import type { import type {
FileAnnouncePayload, FileAnnouncePayload,
@@ -66,8 +72,14 @@ export class AttachmentManagerService {
return; return;
} }
const previousRoomId = this.watchedRoomId;
this.watchedRoomId = this.extractWatchedRoomId(event.urlAfterRedirects || event.url); this.watchedRoomId = this.extractWatchedRoomId(event.urlAfterRedirects || event.url);
if (this.watchedRoomId !== previousRoomId) {
this.releaseDisplayBlobsForInactiveRooms(this.watchedRoomId);
}
if (this.watchedRoomId) { if (this.watchedRoomId) {
void this.restoreLocalAttachmentsForRoom(this.watchedRoomId); void this.restoreLocalAttachmentsForRoom(this.watchedRoomId);
void this.requestAutoDownloadsForRoom(this.watchedRoomId); void this.requestAutoDownloadsForRoom(this.watchedRoomId);
@@ -153,6 +165,10 @@ export class AttachmentManagerService {
return this.transfer.requestImageFromAnyPeer(messageId, attachment); return this.transfer.requestImageFromAnyPeer(messageId, attachment);
} }
hasPendingRequest(messageId: string, attachmentId: string): boolean {
return this.transfer.hasPendingRequest(messageId, attachmentId);
}
async tryRestoreAttachmentFromLocal(attachment: Attachment): Promise<boolean> { async tryRestoreAttachmentFromLocal(attachment: Attachment): Promise<boolean> {
const restored = await this.persistence.tryRestoreAttachmentFromLocal(attachment); const restored = await this.persistence.tryRestoreAttachmentFromLocal(attachment);
@@ -205,6 +221,18 @@ export class AttachmentManagerService {
} }
} }
releaseDisplayBlobsForInactiveRooms(activeRoomId: string | null): void {
const messageIds = collectMessageIdsForInactiveRoomBlobRelease(
Array.from(this.runtimeStore.getAttachmentEntries(), ([messageId]) => messageId),
(messageId) => this.runtimeStore.getMessageRoomId(messageId) ?? null,
activeRoomId
);
for (const messageId of messageIds) {
this.revokeOffscreenDisplayBlobsForMessage(messageId);
}
}
requestFile(messageId: string, attachment: Attachment): Promise<void> { requestFile(messageId: string, attachment: Attachment): Promise<void> {
return this.transfer.requestFile(messageId, attachment); return this.transfer.requestFile(messageId, attachment);
} }
@@ -316,33 +344,40 @@ export class AttachmentManagerService {
await this.restoreLocalAttachmentsForRoom(roomId); await this.restoreLocalAttachmentsForRoom(roomId);
if (isDirectMessageAttachmentRoomId(roomId)) { let messageIds: string[];
await this.requestAutoDownloadsForRuntimeRoom(roomId);
return;
}
if (this.database.isReady()) { if (isDirectMessageAttachmentRoomId(roomId)) {
messageIds = await this.collectMessageIdsForAttachmentsInRoom(roomId);
} else if (this.database.isReady()) {
const messages = await this.database.getMessages(roomId, 500, 0); const messages = await this.database.getMessages(roomId, 500, 0);
for (const message of messages) { for (const message of messages) {
this.runtimeStore.rememberMessageRoom(message.id, message.roomId); this.runtimeStore.rememberMessageRoom(message.id, message.roomId);
await this.requestAutoDownloadsForMessage(message.id);
} }
return; messageIds = messages.map((message) => message.id);
} else {
messageIds = await this.collectMessageIdsForAttachmentsInRoom(roomId);
} }
await this.requestAutoDownloadsForRuntimeRoom(roomId); await runTasksWithBoundedConcurrency(
messageIds.map((messageId) => () => this.requestAutoDownloadsForMessage(messageId)),
ATTACHMENT_AUTO_DOWNLOAD_CONCURRENCY
);
} }
private async requestAutoDownloadsForRuntimeRoom(roomId: string): Promise<void> { private async collectMessageIdsForAttachmentsInRoom(roomId: string): Promise<string[]> {
const messageIds: string[] = [];
for (const [messageId] of this.runtimeStore.getAttachmentEntries()) { for (const [messageId] of this.runtimeStore.getAttachmentEntries()) {
const attachmentRoomId = await this.persistence.resolveMessageRoomId(messageId); const attachmentRoomId = await this.persistence.resolveMessageRoomId(messageId);
if (attachmentRoomId === roomId) { if (attachmentRoomId === roomId) {
await this.requestAutoDownloadsForMessage(messageId); messageIds.push(messageId);
} }
} }
return messageIds;
} }
private async requestAutoDownloadsForMessage(messageId: string, attachmentId?: string): Promise<void> { private async requestAutoDownloadsForMessage(messageId: string, attachmentId?: string): Promise<void> {
@@ -367,8 +402,15 @@ export class AttachmentManagerService {
if (attachment.available) if (attachment.available)
continue; continue;
if ((attachment.receivedBytes ?? 0) > 0) if (shouldResetStalledAttachmentDownload(
attachment,
this.transfer.hasPendingRequest(messageId, attachment.id),
Date.now()
)) {
this.transfer.cancelRequest(messageId, attachment);
} else if ((attachment.receivedBytes ?? 0) > 0) {
continue; continue;
}
if (this.transfer.hasPendingRequest(messageId, attachment.id)) if (this.transfer.hasPendingRequest(messageId, attachment.id))
continue; continue;
@@ -134,6 +134,35 @@ describe('AttachmentPersistenceService', () => {
expect(attachmentStorage.readFile).not.toHaveBeenCalled(); expect(attachmentStorage.readFile).not.toHaveBeenCalled();
}); });
it('does not duplicate disk-hydrated bytes into the original-file cache', async () => {
const injector = Injector.create({
providers: [
AttachmentPersistenceService,
AttachmentRuntimeStore,
{ provide: DatabaseService, useValue: database },
{ provide: AttachmentStorageService, useValue: attachmentStorage },
{ provide: Store, useValue: { select: () => of('room-1') } }
]
});
const service = runInInjectionContext(injector, () => injector.get(AttachmentPersistenceService));
const runtimeStore = injector.get(AttachmentRuntimeStore);
const attachment = {
id: 'att-1',
messageId: 'msg-1',
filename: 'photo.png',
size: 3,
mime: 'image/png',
isImage: true,
savedPath: '/appdata/photo.png',
available: false
};
await expect(service.ensureInlineDisplayObjectUrl(attachment)).resolves.toBe(true);
expect(attachment.objectUrl).toMatch(/^blob:/);
expect(runtimeStore.getOriginalFile('msg-1:att-1')).toBeUndefined();
});
it('restores a blob from a whole-file read when the store cannot read chunks (browser store)', async () => { it('restores a blob from a whole-file read when the store cannot read chunks (browser store)', async () => {
attachmentStorage.canReadFileChunks.mockReturnValue(false); attachmentStorage.canReadFileChunks.mockReturnValue(false);
@@ -263,4 +292,66 @@ describe('AttachmentPersistenceService', () => {
revokeSpy.mockRestore(); revokeSpy.mockRestore();
}); });
it('releases the cached original file when revoking a disk-backed display blob', () => {
const injector = Injector.create({
providers: [
AttachmentPersistenceService,
AttachmentRuntimeStore,
{ provide: DatabaseService, useValue: database },
{ provide: AttachmentStorageService, useValue: attachmentStorage },
{ provide: Store, useValue: { select: () => of('room-1') } }
]
});
const service = runInInjectionContext(injector, () => injector.get(AttachmentPersistenceService));
const runtimeStore = injector.get(AttachmentRuntimeStore);
const attachment = {
id: 'att-1',
messageId: 'msg-1',
filename: 'photo.png',
size: 3,
mime: 'image/png',
isImage: true,
savedPath: '/appdata/photo.png',
available: true,
objectUrl: 'blob:http://localhost/abc'
};
const revokeSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
runtimeStore.setOriginalFile('msg-1:att-1', new File(['abc'], 'photo.png', { type: 'image/png' }));
expect(service.revokeAttachmentDisplayBlob(attachment)).toBe(true);
expect(runtimeStore.getOriginalFile('msg-1:att-1')).toBeUndefined();
revokeSpy.mockRestore();
});
it('keeps the cached original file when the attachment is not persisted to disk yet', () => {
const injector = Injector.create({
providers: [
AttachmentPersistenceService,
AttachmentRuntimeStore,
{ provide: DatabaseService, useValue: database },
{ provide: AttachmentStorageService, useValue: attachmentStorage },
{ provide: Store, useValue: { select: () => of('room-1') } }
]
});
const service = runInInjectionContext(injector, () => injector.get(AttachmentPersistenceService));
const runtimeStore = injector.get(AttachmentRuntimeStore);
const attachment = {
id: 'att-2',
messageId: 'msg-1',
filename: 'clip.mp4',
size: 3,
mime: 'video/mp4',
isImage: false,
available: true,
objectUrl: 'blob:http://localhost/def'
};
runtimeStore.setOriginalFile('msg-1:att-2', new File(['abc'], 'clip.mp4', { type: 'video/mp4' }));
expect(service.revokeAttachmentDisplayBlob(attachment)).toBe(false);
expect(runtimeStore.getOriginalFile('msg-1:att-2')).toBeDefined();
});
}); });
@@ -141,6 +141,13 @@ export class AttachmentPersistenceService {
this.revokeAttachmentObjectUrl(attachment); this.revokeAttachmentObjectUrl(attachment);
attachment.objectUrl = undefined; attachment.objectUrl = undefined;
// Once the bytes live on disk, the cached File duplicate is redundant:
// peer requests are served from the disk path and re-display rehydrates
// from disk, so keeping it would double the attachment's memory cost.
if (attachment.savedPath?.trim()) {
this.runtimeStore.deleteOriginalFile(`${attachment.messageId}:${attachment.id}`);
}
return true; return true;
} }
@@ -388,15 +395,12 @@ export class AttachmentPersistenceService {
return true; return true;
} }
// The blob always comes from a disk path here, so peers are served from
// disk and no original-file copy is cached; caching one would keep a second
// full copy of the bytes alive for the whole session.
private applyAttachmentBlob(attachment: Attachment, blob: Blob): void { private applyAttachmentBlob(attachment: Attachment, blob: Blob): void {
attachment.objectUrl = URL.createObjectURL(blob); attachment.objectUrl = URL.createObjectURL(blob);
attachment.available = true; attachment.available = true;
this.runtimeStore.setOriginalFile(
`${attachment.messageId}:${attachment.id}`,
new File([blob], attachment.filename, { type: attachment.mime })
);
this.runtimeStore.touch(); this.runtimeStore.touch();
} }
@@ -52,6 +52,7 @@ describe('AttachmentTransferService', () => {
getFileUrl: ReturnType<typeof vi.fn>; getFileUrl: ReturnType<typeof vi.fn>;
resolveExistingPath: ReturnType<typeof vi.fn>; resolveExistingPath: ReturnType<typeof vi.fn>;
resolveLegacyImagePath: ReturnType<typeof vi.fn>; resolveLegacyImagePath: ReturnType<typeof vi.fn>;
getFileSize: ReturnType<typeof vi.fn>;
appendBase64: ReturnType<typeof vi.fn>; appendBase64: ReturnType<typeof vi.fn>;
appendBytes: ReturnType<typeof vi.fn>; appendBytes: ReturnType<typeof vi.fn>;
createWritableFile: ReturnType<typeof vi.fn>; createWritableFile: ReturnType<typeof vi.fn>;
@@ -94,6 +95,7 @@ describe('AttachmentTransferService', () => {
getFileUrl: vi.fn(async () => null), getFileUrl: vi.fn(async () => null),
resolveExistingPath: vi.fn(async () => null), resolveExistingPath: vi.fn(async () => null),
resolveLegacyImagePath: vi.fn(async () => null), resolveLegacyImagePath: vi.fn(async () => null),
getFileSize: vi.fn(async () => null),
appendBase64: vi.fn(async () => true), appendBase64: vi.fn(async () => true),
appendBytes: vi.fn(async () => true), appendBytes: vi.fn(async () => true),
createWritableFile: vi.fn(async () => '/appdata/server/room/files/file-1'), createWritableFile: vi.fn(async () => '/appdata/server/room/files/file-1'),
@@ -391,11 +393,43 @@ describe('AttachmentTransferService', () => {
return attachment; return attachment;
} }
it('streams playable media to disk when the store supports streaming', async () => { it('assembles small images in memory even when the store supports disk streaming', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(true); attachmentStorage.canStreamToDisk.mockReturnValue(true);
const service = createService(); const service = createService();
const attachment = registerIncomingVideo(3); const attachment = registerIncomingAttachment(9);
service.handleFileChunk(chunkPayload(0, 3, [
1,
2,
3
]));
service.handleFileChunk(chunkPayload(1, 3, [
4,
5,
6
]));
service.handleFileChunk(chunkPayload(2, 3, [
7,
8,
9
]));
await vi.waitFor(() => expect(attachment.available).toBe(true));
expect(attachmentStorage.createWritableFile).not.toHaveBeenCalled();
expect(attachmentStorage.appendBytes).not.toHaveBeenCalled();
expect(persistence.saveFileToDisk).toHaveBeenCalledTimes(1);
expect(attachment.objectUrl).toMatch(/^blob:/);
});
it('streams oversized playable media to disk when the store supports streaming', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(true);
const service = createService();
const attachment = registerIncomingVideo(12 * 1024 * 1024);
service.handleFileChunk(chunkPayload(0, 1, [ service.handleFileChunk(chunkPayload(0, 1, [
1, 1,
@@ -414,6 +448,7 @@ describe('AttachmentTransferService', () => {
fileId: FILE_ID, fileId: FILE_ID,
index: 0 index: 0
}); });
expect(persistence.saveFileToDisk).not.toHaveBeenCalled(); expect(persistence.saveFileToDisk).not.toHaveBeenCalled();
}); });
@@ -480,6 +515,7 @@ describe('AttachmentTransferService', () => {
fileId: FILE_ID, fileId: FILE_ID,
index: 0 index: 0
}); });
expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled(); expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled();
expect(persistence.saveFileToDisk).not.toHaveBeenCalled(); expect(persistence.saveFileToDisk).not.toHaveBeenCalled();
expect(attachment.objectUrl).toBeUndefined(); expect(attachment.objectUrl).toBeUndefined();
@@ -510,15 +546,16 @@ describe('AttachmentTransferService', () => {
fileId: FILE_ID, fileId: FILE_ID,
index: 0 index: 0
}); });
expect(persistence.saveFileToDisk).not.toHaveBeenCalled(); expect(persistence.saveFileToDisk).not.toHaveBeenCalled();
expect(runtimeStore.getChunkBuffer(`${MESSAGE_ID}:${FILE_ID}`)).toBeUndefined(); expect(runtimeStore.getChunkBuffer(`${MESSAGE_ID}:${FILE_ID}`)).toBeUndefined();
}); });
it('does not hydrate media blobs after a disk-streamed download completes', async () => { it('does not hydrate image blobs after a disk-streamed oversized download completes', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(true); attachmentStorage.canStreamToDisk.mockReturnValue(true);
const service = createService(); const service = createService();
const attachment = registerIncomingVideo(3); const attachment = registerIncomingAttachment(12 * 1024 * 1024);
service.handleFileChunk(chunkPayload(0, 1, [ service.handleFileChunk(chunkPayload(0, 1, [
1, 1,
@@ -530,9 +567,55 @@ describe('AttachmentTransferService', () => {
expect(attachment.savedPath).toBeTruthy(); expect(attachment.savedPath).toBeTruthy();
expect(attachment.objectUrl).toBeUndefined(); expect(attachment.objectUrl).toBeUndefined();
expect(attachmentStorage.getFileUrl).not.toHaveBeenCalled();
expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled(); expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled();
}); });
it('hydrates playable media with a native file url after disk-streamed oversized download completes', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(true);
attachmentStorage.getFileUrl.mockResolvedValue('file:///appdata/server/room/files/clip.mp4');
const service = createService();
const attachment = registerIncomingVideo(12 * 1024 * 1024);
service.handleFileChunk(chunkPayload(0, 1, [
1,
2,
3
]));
await vi.waitFor(() => expect(attachment.objectUrl).toBe('file:///appdata/server/room/files/clip.mp4'));
expect(attachment.available).toBe(true);
expect(attachment.savedPath).toBeTruthy();
expect(attachmentStorage.getFileUrl).toHaveBeenCalledWith(attachment.savedPath);
expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled();
});
it('falls back to inline blob hydration for oversized playable media when no native file url exists', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(true);
attachmentStorage.getFileUrl.mockResolvedValue(null);
persistence.ensureInlineDisplayObjectUrl.mockImplementation(async (entry) => {
entry.objectUrl = 'blob:http://localhost/clip';
entry.available = true;
return true;
});
const service = createService();
const attachment = registerIncomingVideo(12 * 1024 * 1024);
service.handleFileChunk(chunkPayload(0, 1, [
1,
2,
3
]));
await vi.waitFor(() => expect(persistence.ensureInlineDisplayObjectUrl).toHaveBeenCalled());
expect(attachment.objectUrl).toBe('blob:http://localhost/clip');
expect(attachment.available).toBe(true);
});
it('rejects oversized browser downloads before requesting peers', async () => { it('rejects oversized browser downloads before requesting peers', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(false); attachmentStorage.canStreamToDisk.mockReturnValue(false);
attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024); attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024);
@@ -546,6 +629,36 @@ describe('AttachmentTransferService', () => {
expect(webrtc.sendToPeer).not.toHaveBeenCalled(); expect(webrtc.sendToPeer).not.toHaveBeenCalled();
}); });
it('assembles generic files above the auto-save cap in memory when the store cannot stream but can persist them', async () => {
// Browser receiver: no disk streaming, persistable up to 50 MB. The request
// gate admits a 20 MB file for in-memory receive, so the chunk handler must
// accept its chunks instead of dropping them with a file-too-large error.
attachmentStorage.canStreamToDisk.mockReturnValue(false);
attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024);
const service = createService();
const attachment = registerIncomingGenericFile(20 * 1024 * 1024);
service.handleFileChunk(chunkPayload(0, 2, [
1,
2,
3
]));
expect(attachment.requestError).toBeUndefined();
expect(attachment.receivedBytes).toBe(3);
service.handleFileChunk(chunkPayload(1, 2, [
4,
5,
6
]));
await vi.waitFor(() => expect(attachment.available).toBe(true));
expect(attachment.objectUrl).toMatch(/^blob:/);
});
it('assembles browser-sized generic files in memory when streaming is unavailable', async () => { it('assembles browser-sized generic files in memory when streaming is unavailable', async () => {
attachmentStorage.canStreamToDisk.mockReturnValue(false); attachmentStorage.canStreamToDisk.mockReturnValue(false);
attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024); attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024);
@@ -583,8 +696,30 @@ describe('AttachmentTransferService', () => {
expect(persistence.persistUploadCopyFromSourcePath).toHaveBeenCalled(); expect(persistence.persistUploadCopyFromSourcePath).toHaveBeenCalled();
}); });
it('falls back to the in-memory upload when the resolved disk path is empty', async () => {
attachmentStorage.resolveExistingPath.mockResolvedValue('/appdata/server/room/files/photo.png');
attachmentStorage.getFileSize.mockResolvedValue(0);
const service = createService();
const attachment = registerIncomingAttachment(9);
attachment.available = true;
attachment.savedPath = '/appdata/server/room/files/photo.png';
runtimeStore.setOriginalFile(`${MESSAGE_ID}:${FILE_ID}`, new File([new Uint8Array(9)], 'photo.png', { type: 'image/png' }));
await service.handleFileRequest({
messageId: MESSAGE_ID,
fileId: FILE_ID,
fromPeerId: 'peer-2'
});
expect(transport.streamFileFromDiskToPeer).not.toHaveBeenCalled();
expect(transport.streamFileToPeer).toHaveBeenCalledTimes(1);
});
it('streams a restored oversized generic file from app data when the in-memory upload is gone', async () => { it('streams a restored oversized generic file from app data when the in-memory upload is gone', async () => {
attachmentStorage.resolveExistingPath.mockResolvedValue('/appdata/server/room/files/setup.exe'); attachmentStorage.resolveExistingPath.mockResolvedValue('/appdata/server/room/files/setup.exe');
attachmentStorage.getFileSize.mockResolvedValue(12 * 1024 * 1024);
const service = createService(); const service = createService();
const attachment = registerIncomingGenericFile(12 * 1024 * 1024); const attachment = registerIncomingGenericFile(12 * 1024 * 1024);
@@ -688,6 +823,7 @@ describe('AttachmentTransferService', () => {
it('prefers streaming from disk over an in-memory original file when both exist', async () => { it('prefers streaming from disk over an in-memory original file when both exist', async () => {
attachmentStorage.resolveExistingPath.mockResolvedValue('/appdata/server/room/files/setup.exe'); attachmentStorage.resolveExistingPath.mockResolvedValue('/appdata/server/room/files/setup.exe');
attachmentStorage.getFileSize.mockResolvedValue(12 * 1024 * 1024);
const service = createService(); const service = createService();
const attachment = registerIncomingGenericFile(12 * 1024 * 1024); const attachment = registerIncomingGenericFile(12 * 1024 * 1024);
@@ -727,4 +863,148 @@ describe('AttachmentTransferService', () => {
expect(attachment.available).toBe(true); expect(attachment.available).toBe(true);
expect(attachment.savedPath).toBe('/appdata/server/room/files/setup.exe'); expect(attachment.savedPath).toBe('/appdata/server/room/files/setup.exe');
}); });
it('sends file-cancel to pending request peers instead of only the uploader', async () => {
const mirrorPeer = 'mirror-peer';
webrtc.getConnectedPeers.mockReturnValue([mirrorPeer]);
webrtc.sendToPeer.mockClear();
const service = createService();
const attachment = registerIncomingAttachment(3_000);
attachment.uploaderPeerId = 'uploader-peer';
runtimeStore.addAnnouncedHost(`${MESSAGE_ID}:${FILE_ID}`, mirrorPeer);
runtimeStore.addAnnouncedHost(`${MESSAGE_ID}:${FILE_ID}`, attachment.uploaderPeerId);
await service.requestFromAnyPeer(MESSAGE_ID, attachment);
expect(webrtc.sendToPeer).toHaveBeenCalledWith(mirrorPeer, expect.objectContaining({
type: 'file-request'
}));
attachment.receivedBytes = 512;
service.cancelRequest(MESSAGE_ID, attachment);
expect(webrtc.sendToPeer).toHaveBeenCalledWith(mirrorPeer, {
type: 'file-cancel',
messageId: MESSAGE_ID,
fileId: FILE_ID
});
expect(attachment.receivedBytes).toBe(0);
expect(attachment.available).toBe(false);
expect(service.hasPendingRequest(MESSAGE_ID, FILE_ID)).toBe(false);
});
it('normalizes generic octet-stream announces into image metadata for gallery grouping', () => {
const service = createService();
expect(service.handleFileAnnounce({
messageId: MESSAGE_ID,
fromPeerId: PEER_ID,
file: {
id: FILE_ID,
filename: 'grid.png',
size: 512,
mime: 'application/octet-stream',
isImage: false,
uploaderPeerId: PEER_ID
}
})).toBe(true);
const attachment = runtimeStore.getAttachmentsForMessage(MESSAGE_ID)[0];
expect(attachment.mime).toBe('image/png');
expect(attachment.isImage).toBe(true);
});
it('hydrates playable media from disk without re-requesting when display url is missing', async () => {
persistence.tryRestoreAttachmentFromLocal.mockImplementation(async (attachment) => {
attachment.objectUrl = 'file:///appdata/song.mp3';
attachment.available = true;
return true;
});
const service = createService();
const attachment: Attachment = {
id: FILE_ID,
messageId: MESSAGE_ID,
filename: 'song.mp3',
size: 1024,
mime: 'audio/mpeg',
isImage: false,
uploaderPeerId: PEER_ID,
available: true,
savedPath: '/appdata/song.mp3',
receivedBytes: 0
};
runtimeStore.setAttachmentsForMessage(MESSAGE_ID, [attachment]);
await service.requestFromAnyPeer(MESSAGE_ID, attachment);
expect(persistence.tryRestoreAttachmentFromLocal).toHaveBeenCalled();
expect(webrtc.sendToPeer).not.toHaveBeenCalled();
expect(attachment.objectUrl).toBe('file:///appdata/song.mp3');
});
it('hydrates small in-memory audio downloads with a native file url when available', async () => {
attachmentStorage.getFileUrl.mockResolvedValue('file:///appdata/song.mp3');
persistence.saveFileToDisk.mockImplementation(async (attachment) => {
attachment.savedPath = '/appdata/song.mp3';
return attachment.savedPath;
});
const service = createService();
const attachment: Attachment = {
id: FILE_ID,
messageId: MESSAGE_ID,
filename: 'song.mp3',
size: 1024,
mime: 'audio/mpeg',
isImage: false,
uploaderPeerId: PEER_ID,
available: false,
receivedBytes: 0
};
runtimeStore.setAttachmentsForMessage(MESSAGE_ID, [attachment]);
service.handleFileChunk(chunkPayload(0, 1, [
1,
2,
3
]));
await vi.waitFor(() => expect(attachment.objectUrl).toBe('file:///appdata/song.mp3'));
expect(attachment.available).toBe(true);
expect(attachment.savedPath).toBe('/appdata/song.mp3');
});
it('does not cancel hydrating gallery retries before attempting local restore', async () => {
persistence.tryRestoreAttachmentFromLocal.mockResolvedValue(true);
const service = createService();
const attachment: Attachment = {
id: FILE_ID,
messageId: MESSAGE_ID,
filename: 'grid.png',
size: 512,
mime: 'image/png',
isImage: true,
uploaderPeerId: PEER_ID,
available: false,
savedPath: '/appdata/grid.png',
receivedBytes: 0
};
runtimeStore.setAttachmentsForMessage(MESSAGE_ID, [attachment]);
await service.requestImageFromAnyPeer(MESSAGE_ID, attachment);
expect(persistence.tryRestoreAttachmentFromLocal).toHaveBeenCalled();
expect(webrtc.sendToPeer).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ type: 'file-cancel' }));
});
}); });
@@ -13,10 +13,14 @@ import { isSharingFromThisDevice, canHostAttachment } from '../../domain/logic/a
import { selectFileRequestPeer } from '../../domain/logic/attachment-request.rules'; import { selectFileRequestPeer } from '../../domain/logic/attachment-request.rules';
import { import {
canReceiveAttachment, canReceiveAttachment,
needsAttachmentDisplayHydration,
shouldCopyLargeUploaderFileToAppData, shouldCopyLargeUploaderFileToAppData,
shouldPersistDownloadedAttachment, shouldPersistDownloadedAttachment,
shouldStreamAttachmentReceiveToDisk shouldStreamAttachmentReceiveToDisk
} from '../../domain/logic/attachment.logic'; } from '../../domain/logic/attachment.logic';
import { normalizeAttachmentMeta } from '../../domain/logic/attachment-normalize.rules';
import { resolveAttachmentMime } from '../../domain/logic/attachment-mime.rules';
import { shouldServeAttachmentFromDiskPath } from '../../domain/logic/attachment-serve.rules';
import type { Attachment, AttachmentMeta } from '../../domain/models/attachment.model'; import type { Attachment, AttachmentMeta } from '../../domain/models/attachment.model';
import { import {
ATTACHMENT_TRANSFER_EWMA_CURRENT_WEIGHT, ATTACHMENT_TRANSFER_EWMA_CURRENT_WEIGHT,
@@ -140,9 +144,11 @@ export class AttachmentTransferService {
const alreadyKnown = existing.find((entry) => entry.id === meta.id); const alreadyKnown = existing.find((entry) => entry.id === meta.id);
if (!alreadyKnown) { if (!alreadyKnown) {
const attachment: Attachment = { ...meta, const attachment: Attachment = {
...normalizeAttachmentMeta(meta),
available: false, available: false,
receivedBytes: 0 }; receivedBytes: 0
};
existing.push(attachment); existing.push(attachment);
newAttachments.push(attachment); newAttachments.push(attachment);
@@ -170,6 +176,16 @@ export class AttachmentTransferService {
// request makes the sender stream the file twice and corrupts byte accounting. // request makes the sender stream the file twice and corrupts byte accounting.
this.runtimeStore.setPendingRequestPeers(requestKey, new Set<string>()); this.runtimeStore.setPendingRequestPeers(requestKey, new Set<string>());
if (needsAttachmentDisplayHydration(attachment)) {
const hydratedLocally = await this.persistence.tryRestoreAttachmentFromLocal(attachment);
if (hydratedLocally) {
this.runtimeStore.deletePendingRequest(requestKey);
this.runtimeStore.touch();
return;
}
}
if (!attachment.available) { if (!attachment.available) {
const restoredLocally = await this.persistence.tryRestoreAttachmentFromLocal(attachment); const restoredLocally = await this.persistence.tryRestoreAttachmentFromLocal(attachment);
@@ -229,6 +245,14 @@ export class AttachmentTransferService {
} }
requestImageFromAnyPeer(messageId: string, attachment: Attachment): Promise<void> { requestImageFromAnyPeer(messageId: string, attachment: Attachment): Promise<void> {
if (needsAttachmentDisplayHydration(attachment)) {
return this.requestFromAnyPeer(messageId, attachment);
}
if ((attachment.receivedBytes ?? 0) > 0 || this.hasPendingRequest(messageId, attachment.id)) {
this.cancelRequest(messageId, attachment);
}
return this.requestFromAnyPeer(messageId, attachment); return this.requestFromAnyPeer(messageId, attachment);
} }
@@ -254,7 +278,7 @@ export class AttachmentTransferService {
messageId, messageId,
filename: file.name, filename: file.name,
size: file.size, size: file.size,
mime: file.type || DEFAULT_ATTACHMENT_MIME_TYPE, mime: resolveAttachmentMime(file.name, file.type || DEFAULT_ATTACHMENT_MIME_TYPE),
isImage: resolvePublishAttachmentIsImage(file), isImage: resolvePublishAttachmentIsImage(file),
uploaderPeerId, uploaderPeerId,
filePath: (file as LocalFileWithPath).path, filePath: (file as LocalFileWithPath).path,
@@ -322,29 +346,40 @@ export class AttachmentTransferService {
const alreadyKnown = list.find((entry) => entry.id === file.id); const alreadyKnown = list.find((entry) => entry.id === file.id);
if (alreadyKnown) { if (alreadyKnown) {
alreadyKnown.filename = file.filename;
alreadyKnown.size = file.size;
alreadyKnown.mime = resolveAttachmentMime(file.filename, file.mime);
alreadyKnown.isImage = isImageAttachment({
filename: file.filename,
isImage: !!file.isImage,
mime: alreadyKnown.mime
});
alreadyKnown.uploaderPeerId = file.uploaderPeerId ?? alreadyKnown.uploaderPeerId;
this.runtimeStore.touch();
void this.persistence.persistAttachmentMeta(alreadyKnown);
return false; return false;
} }
const attachment: Attachment = { const normalizedMeta = normalizeAttachmentMeta({
id: file.id, id: file.id,
messageId, messageId,
filename: file.filename, filename: file.filename,
size: file.size, size: file.size,
mime: file.mime, mime: file.mime,
isImage: isImageAttachment({
filename: file.filename,
isImage: !!file.isImage, isImage: !!file.isImage,
mime: file.mime uploaderPeerId: file.uploaderPeerId
}), });
uploaderPeerId: file.uploaderPeerId, const runtimeAttachment: Attachment = {
...normalizedMeta,
available: false, available: false,
receivedBytes: 0 receivedBytes: 0
}; };
list.push(attachment); list.push(runtimeAttachment);
this.runtimeStore.setAttachmentsForMessage(messageId, list); this.runtimeStore.setAttachmentsForMessage(messageId, list);
this.runtimeStore.touch(); this.runtimeStore.touch();
void this.persistence.persistAttachmentMeta(attachment); void this.persistence.persistAttachmentMeta(runtimeAttachment);
return true; return true;
} }
@@ -390,12 +425,11 @@ export class AttachmentTransferService {
return; return;
} }
if (attachment.size > MAX_AUTO_SAVE_SIZE_BYTES) { // Reaching here means canReceiveAttachment passed and disk streaming is not
attachment.requestError = this.appI18n.instant(ATTACHMENT_FILE_TOO_LARGE_KEY); // used, so the in-memory path is the agreed receive strategy - including
this.runtimeStore.touch(); // above-auto-save-cap files on stores that cannot stream but can persist
return; // them (browser). A stricter size guard here would silently drop chunks the
} // request gate already admitted.
const decodedBytes = this.transport.decodeBase64(data); const decodedBytes = this.transport.decodeBase64(data);
const assemblyKey = `${messageId}:${fileId}`; const assemblyKey = `${messageId}:${fileId}`;
const requestKey = this.buildRequestKey(messageId, fileId); const requestKey = this.buildRequestKey(messageId, fileId);
@@ -456,22 +490,22 @@ export class AttachmentTransferService {
} }
cancelRequest(messageId: string, attachment: Attachment): void { cancelRequest(messageId: string, attachment: Attachment): void {
const targetPeerId = attachment.uploaderPeerId;
if (!targetPeerId)
return;
try { try {
const requestKey = this.buildRequestKey(messageId, attachment.id);
const assemblyKey = `${messageId}:${attachment.id}`; const assemblyKey = `${messageId}:${attachment.id}`;
const pendingPeers = this.runtimeStore.getPendingRequestPeers(requestKey);
this.runtimeStore.deleteChunkBuffer(assemblyKey); this.runtimeStore.deleteChunkBuffer(assemblyKey);
this.runtimeStore.deleteChunkCount(assemblyKey); this.runtimeStore.deleteChunkCount(assemblyKey);
this.runtimeStore.deletePendingRequest(requestKey);
void this.deleteDiskReceiveAssembly(assemblyKey); void this.deleteDiskReceiveAssembly(assemblyKey);
this.chunkAcks.cancelPendingForFile(messageId, attachment.id);
attachment.receivedBytes = 0; attachment.receivedBytes = 0;
attachment.speedBps = 0; attachment.speedBps = 0;
attachment.startedAtMs = undefined; attachment.startedAtMs = undefined;
attachment.lastUpdateMs = undefined; attachment.lastUpdateMs = undefined;
attachment.requestError = undefined;
if (attachment.objectUrl) { if (attachment.objectUrl) {
try { try {
@@ -489,8 +523,21 @@ export class AttachmentTransferService {
messageId, messageId,
fileId: attachment.id fileId: attachment.id
}; };
const peersToNotify = new Set<string>();
this.webrtc.sendToPeer(targetPeerId, fileCancelEvent); if (pendingPeers) {
for (const peerId of pendingPeers) {
peersToNotify.add(peerId);
}
}
if (attachment.uploaderPeerId) {
peersToNotify.add(attachment.uploaderPeerId);
}
for (const peerId of peersToNotify) {
this.webrtc.sendToPeer(peerId, fileCancelEvent);
}
} catch { /* best-effort */ } } catch { /* best-effort */ }
} }
@@ -547,7 +594,7 @@ export class AttachmentTransferService {
? await this.attachmentStorage.resolveExistingPath(attachment) ? await this.attachmentStorage.resolveExistingPath(attachment)
: null; : null;
if (diskPath) { if (diskPath && shouldServeAttachmentFromDiskPath(await this.attachmentStorage.getFileSize(diskPath))) {
await this.transport.streamFileFromDiskToPeer( await this.transport.streamFileFromDiskToPeer(
fromPeerId, fromPeerId,
messageId, messageId,
@@ -581,7 +628,7 @@ export class AttachmentTransferService {
roomName roomName
); );
if (legacyDiskPath) { if (legacyDiskPath && shouldServeAttachmentFromDiskPath(await this.attachmentStorage.getFileSize(legacyDiskPath))) {
await this.transport.streamFileFromDiskToPeer( await this.transport.streamFileFromDiskToPeer(
fromPeerId, fromPeerId,
messageId, messageId,
@@ -775,6 +822,10 @@ export class AttachmentTransferService {
this.runtimeStore.touch(); this.runtimeStore.touch();
void this.persistence.persistAttachmentMeta(attachment); void this.persistence.persistAttachmentMeta(attachment);
void this.announceLocalHost(attachment); void this.announceLocalHost(attachment);
if (this.isPlayableMedia(attachment)) {
await this.hydratePlayableMediaAfterDiskReceive(attachment);
}
} }
/** /**
@@ -997,6 +1048,23 @@ export class AttachmentTransferService {
this.runtimeStore.touch(); this.runtimeStore.touch();
void this.persistence.persistAttachmentMeta(attachment); void this.persistence.persistAttachmentMeta(attachment);
void this.announceLocalHost(attachment); void this.announceLocalHost(attachment);
void this.hydratePlayableMediaAfterDiskReceive(attachment);
}
private async hydratePlayableMediaAfterDiskReceive(attachment: Attachment): Promise<void> {
if (!this.isPlayableMedia(attachment) || !attachment.savedPath) {
return;
}
const nativeUrl = await this.attachmentStorage.getFileUrl(attachment.savedPath);
if (nativeUrl) {
attachment.objectUrl = nativeUrl;
this.runtimeStore.touch();
return;
}
await this.persistence.ensureInlineDisplayObjectUrl(attachment);
} }
private async getOrCreateDiskReceiveAssembly( private async getOrCreateDiskReceiveAssembly(
@@ -0,0 +1,29 @@
import { runTasksWithBoundedConcurrency } from './attachment-autodownload-concurrency.rules';
describe('attachment-autodownload-concurrency.rules', () => {
it('runs tasks with bounded concurrency', async () => {
let active = 0;
let maxActive = 0;
const tasks = Array.from({ length: 6 }, (_, index) => async () => {
active += 1;
maxActive = Math.max(maxActive, active);
await new Promise((resolve) => setTimeout(resolve, 5));
active -= 1;
return index;
});
const results = await runTasksWithBoundedConcurrency(tasks, 2);
expect(results).toEqual([
0,
1,
2,
3,
4,
5
]);
expect(maxActive).toBeLessThanOrEqual(2);
});
});
@@ -0,0 +1,29 @@
/** Default parallel attachment auto-download limit per watched room. */
export const ATTACHMENT_AUTO_DOWNLOAD_CONCURRENCY = 3;
export async function runTasksWithBoundedConcurrency<T>(
tasks: readonly (() => Promise<T>)[],
concurrency: number
): Promise<T[]> {
if (tasks.length === 0) {
return [];
}
const limit = Math.max(1, Math.min(concurrency, tasks.length));
const results: T[] = new Array(tasks.length);
let nextIndex = 0;
async function runWorker(): Promise<void> {
while (nextIndex < tasks.length) {
const currentIndex = nextIndex;
nextIndex += 1;
results[currentIndex] = await tasks[currentIndex]();
}
}
await Promise.all(Array.from({ length: limit }, () => runWorker()));
return results;
}
@@ -0,0 +1,52 @@
import { ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS, shouldResetStalledAttachmentDownload } from './attachment-autodownload.rules';
const NOW_MS = 1_750_000_000_000;
describe('attachment autodownload rules', () => {
it('does not reset an actively transferring download with recent chunk progress', () => {
// Regression: the pending-request marker is deleted on the first received
// chunk, so an in-flight multi-chunk transfer has receivedBytes > 0 and no
// pending request - it must NOT be treated as stalled while chunks flow.
expect(shouldResetStalledAttachmentDownload({
available: false,
receivedBytes: 128,
lastUpdateMs: NOW_MS - 100
}, false, NOW_MS)).toBe(false);
});
it('resets partial downloads with no progress past the stall threshold', () => {
expect(shouldResetStalledAttachmentDownload({
available: false,
receivedBytes: 128,
lastUpdateMs: NOW_MS - ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS - 1
}, false, NOW_MS)).toBe(true);
});
it('treats partial downloads without a progress timestamp as stalled', () => {
expect(shouldResetStalledAttachmentDownload({
available: false,
receivedBytes: 128
}, false, NOW_MS)).toBe(true);
});
it('never resets downloads with a pending request or already available', () => {
expect(shouldResetStalledAttachmentDownload({
available: false,
receivedBytes: 128,
lastUpdateMs: NOW_MS - ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS - 1
}, true, NOW_MS)).toBe(false);
expect(shouldResetStalledAttachmentDownload({
available: true,
receivedBytes: 128,
lastUpdateMs: NOW_MS - ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS - 1
}, false, NOW_MS)).toBe(false);
});
it('never resets downloads that have not received any bytes', () => {
expect(shouldResetStalledAttachmentDownload({
available: false,
receivedBytes: 0
}, false, NOW_MS)).toBe(false);
});
});
@@ -0,0 +1,33 @@
/**
* How long a partial download may go without chunk progress before an
* auto-download pass treats it as stalled and resets it for a retry.
*/
export const ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS = 15_000;
/**
* The pending-request marker is deleted as soon as the first chunk arrives, so
* "no pending request" does NOT mean "not transferring". An in-flight transfer
* is recognized by recent chunk progress (`lastUpdateMs`); only partials with
* no progress past the stall threshold (or with no progress timestamp at all,
* e.g. leftovers from a previous session) may be reset - resetting an active
* transfer cancels it on the sender and deadlocks the retry against the
* sender's active-transfer dedupe.
*/
export function shouldResetStalledAttachmentDownload(
attachment: Pick<
{ available?: boolean; lastUpdateMs?: number; receivedBytes?: number },
'available' | 'lastUpdateMs' | 'receivedBytes'
>,
hasPendingRequest: boolean,
nowMs: number
): boolean {
if (attachment.available || hasPendingRequest || (attachment.receivedBytes ?? 0) === 0) {
return false;
}
if (!attachment.lastUpdateMs) {
return true;
}
return nowMs - attachment.lastUpdateMs > ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS;
}
@@ -7,6 +7,7 @@ import {
import { import {
buildAttachmentDisplayPinKey, buildAttachmentDisplayPinKey,
canRevokeAttachmentDisplayBlob, canRevokeAttachmentDisplayBlob,
collectMessageIdsForInactiveRoomBlobRelease,
shouldRevokeDisplayBlobForAttachment shouldRevokeDisplayBlobForAttachment
} from './attachment-blob-eviction.rules'; } from './attachment-blob-eviction.rules';
@@ -58,4 +59,40 @@ describe('attachment-blob-eviction rules', () => {
expect(shouldRevokeDisplayBlobForAttachment('msg-1', attachment, new Set())).toBe(true); expect(shouldRevokeDisplayBlobForAttachment('msg-1', attachment, new Set())).toBe(true);
}); });
describe('collectMessageIdsForInactiveRoomBlobRelease', () => {
const messageRoomIds = new Map([
['msg-a', 'room-1'],
['msg-b', 'room-2'],
['msg-c', 'room-2']
]);
it('selects messages that belong to rooms other than the active one', () => {
expect(collectMessageIdsForInactiveRoomBlobRelease(
[
'msg-a',
'msg-b',
'msg-c'
],
(messageId) => messageRoomIds.get(messageId) ?? null,
'room-1'
)).toEqual(['msg-b', 'msg-c']);
});
it('skips messages with an unknown room so they are not evicted by mistake', () => {
expect(collectMessageIdsForInactiveRoomBlobRelease(
['msg-a', 'msg-unknown'],
(messageId) => messageRoomIds.get(messageId) ?? null,
'room-2'
)).toEqual(['msg-a']);
});
it('selects every known-room message when no room is active', () => {
expect(collectMessageIdsForInactiveRoomBlobRelease(
['msg-a', 'msg-b'],
(messageId) => messageRoomIds.get(messageId) ?? null,
null
)).toEqual(['msg-a', 'msg-b']);
});
});
}); });
@@ -45,6 +45,31 @@ export function shouldRevokeDisplayBlobForAttachment(
return canRevokeAttachmentDisplayBlob(attachment); return canRevokeAttachmentDisplayBlob(attachment);
} }
/**
* On room switch, display blobs from every other room are released so their
* memory does not accumulate across the servers a user visits in a session.
* Messages whose room is unknown are left alone rather than evicted blindly.
*/
export function collectMessageIdsForInactiveRoomBlobRelease(
messageIds: Iterable<string>,
resolveMessageRoomId: (messageId: string) => string | null,
activeRoomId: string | null
): string[] {
const selected: string[] = [];
for (const messageId of messageIds) {
const roomId = resolveMessageRoomId(messageId);
if (!roomId || roomId === activeRoomId) {
continue;
}
selected.push(messageId);
}
return selected;
}
function hasNonEmptyString(value: string | null | undefined): boolean { function hasNonEmptyString(value: string | null | undefined): boolean {
return typeof value === 'string' && value.trim().length > 0; return typeof value === 'string' && value.trim().length > 0;
} }
@@ -4,10 +4,7 @@ import {
it it
} from 'vitest'; } from 'vitest';
import { import { base64DecodedByteLength, decodeBase64ToUint8Array } from './attachment-blob.rules';
base64DecodedByteLength,
decodeBase64ToUint8Array
} from './attachment-blob.rules';
describe('attachment blob rules', () => { describe('attachment blob rules', () => {
it('decodes base64 payloads into byte arrays', () => { it('decodes base64 payloads into byte arrays', () => {
@@ -4,10 +4,7 @@ import {
it it
} from 'vitest'; } from 'vitest';
import { import { canDownloadAttachment, resolveAttachmentDiskPath } from './attachment-download.rules';
canDownloadAttachment,
resolveAttachmentDiskPath
} from './attachment-download.rules';
describe('attachment-download.rules', () => { describe('attachment-download.rules', () => {
it('allows download when a completed disk-only attachment has no object URL', () => { it('allows download when a completed disk-only attachment has no object URL', () => {
@@ -0,0 +1,31 @@
import {
describe,
expect,
it
} from 'vitest';
import { buildAttachmentExportFileName } from './attachment-export.rules';
describe('buildAttachmentExportFileName', () => {
it('appends the timestamp before the extension so exports never collide', () => {
expect(buildAttachmentExportFileName('report.pdf', 1_720_900_000_000)).toBe('report-1720900000000.pdf');
});
it('appends the timestamp at the end when there is no extension', () => {
expect(buildAttachmentExportFileName('README', 42)).toBe('README-42');
});
it('keeps dotfiles intact instead of treating the leading dot as an extension', () => {
expect(buildAttachmentExportFileName('.env', 42)).toBe('.env-42');
});
it('strips directory components from the filename', () => {
expect(buildAttachmentExportFileName('../secret/../../etc/passwd.txt', 7)).toBe('passwd-7.txt');
expect(buildAttachmentExportFileName('folder\\file.bin', 7)).toBe('file-7.bin');
});
it('falls back to a generic name when the filename is empty after sanitising', () => {
expect(buildAttachmentExportFileName(' ', 7)).toBe('attachment-7');
expect(buildAttachmentExportFileName('a/b/', 7)).toBe('attachment-7');
});
});
@@ -0,0 +1,23 @@
const FALLBACK_EXPORT_BASE_NAME = 'attachment';
/**
* Build the file name used when exporting an attachment to a user-visible
* directory (e.g. Android `Documents`). The timestamp is appended before the
* extension so repeated exports of the same file never collide - public
* directories on Android 11+ reject overwrites of files the app did not create.
*/
export function buildAttachmentExportFileName(filename: string, timestamp: number): string {
const baseName = stripDirectoryComponents(filename);
const dotIndex = baseName.lastIndexOf('.');
const hasExtension = dotIndex > 0;
const stem = hasExtension ? baseName.slice(0, dotIndex) : baseName;
const extension = hasExtension ? baseName.slice(dotIndex) : '';
return `${stem || FALLBACK_EXPORT_BASE_NAME}-${timestamp}${extension}`;
}
function stripDirectoryComponents(filename: string): string {
const segments = filename.split(/[/\\]/);
return segments[segments.length - 1]?.trim() ?? '';
}
@@ -0,0 +1,46 @@
import { shouldHydrateInlineImageForVisibility, shouldHydratePlayableMediaForVisibility } from './attachment-hydration-visibility.rules';
const diskBackedImage = {
available: false,
filename: 'photo.png',
id: 'att-1',
isImage: true,
mime: 'image/png',
savedPath: '/appdata/photo.png'
};
const diskBackedVideo = {
available: false,
mime: 'video/mp4',
savedPath: '/appdata/clip.mp4'
};
describe('attachment hydration visibility rules', () => {
it('hydrates a disk-backed image only when the message is visible', () => {
expect(shouldHydrateInlineImageForVisibility(diskBackedImage, true)).toBe(true);
expect(shouldHydrateInlineImageForVisibility(diskBackedImage, false)).toBe(false);
});
it('never hydrates an image that is already displayable', () => {
const displayable = {
...diskBackedImage,
available: true,
objectUrl: 'blob:http://localhost/abc'
};
expect(shouldHydrateInlineImageForVisibility(displayable, true)).toBe(false);
});
it('hydrates disk-backed playable media only when the message is visible', () => {
expect(shouldHydratePlayableMediaForVisibility(diskBackedVideo, true)).toBe(true);
expect(shouldHydratePlayableMediaForVisibility(diskBackedVideo, false)).toBe(false);
});
it('never hydrates media that already has an object URL', () => {
const hydrated = {
...diskBackedVideo,
objectUrl: 'blob:http://localhost/def'
};
expect(shouldHydratePlayableMediaForVisibility(hydrated, true)).toBe(false);
});
});
@@ -0,0 +1,49 @@
import type { Attachment } from '../models/attachment.model';
import { isAttachmentPendingInlineHydration, isInlineDisplayableImage } from './attachment-image.rules';
import { isAttachmentPendingMediaHydration } from './attachment.logic';
type InlineImageCandidate = Pick<
Attachment,
'available' | 'filePath' | 'filename' | 'isImage' | 'mime' | 'objectUrl' | 'receivedBytes' | 'savedPath'
>;
type PlayableMediaCandidate = Pick<
Attachment,
'available' | 'filePath' | 'mime' | 'objectUrl' | 'receivedBytes' | 'savedPath'
>;
/**
* Display blobs are only hydrated for messages inside (or near) the viewport.
* Hydrating off-screen rows loads full decoded media into the blob store for
* rows the user may never scroll to, which is the main renderer/browser-process
* memory driver in attachment-heavy rooms.
*/
export function shouldHydrateInlineImageForVisibility(
image: InlineImageCandidate,
isMessageVisible: boolean
): boolean {
if (!isMessageVisible) {
return false;
}
if (isInlineDisplayableImage(image)) {
return false;
}
return isAttachmentPendingInlineHydration(image);
}
export function shouldHydratePlayableMediaForVisibility(
media: PlayableMediaCandidate,
isMessageVisible: boolean
): boolean {
if (!isMessageVisible) {
return false;
}
if (media.objectUrl) {
return false;
}
return isAttachmentPendingMediaHydration(media);
}
@@ -0,0 +1,41 @@
import { resolveAttachmentMime } from './attachment-mime.rules';
import { normalizeAttachmentMeta } from './attachment-normalize.rules';
describe('attachment mime rules', () => {
it('keeps explicit audio and video mime types', () => {
expect(resolveAttachmentMime('song.mp3', 'audio/mpeg')).toBe('audio/mpeg');
expect(resolveAttachmentMime('clip.mp4', 'video/mp4')).toBe('video/mp4');
});
it('infers mime types from filenames when the declared type is generic', () => {
expect(resolveAttachmentMime('song.mp3', 'application/octet-stream')).toBe('audio/mpeg');
expect(resolveAttachmentMime('clip.webm', '')).toBe('video/webm');
expect(resolveAttachmentMime('photo.heic', 'application/octet-stream')).toBe('image/heic');
});
it('normalizes synced metadata so images and playable media classify correctly', () => {
expect(normalizeAttachmentMeta({
id: 'a1',
messageId: 'm1',
filename: 'clip.mp4',
size: 1024,
mime: 'application/octet-stream',
isImage: false
})).toEqual(expect.objectContaining({
mime: 'video/mp4',
isImage: false
}));
expect(normalizeAttachmentMeta({
id: 'a2',
messageId: 'm1',
filename: 'grid.png',
size: 512,
mime: 'application/octet-stream',
isImage: false
})).toEqual(expect.objectContaining({
mime: 'image/png',
isImage: true
}));
});
});
@@ -0,0 +1,57 @@
import { DEFAULT_ATTACHMENT_MIME_TYPE } from '../constants/attachment-transfer.constants';
const GENERIC_MIME_TYPES = new Set([
'',
DEFAULT_ATTACHMENT_MIME_TYPE,
'binary/octet-stream'
]);
const EXTENSION_MIME_MAP: Record<string, string> = {
'.aac': 'audio/aac',
'.avi': 'video/x-msvideo',
'.bmp': 'image/bmp',
'.flac': 'audio/flac',
'.gif': 'image/gif',
'.heic': 'image/heic',
'.heif': 'image/heif',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.m4a': 'audio/mp4',
'.mkv': 'video/x-matroska',
'.mov': 'video/quicktime',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.ogg': 'audio/ogg',
'.ogv': 'video/ogg',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.webm': 'video/webm',
'.webp': 'image/webp'
};
export function resolveAttachmentMime(filename: string, declaredType?: string | null): string {
const normalizedType = declaredType?.trim() ?? '';
if (normalizedType && !GENERIC_MIME_TYPES.has(normalizedType.toLowerCase())) {
return normalizedType;
}
const extension = extractFilenameExtension(filename);
if (extension) {
return EXTENSION_MIME_MAP[extension] ?? (normalizedType || DEFAULT_ATTACHMENT_MIME_TYPE);
}
return normalizedType || DEFAULT_ATTACHMENT_MIME_TYPE;
}
function extractFilenameExtension(filename: string): string | null {
const normalized = filename.trim().toLowerCase();
const extensionIndex = normalized.lastIndexOf('.');
if (extensionIndex <= 0) {
return null;
}
return normalized.slice(extensionIndex);
}
@@ -0,0 +1,17 @@
import { isImageAttachment } from './attachment-image.rules';
import { resolveAttachmentMime } from './attachment-mime.rules';
import type { AttachmentMeta } from '../models/attachment.model';
export function normalizeAttachmentMeta<T extends AttachmentMeta>(meta: T): T {
const mime = resolveAttachmentMime(meta.filename, meta.mime);
return {
...meta,
mime,
isImage: isImageAttachment({
filename: meta.filename,
isImage: meta.isImage,
mime
})
};
}
@@ -0,0 +1,15 @@
import { shouldServeAttachmentFromDiskPath } from './attachment-serve.rules';
describe('shouldServeAttachmentFromDiskPath', () => {
it('accepts paths with a positive byte length', () => {
expect(shouldServeAttachmentFromDiskPath(1)).toBe(true);
expect(shouldServeAttachmentFromDiskPath(4096)).toBe(true);
});
it('rejects empty, missing, or invalid sizes', () => {
expect(shouldServeAttachmentFromDiskPath(0)).toBe(false);
expect(shouldServeAttachmentFromDiskPath(null)).toBe(false);
expect(shouldServeAttachmentFromDiskPath(undefined)).toBe(false);
expect(shouldServeAttachmentFromDiskPath(Number.NaN)).toBe(false);
});
});
@@ -0,0 +1,4 @@
/** True when a resolved on-disk path contains bytes worth streaming to a peer. */
export function shouldServeAttachmentFromDiskPath(fileSize: number | null | undefined): boolean {
return typeof fileSize === 'number' && Number.isFinite(fileSize) && fileSize > 0;
}
@@ -1,6 +1,9 @@
import { import {
getWatchedAttachmentRoomIdFromUrl, getWatchedAttachmentRoomIdFromUrl,
isAttachmentPendingMediaHydration,
isDirectMessageAttachmentRoomId, isDirectMessageAttachmentRoomId,
isPlayableAttachmentMedia,
needsAttachmentDisplayHydration,
shouldCopyUploaderMediaToAppData, shouldCopyUploaderMediaToAppData,
shouldCopyLargeUploaderFileToAppData, shouldCopyLargeUploaderFileToAppData,
shouldStreamAttachmentReceiveToDisk, shouldStreamAttachmentReceiveToDisk,
@@ -58,7 +61,7 @@ describe('attachment logic', () => {
}, undefined, true)).toBe(false); }, undefined, true)).toBe(false);
}); });
it('streams any persistable download to disk when the store supports streaming', () => { it('streams only oversized persistable downloads to disk when the store supports streaming', () => {
const capabilities = { const capabilities = {
canStreamToDisk: true, canStreamToDisk: true,
canPersistSize: (bytes: number) => bytes <= 256 * 1024 * 1024 canPersistSize: (bytes: number) => bytes <= 256 * 1024 * 1024
@@ -72,9 +75,15 @@ describe('attachment logic', () => {
expect(shouldStreamAttachmentReceiveToDisk({ expect(shouldStreamAttachmentReceiveToDisk({
size: 3, size: 3,
mime: 'application/zip', mime: 'image/png',
filePath: undefined filePath: undefined
}, capabilities)).toBe(true); }, capabilities)).toBe(false);
expect(shouldStreamAttachmentReceiveToDisk({
size: 10 * 1024 * 1024,
mime: 'image/jpeg',
filePath: undefined
}, capabilities)).toBe(false);
expect(shouldStreamAttachmentReceiveToDisk({ expect(shouldStreamAttachmentReceiveToDisk({
size: 200 * 1024 * 1024, size: 200 * 1024 * 1024,
@@ -83,6 +92,51 @@ describe('attachment logic', () => {
}, capabilities)).toBe(true); }, capabilities)).toBe(true);
}); });
it('combines inline image and playable media hydration needs', () => {
expect(needsAttachmentDisplayHydration({
filename: 'photo.png',
mime: 'image/png',
isImage: true,
available: false,
savedPath: '/data/photo.png'
})).toBe(true);
expect(needsAttachmentDisplayHydration({
filename: 'song.mp3',
mime: 'audio/mpeg',
isImage: false,
available: true,
savedPath: '/data/song.mp3'
})).toBe(true);
expect(needsAttachmentDisplayHydration({
filename: 'song.mp3',
mime: 'audio/mpeg',
isImage: false,
available: true,
objectUrl: 'file:///data/song.mp3',
savedPath: '/data/song.mp3'
})).toBe(false);
});
it('identifies playable media pending hydration from disk paths', () => {
expect(isPlayableAttachmentMedia({ mime: 'video/mp4' })).toBe(true);
expect(isPlayableAttachmentMedia({ mime: 'image/png' })).toBe(false);
expect(isAttachmentPendingMediaHydration({
mime: 'audio/mpeg',
available: true,
savedPath: '/data/song.mp3'
})).toBe(true);
expect(isAttachmentPendingMediaHydration({
mime: 'audio/mpeg',
available: true,
objectUrl: 'file:///data/song.mp3',
savedPath: '/data/song.mp3'
})).toBe(false);
});
it('receives browser-sized files in memory when disk streaming is unavailable', () => { it('receives browser-sized files in memory when disk streaming is unavailable', () => {
const browserCapabilities = { const browserCapabilities = {
canStreamToDisk: false, canStreamToDisk: false,
@@ -1,3 +1,4 @@
import { isAttachmentPendingInlineHydration } from './attachment-image.rules';
import { MAX_AUTO_SAVE_SIZE_BYTES } from '../constants/attachment.constants'; import { MAX_AUTO_SAVE_SIZE_BYTES } from '../constants/attachment.constants';
import type { Attachment } from '../models/attachment.model'; import type { Attachment } from '../models/attachment.model';
@@ -11,6 +12,36 @@ export function isAttachmentMedia(attachment: Pick<Attachment, 'mime'>): boolean
attachment.mime.startsWith('audio/'); attachment.mime.startsWith('audio/');
} }
export function isPlayableAttachmentMedia(attachment: Pick<Attachment, 'mime'>): boolean {
return attachment.mime.startsWith('video/') || attachment.mime.startsWith('audio/');
}
export function isAttachmentPendingMediaHydration(
attachment: Pick<
Attachment,
'available' | 'filePath' | 'mime' | 'objectUrl' | 'receivedBytes' | 'savedPath'
>
): boolean {
if (!isPlayableAttachmentMedia(attachment) || attachment.objectUrl) {
return false;
}
if ((attachment.receivedBytes ?? 0) > 0 && attachment.available !== true) {
return false;
}
return !!(attachment.savedPath?.trim() || attachment.filePath?.trim());
}
export function needsAttachmentDisplayHydration(
attachment: Pick<
Attachment,
'available' | 'filePath' | 'filename' | 'isImage' | 'mime' | 'objectUrl' | 'receivedBytes' | 'savedPath'
>
): boolean {
return isAttachmentPendingInlineHydration(attachment) || isAttachmentPendingMediaHydration(attachment);
}
export function shouldAutoRequestWhenWatched(attachment: Attachment): boolean { export function shouldAutoRequestWhenWatched(attachment: Attachment): boolean {
return attachment.isImage || return attachment.isImage ||
(isAttachmentMedia(attachment) && attachment.size <= MAX_AUTO_SAVE_SIZE_BYTES); (isAttachmentMedia(attachment) && attachment.size <= MAX_AUTO_SAVE_SIZE_BYTES);
@@ -71,7 +102,10 @@ export function shouldStreamAttachmentReceiveToDisk(
return false; return false;
} }
return true; // Small files assemble in memory (parallel chunk receive + immediate acks) and are
// persisted after completion. Disk streaming is reserved for oversized downloads
// so we never buffer an entire large file in RAM.
return attachment.size > MAX_AUTO_SAVE_SIZE_BYTES;
} }
export function canReceiveAttachmentInMemory( export function canReceiveAttachmentInMemory(
@@ -0,0 +1,121 @@
import {
afterEach,
beforeEach,
describe,
expect,
it,
vi
} from 'vitest';
const isCapacitorNativeRuntimeMock = vi.fn(() => true);
const loadFilesystemMock = vi.fn();
vi.mock('../../../../infrastructure/mobile/logic/platform-detection.rules', () => ({
isCapacitorNativeRuntime: () => isCapacitorNativeRuntimeMock()
}));
vi.mock('./capacitor-attachment-filesystem.adapter', () => ({
loadCapacitorAttachmentFilesystem: () => loadFilesystemMock()
}));
import { CapacitorAttachmentExportService } from './capacitor-attachment-export.service';
import type { Attachment } from '../../domain/models/attachment.model';
function createFakeAdapter() {
return {
filesystem: {
copy: vi.fn(async () => undefined),
writeFile: vi.fn(async () => ({ uri: 'file:///docs/out' }))
},
directory: 'DATA',
exportDirectory: 'DOCUMENTS',
convertFileSrc: (url: string) => url
};
}
function makeAttachment(overrides: Partial<Attachment>): Attachment {
return {
id: 'file-1',
messageId: 'message-1',
filename: 'photo.png',
mime: 'image/png',
size: 1024,
available: true,
...overrides
};
}
describe('CapacitorAttachmentExportService', () => {
let service: CapacitorAttachmentExportService;
let fakeAdapter: ReturnType<typeof createFakeAdapter>;
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(1_720_900_000_000);
isCapacitorNativeRuntimeMock.mockReturnValue(true);
fakeAdapter = createFakeAdapter();
loadFilesystemMock.mockResolvedValue(fakeAdapter);
service = new CapacitorAttachmentExportService();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('copies a disk-backed attachment from app data into the export directory', async () => {
const attachment = makeAttachment({ savedPath: 'metoyou/server/room/files/photo.png' });
await expect(service.exportToDevice(attachment)).resolves.toBe(true);
expect(fakeAdapter.filesystem.copy).toHaveBeenCalledWith({
from: 'metoyou/server/room/files/photo.png',
directory: 'DATA',
to: 'photo-1720900000000.png',
toDirectory: 'DOCUMENTS'
});
expect(fakeAdapter.filesystem.writeFile).not.toHaveBeenCalled();
});
it('writes an in-memory attachment fetched from its object URL into the export directory', async () => {
const bytes = new TextEncoder().encode('hello');
vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes)));
const attachment = makeAttachment({ objectUrl: 'blob:https://app/abc' });
await expect(service.exportToDevice(attachment)).resolves.toBe(true);
expect(fakeAdapter.filesystem.writeFile).toHaveBeenCalledWith({
path: 'photo-1720900000000.png',
data: btoa('hello'),
directory: 'DOCUMENTS',
recursive: true
});
});
it('falls back to the object URL when copying from disk fails', async () => {
fakeAdapter.filesystem.copy.mockRejectedValue(new Error('copy failed'));
vi.stubGlobal('fetch', vi.fn(async () => new Response(new TextEncoder().encode('x'))));
const attachment = makeAttachment({
savedPath: 'metoyou/server/room/files/photo.png',
objectUrl: 'capacitor://localhost/_capacitor_file_/photo.png'
});
await expect(service.exportToDevice(attachment)).resolves.toBe(true);
expect(fakeAdapter.filesystem.writeFile).toHaveBeenCalled();
});
it('returns false off a native shell', async () => {
isCapacitorNativeRuntimeMock.mockReturnValue(false);
await expect(service.exportToDevice(makeAttachment({ savedPath: 'x' }))).resolves.toBe(false);
});
it('returns false when there is neither a disk path nor an object URL', async () => {
await expect(service.exportToDevice(makeAttachment({}))).resolves.toBe(false);
});
});
@@ -0,0 +1,81 @@
import { Injectable } from '@angular/core';
import { isCapacitorNativeRuntime } from '../../../../infrastructure/mobile/logic/platform-detection.rules';
import { encodeUint8ArrayToBase64 } from '../../domain/logic/attachment-blob.rules';
import { resolveAttachmentDiskPath } from '../../domain/logic/attachment-download.rules';
import { buildAttachmentExportFileName } from '../../domain/logic/attachment-export.rules';
import type { Attachment } from '../../domain/models/attachment.model';
import { loadCapacitorAttachmentFilesystem } from './capacitor-attachment-filesystem.adapter';
/**
* Exports attachments out of the app-private data directory into the device's
* user-visible `Documents` directory on Capacitor. Anchor-based `download`
* links do nothing in the Android WebView, so "download" on mobile means
* copying the bytes somewhere the user can reach through the Files app.
*/
@Injectable({ providedIn: 'root' })
export class CapacitorAttachmentExportService {
async exportToDevice(attachment: Attachment): Promise<boolean> {
if (!isCapacitorNativeRuntime()) {
return false;
}
const filesystem = await loadCapacitorAttachmentFilesystem();
if (!filesystem) {
return false;
}
const exportPath = buildAttachmentExportFileName(attachment.filename, Date.now());
const diskPath = resolveAttachmentDiskPath(attachment);
if (diskPath) {
try {
await filesystem.filesystem.copy({
from: diskPath,
directory: filesystem.directory,
to: exportPath,
toDirectory: filesystem.exportDirectory
});
return true;
} catch {
/* fall back to the object URL below */
}
}
if (!attachment.objectUrl) {
return false;
}
const base64 = await this.fetchAsBase64(attachment.objectUrl);
if (base64 === null) {
return false;
}
try {
await filesystem.filesystem.writeFile({
path: exportPath,
data: base64,
directory: filesystem.exportDirectory,
recursive: true
});
return true;
} catch {
return false;
}
}
private async fetchAsBase64(objectUrl: string): Promise<string | null> {
try {
const response = await fetch(objectUrl);
const buffer = await response.arrayBuffer();
return encodeUint8ArrayToBase64(new Uint8Array(buffer));
} catch {
return null;
}
}
}
@@ -82,6 +82,7 @@ function createFakeFilesystem() {
adapter: { adapter: {
filesystem, filesystem,
directory: 'DATA', directory: 'DATA',
exportDirectory: 'DOCUMENTS',
convertFileSrc: (url: string) => url.replace('file://', 'capacitor://localhost/_capacitor_file_') convertFileSrc: (url: string) => url.replace('file://', 'capacitor://localhost/_capacitor_file_')
} }
}; };
@@ -10,6 +10,8 @@ type CapacitorCoreModule = typeof import('@capacitor/core');
export interface CapacitorAttachmentFilesystem { export interface CapacitorAttachmentFilesystem {
filesystem: CapacitorFilesystemModule['Filesystem']; filesystem: CapacitorFilesystemModule['Filesystem'];
directory: CapacitorFilesystemModule['Directory'][keyof CapacitorFilesystemModule['Directory']]; directory: CapacitorFilesystemModule['Directory'][keyof CapacitorFilesystemModule['Directory']];
/** User-visible directory (`Documents`) used when exporting attachments out of app storage. */
exportDirectory: CapacitorFilesystemModule['Directory'][keyof CapacitorFilesystemModule['Directory']];
convertFileSrc: (url: string) => string; convertFileSrc: (url: string) => string;
} }
@@ -42,6 +44,7 @@ async function resolveCapacitorAttachmentFilesystem(): Promise<CapacitorAttachme
return { return {
filesystem: filesystemModule.Filesystem, filesystem: filesystemModule.Filesystem,
directory: filesystemModule.Directory.Data, directory: filesystemModule.Directory.Data,
exportDirectory: filesystemModule.Directory.Documents,
convertFileSrc: (url: string) => coreModule.Capacitor.convertFileSrc(url) convertFileSrc: (url: string) => coreModule.Capacitor.convertFileSrc(url)
}; };
} catch { } catch {
@@ -0,0 +1,120 @@
import '@angular/compiler';
import { Injector, runInInjectionContext } from '@angular/core';
import {
beforeEach,
describe,
expect,
it,
vi
} from 'vitest';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { of } from 'rxjs';
import { ServerDirectoryFacade } from '../../../server-directory';
import { SignalServerAuthService } from './signal-server-auth.service';
import { SignalServerAuthorizeService } from './signal-server-authorize.service';
const HOME_URL = 'https://signal.toju.app';
const FOREIGN_URL = 'https://signal-sweden.toju.app';
const homeUser = {
id: 'user-1',
username: 'alice',
displayName: 'Alice',
homeSignalServerUrl: HOME_URL
};
describe('SignalServerAuthorizeService', () => {
let router: { navigate: ReturnType<typeof vi.fn>; url: string };
let store: { select: ReturnType<typeof vi.fn> };
let serverDirectory: {
ensureServerEndpoint: ReturnType<typeof vi.fn>;
findServerByUrl: ReturnType<typeof vi.fn>;
servers: ReturnType<typeof vi.fn>;
testServer: ReturnType<typeof vi.fn>;
};
let signalServerAuth: {
ensureProvisioned: ReturnType<typeof vi.fn>;
hasValidCredential: ReturnType<typeof vi.fn>;
migrateHomeCredential: ReturnType<typeof vi.fn>;
};
let service: SignalServerAuthorizeService;
beforeEach(() => {
router = { navigate: vi.fn(() => Promise.resolve(true)), url: '/room/room-1' };
store = { select: vi.fn(() => of(homeUser)) };
serverDirectory = {
ensureServerEndpoint: vi.fn(() => ({ id: 'endpoint-1' })),
findServerByUrl: vi.fn(() => ({ id: 'endpoint-1', status: 'online' })),
servers: vi.fn(() => []),
testServer: vi.fn(() => Promise.resolve())
};
signalServerAuth = {
ensureProvisioned: vi.fn(() => Promise.resolve({ kind: 'skipped', reason: 'no-provision-secret' })),
hasValidCredential: vi.fn(() => false),
migrateHomeCredential: vi.fn()
};
const injector = Injector.create({
providers: [
SignalServerAuthorizeService,
{ provide: Router, useValue: router },
{ provide: Store, useValue: store },
{ provide: ServerDirectoryFacade, useValue: serverDirectory },
{ provide: SignalServerAuthService, useValue: signalServerAuth }
]
});
service = runInInjectionContext(injector, () => injector.get(SignalServerAuthorizeService));
});
it('returns true immediately when a valid credential already exists', async () => {
signalServerAuth.hasValidCredential.mockReturnValue(true);
await expect(service.ensureCredentialForServerUrl(FOREIGN_URL)).resolves.toBe(true);
expect(signalServerAuth.ensureProvisioned).not.toHaveBeenCalled();
});
it('never provisions or opens the authorize login page for the home signal server', async () => {
await expect(service.ensureCredentialForServerUrl(HOME_URL)).resolves.toBe(false);
expect(signalServerAuth.ensureProvisioned).not.toHaveBeenCalled();
expect(router.navigate).not.toHaveBeenCalled();
});
it('restores the home credential from the legacy token store instead of provisioning', async () => {
signalServerAuth.hasValidCredential
.mockReturnValueOnce(false)
.mockReturnValue(true);
await expect(service.ensureCredentialForServerUrl(HOME_URL)).resolves.toBe(true);
expect(signalServerAuth.migrateHomeCredential).toHaveBeenCalledWith(homeUser);
expect(signalServerAuth.ensureProvisioned).not.toHaveBeenCalled();
expect(router.navigate).not.toHaveBeenCalled();
});
it('treats scheme variants of the home url as the home server', async () => {
await expect(service.ensureCredentialForServerUrl('wss://signal.toju.app/')).resolves.toBe(false);
expect(signalServerAuth.ensureProvisioned).not.toHaveBeenCalled();
expect(router.navigate).not.toHaveBeenCalled();
});
it('still provisions foreign servers and navigates to authorize when the secret is missing', async () => {
await expect(service.ensureCredentialForServerUrl(FOREIGN_URL)).resolves.toBe(false);
expect(signalServerAuth.ensureProvisioned).toHaveBeenCalledWith(FOREIGN_URL, homeUser);
expect(router.navigate).toHaveBeenCalledWith(['/login'], expect.objectContaining({
queryParams: expect.objectContaining({ mode: 'authorize' })
}));
});
it('returns true when foreign provisioning succeeds', async () => {
signalServerAuth.ensureProvisioned.mockResolvedValue({ kind: 'provisioned', result: {} });
await expect(service.ensureCredentialForServerUrl(FOREIGN_URL)).resolves.toBe(true);
expect(router.navigate).not.toHaveBeenCalled();
});
});
@@ -7,6 +7,7 @@ import { ServerDirectoryFacade } from '../../../server-directory';
import { AUTH_MODE_AUTHORIZE, buildLoginReturnQueryParams } from '../../domain/logic/auth-navigation.rules'; import { AUTH_MODE_AUTHORIZE, buildLoginReturnQueryParams } from '../../domain/logic/auth-navigation.rules';
import { isEndpointOnlineForConnection } from '../../../server-directory/domain/logic/server-endpoint-connectivity.rules'; import { isEndpointOnlineForConnection } from '../../../server-directory/domain/logic/server-endpoint-connectivity.rules';
import { shouldNavigateToAuthorizeSignalServer } from '../../domain/logic/signal-server-authorize.rules'; import { shouldNavigateToAuthorizeSignalServer } from '../../domain/logic/signal-server-authorize.rules';
import { isSameSignalServerUrl } from '../../domain/logic/signal-server-auth-failure.rules';
import { SignalServerAuthService } from './signal-server-auth.service'; import { SignalServerAuthService } from './signal-server-auth.service';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
@@ -27,6 +28,16 @@ export class SignalServerAuthorizeService {
return false; return false;
} }
if (isSameSignalServerUrl(serverUrl, currentUser.homeSignalServerUrl)) {
// The home account is never auto-provisioned or re-authorized as a
// foreign account. Resurrect the credential from the legacy token store
// (session-restore case); a genuinely missing home session is handled by
// the session-expiry flow, not the authorize login page.
this.signalServerAuth.migrateHomeCredential(currentUser);
return this.signalServerAuth.hasValidCredential(serverUrl);
}
let result; let result;
try { try {
@@ -9,6 +9,7 @@ import { UsersActions } from '../../../../store/users/users.actions';
import { import {
buildLoginReturnQueryParams, buildLoginReturnQueryParams,
resolveSafeReturnUrl, resolveSafeReturnUrl,
resolveSessionExpiredNavigation,
resolveUnauthenticatedStartupRedirect, resolveUnauthenticatedStartupRedirect,
waitForAuthenticationOutcome waitForAuthenticationOutcome
} from './auth-navigation.rules'; } from './auth-navigation.rules';
@@ -89,6 +90,28 @@ describe('resolveUnauthenticatedStartupRedirect', () => {
}); });
}); });
describe('resolveSessionExpiredNavigation', () => {
const currentUser = { id: 'user-1' };
it('keeps an authenticated user on protected routes', () => {
expect(resolveSessionExpiredNavigation(currentUser, '/room/abc')).toEqual({ kind: 'stay' });
});
it('leaves the login page when the in-memory user is still authenticated', () => {
expect(resolveSessionExpiredNavigation(currentUser, '/login?returnUrl=%2Fservers')).toEqual({
kind: 'leave-auth-route',
returnUrl: '/servers'
});
});
it('sends fully signed-out users to login with a safe returnUrl', () => {
expect(resolveSessionExpiredNavigation(null, '/room/abc')).toEqual({
kind: 'navigate-login',
queryParams: { returnUrl: '/room/abc' }
});
});
});
describe('waitForAuthenticationOutcome', () => { describe('waitForAuthenticationOutcome', () => {
it('resolves when authentication storage preparation succeeds', async () => { it('resolves when authentication storage preparation succeeds', async () => {
const user = { const user = {
@@ -134,6 +134,39 @@ export function isAuthorizeAuthMode(mode: string | null | undefined): boolean {
return mode?.trim() === AUTH_MODE_AUTHORIZE; return mode?.trim() === AUTH_MODE_AUTHORIZE;
} }
export type SessionExpiredNavigation =
| { kind: 'stay' }
| { kind: 'navigate-login'; queryParams: Record<string, string> }
| { kind: 'leave-auth-route'; returnUrl: string };
/**
* Decide how to react when a persisted session is rejected as expired.
* A live in-memory user must never be left on the login page while the rail
* still treats them as authenticated.
*/
export function resolveSessionExpiredNavigation(
currentUser: Pick<User, 'id'> | null | undefined,
currentUrl: string
): SessionExpiredNavigation {
if (currentUser) {
const path = getRoutePathFromUrl(currentUrl);
if (isAuthRoutePath(path)) {
return {
kind: 'leave-auth-route',
returnUrl: resolveSafeReturnUrl(extractReturnUrlParam(currentUrl))
};
}
return { kind: 'stay' };
}
return {
kind: 'navigate-login',
queryParams: buildLoginReturnQueryParams(currentUrl)
};
}
export function waitForAuthenticationOutcome( export function waitForAuthenticationOutcome(
actions$: Observable<{ type: string; user?: User; error?: string }> actions$: Observable<{ type: string; user?: User; error?: string }>
): Observable<AuthenticationOutcome> { ): Observable<AuthenticationOutcome> {
@@ -7,7 +7,8 @@ import type { User } from '../../../../shared-kernel';
import { import {
SESSION_EXPIRED_ERROR_CODE, SESSION_EXPIRED_ERROR_CODE,
collectSessionTokenLookupUrls, collectSessionTokenLookupUrls,
hasValidPersistedSession hasValidPersistedSession,
resolveAuthenticatedLocalUserId
} from './auth-session.rules'; } from './auth-session.rules';
describe('auth-session.rules', () => { describe('auth-session.rules', () => {
@@ -46,4 +47,22 @@ describe('auth-session.rules', () => {
it('exports a stable session-expired error code', () => { it('exports a stable session-expired error code', () => {
expect(SESSION_EXPIRED_ERROR_CODE).toBe('SESSION_EXPIRED'); expect(SESSION_EXPIRED_ERROR_CODE).toBe('SESSION_EXPIRED');
}); });
describe('resolveAuthenticatedLocalUserId', () => {
it('prefers the persisted user id', () => {
expect(resolveAuthenticatedLocalUserId('stored-id', { id: 'live-id' })).toBe('stored-id');
});
it('falls back to the live in-memory user when persisted scope was cleared', () => {
// A transient clearStoredCurrentUserId() must never make a logged-in
// user look signed out (half-logged-in login page with the rail visible).
expect(resolveAuthenticatedLocalUserId(null, { id: 'live-id' })).toBe('live-id');
expect(resolveAuthenticatedLocalUserId('', { id: 'live-id' })).toBe('live-id');
});
it('returns null when neither source knows a user', () => {
expect(resolveAuthenticatedLocalUserId(null, null)).toBeNull();
expect(resolveAuthenticatedLocalUserId(null, undefined)).toBeNull();
});
});
}); });
@@ -30,6 +30,19 @@ export function hasValidSessionTokenForUrls(
return urls.some((url) => !!getToken(url)); return urls.some((url) => !!getToken(url));
} }
/**
* Resolve the acting local user id from the persisted storage scope with a
* fallback to the live in-memory user. A transient `clearStoredCurrentUserId()`
* (e.g. during signal-server auth churn) must never make a logged-in user look
* signed out.
*/
export function resolveAuthenticatedLocalUserId(
storedUserId: string | null | undefined,
currentUser: Pick<User, 'id'> | null | undefined
): string | null {
return storedUserId || currentUser?.id || null;
}
export function hasValidPersistedSession( export function hasValidPersistedSession(
user: Pick<User, 'homeSignalServerUrl'>, user: Pick<User, 'homeSignalServerUrl'>,
activeServerUrl: string | null | undefined, activeServerUrl: string | null | undefined,
@@ -0,0 +1,99 @@
import {
describe,
expect,
it
} from 'vitest';
import { isSameSignalServerUrl, resolveSignalServerAuthFailure } from './signal-server-auth-failure.rules';
describe('isSameSignalServerUrl', () => {
it('matches identical http urls ignoring trailing slashes', () => {
expect(isSameSignalServerUrl('https://signal.toju.app', 'https://signal.toju.app/')).toBe(true);
});
it('matches ws/wss urls against their http/https equivalents', () => {
expect(isSameSignalServerUrl('wss://signal.toju.app', 'https://signal.toju.app')).toBe(true);
expect(isSameSignalServerUrl('ws://localhost:3001', 'http://localhost:3001')).toBe(true);
});
it('does not match different hosts or missing urls', () => {
expect(isSameSignalServerUrl('https://signal.toju.app', 'https://signal-sweden.toju.app')).toBe(false);
expect(isSameSignalServerUrl('https://signal.toju.app', undefined)).toBe(false);
expect(isSameSignalServerUrl('', 'https://signal.toju.app')).toBe(false);
});
it('treats host case-insensitively', () => {
expect(isSameSignalServerUrl('https://Signal.Toju.App', 'https://signal.toju.app')).toBe(true);
});
});
describe('resolveSignalServerAuthFailure', () => {
it('re-identifies on any auth failure while a valid credential and retry budget exist', () => {
for (const reason of ['auth_required', 'auth_error'] as const) {
expect(resolveSignalServerAuthFailure({
reason,
hasValidCredential: true,
retryAllowed: true,
isHomeServer: true
})).toBe('reidentify');
}
});
it('never tears down a session for auth_required while the local credential is still valid', () => {
// auth_required only means a message raced ahead of identify - the server
// never evaluated the token, so exhausted retries must not log the user out.
expect(resolveSignalServerAuthFailure({
reason: 'auth_required',
hasValidCredential: true,
retryAllowed: false,
isHomeServer: true
})).toBe('ignore');
expect(resolveSignalServerAuthFailure({
reason: 'auth_required',
hasValidCredential: true,
retryAllowed: false,
isHomeServer: false
})).toBe('ignore');
});
it('expires the home session when the home server rejects an identify token', () => {
expect(resolveSignalServerAuthFailure({
reason: 'auth_error',
hasValidCredential: true,
retryAllowed: false,
isHomeServer: true
})).toBe('expire-home-session');
expect(resolveSignalServerAuthFailure({
reason: 'auth_error',
hasValidCredential: false,
retryAllowed: false,
isHomeServer: true
})).toBe('expire-home-session');
});
it('re-provisions foreign servers when their credential is rejected or missing', () => {
expect(resolveSignalServerAuthFailure({
reason: 'auth_error',
hasValidCredential: false,
retryAllowed: false,
isHomeServer: false
})).toBe('provision-foreign');
expect(resolveSignalServerAuthFailure({
reason: 'auth_required',
hasValidCredential: false,
retryAllowed: false,
isHomeServer: false
})).toBe('provision-foreign');
});
it('expires the home session when auth_required arrives with no resolvable home credential', () => {
expect(resolveSignalServerAuthFailure({
reason: 'auth_required',
hasValidCredential: false,
retryAllowed: false,
isHomeServer: true
})).toBe('expire-home-session');
});
});
@@ -0,0 +1,67 @@
export type SignalServerAuthFailureReason = 'auth_required' | 'auth_error';
export type SignalServerAuthFailureResolution =
| 'reidentify'
| 'ignore'
| 'expire-home-session'
| 'provision-foreign';
function normalizeSignalServerUrlForComparison(serverUrl: string): string {
const withHttpScheme = serverUrl
.trim()
.replace(/\/+$/, '')
.replace(/^ws/i, 'http');
try {
const parsed = new URL(withHttpScheme);
const portSuffix = parsed.port ? `:${parsed.port}` : '';
const path = parsed.pathname.replace(/\/+$/, '');
return `${parsed.protocol.toLowerCase()}//${parsed.hostname.toLowerCase()}${portSuffix}${path}`;
} catch {
return withHttpScheme.toLowerCase();
}
}
/**
* Compare two signal-server URLs regardless of ws/http scheme flavor,
* trailing slashes, or host casing. Used to decide whether an auth event
* concerns the user's home signal server.
*/
export function isSameSignalServerUrl(
leftUrl: string | null | undefined,
rightUrl: string | null | undefined
): boolean {
if (!leftUrl?.trim() || !rightUrl?.trim()) {
return false;
}
return normalizeSignalServerUrlForComparison(leftUrl) === normalizeSignalServerUrlForComparison(rightUrl);
}
/**
* Decide how to react to a signal-server auth failure message.
*
* `auth_required` is sent when any non-identify message arrives before the
* connection authenticated - it says nothing about token validity, so while a
* locally valid credential exists it may only trigger a (bounded) re-identify,
* never a session teardown. `auth_error` is the server rejecting the identify
* token itself: after the transient-retry budget, the credential is genuinely
* unusable, which means session expiry (home) or re-provisioning (foreign).
*/
export function resolveSignalServerAuthFailure(params: {
reason: SignalServerAuthFailureReason;
hasValidCredential: boolean;
retryAllowed: boolean;
isHomeServer: boolean;
}): SignalServerAuthFailureResolution {
if (params.hasValidCredential && params.retryAllowed) {
return 'reidentify';
}
if (params.reason === 'auth_required' && params.hasValidCredential) {
return 'ignore';
}
return params.isHomeServer ? 'expire-home-session' : 'provision-foreign';
}
@@ -1,5 +1,5 @@
<div class="h-full grid place-items-center bg-background"> <div class="h-full grid place-items-center overflow-y-auto bg-background p-4">
<div class="w-[360px] bg-card border border-border rounded-xl p-6 shadow-sm"> <div class="w-full max-w-[360px] bg-card border border-border rounded-xl p-6 shadow-sm">
<div class="flex items-center gap-2 mb-4"> <div class="flex items-center gap-2 mb-4">
<ng-icon <ng-icon
name="lucideLogIn" name="lucideLogIn"
@@ -2,6 +2,7 @@
import { import {
Component, Component,
computed, computed,
effect,
inject, inject,
OnInit, OnInit,
signal signal
@@ -13,11 +14,7 @@ import { Actions } from '@ngrx/effects';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { NgIcon, provideIcons } from '@ng-icons/core'; import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideLogIn } from '@ng-icons/lucide'; import { lucideLogIn } from '@ng-icons/lucide';
import { import { firstValueFrom } from 'rxjs';
filter,
firstValueFrom,
take
} from 'rxjs';
import { AuthenticationService } from '../../application/services/authentication.service'; import { AuthenticationService } from '../../application/services/authentication.service';
import { ServerDirectoryFacade } from '../../../server-directory'; import { ServerDirectoryFacade } from '../../../server-directory';
@@ -71,8 +68,27 @@ export class LoginComponent implements OnInit {
private auth = inject(AuthenticationService); private auth = inject(AuthenticationService);
private actions$ = inject(Actions); private actions$ = inject(Actions);
private store = inject(Store); private store = inject(Store);
private route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private router = inject(Router); private readonly router = inject(Router);
private readonly currentUser = this.store.selectSignal(selectCurrentUser);
constructor() {
effect(() => {
if (this.isAuthorizeMode()) {
return;
}
const user = this.currentUser();
if (!user) {
return;
}
const returnUrl = resolveSafeReturnUrl(this.route.snapshot.queryParamMap.get('returnUrl'));
void this.router.navigateByUrl(returnUrl);
});
}
/** TrackBy function for server list rendering. */ /** TrackBy function for server list rendering. */
trackById(_index: number, item: { id: string }) { return item.id; } trackById(_index: number, item: { id: string }) { return item.id; }
@@ -86,20 +102,6 @@ export class LoginComponent implements OnInit {
if (requestedServerId) { if (requestedServerId) {
this.serverId = requestedServerId; this.serverId = requestedServerId;
} }
if (this.isAuthorizeMode()) {
return;
}
this.store.select(selectCurrentUser).pipe(
filter(Boolean),
take(1)
)
.subscribe(() => {
const returnUrl = resolveSafeReturnUrl(this.route.snapshot.queryParamMap.get('returnUrl'));
void this.router.navigateByUrl(returnUrl);
});
} }
/** Validate and submit the login form, then navigate to search on success. */ /** Validate and submit the login form, then navigate to search on success. */
@@ -1,5 +1,5 @@
<div class="h-full grid place-items-center bg-background"> <div class="h-full grid place-items-center overflow-y-auto bg-background p-4">
<div class="w-[380px] bg-card border border-border rounded-xl p-6 shadow-sm"> <div class="w-full max-w-[380px] bg-card border border-border rounded-xl p-6 shadow-sm">
<div class="flex items-center gap-2 mb-4"> <div class="flex items-center gap-2 mb-4">
<ng-icon <ng-icon
name="lucideUserPlus" name="lucideUserPlus"
+8
View File
@@ -178,3 +178,11 @@ Opening a conversation must land on the newest message even though images, link/
## Typing indicator ## Typing indicator
`TypingIndicatorComponent` listens for typing events from peers scoped to the current server and active text channel. Each positive event resets a 3-second TTL timer for that channel; an explicit `isTyping: false` event clears that user immediately. If no new event arrives within 3 seconds, the user is removed from the typing list. At most 4 names are shown; beyond that it displays "N users are typing". `TypingIndicatorComponent` listens for typing events from peers scoped to the current server and active text channel. Each positive event resets a 3-second TTL timer for that channel; an explicit `isTyping: false` event clears that user immediately. If no new event arrives within 3 seconds, the user is removed from the typing list. At most 4 names are shown; beyond that it displays "N users are typing".
## Cross-context feature docs
- [`agents-docs/features/messaging.md`](../../../../../agents-docs/features/messaging.md) — server chat + DM transports, sync, delivery states
- [`agents-docs/features/message-integrity.md`](../../../../../agents-docs/features/message-integrity.md) — signed revisions
- [`agents-docs/features/custom-emoji.md`](../../../../../agents-docs/features/custom-emoji.md)
- [`agents-docs/features/klipy-gifs.md`](../../../../../agents-docs/features/klipy-gifs.md)
- [`agents-docs/features/link-preview-media-proxy.md`](../../../../../agents-docs/features/link-preview-media-proxy.md)
@@ -0,0 +1,68 @@
import {
describe,
expect,
it
} from 'vitest';
import { buildChatMessageGalleryTiles, resolveChatMessageGalleryTileState } from './chat-message-image-gallery.rules';
describe('buildChatMessageGalleryTiles', () => {
it('marks displayable, hydrating, downloading, and retry tiles from attachment state', () => {
const tiles = buildChatMessageGalleryTiles([
{
id: 'displayable',
filename: 'ready.png',
mime: 'image/png',
isImage: true,
available: true,
objectUrl: 'blob:http://localhost/ready'
},
{
id: 'hydrating',
filename: 'saved.png',
mime: 'image/png',
isImage: true,
available: false,
savedPath: '/appdata/saved.png'
},
{
id: 'partial',
filename: 'partial.png',
mime: 'image/png',
isImage: true,
available: false,
receivedBytes: 128,
size: 512
},
{
id: 'retry',
filename: 'failed.png',
mime: 'image/png',
isImage: true,
available: false,
size: 256
}
]);
expect(tiles.map((tile) => tile.state)).toEqual([
'displayable',
'hydrating',
'downloading',
'retry'
]);
});
it('treats zero-byte pending requests as downloading instead of retry', () => {
const attachment = {
id: 'pending',
filename: 'waiting.png',
mime: 'image/png',
isImage: true,
available: false,
size: 256
};
expect(resolveChatMessageGalleryTileState(attachment)).toBe('retry');
expect(resolveChatMessageGalleryTileState(attachment, { pendingRequest: true })).toBe('downloading');
});
});
@@ -0,0 +1,48 @@
import {
isAttachmentPendingInlineHydration,
isInlineDisplayableImage,
type ImageAttachmentCandidate
} from '../../../attachment/domain/logic/attachment-image.rules';
export type ChatMessageGalleryTileState = 'displayable' | 'hydrating' | 'downloading' | 'retry';
export interface ChatMessageGalleryTile<T extends ImageAttachmentCandidate = ImageAttachmentCandidate> {
attachment: T;
state: ChatMessageGalleryTileState;
}
export interface ChatMessageGalleryTileOptions {
pendingRequest?: boolean;
}
export function buildChatMessageGalleryTiles<T extends ImageAttachmentCandidate>(
attachments: readonly T[],
options: ChatMessageGalleryTileOptions | ((attachment: T) => ChatMessageGalleryTileOptions) = {}
): ChatMessageGalleryTile<T>[] {
return attachments.map((attachment) => ({
attachment,
state: resolveChatMessageGalleryTileState(
attachment,
typeof options === 'function' ? options(attachment) : options
)
}));
}
export function resolveChatMessageGalleryTileState<T extends ImageAttachmentCandidate>(
attachment: T,
options: ChatMessageGalleryTileOptions = {}
): ChatMessageGalleryTileState {
if (isInlineDisplayableImage(attachment)) {
return 'displayable';
}
if (isAttachmentPendingInlineHydration(attachment)) {
return 'hydrating';
}
if (options.pendingRequest || (attachment.receivedBytes ?? 0) > 0) {
return 'downloading';
}
return 'retry';
}
@@ -3,9 +3,23 @@ import {
it, it,
expect expect
} from 'vitest'; } from 'vitest';
import { findMissingIds } from './message-sync.rules'; import {
findMissingIds,
FULL_SYNC_LIMIT,
INVENTORY_LIMIT
} from './message-sync.rules';
describe('message-sync.rules', () => { describe('message-sync.rules', () => {
it('keeps sync limits bounded so full-room loads cannot spike memory unbounded', () => {
// Sync inventories and full-sync batches load complete message rows into
// memory. An effectively-unlimited ceiling (previously 1,000,000) turns a
// pathological room into a multi-hundred-MB allocation in one sync cycle.
expect(INVENTORY_LIMIT).toBeLessThanOrEqual(20_000);
expect(FULL_SYNC_LIMIT).toBeLessThanOrEqual(20_000);
expect(INVENTORY_LIMIT).toBeGreaterThanOrEqual(5_000);
expect(FULL_SYNC_LIMIT).toBeGreaterThanOrEqual(5_000);
});
it('requests ids with newer revision or mismatched head hash', () => { it('requests ids with newer revision or mismatched head hash', () => {
const localMap = new Map<string, { ts: number; rc: number; ac: number; revision: number; headHash: string }>(); const localMap = new Map<string, { ts: number; rc: number; ac: number; revision: number; headHash: string }>();
@@ -6,12 +6,14 @@ import {
/** Maximum number of messages to include in sync inventories. /** Maximum number of messages to include in sync inventories.
* *
* The inventory protocol now ships every message in the room (id, ts, rc, ac) * The inventory protocol ships messages in the room (id, ts, rc, ac) chunked
* chunked at `CHUNK_SIZE`, so peers converge on the full history regardless * at `CHUNK_SIZE`. Building an inventory loads the full message rows into
* of how lopsided their message counts are. The constant remains as a safety * memory, so this ceiling must stay bounded: the previous effectively-
* ceiling for pathological rooms. * unlimited value (1,000,000) let a single sync cycle allocate hundreds of MB
* in a pathological room. The most recent `INVENTORY_LIMIT` messages are
* reconciled; anything older stays local-only.
*/ */
export const INVENTORY_LIMIT = 1_000_000; export const INVENTORY_LIMIT = 20_000;
/** Number of messages per chunk for inventory / batch transfers. */ /** Number of messages per chunk for inventory / batch transfers. */
export const CHUNK_SIZE = 200; export const CHUNK_SIZE = 200;
@@ -25,8 +27,8 @@ export const SYNC_POLL_SLOW_MS = 900_000;
/** Sync timeout duration before auto-completing a cycle (5 seconds). */ /** Sync timeout duration before auto-completing a cycle (5 seconds). */
export const SYNC_TIMEOUT_MS = 5_000; export const SYNC_TIMEOUT_MS = 5_000;
/** Large limit used for legacy full-sync operations. */ /** Ceiling for legacy full-sync and account-sync batches (most recent first). */
export const FULL_SYNC_LIMIT = 1_000_000; export const FULL_SYNC_LIMIT = 20_000;
/** Inventory item representing a message's sync state. */ /** Inventory item representing a message's sync state. */
export interface InventoryItem { export interface InventoryItem {
@@ -67,7 +67,7 @@
style="-webkit-app-region: no-drag" style="-webkit-app-region: no-drag"
></div> ></div>
<div class="pointer-events-none fixed inset-0 z-[90]"> <div class="pointer-events-none fixed metoyou-fixed-safe-viewport z-[90]">
<div <div
appThemeNode="chatGifPickerSurface" appThemeNode="chatGifPickerSurface"
class="pointer-events-auto absolute w-[calc(100vw-2rem)] max-w-5xl sm:w-[34rem] md:w-[42rem] xl:w-[52rem]" class="pointer-events-auto absolute w-[calc(100vw-2rem)] max-w-5xl sm:w-[34rem] md:w-[42rem] xl:w-[52rem]"
@@ -96,5 +96,7 @@
(copyRequested)="copyImageToClipboard($event)" (copyRequested)="copyImageToClipboard($event)"
(imageOpened)="openLightbox($event)" (imageOpened)="openLightbox($event)"
(imageContextMenuRequested)="openImageContextMenu($event)" (imageContextMenuRequested)="openImageContextMenu($event)"
(imageRetryRequested)="retryGalleryImage($event)"
(imageCancelRequested)="cancelGalleryImage($event)"
/> />
</div> </div>
@@ -47,6 +47,7 @@ import {
ChatMessageDeleteEvent, ChatMessageDeleteEvent,
ChatMessageEditEvent, ChatMessageEditEvent,
ChatMessageEmbedRemoveEvent, ChatMessageEmbedRemoveEvent,
ChatMessageAttachmentEvent,
ChatMessageImageContextMenuEvent, ChatMessageImageContextMenuEvent,
ChatMessageImageLightboxEvent, ChatMessageImageLightboxEvent,
ChatMessageReactionEvent, ChatMessageReactionEvent,
@@ -103,7 +104,26 @@ export class ChatMessagesComponent {
readonly replyTo = signal<Message | null>(null); readonly replyTo = signal<Message | null>(null);
readonly showKlipyGifPicker = signal(false); readonly showKlipyGifPicker = signal(false);
readonly lightboxState = signal<ChatLightboxState | null>(null); readonly lightboxState = signal<ChatLightboxState | null>(null);
readonly galleryAttachments = signal<Attachment[] | null>(null); readonly galleryMessageId = signal<string | null>(null);
readonly galleryAttachmentOrder = signal<readonly string[]>([]);
readonly galleryAttachments = computed(() => {
const messageId = this.galleryMessageId();
const attachmentIds = this.galleryAttachmentOrder();
void this.attachmentsSvc.updated;
if (!messageId || attachmentIds.length === 0) {
return null;
}
const attachmentsById = new Map(
this.attachmentsSvc.getForMessage(messageId).map((attachment) => [attachment.id, attachment])
);
return attachmentIds
.map((attachmentId) => attachmentsById.get(attachmentId))
.filter((attachment): attachment is Attachment => !!attachment);
});
readonly imageContextMenu = signal<ChatMessageImageContextMenuEvent | null>(null); readonly imageContextMenu = signal<ChatMessageImageContextMenuEvent | null>(null);
constructor() { constructor() {
@@ -340,14 +360,24 @@ export class ChatMessagesComponent {
} }
openImageGallery(attachments: Attachment[]): void { openImageGallery(attachments: Attachment[]): void {
const availableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl); if (attachments.length < 2) {
if (availableImages.length < 2) {
return; return;
} }
this.attachmentsSvc.pinDisplayBlobs(availableImages); const messageId = attachments[0]?.messageId;
this.galleryAttachments.set(availableImages);
if (!messageId) {
return;
}
const displayableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl);
if (displayableImages.length > 0) {
this.attachmentsSvc.pinDisplayBlobs(displayableImages);
}
this.galleryMessageId.set(messageId);
this.galleryAttachmentOrder.set(attachments.map((attachment) => attachment.id));
} }
closeImageGallery(): void { closeImageGallery(): void {
@@ -357,7 +387,8 @@ export class ChatMessagesComponent {
this.attachmentsSvc.unpinDisplayBlobs(gallery); this.attachmentsSvc.unpinDisplayBlobs(gallery);
} }
this.galleryAttachments.set(null); this.galleryMessageId.set(null);
this.galleryAttachmentOrder.set([]);
} }
openImageContextMenu(event: ChatMessageImageContextMenuEvent): void { openImageContextMenu(event: ChatMessageImageContextMenuEvent): void {
@@ -372,6 +403,22 @@ export class ChatMessagesComponent {
await this.attachmentDownload.downloadToUserLocation(attachment); await this.attachmentDownload.downloadToUserLocation(attachment);
} }
retryGalleryImage(event: ChatMessageAttachmentEvent): void {
const { messageId, attachment } = event;
const liveAttachment = this.attachmentsSvc.getForMessage(messageId).find((entry) => entry.id === attachment.id)
?? attachment;
if ((liveAttachment.receivedBytes ?? 0) > 0 || this.attachmentsSvc.hasPendingRequest(messageId, liveAttachment.id)) {
this.attachmentsSvc.cancelRequest(messageId, liveAttachment);
}
void this.attachmentsSvc.requestImageFromAnyPeer(messageId, liveAttachment);
}
cancelGalleryImage(event: ChatMessageAttachmentEvent): void {
this.attachmentsSvc.cancelRequest(event.messageId, event.attachment);
}
async copyImageToClipboard(attachment: Attachment): Promise<void> { async copyImageToClipboard(attachment: Attachment): Promise<void> {
this.closeImageContextMenu(); this.closeImageContextMenu();
@@ -205,6 +205,22 @@
<span class="chat-image-grid-loading-label" <span class="chat-image-grid-loading-label"
>{{ ((gridImage.receivedBytes || 0) * 100) / gridImage.size | number: '1.0-0' }}%</span >{{ ((gridImage.receivedBytes || 0) * 100) / gridImage.size | number: '1.0-0' }}%</span
> >
<div class="mt-2 flex gap-2">
<button
type="button"
class="chat-image-grid-retry"
(click)="cancelAttachment(gridImage)"
>
{{ 'chat.message.cancel' | translate }}
</button>
<button
type="button"
class="chat-image-grid-retry"
(click)="retryImageRequest(gridImage)"
>
{{ 'chat.message.retry' | translate }}
</button>
</div>
</div> </div>
} @else { } @else {
<div class="chat-image-grid-cell chat-image-grid-loading"> <div class="chat-image-grid-cell chat-image-grid-loading">
@@ -226,7 +242,7 @@
<button <button
type="button" type="button"
class="chat-image-grid-cell chat-image-grid-overflow" class="chat-image-grid-cell chat-image-grid-overflow"
[attr.aria-label]="viewAllImagesAriaLabel(displayableImages().length)" [attr.aria-label]="viewAllImagesAriaLabel(imageAttachments().length)"
(click)="openImageGallery()" (click)="openImageGallery()"
> >
<span class="chat-image-grid-overflow-label">{{ imageOverflowLabel(cell.hiddenCount) }}</span> <span class="chat-image-grid-overflow-label">{{ imageOverflowLabel(cell.hiddenCount) }}</span>
@@ -1,4 +1,4 @@
/* eslint-disable @typescript-eslint/member-ordering, */
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { import {
@@ -49,6 +49,9 @@ import {
isImageAttachment, isImageAttachment,
isInlineDisplayableImage isInlineDisplayableImage
} from '../../../../../attachment/domain/logic/attachment-image.rules'; } from '../../../../../attachment/domain/logic/attachment-image.rules';
import { isAttachmentPendingMediaHydration } from '../../../../../attachment/domain/logic/attachment.logic';
import { shouldHydrateInlineImageForVisibility } from '../../../../../attachment/domain/logic/attachment-hydration-visibility.rules';
import { shouldHydratePlayableMediaForVisibility } from '../../../../../attachment/domain/logic/attachment-hydration-visibility.rules';
import { ATTACHMENT_BLOB_VISIBILITY_ROOT_MARGIN } from '../../../../../attachment/domain/logic/attachment-blob-eviction.rules'; import { ATTACHMENT_BLOB_VISIBILITY_ROOT_MARGIN } from '../../../../../attachment/domain/logic/attachment-blob-eviction.rules';
import { PlatformService, ViewportService } from '../../../../../../core/platform'; import { PlatformService, ViewportService } from '../../../../../../core/platform';
import { ElectronBridgeService } from '../../../../../../core/platform/electron/electron-bridge.service'; import { ElectronBridgeService } from '../../../../../../core/platform/electron/electron-bridge.service';
@@ -268,16 +271,13 @@ export class ChatMessageItemComponent implements AfterViewInit, OnDestroy {
private readonly hydrateMessageImages = effect(() => { private readonly hydrateMessageImages = effect(() => {
const messageId = this.message().id; const messageId = this.message().id;
const images = this.imageAttachments(); const images = this.imageAttachments();
const mediaAttachments = this.attachmentViewModels().filter((attachment) => attachment.isVideo || attachment.isAudio);
void this.attachmentVersion(); void this.attachmentVersion();
const isVisible = this.isMessageVisible(); const isVisible = this.isMessageVisible();
for (const image of images) { for (const image of images) {
if (isInlineDisplayableImage(image)) { if (!shouldHydrateInlineImageForVisibility(image, isVisible)) {
continue;
}
if (!isAttachmentPendingInlineHydration(image)) {
continue; continue;
} }
@@ -290,11 +290,31 @@ export class ChatMessageItemComponent implements AfterViewInit, OnDestroy {
void this.attachmentsSvc.tryRestoreAttachmentFromLocal(liveAttachment); void this.attachmentsSvc.tryRestoreAttachmentFromLocal(liveAttachment);
} }
for (const media of mediaAttachments) {
if (!shouldHydratePlayableMediaForVisibility(media, isVisible)) {
continue;
}
const liveAttachment = this.getLiveAttachment(media.id);
if (!liveAttachment) {
continue;
}
void this.attachmentsSvc.tryRestoreAttachmentFromLocal(liveAttachment);
}
if (!isVisible) { if (!isVisible) {
return; return;
} }
if (images.some((image) => !isInlineDisplayableImage(image) && !isAttachmentPendingInlineHydration(image))) { const needsAutoDownload = images.some((image) =>
!isInlineDisplayableImage(image) && !isAttachmentPendingInlineHydration(image)
) || mediaAttachments.some((media) =>
!media.objectUrl && !isAttachmentPendingMediaHydration(media) && (media.receivedBytes ?? 0) === 0
);
if (needsAutoDownload) {
void this.attachmentsSvc.queueAutoDownloadsForMessage(messageId); void this.attachmentsSvc.queueAutoDownloadsForMessage(messageId);
} }
}); });
@@ -573,9 +593,10 @@ export class ChatMessageItemComponent implements AfterViewInit, OnDestroy {
this.visibilityObserver?.disconnect(); this.visibilityObserver?.disconnect();
this.visibilityObserver = null; this.visibilityObserver = null;
if (this.isMessageVisible()) { // Destroyed rows always release their display blobs (pins are respected
// inside the facade); rows destroyed while off-screen previously kept
// their blobs alive for the rest of the session.
this.attachmentsSvc.revokeOffscreenDisplayBlobsForMessage(this.message().id); this.attachmentsSvc.revokeOffscreenDisplayBlobsForMessage(this.message().id);
}
this.clearLongPressTimer(); this.clearLongPressTimer();
this.detachMobileSheet(); this.detachMobileSheet();
@@ -811,9 +832,17 @@ export class ChatMessageItemComponent implements AfterViewInit, OnDestroy {
retryImageRequest(attachment: Attachment): void { retryImageRequest(attachment: Attachment): void {
const liveAttachment = this.getLiveAttachment(attachment.id); const liveAttachment = this.getLiveAttachment(attachment.id);
if (liveAttachment) { if (!liveAttachment) {
this.attachmentsSvc.requestImageFromAnyPeer(this.message().id, liveAttachment); return;
} }
const messageId = this.message().id;
if ((liveAttachment.receivedBytes ?? 0) > 0 || this.attachmentsSvc.hasPendingRequest(messageId, liveAttachment.id)) {
this.attachmentsSvc.cancelRequest(messageId, liveAttachment);
}
this.attachmentsSvc.requestImageFromAnyPeer(messageId, liveAttachment);
} }
openLightbox(attachment: Attachment): void { openLightbox(attachment: Attachment): void {
@@ -830,7 +859,7 @@ export class ChatMessageItemComponent implements AfterViewInit, OnDestroy {
} }
openImageGallery(): void { openImageGallery(): void {
const images = this.displayableImages(); const images = this.imageAttachments();
if (images.length < 2) { if (images.length < 2) {
return; return;
@@ -5,7 +5,7 @@
[ariaLabel]="'chat.overlays.closeGalleryAria' | translate" [ariaLabel]="'chat.overlays.closeGalleryAria' | translate"
(dismissed)="closeGallery()" (dismissed)="closeGallery()"
/> />
<div class="pointer-events-none fixed inset-0 z-[101] flex items-center justify-center p-4"> <div class="pointer-events-none fixed metoyou-fixed-safe-viewport z-[101] flex items-center justify-center p-4">
<div <div
class="pointer-events-auto relative flex max-h-[90vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl" class="pointer-events-auto relative flex max-h-[90vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl"
(click)="$event.stopPropagation()" (click)="$event.stopPropagation()"
@@ -32,22 +32,73 @@
</div> </div>
<div class="overflow-y-auto p-4"> <div class="overflow-y-auto p-4">
<div class="grid grid-cols-2 gap-3 sm:grid-cols-3"> <div class="grid grid-cols-2 gap-3 sm:grid-cols-3">
@for (attachment of galleryAttachments(); track attachment.id) { @for (tile of galleryTiles(); track tile.attachment.id) {
@switch (tile.state) {
@case ('displayable') {
<button <button
type="button" type="button"
class="group/gallery relative aspect-square overflow-hidden rounded-md bg-secondary/40" class="group/gallery relative aspect-square overflow-hidden rounded-md bg-secondary/40"
[attr.aria-label]="openImageAriaLabel(attachment.filename)" [attr.aria-label]="openImageAriaLabel(tile.attachment.filename)"
(click)="openGalleryImage(attachment)" (click)="openGalleryImage(tile.attachment)"
(contextmenu)="openImageContextMenu($event, attachment)" (contextmenu)="openImageContextMenu($event, tile.attachment)"
> >
<img <img
[src]="attachment.objectUrl" [src]="tile.attachment.objectUrl"
[alt]="attachment.filename" [alt]="tile.attachment.filename"
class="h-full w-full object-cover transition-transform duration-200 group-hover/gallery:scale-[1.02]" class="h-full w-full object-cover transition-transform duration-200 group-hover/gallery:scale-[1.02]"
/> />
<div class="pointer-events-none absolute inset-0 bg-black/0 transition-colors group-hover/gallery:bg-black/15"></div> <div class="pointer-events-none absolute inset-0 bg-black/0 transition-colors group-hover/gallery:bg-black/15"></div>
</button> </button>
} }
@case ('hydrating') {
<div class="flex aspect-square flex-col items-center justify-center gap-2 rounded-md border border-border bg-secondary/40 p-3 text-center">
<div class="h-6 w-6 animate-spin rounded-full border-b-2 border-primary"></div>
<button
type="button"
class="rounded-md bg-secondary px-2 py-1 text-xs text-foreground"
(click)="retryGalleryImage(tile.attachment)"
>
{{ 'chat.message.retry' | translate }}
</button>
</div>
}
@case ('downloading') {
<div class="flex aspect-square flex-col items-center justify-center gap-2 rounded-md border border-border bg-secondary/40 p-3 text-center">
<div class="text-xs font-medium text-primary">
{{ ((tile.attachment.receivedBytes || 0) * 100) / tile.attachment.size | number: '1.0-0' }}%
</div>
<div class="flex gap-2">
<button
type="button"
class="rounded-md bg-secondary px-2 py-1 text-xs text-foreground"
(click)="cancelGalleryImage(tile.attachment)"
>
{{ 'chat.message.cancel' | translate }}
</button>
<button
type="button"
class="rounded-md bg-secondary px-2 py-1 text-xs text-foreground"
(click)="retryGalleryImage(tile.attachment)"
>
{{ 'chat.message.retry' | translate }}
</button>
</div>
</div>
}
@default {
<div class="flex aspect-square flex-col items-center justify-center gap-2 rounded-md border border-dashed border-border bg-secondary/20 p-3 text-center">
<span class="line-clamp-2 text-xs text-muted-foreground">{{ tile.attachment.filename }}</span>
<button
type="button"
class="rounded-md bg-secondary px-2 py-1 text-xs text-foreground"
(click)="retryGalleryImage(tile.attachment)"
>
{{ 'chat.message.retry' | translate }}
</button>
</div>
}
}
}
</div> </div>
</div> </div>
</div> </div>
@@ -60,7 +111,7 @@
[ariaLabel]="'chat.overlays.closePreviewAria' | translate" [ariaLabel]="'chat.overlays.closePreviewAria' | translate"
(dismissed)="closeLightbox()" (dismissed)="closeLightbox()"
/> />
<div class="pointer-events-none fixed inset-0 z-[110] flex items-center justify-center p-4"> <div class="pointer-events-none fixed metoyou-fixed-safe-viewport z-[110] flex items-center justify-center p-4">
<div <div
class="lightbox-stage pointer-events-auto relative max-h-[90vh] max-w-[90vw]" class="lightbox-stage pointer-events-auto relative max-h-[90vh] max-w-[90vw]"
[class.lightbox-chrome-hidden]="!lightboxControlsVisible()" [class.lightbox-chrome-hidden]="!lightboxControlsVisible()"
@@ -18,12 +18,15 @@ import {
lucideDownload, lucideDownload,
lucideX lucideX
} from '@ng-icons/lucide'; } from '@ng-icons/lucide';
import { Attachment } from '../../../../../attachment'; import { Attachment, AttachmentFacade } from '../../../../../attachment';
import { isAttachmentPendingInlineHydration } from '../../../../../attachment/domain/logic/attachment-image.rules';
import { canStepLightbox } from '../../../../domain/rules/chat-message-lightbox.rules'; import { canStepLightbox } from '../../../../domain/rules/chat-message-lightbox.rules';
import { buildChatMessageGalleryTiles, type ChatMessageGalleryTile } from '../../../../domain/rules/chat-message-image-gallery.rules';
import { AppI18nService, APP_TRANSLATE_IMPORTS } from '../../../../../../core/i18n'; import { AppI18nService, APP_TRANSLATE_IMPORTS } from '../../../../../../core/i18n';
import { ContextMenuComponent, ModalBackdropComponent } from '../../../../../../shared'; import { ContextMenuComponent, ModalBackdropComponent } from '../../../../../../shared';
import { import {
ChatLightboxState, ChatLightboxState,
ChatMessageAttachmentEvent,
ChatMessageImageGalleryEvent, ChatMessageImageGalleryEvent,
ChatMessageImageContextMenuEvent, ChatMessageImageContextMenuEvent,
ChatMessageImageLightboxEvent ChatMessageImageLightboxEvent
@@ -68,6 +71,22 @@ export class ChatMessageOverlaysComponent implements OnDestroy {
readonly copyRequested = output<Attachment>(); readonly copyRequested = output<Attachment>();
readonly imageOpened = output<ChatMessageImageLightboxEvent>(); readonly imageOpened = output<ChatMessageImageLightboxEvent>();
readonly imageContextMenuRequested = output<ChatMessageImageContextMenuEvent>(); readonly imageContextMenuRequested = output<ChatMessageImageContextMenuEvent>();
readonly imageRetryRequested = output<ChatMessageAttachmentEvent>();
readonly imageCancelRequested = output<ChatMessageAttachmentEvent>();
readonly galleryTiles = computed<ChatMessageGalleryTile<Attachment>[]>(() => {
const attachments = this.galleryAttachments();
if (!attachments) {
return [];
}
const messageId = attachments[0]?.messageId;
return buildChatMessageGalleryTiles(attachments, (attachment) => ({
pendingRequest: !!messageId && this.attachmentsSvc.hasPendingRequest(messageId, attachment.id)
}));
});
readonly lightboxAttachment = computed(() => { readonly lightboxAttachment = computed(() => {
const state = this.lightboxState(); const state = this.lightboxState();
@@ -109,7 +128,26 @@ export class ChatMessageOverlaysComponent implements OnDestroy {
return `${state.index + 1} / ${state.attachments.length}`; return `${state.index + 1} / ${state.attachments.length}`;
}); });
private readonly syncGalleryHydration = effect(() => {
const attachments = this.galleryAttachments();
void this.attachmentsSvc.updated;
if (!attachments?.length) {
return;
}
for (const attachment of attachments) {
if (!isAttachmentPendingInlineHydration(attachment)) {
continue;
}
void this.attachmentsSvc.tryRestoreAttachmentFromLocal(attachment);
}
});
private readonly appI18n = inject(AppI18nService); private readonly appI18n = inject(AppI18nService);
private readonly attachmentsSvc = inject(AttachmentFacade);
private readonly LIGHTBOX_CONTROLS_IDLE_MS = 2200; private readonly LIGHTBOX_CONTROLS_IDLE_MS = 2200;
private lightboxControlsHideTimer: ReturnType<typeof setTimeout> | null = null; private lightboxControlsHideTimer: ReturnType<typeof setTimeout> | null = null;
@@ -200,6 +238,28 @@ export class ChatMessageOverlaysComponent implements OnDestroy {
}); });
} }
retryGalleryImage(attachment: Attachment): void {
if (!attachment.messageId) {
return;
}
this.imageRetryRequested.emit({
messageId: attachment.messageId,
attachment
});
}
cancelGalleryImage(attachment: Attachment): void {
if (!attachment.messageId) {
return;
}
this.imageCancelRequested.emit({
messageId: attachment.messageId,
attachment
});
}
closeImageContextMenu(): void { closeImageContextMenu(): void {
this.contextMenuClosed.emit(); this.contextMenuClosed.emit();
} }
@@ -0,0 +1,46 @@
# Custom Emoji Domain
User-created image emoji: validation, local asset storage, saved-library membership, P2P sync, and the shared picker consumed by chat reactions and the composer.
**Wire contract (P2P envelopes, `account_sync` relay):** [`agents-docs/features/custom-emoji.md`](../../../../../agents-docs/features/custom-emoji.md)
## Module map
```
custom-emoji/
├── domain/
│ ├── custom-emoji.rules.ts Validation, tokens, chunk limits, shortcut selection
│ └── custom-emoji.rules.spec.ts
├── application/
│ ├── custom-emoji.service.ts Upload, library, known-asset cache, proactive push
│ ├── custom-emoji.service.spec.ts
│ └── custom-emoji-sync.effects.ts NgRx effects: data-channel + account_sync handling
├── feature/
│ └── custom-emoji-picker/ Picker UI, search, shortcut row
└── index.ts Barrel — `CustomEmojiService`, picker component, effects
```
## Public entry points
| Export | Role |
|--------|------|
| `CustomEmojiService` | Upload, save/remove library, resolve tokens, peer summaries |
| `CustomEmojiPickerComponent` | Emoji selector for composer and reactions |
| `CustomEmojiSyncEffects` | Registers with NgRx for inbound sync events |
## NgRx / realtime touchpoints
- `CustomEmojiSyncEffects` listens for P2P `ChatEvent` types and `account_sync` payloads relayed from [`signaling`](../../../../../agents-docs/features/signaling.md).
- Chat domain calls `CustomEmojiService` when sending messages/reactions to push referenced assets to peers.
## UI integration
- **Chat composer**`:name:` aliases rewrite to `:emoji[id](name)` on send; shortcut row shows top seven saved emoji.
- **Message reactions** — custom emoji reactions use the same token format.
- **Context menu** — add/remove from library on rendered custom emoji (`data-custom-emoji` attributes).
## Boundaries
- Does not own chat message persistence or signaling server storage.
- Usage ranking is local per user id; not synced across devices.
- Import from `domains/custom-emoji` barrel only; chat imports the service, not internal paths.
@@ -14,6 +14,6 @@ Direct calls coordinate private voice sessions started from people cards, direct
8. Joining, leaving, ending, participant additions, and call chat conversion updates are mirrored as `direct-call` events over the same P2P/signaling fallback path used by direct messages. 8. Joining, leaving, ending, participant additions, and call chat conversion updates are mirrored as `direct-call` events over the same P2P/signaling fallback path used by direct messages.
9. The server rail shows call icons only while at least one participant is joined. If a user is viewing a private call after the session ends, the route returns to the call's chat view. 9. The server rail shows call icons only while at least one participant is joined. If a user is viewing a private call after the session ends, the route returns to the call's chat view.
Incoming `direct-call` events are ignored unless the current user is declared in the event's `participantIds` or participant profiles, so only invited PM/group-call participants can receive call audio, the in-app incoming-call modal, or a desktop ring notification. Incoming `direct-call` events are ignored unless the current user is declared in the event's `participantIds` or participant profiles, so only invited PM/group-call participants can receive call audio, the in-app incoming-call modal, or a desktop ring notification. That declaration check — and every other self check (sender echo filter, `remoteParticipantIds`, the DM-header peer lookup) — must match **every local identity alias**: home id, entity id, peer id, and each provisioned signal-server actor id from `SignalServerCredentialStoreService`. A caller who met the callee on a foreign signal server addresses them by the provisioned actor id, not the home id; checking only `oderId || id` silently drops the ring while the caller's UI moves to "In Voice" (`normalizeDirectCallPayloadSelfAliases` in `direct-call-participant-identity.rules.ts` collapses those aliases onto the canonical local id before session state is built, so the alias never appears as a phantom third participant).
Two-person calls use the one-to-one direct-message conversation id as their call id. Converted group calls keep the original call id for media routing but point `conversationId` at the new group chat so active streams stay connected while the chat history boundary changes. Two-person calls use the one-to-one direct-message conversation id as their call id. Converted group calls keep the original call id for media routing but point `conversationId` at the new group chat so active streams stay connected while the chat history boundary changes.
@@ -17,6 +17,7 @@ import {
import { initializeAppI18nForTests, provideAppI18nForTests } from '../../../../core/i18n/app-i18n.testing'; import { initializeAppI18nForTests, provideAppI18nForTests } from '../../../../core/i18n/app-i18n.testing';
import { ViewportService } from '../../../../core/platform'; import { ViewportService } from '../../../../core/platform';
import { RealtimeSessionFacade } from '../../../../core/realtime'; import { RealtimeSessionFacade } from '../../../../core/realtime';
import { SignalServerCredentialStoreService } from '../../../authentication/application/services/signal-server-credential-store.service';
import { import {
VoiceActivityService, VoiceActivityService,
VoiceConnectionFacade, VoiceConnectionFacade,
@@ -110,6 +111,111 @@ describe('DirectCallService', () => {
expect(context.directMessages.createGroupConversation).not.toHaveBeenCalled(); expect(context.directMessages.createGroupConversation).not.toHaveBeenCalled();
}); });
it('notifies when a ring addresses the local user via a provisioned signal-server actor id', async () => {
// Bob's home identity is "bob", but on the caller's signal server he acts
// through the provisioned identity "bob-actor". The ring payload only
// carries the actor id, so admission must match every local alias.
const context = createServiceContext({
currentUser: bob,
allUsers: [alice, bob],
selfActorIds: ['bob-actor']
});
context.directCallEvents.next({
type: 'direct-call',
directCall: {
action: 'ring',
callId: 'dm-alice-bob-actor',
conversationId: 'dm-alice-bob-actor',
createdAt: 10,
sender: toParticipant(alice),
participantIds: ['alice', 'bob-actor'],
participants: [toParticipant(alice), { userId: 'bob-actor', username: 'bob', displayName: 'Bob' }]
}
});
await vi.waitFor(() => expect(context.service.incomingCall()?.callId).toBe('dm-alice-bob-actor'));
await vi.waitFor(() => expect(context.audio.playLoop).toHaveBeenCalledWith(AppSound.Call));
const session = context.service.sessionById('dm-alice-bob-actor');
// The actor alias must collapse onto the local user instead of appearing
// as a third participant (which would convert the call into a group chat).
expect(session?.participantIds.sort()).toEqual(['alice', 'bob']);
expect(context.directMessages.createGroupConversation).not.toHaveBeenCalled();
});
it('ignores rings echoed back to the sender through a provisioned actor alias', async () => {
const context = createServiceContext({
currentUser: bob,
allUsers: [alice, bob],
selfActorIds: ['bob-actor']
});
context.directCallEvents.next({
type: 'direct-call',
directCall: {
action: 'ring',
callId: 'dm-alice-bob',
conversationId: 'dm-alice-bob',
createdAt: 10,
sender: { userId: 'bob-actor', username: 'bob', displayName: 'Bob' },
participantIds: ['alice', 'bob-actor'],
participants: [toParticipant(alice), { userId: 'bob-actor', username: 'bob', displayName: 'Bob' }]
}
});
await Promise.resolve();
expect(context.service.sessionById('dm-alice-bob')).toBeNull();
expect(context.audio.playLoop).not.toHaveBeenCalled();
});
it('excludes provisioned actor aliases from remote participant ids', () => {
const context = createServiceContext({
currentUser: bob,
allUsers: [alice, bob],
selfActorIds: ['bob-actor']
});
expect(context.service.remoteParticipantIds({
...createSession('ringing', false),
participantIds: [
'alice',
'bob',
'bob-actor'
]
})).toEqual(['alice']);
});
it('starts a DM-header call to the peer even when the conversation stores the local user under an actor alias', async () => {
const context = createServiceContext({
currentUser: bob,
allUsers: [alice, bob],
selfActorIds: ['bob-actor']
});
const conversation: DirectMessageConversation = {
id: 'dm-alice-bob-actor',
kind: 'direct',
lastMessageAt: 10,
messages: [],
participantProfiles: {
'alice': toParticipant(alice),
'bob-actor': { userId: 'bob-actor', username: 'bob', displayName: 'Bob' }
},
participants: ['alice', 'bob-actor'],
unreadCount: 0
};
context.service.joinCall = vi.fn(async () => undefined);
await context.service.startConversationCall(conversation);
expect(context.delivery.sendCallEvent).toHaveBeenCalledWith('alice', expect.objectContaining({
directCall: expect.objectContaining({ action: 'ring' }),
type: 'direct-call'
}));
});
it('marks a remote join against the session participant alias stored locally', async () => { it('marks a remote join against the session participant alias stored locally', async () => {
const aliceForeign = createUser('alice-foreign', 'Alice'); const aliceForeign = createUser('alice-foreign', 'Alice');
const bobForeign = createUser('bob-foreign', 'Bob'); const bobForeign = createUser('bob-foreign', 'Bob');
@@ -371,6 +477,56 @@ describe('DirectCallService', () => {
expect(context.voiceSession.endSession).toHaveBeenCalled(); expect(context.voiceSession.endSession).toHaveBeenCalled();
}); });
it('surfaces a join error when the microphone permission is denied instead of failing silently', async () => {
const context = createServiceContext({ currentUser: alice, allUsers: [alice, bob] });
const session = createSession('connected', false);
session.participants.bob.joined = true;
(context.service as DirectCallService & { upsertSession: (nextSession: DirectCallSession) => void }).upsertSession(session);
context.mobileMedia.ensureVoiceCapturePermissions.mockResolvedValue(false);
await withStubbedGetUserMedia(vi.fn(async () => new FakeMediaStream()), async () => {
await context.service.joinCall(session.callId);
});
expect(context.service.joinError()).not.toBeNull();
expect(context.voice.setLocalStream).not.toHaveBeenCalled();
expect(context.service.sessionById(session.callId)?.participants.alice.joined).not.toBe(true);
});
it('surfaces a join error when getUserMedia rejects', async () => {
const context = createServiceContext({ currentUser: alice, allUsers: [alice, bob] });
const session = createSession('connected', false);
session.participants.bob.joined = true;
(context.service as DirectCallService & { upsertSession: (nextSession: DirectCallSession) => void }).upsertSession(session);
await withStubbedGetUserMedia(vi.fn(async () => {
throw new Error('NotReadableError');
}), async () => {
await context.service.joinCall(session.callId);
});
expect(context.service.joinError()).not.toBeNull();
expect(context.voice.setLocalStream).not.toHaveBeenCalled();
});
it('clears the join error on a successful join', async () => {
const context = createServiceContext({ currentUser: alice, allUsers: [alice, bob] });
const session = createSession('connected', false);
session.participants.bob.joined = true;
(context.service as DirectCallService & { upsertSession: (nextSession: DirectCallSession) => void }).upsertSession(session);
await withStubbedGetUserMedia(vi.fn(async () => new FakeMediaStream()), async () => {
await context.service.joinCall(session.callId);
});
expect(context.service.joinError()).toBeNull();
expect(context.voice.setLocalStream).toHaveBeenCalled();
expect(context.service.sessionById(session.callId)?.participants.alice.joined).toBe(true);
});
it('starts group calls by keeping the rail-visible call session and ringing every other participant', async () => { it('starts group calls by keeping the rail-visible call session and ringing every other participant', async () => {
const context = createServiceContext({ currentUser: alice, allUsers: [ const context = createServiceContext({ currentUser: alice, allUsers: [
alice, alice,
@@ -429,6 +585,7 @@ describe('DirectCallService', () => {
interface ServiceContextOptions { interface ServiceContextOptions {
allUsers: User[]; allUsers: User[];
currentUser: User | null; currentUser: User | null;
selfActorIds?: string[];
} }
interface ServiceContext { interface ServiceContext {
@@ -536,6 +693,21 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext {
const voiceSession = { const voiceSession = {
endSession: vi.fn() endSession: vi.fn()
}; };
const mobileMedia = {
ensureVoiceCapturePermissions: vi.fn(async () => true),
setSpeakerphoneEnabled: vi.fn(async () => undefined)
};
const credentialStore = {
listValidCredentials: vi.fn(() => (options.selfActorIds ?? []).map((userId) => ({
serverUrl: `https://signal.example/${userId}`,
userId,
username: userId,
displayName: userId,
token: 'token',
expiresAt: Date.now() + 60_000,
provisioned: true
})))
};
const injector = Injector.create({ const injector = Injector.create({
providers: [ providers: [
{ {
@@ -614,10 +786,7 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext {
}, },
{ {
provide: MobileMediaService, provide: MobileMediaService,
useValue: { useValue: mobileMedia
ensureVoiceCapturePermissions: vi.fn(async () => true),
setSpeakerphoneEnabled: vi.fn(async () => undefined)
}
}, },
{ {
provide: RealtimeSessionFacade, provide: RealtimeSessionFacade,
@@ -626,6 +795,10 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext {
requestVoiceClientTakeover: vi.fn() requestVoiceClientTakeover: vi.fn()
} }
}, },
{
provide: SignalServerCredentialStoreService,
useValue: credentialStore
},
...provideAppI18nForTests() ...provideAppI18nForTests()
] ]
}); });
@@ -639,6 +812,7 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext {
directCallEvents, directCallEvents,
directMessages, directMessages,
effectScheduler, effectScheduler,
mobileMedia,
router, router,
service: runInInjectionContext(injector, () => new DirectCallService()), service: runInInjectionContext(injector, () => new DirectCallService()),
voice, voice,
@@ -646,6 +820,42 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext {
}; };
} }
class FakeMediaStream {
getTracks(): unknown[] {
return [];
}
}
/** Temporarily provide `navigator.mediaDevices.getUserMedia` for the join path under Node. */
async function withStubbedGetUserMedia(
getUserMedia: () => Promise<unknown>,
run: () => Promise<void>
): Promise<void> {
const globalWithNavigator = globalThis as { navigator?: { mediaDevices?: unknown } };
const originalNavigator = globalWithNavigator.navigator;
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: {
...(originalNavigator ?? {}),
mediaDevices: { getUserMedia }
}
});
try {
await run();
} finally {
if (originalNavigator === undefined) {
delete globalWithNavigator.navigator;
} else {
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: originalNavigator
});
}
}
}
function createCallEvent(action: 'leave' | 'ring', sender: User, participantIds: string[]): ChatEvent { function createCallEvent(action: 'leave' | 'ring', sender: User, participantIds: string[]): ChatEvent {
return { return {
type: 'direct-call', type: 'direct-call',
@@ -23,6 +23,7 @@ import {
} from '../../../voice-connection'; } from '../../../voice-connection';
import { VoiceSessionFacade, isVoiceOnAnotherClient } from '../../../voice-session'; import { VoiceSessionFacade, isVoiceOnAnotherClient } from '../../../voice-session';
import { RealtimeSessionFacade } from '../../../../core/realtime'; import { RealtimeSessionFacade } from '../../../../core/realtime';
import { SignalServerCredentialStoreService } from '../../../authentication/application/services/signal-server-credential-store.service';
import { DirectMessageService, PeerDeliveryService } from '../../../direct-message'; import { DirectMessageService, PeerDeliveryService } from '../../../direct-message';
import type { DirectMessageConversation } from '../../../direct-message'; import type { DirectMessageConversation } from '../../../direct-message';
import { selectAllUsers, selectCurrentUser } from '../../../../store/users/users.selectors'; import { selectAllUsers, selectCurrentUser } from '../../../../store/users/users.selectors';
@@ -34,9 +35,12 @@ import {
} from '../../../../shared-kernel'; } from '../../../../shared-kernel';
import { DirectCallSession, participantToUser } from '../../domain/models/direct-call.model'; import { DirectCallSession, participantToUser } from '../../domain/models/direct-call.model';
import { import {
collectDirectCallUserIdentityKeys,
directCallPayloadIncludesAnyId,
findDirectCallParticipantEntry, findDirectCallParticipantEntry,
findDirectCallParticipantEntryForUser, findDirectCallParticipantEntryForUser,
isDirectCallParticipantJoined isDirectCallParticipantJoined,
normalizeDirectCallPayloadSelfAliases
} from '../../domain/logic/direct-call-participant-identity.rules'; } from '../../domain/logic/direct-call-participant-identity.rules';
import { toDirectMessageParticipant } from '../../../direct-message'; import { toDirectMessageParticipant } from '../../../direct-message';
@@ -56,6 +60,7 @@ export class DirectCallService {
private readonly mobileNotifications = inject(MobileNotificationsService); private readonly mobileNotifications = inject(MobileNotificationsService);
private readonly mobileCallSession = inject(MobileCallSessionService); private readonly mobileCallSession = inject(MobileCallSessionService);
private readonly mobileMedia = inject(MobileMediaService); private readonly mobileMedia = inject(MobileMediaService);
private readonly credentialStore = inject(SignalServerCredentialStoreService);
private readonly i18n = inject(AppI18nService); private readonly i18n = inject(AppI18nService);
private readonly currentUser = this.store.selectSignal(selectCurrentUser); private readonly currentUser = this.store.selectSignal(selectCurrentUser);
private readonly users = this.store.selectSignal(selectAllUsers); private readonly users = this.store.selectSignal(selectAllUsers);
@@ -86,6 +91,8 @@ export class DirectCallService {
&& this.hasConnectedParticipant(session)) ?? null; && this.hasConnectedParticipant(session)) ?? null;
}); });
readonly currentSession = signal<DirectCallSession | null>(null); readonly currentSession = signal<DirectCallSession | null>(null);
/** User-facing reason the last joinCall attempt failed; null after a successful join. */
readonly joinError = signal<string | null>(null);
readonly hasActiveCall = computed(() => this.visibleActiveSessions().length > 0); readonly hasActiveCall = computed(() => this.visibleActiveSessions().length > 0);
readonly mobileOverlaySession = computed(() => { readonly mobileOverlaySession = computed(() => {
const callId = this.mobileOverlayCallId(); const callId = this.mobileOverlayCallId();
@@ -234,8 +241,8 @@ export class DirectCallService {
return await this.startGroupCall(conversation); return await this.startGroupCall(conversation);
} }
const meId = this.currentUserId(); const selfIds = this.selfIdentityIds();
const peerId = conversation.participants.find((participantId) => participantId !== meId); const peerId = conversation.participants.find((participantId) => !selfIds.has(participantId));
if (!peerId) { if (!peerId) {
throw new Error(this.i18n.instant('call.errors.noRecipient')); throw new Error(this.i18n.instant('call.errors.noRecipient'));
@@ -328,6 +335,7 @@ export class DirectCallService {
return; return;
} }
this.joinError.set(null);
this.leaveOtherJoinedCalls(callId); this.leaveOtherJoinedCalls(callId);
this.leaveCurrentVoiceTargetForCall(callId); this.leaveCurrentVoiceTargetForCall(callId);
this.audio.stop(AppSound.Call); this.audio.stop(AppSound.Call);
@@ -339,22 +347,36 @@ export class DirectCallService {
const ok = await this.voice.ensureSignalingConnected(); const ok = await this.voice.ensureSignalingConnected();
if (!ok || !navigator.mediaDevices?.getUserMedia) { if (!ok) {
this.joinError.set(this.i18n.instant('call.errors.signalingUnavailable'));
return;
}
if (!navigator.mediaDevices?.getUserMedia) {
this.joinError.set(this.i18n.instant('call.errors.captureUnsupported'));
return; return;
} }
const voicePermissionsGranted = await this.mobileMedia.ensureVoiceCapturePermissions(); const voicePermissionsGranted = await this.mobileMedia.ensureVoiceCapturePermissions();
if (!voicePermissionsGranted) { if (!voicePermissionsGranted) {
this.joinError.set(this.i18n.instant('call.errors.microphonePermissionDenied'));
return; return;
} }
const stream = await navigator.mediaDevices.getUserMedia({ let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getUserMedia({
audio: { audio: {
echoCancellation: true, echoCancellation: true,
noiseSuppression: false noiseSuppression: false
} }
}); });
} catch {
this.joinError.set(this.i18n.instant('call.errors.microphoneUnavailable'));
return;
}
await this.voice.setLocalStream(stream); await this.voice.setLocalStream(stream);
this.voiceActivity.trackLocalMic(meId, stream); this.voiceActivity.trackLocalMic(meId, stream);
@@ -433,9 +455,9 @@ export class DirectCallService {
} }
remoteParticipantIds(session: DirectCallSession): string[] { remoteParticipantIds(session: DirectCallSession): string[] {
const meId = this.currentUserId(); const selfIds = this.selfIdentityIds();
return session.participantIds.filter((participantId) => participantId !== meId); return session.participantIds.filter((participantId) => !selfIds.has(participantId));
} }
userForParticipant(participantId: string): User | null { userForParticipant(participantId: string): User | null {
@@ -464,29 +486,35 @@ export class DirectCallService {
} }
} }
private async handleIncomingCallEvent(payload: DirectCallEventPayload): Promise<void> { private async handleIncomingCallEvent(rawPayload: DirectCallEventPayload): Promise<void> {
const meId = this.currentUserId(); const meId = this.currentUserId();
if (!meId) { if (!meId) {
if (payload.action === 'ring') { if (rawPayload.action === 'ring') {
this.pendingIncomingCallPayloads.push(payload); this.pendingIncomingCallPayloads.push(rawPayload);
} }
return; return;
} }
if (payload.sender.userId === meId) { // Callers on a foreign signal server address the local user through the
// provisioned actor identity, not the home id, so every self check and the
// stored participant state must work across all local identity aliases.
const selfIds = this.selfIdentityIds();
if (selfIds.has(rawPayload.sender.userId)) {
return; return;
} }
if (!this.callPayloadIncludesParticipant(payload, meId)) { if (!directCallPayloadIncludesAnyId(rawPayload, selfIds)) {
return; return;
} }
if (payload.action === 'ring' && this.declinedCallIds.has(payload.callId)) { if (rawPayload.action === 'ring' && this.declinedCallIds.has(rawPayload.callId)) {
return; return;
} }
const payload = normalizeDirectCallPayloadSelfAliases(rawPayload, meId, selfIds);
const participants = this.callParticipantsFromPayload(payload); const participants = this.callParticipantsFromPayload(payload);
const existing = this.sessionById(payload.callId); const existing = this.sessionById(payload.callId);
const incomingSession = this.createSession({ const incomingSession = this.createSession({
@@ -826,11 +854,6 @@ export class DirectCallService {
]); ]);
} }
private callPayloadIncludesParticipant(payload: DirectCallEventPayload, participantId: string): boolean {
return payload.participantIds.includes(participantId)
|| (payload.participants ?? []).some((participant) => participant.userId === participantId);
}
private groupConversationTitle(session: DirectCallSession): string { private groupConversationTitle(session: DirectCallSession): string {
const names = Object.values(session.participants) const names = Object.values(session.participants)
.map((participant) => participant.profile.displayName || participant.profile.username || participant.userId); .map((participant) => participant.profile.displayName || participant.profile.username || participant.userId);
@@ -1056,6 +1079,19 @@ export class DirectCallService {
return user ? this.userKey(user) : null; return user ? this.userKey(user) : null;
} }
/** Every id that can address the local user, including provisioned signal-server actor ids. */
private selfIdentityIds(): ReadonlySet<string> {
const user = this.currentUser();
if (!user) {
return new Set();
}
const actorUserIds = this.credentialStore.listValidCredentials().map((credential) => credential.userId);
return new Set(collectDirectCallUserIdentityKeys(user, actorUserIds));
}
private requireCurrentUser(): User { private requireCurrentUser(): User {
const user = this.currentUser(); const user = this.currentUser();
@@ -1,8 +1,11 @@
import type { DirectCallEventPayload } from '../../../../shared-kernel';
import type { DirectCallSession } from '../models/direct-call.model'; import type { DirectCallSession } from '../models/direct-call.model';
import { import {
directCallPayloadIncludesAnyId,
findDirectCallParticipantEntry, findDirectCallParticipantEntry,
findDirectCallParticipantEntryForUser, findDirectCallParticipantEntryForUser,
isDirectCallParticipantJoined isDirectCallParticipantJoined,
normalizeDirectCallPayloadSelfAliases
} from './direct-call-participant-identity.rules'; } from './direct-call-participant-identity.rules';
function createSession(participants: DirectCallSession['participants']): DirectCallSession { function createSession(participants: DirectCallSession['participants']): DirectCallSession {
@@ -77,4 +80,58 @@ describe('direct-call-participant-identity.rules', () => {
oderId: 'bob-foreign' oderId: 'bob-foreign'
}, ['bob-foreign'])).toBe(false); }, ['bob-foreign'])).toBe(false);
}); });
it('directCallPayloadIncludesAnyId matches participant ids and participant profiles', () => {
const payload = createRingPayload();
expect(directCallPayloadIncludesAnyId(payload, new Set(['bob-actor']))).toBe(true);
expect(directCallPayloadIncludesAnyId(payload, new Set(['bob-profile-only']))).toBe(true);
expect(directCallPayloadIncludesAnyId(payload, new Set(['charlie']))).toBe(false);
}); });
it('normalizeDirectCallPayloadSelfAliases collapses provisioned aliases onto the canonical local id', () => {
const normalized = normalizeDirectCallPayloadSelfAliases(createRingPayload(), 'bob-home', new Set([
'bob-home',
'bob-actor',
'bob-profile-only'
]));
expect(normalized.participantIds).toEqual(['alice', 'bob-home']);
expect(normalized.participants?.map((participant) => participant.userId)).toEqual(['alice', 'bob-home']);
});
it('normalizeDirectCallPayloadSelfAliases leaves payloads without self aliases untouched', () => {
const payload = createRingPayload();
const normalized = normalizeDirectCallPayloadSelfAliases(payload, 'charlie', new Set(['charlie']));
expect(normalized.participantIds).toEqual(payload.participantIds);
expect(normalized.participants).toEqual(payload.participants);
});
});
function createRingPayload(): DirectCallEventPayload {
return {
action: 'ring',
callId: 'dm-alice--bob-actor',
conversationId: 'dm-alice--bob-actor',
createdAt: 1,
sender: {
userId: 'alice',
username: 'alice',
displayName: 'Alice'
},
participantIds: ['alice', 'bob-actor'],
participants: [
{
userId: 'alice',
username: 'alice',
displayName: 'Alice'
},
{
userId: 'bob-profile-only',
username: 'bob',
displayName: 'Bob'
}
]
};
}
@@ -1,4 +1,4 @@
import type { User } from '../../../../shared-kernel'; import type { DirectCallEventPayload, User } from '../../../../shared-kernel';
import type { DirectCallParticipant, DirectCallSession } from '../models/direct-call.model'; import type { DirectCallParticipant, DirectCallSession } from '../models/direct-call.model';
type UserIdentityFields = Pick<User, 'id' | 'oderId' | 'peerId'>; type UserIdentityFields = Pick<User, 'id' | 'oderId' | 'peerId'>;
@@ -86,3 +86,52 @@ export function isDirectCallParticipantJoined(
): boolean { ): boolean {
return !!findDirectCallParticipantEntryForUser(session, user, additionalIds)?.participant.joined; return !!findDirectCallParticipantEntryForUser(session, user, additionalIds)?.participant.joined;
} }
/** True when any of the given ids is declared in the payload's participant ids or profiles. */
export function directCallPayloadIncludesAnyId(
payload: Pick<DirectCallEventPayload, 'participantIds' | 'participants'>,
ids: ReadonlySet<string>
): boolean {
return payload.participantIds.some((participantId) => ids.has(participantId))
|| (payload.participants ?? []).some((participant) => ids.has(participant.userId));
}
/**
* Rewrite every self alias (home id, entity id, provisioned signal-server
* actor ids) in an incoming call payload to the canonical local id. Callers
* on a foreign signal server address the local user by the provisioned actor
* identity; without collapsing it the alias shows up as an extra third
* participant and never matches the local user's session key.
*/
export function normalizeDirectCallPayloadSelfAliases(
payload: DirectCallEventPayload,
canonicalId: string,
selfIds: ReadonlySet<string>
): DirectCallEventPayload {
const participantIds = [
...new Set(payload.participantIds.map((participantId) =>
(selfIds.has(participantId) ? canonicalId : participantId)))
];
const seenParticipantIds = new Set<string>();
const participants = payload.participants
?.map((participant) => (selfIds.has(participant.userId)
? {
...participant,
userId: canonicalId
}
: participant))
.filter((participant) => {
if (seenParticipantIds.has(participant.userId)) {
return false;
}
seenParticipantIds.add(participant.userId);
return true;
});
return {
...payload,
participantIds,
participants
};
}

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