From fa450524321da49e813efeb379001b0ad08b0fff Mon Sep 17 00:00:00 2001 From: Myx Date: Sun, 14 Jun 2026 13:05:23 +0200 Subject: [PATCH 01/11] 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 --- .../multi-device-attachment-sharing.spec.ts | 55 ++++++++++++ e2e/tests/chat/multi-image-gallery.spec.ts | 61 +++++++++++++ toju-app/src/app/domains/attachment/README.md | 6 +- .../application/facades/attachment.facade.ts | 6 ++ .../services/attachment-manager.service.ts | 32 ++++--- .../attachment-transfer.service.spec.ts | 86 ++++++++++++++++++- .../services/attachment-transfer.service.ts | 46 ++++++++-- ...ent-autodownload-concurrency.rules.spec.ts | 29 +++++++ ...tachment-autodownload-concurrency.rules.ts | 29 +++++++ .../logic/attachment-blob.rules.spec.ts | 5 +- .../logic/attachment-download.rules.spec.ts | 5 +- .../domain/logic/attachment.logic.spec.ts | 20 +++++ .../domain/logic/attachment.logic.ts | 21 +++++ .../chat-message-image-gallery.rules.spec.ts | 54 ++++++++++++ .../rules/chat-message-image-gallery.rules.ts | 39 +++++++++ .../chat-messages.component.html | 2 + .../chat-messages/chat-messages.component.ts | 28 ++++-- .../chat-message-item.component.html | 18 +++- .../chat-message-item.component.ts | 38 +++++++- .../chat-message-overlays.component.html | 74 ++++++++++++---- .../chat-message-overlays.component.ts | 36 ++++++++ .../src/app/domains/direct-message/README.md | 11 +-- .../services/direct-message.service.ts | 9 +- .../rules/dm-message-send.rules.spec.ts | 30 +++++++ .../domain/rules/dm-message-send.rules.ts | 44 ++++++++++ .../feature/dm-chat/dm-chat.component.html | 2 + .../feature/dm-chat/dm-chat.component.ts | 55 ++++++++++-- .../src/app/infrastructure/realtime/README.md | 2 +- .../account-sync/account-sync.rules.spec.ts | 12 +++ .../account-sync/account-sync.rules.ts | 1 + 30 files changed, 785 insertions(+), 71 deletions(-) create mode 100644 e2e/tests/chat/multi-image-gallery.spec.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.spec.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.ts create mode 100644 toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts create mode 100644 toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts create mode 100644 toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.spec.ts create mode 100644 toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.ts diff --git a/e2e/tests/chat/multi-device-attachment-sharing.spec.ts b/e2e/tests/chat/multi-device-attachment-sharing.spec.ts index fc299df..f06b9b0 100644 --- a/e2e/tests/chat/multi-device-attachment-sharing.spec.ts +++ b/e2e/tests/chat/multi-device-attachment-sharing.spec.ts @@ -85,6 +85,61 @@ test.describe('Multi-device attachment sharing', () => { 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 { diff --git a/e2e/tests/chat/multi-image-gallery.spec.ts b/e2e/tests/chat/multi-image-gallery.spec.ts new file mode 100644 index 0000000..bfdb8cd --- /dev/null +++ b/e2e/tests/chat/multi-image-gallery.spec.ts @@ -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 = ''; + + return { + name, + mimeType: 'image/svg+xml', + base64: Buffer.from(svg, 'utf8').toString('base64') + }; +} diff --git a/toju-app/src/app/domains/attachment/README.md b/toju-app/src/app/domains/attachment/README.md index 8ada65c..a1833ce 100644 --- a/toju-app/src/app/domains/attachment/README.md +++ b/toju-app/src/app/domains/attachment/README.md @@ -107,14 +107,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. - **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. 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 **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. ### 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. -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 sequenceDiagram @@ -144,7 +144,7 @@ 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`. -Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:`, 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:`, 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. 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. diff --git a/toju-app/src/app/domains/attachment/application/facades/attachment.facade.ts b/toju-app/src/app/domains/attachment/application/facades/attachment.facade.ts index a9cede9..99aa959 100644 --- a/toju-app/src/app/domains/attachment/application/facades/attachment.facade.ts +++ b/toju-app/src/app/domains/attachment/application/facades/attachment.facade.ts @@ -135,6 +135,12 @@ export class AttachmentFacade { return this.manager.cancelRequest(...args); } + hasPendingRequest( + ...args: Parameters + ): ReturnType { + return this.manager.hasPendingRequest(...args); + } + handleFileCancel( ...args: Parameters ): ReturnType { diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts index 682253a..ee9c441 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts @@ -16,6 +16,7 @@ import { isDirectMessageAttachmentRoomId, shouldAutoRequestWhenWatched } from '../../domain/logic/attachment.logic'; +import { ATTACHMENT_AUTO_DOWNLOAD_CONCURRENCY, runTasksWithBoundedConcurrency } from '../../domain/logic/attachment-autodownload-concurrency.rules'; import type { Attachment, AttachmentMeta } from '../../domain/models/attachment.model'; import type { FileAnnouncePayload, @@ -153,6 +154,10 @@ export class AttachmentManagerService { return this.transfer.requestImageFromAnyPeer(messageId, attachment); } + hasPendingRequest(messageId: string, attachmentId: string): boolean { + return this.transfer.hasPendingRequest(messageId, attachmentId); + } + async tryRestoreAttachmentFromLocal(attachment: Attachment): Promise { const restored = await this.persistence.tryRestoreAttachmentFromLocal(attachment); @@ -316,33 +321,40 @@ export class AttachmentManagerService { await this.restoreLocalAttachmentsForRoom(roomId); - if (isDirectMessageAttachmentRoomId(roomId)) { - await this.requestAutoDownloadsForRuntimeRoom(roomId); - return; - } + let messageIds: string[]; - 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); for (const message of messages) { 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 { + private async collectMessageIdsForAttachmentsInRoom(roomId: string): Promise { + const messageIds: string[] = []; + for (const [messageId] of this.runtimeStore.getAttachmentEntries()) { const attachmentRoomId = await this.persistence.resolveMessageRoomId(messageId); if (attachmentRoomId === roomId) { - await this.requestAutoDownloadsForMessage(messageId); + messageIds.push(messageId); } } + + return messageIds; } private async requestAutoDownloadsForMessage(messageId: string, attachmentId?: string): Promise { diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts index 86b35ed..6764644 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts @@ -414,6 +414,7 @@ describe('AttachmentTransferService', () => { fileId: FILE_ID, index: 0 }); + expect(persistence.saveFileToDisk).not.toHaveBeenCalled(); }); @@ -480,6 +481,7 @@ describe('AttachmentTransferService', () => { fileId: FILE_ID, index: 0 }); + expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled(); expect(persistence.saveFileToDisk).not.toHaveBeenCalled(); expect(attachment.objectUrl).toBeUndefined(); @@ -510,15 +512,16 @@ describe('AttachmentTransferService', () => { fileId: FILE_ID, index: 0 }); + expect(persistence.saveFileToDisk).not.toHaveBeenCalled(); 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 download completes', async () => { attachmentStorage.canStreamToDisk.mockReturnValue(true); const service = createService(); - const attachment = registerIncomingVideo(3); + const attachment = registerIncomingAttachment(3); service.handleFileChunk(chunkPayload(0, 1, [ 1, @@ -530,9 +533,55 @@ describe('AttachmentTransferService', () => { expect(attachment.savedPath).toBeTruthy(); expect(attachment.objectUrl).toBeUndefined(); + expect(attachmentStorage.getFileUrl).not.toHaveBeenCalled(); expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled(); }); + it('hydrates playable media with a native file url after disk-streamed download completes', async () => { + attachmentStorage.canStreamToDisk.mockReturnValue(true); + attachmentStorage.getFileUrl.mockResolvedValue('file:///appdata/server/room/files/clip.mp4'); + + const service = createService(); + const attachment = registerIncomingVideo(3); + + 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 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(3); + + 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 () => { attachmentStorage.canStreamToDisk.mockReturnValue(false); attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024); @@ -727,4 +776,37 @@ describe('AttachmentTransferService', () => { expect(attachment.available).toBe(true); 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); + }); }); diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts index 1f77afd..11080a9 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts @@ -229,6 +229,10 @@ export class AttachmentTransferService { } requestImageFromAnyPeer(messageId: string, attachment: Attachment): Promise { + if ((attachment.receivedBytes ?? 0) > 0 || this.hasPendingRequest(messageId, attachment.id)) { + this.cancelRequest(messageId, attachment); + } + return this.requestFromAnyPeer(messageId, attachment); } @@ -456,22 +460,22 @@ export class AttachmentTransferService { } cancelRequest(messageId: string, attachment: Attachment): void { - const targetPeerId = attachment.uploaderPeerId; - - if (!targetPeerId) - return; - try { + const requestKey = this.buildRequestKey(messageId, attachment.id); const assemblyKey = `${messageId}:${attachment.id}`; + const pendingPeers = this.runtimeStore.getPendingRequestPeers(requestKey); this.runtimeStore.deleteChunkBuffer(assemblyKey); this.runtimeStore.deleteChunkCount(assemblyKey); + this.runtimeStore.deletePendingRequest(requestKey); void this.deleteDiskReceiveAssembly(assemblyKey); + this.chunkAcks.cancelPendingForFile(messageId, attachment.id); attachment.receivedBytes = 0; attachment.speedBps = 0; attachment.startedAtMs = undefined; attachment.lastUpdateMs = undefined; + attachment.requestError = undefined; if (attachment.objectUrl) { try { @@ -489,8 +493,21 @@ export class AttachmentTransferService { messageId, fileId: attachment.id }; + const peersToNotify = new Set(); - 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 */ } } @@ -997,6 +1014,23 @@ export class AttachmentTransferService { this.runtimeStore.touch(); void this.persistence.persistAttachmentMeta(attachment); void this.announceLocalHost(attachment); + void this.hydratePlayableMediaAfterDiskReceive(attachment); + } + + private async hydratePlayableMediaAfterDiskReceive(attachment: Attachment): Promise { + 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( diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.spec.ts new file mode 100644 index 0000000..bde3645 --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.spec.ts @@ -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); + }); +}); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.ts new file mode 100644 index 0000000..d90fa4e --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload-concurrency.rules.ts @@ -0,0 +1,29 @@ +/** Default parallel attachment auto-download limit per watched room. */ +export const ATTACHMENT_AUTO_DOWNLOAD_CONCURRENCY = 3; + +export async function runTasksWithBoundedConcurrency( + tasks: readonly (() => Promise)[], + concurrency: number +): Promise { + 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 { + while (nextIndex < tasks.length) { + const currentIndex = nextIndex; + + nextIndex += 1; + results[currentIndex] = await tasks[currentIndex](); + } + } + + await Promise.all(Array.from({ length: limit }, () => runWorker())); + + return results; +} diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-blob.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-blob.rules.spec.ts index 37b9634..fd2adf2 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment-blob.rules.spec.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-blob.rules.spec.ts @@ -4,10 +4,7 @@ import { it } from 'vitest'; -import { - base64DecodedByteLength, - decodeBase64ToUint8Array -} from './attachment-blob.rules'; +import { base64DecodedByteLength, decodeBase64ToUint8Array } from './attachment-blob.rules'; describe('attachment blob rules', () => { it('decodes base64 payloads into byte arrays', () => { diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-download.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-download.rules.spec.ts index 40e5d14..8b6ecf9 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment-download.rules.spec.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-download.rules.spec.ts @@ -4,10 +4,7 @@ import { it } from 'vitest'; -import { - canDownloadAttachment, - resolveAttachmentDiskPath -} from './attachment-download.rules'; +import { canDownloadAttachment, resolveAttachmentDiskPath } from './attachment-download.rules'; describe('attachment-download.rules', () => { it('allows download when a completed disk-only attachment has no object URL', () => { diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts index 98e4e4d..26a3116 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts @@ -1,6 +1,8 @@ import { getWatchedAttachmentRoomIdFromUrl, + isAttachmentPendingMediaHydration, isDirectMessageAttachmentRoomId, + isPlayableAttachmentMedia, shouldCopyUploaderMediaToAppData, shouldCopyLargeUploaderFileToAppData, shouldStreamAttachmentReceiveToDisk, @@ -83,6 +85,24 @@ describe('attachment logic', () => { }, capabilities)).toBe(true); }); + 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', () => { const browserCapabilities = { canStreamToDisk: false, diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts index fb0ac09..548c9b5 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts @@ -11,6 +11,27 @@ export function isAttachmentMedia(attachment: Pick): boolean attachment.mime.startsWith('audio/'); } +export function isPlayableAttachmentMedia(attachment: Pick): 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 shouldAutoRequestWhenWatched(attachment: Attachment): boolean { return attachment.isImage || (isAttachmentMedia(attachment) && attachment.size <= MAX_AUTO_SAVE_SIZE_BYTES); diff --git a/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts new file mode 100644 index 0000000..9b3ec1f --- /dev/null +++ b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts @@ -0,0 +1,54 @@ +import { + describe, + expect, + it +} from 'vitest'; + +import { buildChatMessageGalleryTiles } 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' + ]); + }); +}); diff --git a/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts new file mode 100644 index 0000000..8a031cc --- /dev/null +++ b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts @@ -0,0 +1,39 @@ +import { + isAttachmentPendingInlineHydration, + isInlineDisplayableImage, + type ImageAttachmentCandidate +} from '../../../attachment/domain/logic/attachment-image.rules'; + +export type ChatMessageGalleryTileState = 'displayable' | 'hydrating' | 'downloading' | 'retry'; + +export interface ChatMessageGalleryTile { + attachment: T; + state: ChatMessageGalleryTileState; +} + +export function buildChatMessageGalleryTiles( + attachments: readonly T[] +): ChatMessageGalleryTile[] { + return attachments.map((attachment) => ({ + attachment, + state: resolveChatMessageGalleryTileState(attachment) + })); +} + +export function resolveChatMessageGalleryTileState( + attachment: T +): ChatMessageGalleryTileState { + if (isInlineDisplayableImage(attachment)) { + return 'displayable'; + } + + if (isAttachmentPendingInlineHydration(attachment)) { + return 'hydrating'; + } + + if ((attachment.receivedBytes ?? 0) > 0) { + return 'downloading'; + } + + return 'retry'; +} diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.html b/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.html index 5df6c22..bfb79b6 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.html +++ b/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.html @@ -96,5 +96,7 @@ (copyRequested)="copyImageToClipboard($event)" (imageOpened)="openLightbox($event)" (imageContextMenuRequested)="openImageContextMenu($event)" + (imageRetryRequested)="retryGalleryImage($event)" + (imageCancelRequested)="cancelGalleryImage($event)" /> diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts b/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts index 37cfb3f..8b5bac2 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts +++ b/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts @@ -47,6 +47,7 @@ import { ChatMessageDeleteEvent, ChatMessageEditEvent, ChatMessageEmbedRemoveEvent, + ChatMessageAttachmentEvent, ChatMessageImageContextMenuEvent, ChatMessageImageLightboxEvent, ChatMessageReactionEvent, @@ -340,14 +341,17 @@ export class ChatMessagesComponent { } openImageGallery(attachments: Attachment[]): void { - const availableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl); - - if (availableImages.length < 2) { + if (attachments.length < 2) { return; } - this.attachmentsSvc.pinDisplayBlobs(availableImages); - this.galleryAttachments.set(availableImages); + const displayableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl); + + if (displayableImages.length > 0) { + this.attachmentsSvc.pinDisplayBlobs(displayableImages); + } + + this.galleryAttachments.set(attachments); } closeImageGallery(): void { @@ -372,6 +376,20 @@ export class ChatMessagesComponent { await this.attachmentDownload.downloadToUserLocation(attachment); } + retryGalleryImage(event: ChatMessageAttachmentEvent): void { + const { messageId, attachment } = event; + + if ((attachment.receivedBytes ?? 0) > 0 || this.attachmentsSvc.hasPendingRequest(messageId, attachment.id)) { + this.attachmentsSvc.cancelRequest(messageId, attachment); + } + + void this.attachmentsSvc.requestImageFromAnyPeer(messageId, attachment); + } + + cancelGalleryImage(event: ChatMessageAttachmentEvent): void { + this.attachmentsSvc.cancelRequest(event.messageId, event.attachment); + } + async copyImageToClipboard(attachment: Attachment): Promise { this.closeImageContextMenu(); diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-item/chat-message-item.component.html b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-item/chat-message-item.component.html index a5d18a3..8e14aa9 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-item/chat-message-item.component.html +++ b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-item/chat-message-item.component.html @@ -205,6 +205,22 @@ {{ ((gridImage.receivedBytes || 0) * 100) / gridImage.size | number: '1.0-0' }}% +
+ + +
} @else {
@@ -226,7 +242,7 @@
- @for (attachment of galleryAttachments(); track attachment.id) { - + @for (tile of galleryTiles(); track tile.attachment.id) { + @switch (tile.state) { + @case ('displayable') { + + } + @case ('hydrating') { +
+
+
+ } + @case ('downloading') { +
+
+ {{ ((tile.attachment.receivedBytes || 0) * 100) / tile.attachment.size | number: '1.0-0' }}% +
+
+ + +
+
+ } + @default { +
+ {{ tile.attachment.filename }} + +
+ } + } }
diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts index 0dd5ff7..ec51494 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts +++ b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts @@ -20,10 +20,12 @@ import { } from '@ng-icons/lucide'; import { Attachment } from '../../../../../attachment'; 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 { ContextMenuComponent, ModalBackdropComponent } from '../../../../../../shared'; import { ChatLightboxState, + ChatMessageAttachmentEvent, ChatMessageImageGalleryEvent, ChatMessageImageContextMenuEvent, ChatMessageImageLightboxEvent @@ -68,6 +70,18 @@ export class ChatMessageOverlaysComponent implements OnDestroy { readonly copyRequested = output(); readonly imageOpened = output(); readonly imageContextMenuRequested = output(); + readonly imageRetryRequested = output(); + readonly imageCancelRequested = output(); + + readonly galleryTiles = computed[]>(() => { + const attachments = this.galleryAttachments(); + + if (!attachments) { + return []; + } + + return buildChatMessageGalleryTiles(attachments); + }); readonly lightboxAttachment = computed(() => { const state = this.lightboxState(); @@ -200,6 +214,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 { this.contextMenuClosed.emit(); } diff --git a/toju-app/src/app/domains/direct-message/README.md b/toju-app/src/app/domains/direct-message/README.md index 1778f65..b353e7c 100644 --- a/toju-app/src/app/domains/direct-message/README.md +++ b/toju-app/src/app/domains/direct-message/README.md @@ -21,11 +21,12 @@ direct-message/ ## Flow 1. `DirectMessageService.sendMessage()` stores the message locally with `QUEUED`. -2. `PeerDeliveryService` tries to send a `direct-message` P2P event to every other participant's current peer id. -3. If no data channel is connected, `PeerDeliveryService` tries each participant's known signaling route before leaving the message queued. -4. If either transport sends, the sender advances to `SENT`; otherwise the message id remains in `OfflineMessageQueueService`. -5. The recipient persists the message as `DELIVERED` and sends a `direct-message-status` event back. -6. Opening the conversation marks incoming messages as `ACKNOWLEDGED` and emits a status event. +2. `DmChatComponent.handleMessageSubmitted` pre-allocates the outgoing message id via `planDmMessageSend` (`domain/rules/dm-message-send.rules.ts`), passes it to `sendMessage(..., id)`, and binds pending files to that **same** id with `AttachmentFacade.publishAttachments`. Never attach after `sendMessage` resolves by re-discovering the message — caption-less media races the async create path the same way server rooms used to. +3. `PeerDeliveryService` tries to send a `direct-message` P2P event to every other participant's current peer id. +4. If no data channel is connected, `PeerDeliveryService` tries each participant's known signaling route before leaving the message queued. +5. If either transport sends, the sender advances to `SENT`; otherwise the message id remains in `OfflineMessageQueueService`. +6. The recipient persists the message as `DELIVERED` and sends a `direct-message-status` event back. +7. Opening the conversation marks incoming messages as `ACKNOWLEDGED` and emits a status event. Unread counts are idempotent by message id: re-receiving or syncing a message that already exists can update status/content metadata but must not increment the conversation unread count again. diff --git a/toju-app/src/app/domains/direct-message/application/services/direct-message.service.ts b/toju-app/src/app/domains/direct-message/application/services/direct-message.service.ts index 733ae29..13b2b8c 100644 --- a/toju-app/src/app/domains/direct-message/application/services/direct-message.service.ts +++ b/toju-app/src/app/domains/direct-message/application/services/direct-message.service.ts @@ -213,7 +213,12 @@ export class DirectMessageService { } } - async sendMessage(conversationId: string, content: string, replyToId?: string): Promise { + async sendMessage( + conversationId: string, + content: string, + replyToId?: string, + id?: string + ): Promise { const normalizedContent = content.trim(); if (!normalizedContent) { @@ -232,7 +237,7 @@ export class DirectMessageService { } const message: DirectMessage = { - id: uuidv4(), + id: id ?? uuidv4(), conversationId, senderId, recipientId, diff --git a/toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.spec.ts b/toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.spec.ts new file mode 100644 index 0000000..6506484 --- /dev/null +++ b/toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.spec.ts @@ -0,0 +1,30 @@ +import { planDmMessageSend } from './dm-message-send.rules'; + +function makeFile(name: string): File { + return new File(['x'], name, { type: 'image/png' }); +} + +describe('planDmMessageSend', () => { + it('binds attachments to the same pre-allocated message id', () => { + const generateId = () => 'dm-msg-1'; + const plan = planDmMessageSend({ + generateId, + content: 'hello', + pendingFiles: [makeFile('a.png'), makeFile('b.png')] + }); + + expect(plan.action.id).toBe('dm-msg-1'); + expect(plan.attachmentBinding?.messageId).toBe('dm-msg-1'); + expect(plan.attachmentBinding?.files).toHaveLength(2); + }); + + it('returns no attachment binding when there are no pending files', () => { + const plan = planDmMessageSend({ + generateId: () => 'dm-msg-2', + content: 'text only', + pendingFiles: [] + }); + + expect(plan.attachmentBinding).toBeNull(); + }); +}); diff --git a/toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.ts b/toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.ts new file mode 100644 index 0000000..f0420d7 --- /dev/null +++ b/toju-app/src/app/domains/direct-message/domain/rules/dm-message-send.rules.ts @@ -0,0 +1,44 @@ +/** + * Pure planning for an outgoing direct message and its attachments. + * + * Mirrors `planChatMessageSend`: the message id must be allocated before + * dispatch so pending files bind to the same bubble instead of racing the + * async create path and landing on a sibling message. + */ +export interface DmMessageSendAction { + id: string; + content: string; + replyToId?: string; +} + +export interface DmMessageAttachmentBinding { + messageId: string; + files: File[]; +} + +export interface DmMessageSendPlan { + action: DmMessageSendAction; + attachmentBinding: DmMessageAttachmentBinding | null; +} + +export interface DmMessageSendInput { + generateId: () => string; + content: string; + pendingFiles: File[]; + replyToId?: string; +} + +export function planDmMessageSend(input: DmMessageSendInput): DmMessageSendPlan { + const id = input.generateId(); + + return { + action: { + id, + content: input.content, + replyToId: input.replyToId + }, + attachmentBinding: input.pendingFiles.length > 0 + ? { messageId: id, files: input.pendingFiles } + : null + }; +} diff --git a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.html b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.html index f94e8f6..79f684d 100644 --- a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.html +++ b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.html @@ -171,6 +171,8 @@ (copyRequested)="copyImageToClipboard($event)" (imageOpened)="openLightbox($event)" (imageContextMenuRequested)="openImageContextMenu($event)" + (imageRetryRequested)="retryGalleryImage($event)" + (imageCancelRequested)="cancelGalleryImage($event)" /> } @else {
{{ 'dm.chat.selectPrompt' | translate }}
diff --git a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts index 7781f5d..92c4646 100644 --- a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts +++ b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts @@ -14,6 +14,7 @@ import { ActivatedRoute } from '@angular/router'; import { Store } from '@ngrx/store'; import { toSignal } from '@angular/core/rxjs-interop'; import { map } from 'rxjs'; +import { v4 as uuidv4 } from 'uuid'; import { AppI18nService, APP_TRANSLATE_IMPORTS } from '../../../../core/i18n'; import { ViewportService } from '../../../../core/platform'; import { @@ -29,6 +30,7 @@ import { } from '../../../attachment'; import { ThemeNodeDirective } from '../../../theme'; import { DirectMessageService } from '../../application/services/direct-message.service'; +import { planDmMessageSend } from '../../domain/rules/dm-message-send.rules'; import { isConversationBound } from './dm-chat.rules'; import { selectAllUsers, selectCurrentUser } from '../../../../store/users/users.selectors'; import { buildUserIdentityLookup, resolveUserByIdentity } from '../../../../store/users/user-identity-lookup.rules'; @@ -52,7 +54,11 @@ import { type ChatMessageEmbedRemoveEvent } from '../../../chat'; import { stepLightboxIndex } from '../../../chat/domain/rules/chat-message-lightbox.rules'; -import { ChatLightboxState, ChatMessageImageLightboxEvent } from '../../../chat/feature/chat-messages/models/chat-messages.model'; +import { + ChatLightboxState, + ChatMessageAttachmentEvent, + ChatMessageImageLightboxEvent +} from '../../../chat/feature/chat-messages/models/chat-messages.model'; import type { DirectMessageStatus, LinkMetadata, @@ -306,13 +312,32 @@ export class DmChatComponent { } const content = event.content.trim() || event.pendingFiles.map((file) => file.name).join('\n'); + const plan = planDmMessageSend({ + generateId: uuidv4, + content, + pendingFiles: event.pendingFiles, + replyToId: this.replyTo()?.id + }); - void this.directMessages.sendMessage(conversation.id, content, this.replyTo()?.id).then((message) => { + void this.directMessages.sendMessage( + conversation.id, + plan.action.content, + plan.action.replyToId, + plan.action.id + ).then(() => { this.replyTo.set(null); - if (event.pendingFiles.length > 0) { - this.attachments.rememberMessageRoom(message.id, `direct-message:${conversation.id}`); - this.attachments.publishAttachments(message.id, event.pendingFiles, this.currentUserId() || undefined); + if (plan.attachmentBinding) { + this.attachments.rememberMessageRoom( + plan.attachmentBinding.messageId, + `direct-message:${conversation.id}` + ); + + void this.attachments.publishAttachments( + plan.attachmentBinding.messageId, + plan.attachmentBinding.files, + this.currentUserId() || undefined + ); } }); } @@ -466,13 +491,11 @@ export class DmChatComponent { } openImageGallery(attachments: Attachment[]): void { - const availableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl); - - if (availableImages.length < 2) { + if (attachments.length < 2) { return; } - this.galleryAttachments.set(availableImages); + this.galleryAttachments.set(attachments); } closeImageGallery(): void { @@ -491,6 +514,20 @@ export class DmChatComponent { await this.attachmentDownload.downloadToUserLocation(attachment); } + retryGalleryImage(event: ChatMessageAttachmentEvent): void { + const { messageId, attachment } = event; + + if ((attachment.receivedBytes ?? 0) > 0 || this.attachments.hasPendingRequest(messageId, attachment.id)) { + this.attachments.cancelRequest(messageId, attachment); + } + + void this.attachments.requestImageFromAnyPeer(messageId, attachment); + } + + cancelGalleryImage(event: ChatMessageAttachmentEvent): void { + this.attachments.cancelRequest(event.messageId, event.attachment); + } + async copyImageToClipboard(attachment: Attachment): Promise { this.closeImageContextMenu(); diff --git a/toju-app/src/app/infrastructure/realtime/README.md b/toju-app/src/app/infrastructure/realtime/README.md index 77cc1f4..6570bb4 100644 --- a/toju-app/src/app/infrastructure/realtime/README.md +++ b/toju-app/src/app/infrastructure/realtime/README.md @@ -172,7 +172,7 @@ Browsers do not reliably fire WebSocket close events during page refresh or navi Multi-device sessions keep **multiple** open connections for the same `oderId` (different `clientInstanceId` values per tab/device). Server broadcasts exclude only the sending **connection id**, not the whole identity, so chat/typing/voice-state updates reach every logged-in device. Presence `user_joined` / `user_left` broadcasts still exclude the whole identity so other users never see duplicate join/leave events. -Account-owned state (saved servers, friends, profile avatar/card text, custom emoji library, server icons, message edits/reactions, **chat message creates/revisions**) syncs through **`account_sync`** WebSocket messages. The client wraps relayable P2P broadcast events and the server forwards them to other connections for the same identity via `notifyOtherConnectionsForOderId`. When a new device identifies, existing connections receive `account_sync_peer_online` and push a full snapshot including chunked `chat-sync-batch` history for every saved room. Each `chat-sync-batch` carries its messages' attachment metadata (`attachments` map, local paths stripped) so sibling devices learn about synced attachments without holding the bytes. +Account-owned state (saved servers, friends, profile avatar/card text, custom emoji library, server icons, message edits/reactions, **chat message creates/revisions**, **attachment `file-announce` metadata**) syncs through **`account_sync`** WebSocket messages. The client wraps relayable P2P broadcast events and the server forwards them to other connections for the same identity via `notifyOtherConnectionsForOderId`. Relayable types live in `account-sync/account-sync.rules.ts` (`RELAYABLE_ACCOUNT_SYNC_TYPES`); `file-announce` is included so sibling devices learn about new attachment metadata without requiring a cross-user mirror host first. When a new device identifies, existing connections receive `account_sync_peer_online` and push a full snapshot including chunked `chat-sync-batch` history for every saved room. Each `chat-sync-batch` carries its messages' attachment metadata (`attachments` map, local paths stripped) so sibling devices learn about synced attachments without holding the bytes. RTC offers/answers/ICE are routed to the connection marked `voiceActive` for the target user (fallback: any open connection). Voice ownership is tracked per connection from `voice_state` payloads that include `clientInstanceId`. diff --git a/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.spec.ts b/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.spec.ts index f9db461..48abcda 100644 --- a/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.spec.ts +++ b/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.spec.ts @@ -14,6 +14,18 @@ describe('account-sync.rules', () => { expect(isRelayableAccountSyncEvent({ type: 'chat-message', message: {} as never })).toBe(true); expect(isRelayableAccountSyncEvent({ type: 'message-revision', revision: {} as never })).toBe(true); expect(isRelayableAccountSyncEvent({ type: 'chat-sync-batch', roomId: 'r1', messages: [] })).toBe(true); + expect(isRelayableAccountSyncEvent({ + type: 'file-announce', + messageId: 'm1', + file: { + id: 'f1', + filename: 'photo.png', + size: 1, + mime: 'image/png', + isImage: true + } + })).toBe(true); + expect(isRelayableAccountSyncEvent({ type: 'voice-state', voiceState: {} as never })).toBe(false); }); diff --git a/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.ts b/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.ts index 163880b..0dd44d8 100644 --- a/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.ts +++ b/toju-app/src/app/infrastructure/realtime/account-sync/account-sync.rules.ts @@ -5,6 +5,7 @@ const RELAYABLE_ACCOUNT_SYNC_TYPES = new Set([ 'chat-message', 'message-revision', 'chat-sync-batch', + 'file-announce', 'user-avatar-summary', 'user-avatar-request', 'user-avatar-full', -- 2.54.0 From b13f71d2d3799362daebce9366bd59b235030298 Mon Sep 17 00:00:00 2001 From: Myx Date: Sun, 14 Jun 2026 13:19:12 +0200 Subject: [PATCH 02/11] 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 --- toju-app/src/app/domains/attachment/README.md | 2 +- .../attachment-transfer.service.spec.ts | 73 +++++++++++++++++-- .../services/attachment-transfer.service.ts | 5 +- .../logic/attachment-serve.rules.spec.ts | 15 ++++ .../domain/logic/attachment-serve.rules.ts | 4 + .../domain/logic/attachment.logic.spec.ts | 12 ++- .../domain/logic/attachment.logic.ts | 5 +- .../chat-message-image-gallery.rules.spec.ts | 16 +++- .../rules/chat-message-image-gallery.rules.ts | 17 ++++- .../chat-messages/chat-messages.component.ts | 41 +++++++++-- .../chat-message-overlays.component.ts | 9 ++- .../feature/dm-chat/dm-chat.component.ts | 41 +++++++++-- 12 files changed, 206 insertions(+), 34 deletions(-) create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.spec.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.ts diff --git a/toju-app/src/app/domains/attachment/README.md b/toju-app/src/app/domains/attachment/README.md index a1833ce..d2cc349 100644 --- a/toju-app/src/app/domains/attachment/README.md +++ b/toju-app/src/app/domains/attachment/README.md @@ -107,7 +107,7 @@ 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. - **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 **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. +- **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. 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. ### Failure handling diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts index 6764644..7b68050 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts @@ -52,6 +52,7 @@ describe('AttachmentTransferService', () => { getFileUrl: ReturnType; resolveExistingPath: ReturnType; resolveLegacyImagePath: ReturnType; + getFileSize: ReturnType; appendBase64: ReturnType; appendBytes: ReturnType; createWritableFile: ReturnType; @@ -94,6 +95,7 @@ describe('AttachmentTransferService', () => { getFileUrl: vi.fn(async () => null), resolveExistingPath: vi.fn(async () => null), resolveLegacyImagePath: vi.fn(async () => null), + getFileSize: vi.fn(async () => null), appendBase64: vi.fn(async () => true), appendBytes: vi.fn(async () => true), createWritableFile: vi.fn(async () => '/appdata/server/room/files/file-1'), @@ -391,11 +393,43 @@ describe('AttachmentTransferService', () => { 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); 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, [ 1, @@ -517,11 +551,11 @@ describe('AttachmentTransferService', () => { expect(runtimeStore.getChunkBuffer(`${MESSAGE_ID}:${FILE_ID}`)).toBeUndefined(); }); - it('does not hydrate image 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); const service = createService(); - const attachment = registerIncomingAttachment(3); + const attachment = registerIncomingAttachment(12 * 1024 * 1024); service.handleFileChunk(chunkPayload(0, 1, [ 1, @@ -537,12 +571,12 @@ describe('AttachmentTransferService', () => { expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled(); }); - it('hydrates playable media with a native file url after disk-streamed download completes', async () => { + 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(3); + const attachment = registerIncomingVideo(12 * 1024 * 1024); service.handleFileChunk(chunkPayload(0, 1, [ 1, @@ -558,7 +592,7 @@ describe('AttachmentTransferService', () => { expect(persistence.ensureInlineDisplayObjectUrl).not.toHaveBeenCalled(); }); - it('falls back to inline blob hydration for playable media when no native file url exists', async () => { + 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) => { @@ -568,7 +602,7 @@ describe('AttachmentTransferService', () => { }); const service = createService(); - const attachment = registerIncomingVideo(3); + const attachment = registerIncomingVideo(12 * 1024 * 1024); service.handleFileChunk(chunkPayload(0, 1, [ 1, @@ -632,8 +666,30 @@ describe('AttachmentTransferService', () => { 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 () => { attachmentStorage.resolveExistingPath.mockResolvedValue('/appdata/server/room/files/setup.exe'); + attachmentStorage.getFileSize.mockResolvedValue(12 * 1024 * 1024); const service = createService(); const attachment = registerIncomingGenericFile(12 * 1024 * 1024); @@ -737,6 +793,7 @@ describe('AttachmentTransferService', () => { 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.getFileSize.mockResolvedValue(12 * 1024 * 1024); const service = createService(); const attachment = registerIncomingGenericFile(12 * 1024 * 1024); diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts index 11080a9..8bf27f4 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts @@ -17,6 +17,7 @@ import { shouldPersistDownloadedAttachment, shouldStreamAttachmentReceiveToDisk } from '../../domain/logic/attachment.logic'; +import { shouldServeAttachmentFromDiskPath } from '../../domain/logic/attachment-serve.rules'; import type { Attachment, AttachmentMeta } from '../../domain/models/attachment.model'; import { ATTACHMENT_TRANSFER_EWMA_CURRENT_WEIGHT, @@ -564,7 +565,7 @@ export class AttachmentTransferService { ? await this.attachmentStorage.resolveExistingPath(attachment) : null; - if (diskPath) { + if (diskPath && shouldServeAttachmentFromDiskPath(await this.attachmentStorage.getFileSize(diskPath))) { await this.transport.streamFileFromDiskToPeer( fromPeerId, messageId, @@ -598,7 +599,7 @@ export class AttachmentTransferService { roomName ); - if (legacyDiskPath) { + if (legacyDiskPath && shouldServeAttachmentFromDiskPath(await this.attachmentStorage.getFileSize(legacyDiskPath))) { await this.transport.streamFileFromDiskToPeer( fromPeerId, messageId, diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.spec.ts new file mode 100644 index 0000000..ecc9d27 --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.spec.ts @@ -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); + }); +}); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.ts new file mode 100644 index 0000000..c4e0075 --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-serve.rules.ts @@ -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; +} diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts index 26a3116..402597e 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts @@ -60,7 +60,7 @@ describe('attachment logic', () => { }, 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 = { canStreamToDisk: true, canPersistSize: (bytes: number) => bytes <= 256 * 1024 * 1024 @@ -74,9 +74,15 @@ describe('attachment logic', () => { expect(shouldStreamAttachmentReceiveToDisk({ size: 3, - mime: 'application/zip', + mime: 'image/png', filePath: undefined - }, capabilities)).toBe(true); + }, capabilities)).toBe(false); + + expect(shouldStreamAttachmentReceiveToDisk({ + size: 10 * 1024 * 1024, + mime: 'image/jpeg', + filePath: undefined + }, capabilities)).toBe(false); expect(shouldStreamAttachmentReceiveToDisk({ size: 200 * 1024 * 1024, diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts index 548c9b5..ab08216 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts @@ -92,7 +92,10 @@ export function shouldStreamAttachmentReceiveToDisk( 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( diff --git a/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts index 9b3ec1f..7638477 100644 --- a/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts +++ b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.spec.ts @@ -4,7 +4,7 @@ import { it } from 'vitest'; -import { buildChatMessageGalleryTiles } from './chat-message-image-gallery.rules'; +import { buildChatMessageGalleryTiles, resolveChatMessageGalleryTileState } from './chat-message-image-gallery.rules'; describe('buildChatMessageGalleryTiles', () => { it('marks displayable, hydrating, downloading, and retry tiles from attachment state', () => { @@ -51,4 +51,18 @@ describe('buildChatMessageGalleryTiles', () => { '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'); + }); }); diff --git a/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts index 8a031cc..4158ed9 100644 --- a/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts +++ b/toju-app/src/app/domains/chat/domain/rules/chat-message-image-gallery.rules.ts @@ -11,17 +11,26 @@ export interface ChatMessageGalleryTile( - attachments: readonly T[] + attachments: readonly T[], + options: ChatMessageGalleryTileOptions | ((attachment: T) => ChatMessageGalleryTileOptions) = {} ): ChatMessageGalleryTile[] { return attachments.map((attachment) => ({ attachment, - state: resolveChatMessageGalleryTileState(attachment) + state: resolveChatMessageGalleryTileState( + attachment, + typeof options === 'function' ? options(attachment) : options + ) })); } export function resolveChatMessageGalleryTileState( - attachment: T + attachment: T, + options: ChatMessageGalleryTileOptions = {} ): ChatMessageGalleryTileState { if (isInlineDisplayableImage(attachment)) { return 'displayable'; @@ -31,7 +40,7 @@ export function resolveChatMessageGalleryTileState 0) { + if (options.pendingRequest || (attachment.receivedBytes ?? 0) > 0) { return 'downloading'; } diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts b/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts index 8b5bac2..099e5a6 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts +++ b/toju-app/src/app/domains/chat/feature/chat-messages/chat-messages.component.ts @@ -104,7 +104,26 @@ export class ChatMessagesComponent { readonly replyTo = signal(null); readonly showKlipyGifPicker = signal(false); readonly lightboxState = signal(null); - readonly galleryAttachments = signal(null); + readonly galleryMessageId = signal(null); + readonly galleryAttachmentOrder = signal([]); + 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(null); constructor() { @@ -345,13 +364,20 @@ export class ChatMessagesComponent { return; } + const messageId = attachments[0]?.messageId; + + if (!messageId) { + return; + } + const displayableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl); if (displayableImages.length > 0) { this.attachmentsSvc.pinDisplayBlobs(displayableImages); } - this.galleryAttachments.set(attachments); + this.galleryMessageId.set(messageId); + this.galleryAttachmentOrder.set(attachments.map((attachment) => attachment.id)); } closeImageGallery(): void { @@ -361,7 +387,8 @@ export class ChatMessagesComponent { this.attachmentsSvc.unpinDisplayBlobs(gallery); } - this.galleryAttachments.set(null); + this.galleryMessageId.set(null); + this.galleryAttachmentOrder.set([]); } openImageContextMenu(event: ChatMessageImageContextMenuEvent): void { @@ -378,12 +405,14 @@ export class ChatMessagesComponent { retryGalleryImage(event: ChatMessageAttachmentEvent): void { const { messageId, attachment } = event; + const liveAttachment = this.attachmentsSvc.getForMessage(messageId).find((entry) => entry.id === attachment.id) + ?? attachment; - if ((attachment.receivedBytes ?? 0) > 0 || this.attachmentsSvc.hasPendingRequest(messageId, attachment.id)) { - this.attachmentsSvc.cancelRequest(messageId, attachment); + if ((liveAttachment.receivedBytes ?? 0) > 0 || this.attachmentsSvc.hasPendingRequest(messageId, liveAttachment.id)) { + this.attachmentsSvc.cancelRequest(messageId, liveAttachment); } - void this.attachmentsSvc.requestImageFromAnyPeer(messageId, attachment); + void this.attachmentsSvc.requestImageFromAnyPeer(messageId, liveAttachment); } cancelGalleryImage(event: ChatMessageAttachmentEvent): void { diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts index ec51494..06707d4 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts +++ b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts @@ -18,7 +18,7 @@ import { lucideDownload, lucideX } from '@ng-icons/lucide'; -import { Attachment } from '../../../../../attachment'; +import { Attachment, AttachmentFacade } from '../../../../../attachment'; 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'; @@ -80,7 +80,11 @@ export class ChatMessageOverlaysComponent implements OnDestroy { return []; } - return buildChatMessageGalleryTiles(attachments); + const messageId = attachments[0]?.messageId; + + return buildChatMessageGalleryTiles(attachments, (attachment) => ({ + pendingRequest: !!messageId && this.attachmentsSvc.hasPendingRequest(messageId, attachment.id) + })); }); readonly lightboxAttachment = computed(() => { @@ -124,6 +128,7 @@ export class ChatMessageOverlaysComponent implements OnDestroy { }); private readonly appI18n = inject(AppI18nService); + private readonly attachmentsSvc = inject(AttachmentFacade); private readonly LIGHTBOX_CONTROLS_IDLE_MS = 2200; private lightboxControlsHideTimer: ReturnType | null = null; diff --git a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts index 92c4646..ef5867d 100644 --- a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts +++ b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts @@ -119,7 +119,26 @@ export class DmChatComponent { readonly linkMetadataByMessageId = signal>({}); readonly replyTo = signal(null); readonly lightboxState = signal(null); - readonly galleryAttachments = signal(null); + readonly galleryMessageId = signal(null); + readonly galleryAttachmentOrder = signal([]); + readonly galleryAttachments = computed(() => { + const messageId = this.galleryMessageId(); + const attachmentIds = this.galleryAttachmentOrder(); + + void this.attachments.updated; + + if (!messageId || attachmentIds.length === 0) { + return null; + } + + const attachmentsById = new Map( + this.attachments.getForMessage(messageId).map((attachment) => [attachment.id, attachment]) + ); + + return attachmentIds + .map((attachmentId) => attachmentsById.get(attachmentId)) + .filter((attachment): attachment is Attachment => !!attachment); + }); readonly imageContextMenu = signal(null); readonly routeConversationId = toSignal(this.route.paramMap.pipe(map((params) => params.get('conversationId'))), { initialValue: this.route.snapshot.paramMap.get('conversationId') @@ -495,11 +514,19 @@ export class DmChatComponent { return; } - this.galleryAttachments.set(attachments); + const messageId = attachments[0]?.messageId; + + if (!messageId) { + return; + } + + this.galleryMessageId.set(messageId); + this.galleryAttachmentOrder.set(attachments.map((attachment) => attachment.id)); } closeImageGallery(): void { - this.galleryAttachments.set(null); + this.galleryMessageId.set(null); + this.galleryAttachmentOrder.set([]); } openImageContextMenu(event: ChatMessageImageContextMenuEvent): void { @@ -516,12 +543,14 @@ export class DmChatComponent { retryGalleryImage(event: ChatMessageAttachmentEvent): void { const { messageId, attachment } = event; + const liveAttachment = this.attachments.getForMessage(messageId).find((entry) => entry.id === attachment.id) + ?? attachment; - if ((attachment.receivedBytes ?? 0) > 0 || this.attachments.hasPendingRequest(messageId, attachment.id)) { - this.attachments.cancelRequest(messageId, attachment); + if ((liveAttachment.receivedBytes ?? 0) > 0 || this.attachments.hasPendingRequest(messageId, liveAttachment.id)) { + this.attachments.cancelRequest(messageId, liveAttachment); } - void this.attachments.requestImageFromAnyPeer(messageId, attachment); + void this.attachments.requestImageFromAnyPeer(messageId, liveAttachment); } cancelGalleryImage(event: ChatMessageAttachmentEvent): void { -- 2.54.0 From 0078c320a5da2adff77936c71c2a3c38832871b5 Mon Sep 17 00:00:00 2001 From: Myx Date: Sun, 14 Jun 2026 13:30:13 +0200 Subject: [PATCH 03/11] 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 --- toju-app/src/app/domains/attachment/README.md | 4 +- .../services/attachment-manager.service.ts | 9 +- .../attachment-transfer.service.spec.ts | 111 ++++++++++++++++++ .../services/attachment-transfer.service.ts | 58 +++++++-- .../attachment-autodownload.rules.spec.ts | 20 ++++ .../logic/attachment-autodownload.rules.ts | 8 ++ .../logic/attachment-mime.rules.spec.ts | 41 +++++++ .../domain/logic/attachment-mime.rules.ts | 57 +++++++++ .../logic/attachment-normalize.rules.ts | 17 +++ .../domain/logic/attachment.logic.spec.ts | 28 +++++ .../domain/logic/attachment.logic.ts | 10 ++ .../chat-message-overlays.component.html | 9 +- .../chat-message-overlays.component.ts | 19 +++ .../feature/dm-chat/dm-chat.component.ts | 12 ++ 14 files changed, 388 insertions(+), 15 deletions(-) create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.spec.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-normalize.rules.ts diff --git a/toju-app/src/app/domains/attachment/README.md b/toju-app/src/app/domains/attachment/README.md index d2cc349..949a8ae 100644 --- a/toju-app/src/app/domains/attachment/README.md +++ b/toju-app/src/app/domains/attachment/README.md @@ -144,7 +144,9 @@ 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`. -Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:`, 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. +Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:`, 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 with no active pending request are reset automatically before the next auto-download pass. + +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. diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts index ee9c441..278a4dc 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts @@ -17,6 +17,7 @@ import { shouldAutoRequestWhenWatched } 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 { FileAnnouncePayload, @@ -379,8 +380,14 @@ export class AttachmentManagerService { if (attachment.available) continue; - if ((attachment.receivedBytes ?? 0) > 0) + if (shouldResetStalledAttachmentDownload( + attachment, + this.transfer.hasPendingRequest(messageId, attachment.id) + )) { + this.transfer.cancelRequest(messageId, attachment); + } else if ((attachment.receivedBytes ?? 0) > 0) { continue; + } if (this.transfer.hasPendingRequest(messageId, attachment.id)) continue; diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts index 7b68050..99ba722 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts @@ -866,4 +866,115 @@ describe('AttachmentTransferService', () => { 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' })); + }); }); diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts index 8bf27f4..eb36e29 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts @@ -13,10 +13,13 @@ import { isSharingFromThisDevice, canHostAttachment } from '../../domain/logic/a import { selectFileRequestPeer } from '../../domain/logic/attachment-request.rules'; import { canReceiveAttachment, + needsAttachmentDisplayHydration, shouldCopyLargeUploaderFileToAppData, shouldPersistDownloadedAttachment, shouldStreamAttachmentReceiveToDisk } 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 { @@ -141,9 +144,11 @@ export class AttachmentTransferService { const alreadyKnown = existing.find((entry) => entry.id === meta.id); if (!alreadyKnown) { - const attachment: Attachment = { ...meta, + const attachment: Attachment = { + ...normalizeAttachmentMeta(meta), available: false, - receivedBytes: 0 }; + receivedBytes: 0 + }; existing.push(attachment); newAttachments.push(attachment); @@ -171,6 +176,16 @@ export class AttachmentTransferService { // request makes the sender stream the file twice and corrupts byte accounting. this.runtimeStore.setPendingRequestPeers(requestKey, new Set()); + if (needsAttachmentDisplayHydration(attachment)) { + const hydratedLocally = await this.persistence.tryRestoreAttachmentFromLocal(attachment); + + if (hydratedLocally) { + this.runtimeStore.deletePendingRequest(requestKey); + this.runtimeStore.touch(); + return; + } + } + if (!attachment.available) { const restoredLocally = await this.persistence.tryRestoreAttachmentFromLocal(attachment); @@ -230,6 +245,10 @@ export class AttachmentTransferService { } requestImageFromAnyPeer(messageId: string, attachment: Attachment): Promise { + if (needsAttachmentDisplayHydration(attachment)) { + return this.requestFromAnyPeer(messageId, attachment); + } + if ((attachment.receivedBytes ?? 0) > 0 || this.hasPendingRequest(messageId, attachment.id)) { this.cancelRequest(messageId, attachment); } @@ -259,7 +278,7 @@ export class AttachmentTransferService { messageId, filename: file.name, size: file.size, - mime: file.type || DEFAULT_ATTACHMENT_MIME_TYPE, + mime: resolveAttachmentMime(file.name, file.type || DEFAULT_ATTACHMENT_MIME_TYPE), isImage: resolvePublishAttachmentIsImage(file), uploaderPeerId, filePath: (file as LocalFileWithPath).path, @@ -327,29 +346,40 @@ export class AttachmentTransferService { const alreadyKnown = list.find((entry) => entry.id === file.id); 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; } - const attachment: Attachment = { + const normalizedMeta = normalizeAttachmentMeta({ id: file.id, messageId, filename: file.filename, size: file.size, mime: file.mime, - isImage: isImageAttachment({ - filename: file.filename, - isImage: !!file.isImage, - mime: file.mime - }), - uploaderPeerId: file.uploaderPeerId, + isImage: !!file.isImage, + uploaderPeerId: file.uploaderPeerId + }); + const runtimeAttachment: Attachment = { + ...normalizedMeta, available: false, receivedBytes: 0 }; - list.push(attachment); + list.push(runtimeAttachment); this.runtimeStore.setAttachmentsForMessage(messageId, list); this.runtimeStore.touch(); - void this.persistence.persistAttachmentMeta(attachment); + void this.persistence.persistAttachmentMeta(runtimeAttachment); return true; } @@ -793,6 +823,10 @@ export class AttachmentTransferService { this.runtimeStore.touch(); void this.persistence.persistAttachmentMeta(attachment); void this.announceLocalHost(attachment); + + if (this.isPlayableMedia(attachment)) { + await this.hydratePlayableMediaAfterDiskReceive(attachment); + } } /** diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts new file mode 100644 index 0000000..1d071eb --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts @@ -0,0 +1,20 @@ +import { shouldResetStalledAttachmentDownload } from './attachment-autodownload.rules'; + +describe('attachment autodownload rules', () => { + it('resets stalled partial downloads that are no longer actively transferring', () => { + expect(shouldResetStalledAttachmentDownload({ + available: false, + receivedBytes: 128 + }, false)).toBe(true); + + expect(shouldResetStalledAttachmentDownload({ + available: false, + receivedBytes: 128 + }, true)).toBe(false); + + expect(shouldResetStalledAttachmentDownload({ + available: true, + receivedBytes: 128 + }, false)).toBe(false); + }); +}); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts new file mode 100644 index 0000000..ca8784a --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts @@ -0,0 +1,8 @@ +export function shouldResetStalledAttachmentDownload( + attachment: Pick<{ available?: boolean; receivedBytes?: number }, 'available' | 'receivedBytes'>, + hasPendingRequest: boolean +): boolean { + return !attachment.available && + (attachment.receivedBytes ?? 0) > 0 && + !hasPendingRequest; +} diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.spec.ts new file mode 100644 index 0000000..e526a14 --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.spec.ts @@ -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 + })); + }); +}); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.ts new file mode 100644 index 0000000..bd68a93 --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-mime.rules.ts @@ -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 = { + '.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); +} diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-normalize.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-normalize.rules.ts new file mode 100644 index 0000000..631b697 --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-normalize.rules.ts @@ -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(meta: T): T { + const mime = resolveAttachmentMime(meta.filename, meta.mime); + + return { + ...meta, + mime, + isImage: isImageAttachment({ + filename: meta.filename, + isImage: meta.isImage, + mime + }) + }; +} diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts index 402597e..5aadd4f 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.spec.ts @@ -3,6 +3,7 @@ import { isAttachmentPendingMediaHydration, isDirectMessageAttachmentRoomId, isPlayableAttachmentMedia, + needsAttachmentDisplayHydration, shouldCopyUploaderMediaToAppData, shouldCopyLargeUploaderFileToAppData, shouldStreamAttachmentReceiveToDisk, @@ -91,6 +92,33 @@ describe('attachment logic', () => { }, 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); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts index ab08216..c5def78 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment.logic.ts @@ -1,3 +1,4 @@ +import { isAttachmentPendingInlineHydration } from './attachment-image.rules'; import { MAX_AUTO_SAVE_SIZE_BYTES } from '../constants/attachment.constants'; import type { Attachment } from '../models/attachment.model'; @@ -32,6 +33,15 @@ export function isAttachmentPendingMediaHydration( 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 { return attachment.isImage || (isAttachmentMedia(attachment) && attachment.size <= MAX_AUTO_SAVE_SIZE_BYTES); diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.html b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.html index 4c0c51e..9a658a3 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.html +++ b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.html @@ -51,8 +51,15 @@ } @case ('hydrating') { -
+
+
} @case ('downloading') { diff --git a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts index 06707d4..42b686b 100644 --- a/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts +++ b/toju-app/src/app/domains/chat/feature/chat-messages/components/message-overlays/chat-message-overlays.component.ts @@ -19,6 +19,7 @@ import { lucideX } from '@ng-icons/lucide'; import { Attachment, AttachmentFacade } from '../../../../../attachment'; +import { isAttachmentPendingInlineHydration } from '../../../../../attachment/domain/logic/attachment-image.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'; @@ -127,6 +128,24 @@ export class ChatMessageOverlaysComponent implements OnDestroy { 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 attachmentsSvc = inject(AttachmentFacade); private readonly LIGHTBOX_CONTROLS_IDLE_MS = 2200; diff --git a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts index ef5867d..796d873 100644 --- a/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts +++ b/toju-app/src/app/domains/direct-message/feature/dm-chat/dm-chat.component.ts @@ -520,11 +520,23 @@ export class DmChatComponent { return; } + const displayableImages = attachments.filter((attachment) => attachment.available && attachment.objectUrl); + + if (displayableImages.length > 0) { + this.attachments.pinDisplayBlobs(displayableImages); + } + this.galleryMessageId.set(messageId); this.galleryAttachmentOrder.set(attachments.map((attachment) => attachment.id)); } closeImageGallery(): void { + const gallery = this.galleryAttachments(); + + if (gallery) { + this.attachments.unpinDisplayBlobs(gallery); + } + this.galleryMessageId.set(null); this.galleryAttachmentOrder.set([]); } -- 2.54.0 From 497033aff0a188d04092d19d7aa68f128bbbeed0 Mon Sep 17 00:00:00 2001 From: Myx Date: Sun, 12 Jul 2026 21:26:59 +0200 Subject: [PATCH 04/11] 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 --- agents-docs/LESSONS.md | 7 +++ toju-app/src/app/domains/attachment/README.md | 4 +- .../services/attachment-manager.service.ts | 3 +- .../attachment-autodownload.rules.spec.ts | 46 ++++++++++++++++--- .../logic/attachment-autodownload.rules.ts | 35 ++++++++++++-- .../messages-incoming.handlers.spec.ts | 35 +++++++++++++- .../messages/messages-incoming.handlers.ts | 4 ++ 7 files changed, 118 insertions(+), 16 deletions(-) diff --git a/agents-docs/LESSONS.md b/agents-docs/LESSONS.md index 940b36e..55238b7 100644 --- a/agents-docs/LESSONS.md +++ b/agents-docs/LESSONS.md @@ -25,6 +25,13 @@ Durable rules for AI agents working on this project. Read this file at session s ## Lessons +### 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] - **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. diff --git a/toju-app/src/app/domains/attachment/README.md b/toju-app/src/app/domains/attachment/README.md index 949a8ae..b1ca74b 100644 --- a/toju-app/src/app/domains/attachment/README.md +++ b/toju-app/src/app/domains/attachment/README.md @@ -144,7 +144,9 @@ 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`. -Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:`, 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 with no active pending request are reset automatically before the next auto-download pass. +Direct-message routes (`/dm/:conversationId` and `/pm/:conversationId`) are treated as watched attachment containers named `direct-message:`, 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. diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts index 278a4dc..8bf4c9d 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-manager.service.ts @@ -382,7 +382,8 @@ export class AttachmentManagerService { if (shouldResetStalledAttachmentDownload( attachment, - this.transfer.hasPendingRequest(messageId, attachment.id) + this.transfer.hasPendingRequest(messageId, attachment.id), + Date.now() )) { this.transfer.cancelRequest(messageId, attachment); } else if ((attachment.receivedBytes ?? 0) > 0) { diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts index 1d071eb..975c3ae 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.spec.ts @@ -1,20 +1,52 @@ -import { shouldResetStalledAttachmentDownload } from './attachment-autodownload.rules'; +import { ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS, shouldResetStalledAttachmentDownload } from './attachment-autodownload.rules'; + +const NOW_MS = 1_750_000_000_000; describe('attachment autodownload rules', () => { - it('resets stalled partial downloads that are no longer actively transferring', () => { + 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 - }, false)).toBe(true); + 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 - }, true)).toBe(false); + }, 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 - }, false)).toBe(false); + 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); }); }); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts index ca8784a..7bbd2f3 100644 --- a/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-autodownload.rules.ts @@ -1,8 +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; receivedBytes?: number }, 'available' | 'receivedBytes'>, - hasPendingRequest: boolean + attachment: Pick< + { available?: boolean; lastUpdateMs?: number; receivedBytes?: number }, + 'available' | 'lastUpdateMs' | 'receivedBytes' + >, + hasPendingRequest: boolean, + nowMs: number ): boolean { - return !attachment.available && - (attachment.receivedBytes ?? 0) > 0 && - !hasPendingRequest; + if (attachment.available || hasPendingRequest || (attachment.receivedBytes ?? 0) === 0) { + return false; + } + + if (!attachment.lastUpdateMs) { + return true; + } + + return nowMs - attachment.lastUpdateMs > ATTACHMENT_STALLED_DOWNLOAD_THRESHOLD_MS; } diff --git a/toju-app/src/app/store/messages/messages-incoming.handlers.spec.ts b/toju-app/src/app/store/messages/messages-incoming.handlers.spec.ts index e835cd2..583e1fd 100644 --- a/toju-app/src/app/store/messages/messages-incoming.handlers.spec.ts +++ b/toju-app/src/app/store/messages/messages-incoming.handlers.spec.ts @@ -39,13 +39,44 @@ function createContext(overrides: Record = {}) { } as const; } +describe('dispatchIncomingMessage attachment auto-download race', () => { + it('queues attachment auto-downloads when the chat message arrives after its file-announce', async () => { + // file-announce can reach a receiver before the chat-message itself; the + // announce-time auto-download then fails to resolve the room and gives up, + // so the arriving message must re-queue the download. + const saveMessage = vi.fn(async () => undefined); + const rememberMessageRoom = vi.fn(); + const queueAutoDownloadsForMessage = vi.fn(); + const context = createContext({ + db: { saveMessage }, + attachments: { rememberMessageRoom, queueAutoDownloadsForMessage }, + currentUser: { id: 'user-2', oderId: 'user-2' }, + currentRoom: { id: 'room-a' }, + savedRooms: [{ id: 'room-a' }] + }); + const action = await firstValueFrom( + dispatchIncomingMessage( + { + type: 'chat-message', + message: createMessage({ id: 'message-with-attachment', roomId: 'room-a' }) + } as never, + context as never + ).pipe(defaultIfEmpty(null)) + ); + + expect(action).not.toBeNull(); + expect(rememberMessageRoom).toHaveBeenCalledWith('message-with-attachment', 'room-a'); + expect(queueAutoDownloadsForMessage).toHaveBeenCalledWith('message-with-attachment'); + }); +}); + describe('dispatchIncomingMessage multi-device sync', () => { it('accepts own messages that originated on another client instance', async () => { const saveMessage = vi.fn(async () => undefined); const rememberMessageRoom = vi.fn(); const context = createContext({ db: { saveMessage }, - attachments: { rememberMessageRoom }, + attachments: { rememberMessageRoom, queueAutoDownloadsForMessage: vi.fn() }, currentUser: { id: 'user-1', oderId: 'user-1' }, currentRoom: { id: 'room-a' }, savedRooms: [{ id: 'room-a' }], @@ -74,7 +105,7 @@ describe('dispatchIncomingMessage multi-device sync', () => { const rememberMessageRoom = vi.fn(); const context = createContext({ db: { saveMessage }, - attachments: { rememberMessageRoom }, + attachments: { rememberMessageRoom, queueAutoDownloadsForMessage: vi.fn() }, currentUser: { id: 'viewer-home', oderId: 'viewer-home' }, currentRoom: { id: 'room-a' }, savedRooms: [{ id: 'room-a' }] diff --git a/toju-app/src/app/store/messages/messages-incoming.handlers.ts b/toju-app/src/app/store/messages/messages-incoming.handlers.ts index 9845b56..c7f7651 100644 --- a/toju-app/src/app/store/messages/messages-incoming.handlers.ts +++ b/toju-app/src/app/store/messages/messages-incoming.handlers.ts @@ -382,6 +382,10 @@ function handleChatMessage( return EMPTY; attachments.rememberMessageRoom(normalizedMessage.id, normalizedMessage.roomId); + // A file-announce for this message may have arrived before the message itself; + // that announce-time auto-download could not resolve the room and gave up, so + // re-queue now that the message-to-room binding is known. + attachments.queueAutoDownloadsForMessage(normalizedMessage.id); trackBackgroundOperation( db.saveMessage(normalizedMessage), -- 2.54.0 From 590e487250c2ce051e7196196e451fa9e381c34c Mon Sep 17 00:00:00 2001 From: Myx Date: Mon, 13 Jul 2026 18:48:30 +0200 Subject: [PATCH 05/11] 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 --- agents-docs/LESSONS.md | 7 ++ .../chat/large-generic-file-transfer.spec.ts | 114 ++++++++++++++++++ toju-app/src/app/domains/attachment/README.md | 6 +- .../attachment-transfer.service.spec.ts | 30 +++++ .../services/attachment-transfer.service.ts | 11 +- 5 files changed, 161 insertions(+), 7 deletions(-) create mode 100644 e2e/tests/chat/large-generic-file-transfer.spec.ts diff --git a/agents-docs/LESSONS.md b/agents-docs/LESSONS.md index 55238b7..d0e62fb 100644 --- a/agents-docs/LESSONS.md +++ b/agents-docs/LESSONS.md @@ -25,6 +25,13 @@ Durable rules for AI agents working on this project. Read this file at session s ## Lessons +### 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 10–50 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. diff --git a/e2e/tests/chat/large-generic-file-transfer.spec.ts b/e2e/tests/chat/large-generic-file-transfer.spec.ts new file mode 100644 index 0000000..ca17e9a --- /dev/null +++ b/e2e/tests/chat/large-generic-file-transfer.spec.ts @@ -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 { + 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)}`; +} diff --git a/toju-app/src/app/domains/attachment/README.md b/toju-app/src/app/domains/attachment/README.md index b1ca74b..873f389 100644 --- a/toju-app/src/app/domains/attachment/README.md +++ b/toju-app/src/app/domains/attachment/README.md @@ -107,7 +107,7 @@ 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. - **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. 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. 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. +- **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. ### Failure handling @@ -214,3 +214,7 @@ Image inline previews on Electron/desktop use renderer `blob:` URLs rebuilt from - **Serving** is unaffected: peers still download from `savedPath` / `filePath`; blob URLs are display-only. 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) diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts index 99ba722..bbc453f 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.spec.ts @@ -629,6 +629,36 @@ describe('AttachmentTransferService', () => { 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 () => { attachmentStorage.canStreamToDisk.mockReturnValue(false); attachmentStorage.canPersistSize.mockImplementation((bytes: number) => bytes <= 50 * 1024 * 1024); diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts index eb36e29..fd95c44 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-transfer.service.ts @@ -425,12 +425,11 @@ export class AttachmentTransferService { return; } - if (attachment.size > MAX_AUTO_SAVE_SIZE_BYTES) { - attachment.requestError = this.appI18n.instant(ATTACHMENT_FILE_TOO_LARGE_KEY); - this.runtimeStore.touch(); - return; - } - + // Reaching here means canReceiveAttachment passed and disk streaming is not + // used, so the in-memory path is the agreed receive strategy - including + // above-auto-save-cap files on stores that cannot stream but can persist + // them (browser). A stricter size guard here would silently drop chunks the + // request gate already admitted. const decodedBytes = this.transport.decodeBase64(data); const assemblyKey = `${messageId}:${fileId}`; const requestKey = this.buildRequestKey(messageId, fileId); -- 2.54.0 From 3e090933fdd1301e33a7a1c8ba229ddbbd8b21e4 Mon Sep 17 00:00:00 2001 From: Myx Date: Mon, 13 Jul 2026 20:18:37 +0200 Subject: [PATCH 06/11] 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 --- agents-docs/LESSONS.md | 7 + e2e/tests/voice/dm-header-call-ring.spec.ts | 237 ++++++++++++++++++ .../src/app/domains/direct-call/README.md | 2 +- .../services/direct-call.service.spec.ts | 122 +++++++++ .../services/direct-call.service.ts | 51 ++-- ...ct-call-participant-identity.rules.spec.ts | 59 ++++- .../direct-call-participant-identity.rules.ts | 51 +++- 7 files changed, 510 insertions(+), 19 deletions(-) create mode 100644 e2e/tests/voice/dm-header-call-ring.spec.ts diff --git a/agents-docs/LESSONS.md b/agents-docs/LESSONS.md index d0e62fb..9dfe6ae 100644 --- a/agents-docs/LESSONS.md +++ b/agents-docs/LESSONS.md @@ -25,6 +25,13 @@ Durable rules for AI agents working on this project. Read this file at session s ## Lessons +### 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 10–50 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. diff --git a/e2e/tests/voice/dm-header-call-ring.spec.ts b/e2e/tests/voice/dm-header-call-ring.spec.ts new file mode 100644 index 0000000..6314429 --- /dev/null +++ b/e2e/tests/voice/dm-header-call-ring.spec.ts @@ -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 { + 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 { + 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 { + 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)}`; +} diff --git a/toju-app/src/app/domains/direct-call/README.md b/toju-app/src/app/domains/direct-call/README.md index 90df848..c86d828 100644 --- a/toju-app/src/app/domains/direct-call/README.md +++ b/toju-app/src/app/domains/direct-call/README.md @@ -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. 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. diff --git a/toju-app/src/app/domains/direct-call/application/services/direct-call.service.spec.ts b/toju-app/src/app/domains/direct-call/application/services/direct-call.service.spec.ts index ea9ca6b..e3f4408 100644 --- a/toju-app/src/app/domains/direct-call/application/services/direct-call.service.spec.ts +++ b/toju-app/src/app/domains/direct-call/application/services/direct-call.service.spec.ts @@ -17,6 +17,7 @@ import { import { initializeAppI18nForTests, provideAppI18nForTests } from '../../../../core/i18n/app-i18n.testing'; import { ViewportService } from '../../../../core/platform'; import { RealtimeSessionFacade } from '../../../../core/realtime'; +import { SignalServerCredentialStoreService } from '../../../authentication/application/services/signal-server-credential-store.service'; import { VoiceActivityService, VoiceConnectionFacade, @@ -110,6 +111,111 @@ describe('DirectCallService', () => { 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 () => { const aliceForeign = createUser('alice-foreign', 'Alice'); const bobForeign = createUser('bob-foreign', 'Bob'); @@ -429,6 +535,7 @@ describe('DirectCallService', () => { interface ServiceContextOptions { allUsers: User[]; currentUser: User | null; + selfActorIds?: string[]; } interface ServiceContext { @@ -536,6 +643,17 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext { const voiceSession = { endSession: vi.fn() }; + 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({ providers: [ { @@ -626,6 +744,10 @@ function createServiceContext(options: ServiceContextOptions): ServiceContext { requestVoiceClientTakeover: vi.fn() } }, + { + provide: SignalServerCredentialStoreService, + useValue: credentialStore + }, ...provideAppI18nForTests() ] }); diff --git a/toju-app/src/app/domains/direct-call/application/services/direct-call.service.ts b/toju-app/src/app/domains/direct-call/application/services/direct-call.service.ts index 7c853d0..9c7b3dc 100644 --- a/toju-app/src/app/domains/direct-call/application/services/direct-call.service.ts +++ b/toju-app/src/app/domains/direct-call/application/services/direct-call.service.ts @@ -23,6 +23,7 @@ import { } from '../../../voice-connection'; import { VoiceSessionFacade, isVoiceOnAnotherClient } from '../../../voice-session'; import { RealtimeSessionFacade } from '../../../../core/realtime'; +import { SignalServerCredentialStoreService } from '../../../authentication/application/services/signal-server-credential-store.service'; import { DirectMessageService, PeerDeliveryService } from '../../../direct-message'; import type { DirectMessageConversation } from '../../../direct-message'; import { selectAllUsers, selectCurrentUser } from '../../../../store/users/users.selectors'; @@ -34,9 +35,12 @@ import { } from '../../../../shared-kernel'; import { DirectCallSession, participantToUser } from '../../domain/models/direct-call.model'; import { + collectDirectCallUserIdentityKeys, + directCallPayloadIncludesAnyId, findDirectCallParticipantEntry, findDirectCallParticipantEntryForUser, - isDirectCallParticipantJoined + isDirectCallParticipantJoined, + normalizeDirectCallPayloadSelfAliases } from '../../domain/logic/direct-call-participant-identity.rules'; import { toDirectMessageParticipant } from '../../../direct-message'; @@ -56,6 +60,7 @@ export class DirectCallService { private readonly mobileNotifications = inject(MobileNotificationsService); private readonly mobileCallSession = inject(MobileCallSessionService); private readonly mobileMedia = inject(MobileMediaService); + private readonly credentialStore = inject(SignalServerCredentialStoreService); private readonly i18n = inject(AppI18nService); private readonly currentUser = this.store.selectSignal(selectCurrentUser); private readonly users = this.store.selectSignal(selectAllUsers); @@ -234,8 +239,8 @@ export class DirectCallService { return await this.startGroupCall(conversation); } - const meId = this.currentUserId(); - const peerId = conversation.participants.find((participantId) => participantId !== meId); + const selfIds = this.selfIdentityIds(); + const peerId = conversation.participants.find((participantId) => !selfIds.has(participantId)); if (!peerId) { throw new Error(this.i18n.instant('call.errors.noRecipient')); @@ -433,9 +438,9 @@ export class DirectCallService { } 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 { @@ -464,29 +469,35 @@ export class DirectCallService { } } - private async handleIncomingCallEvent(payload: DirectCallEventPayload): Promise { + private async handleIncomingCallEvent(rawPayload: DirectCallEventPayload): Promise { const meId = this.currentUserId(); if (!meId) { - if (payload.action === 'ring') { - this.pendingIncomingCallPayloads.push(payload); + if (rawPayload.action === 'ring') { + this.pendingIncomingCallPayloads.push(rawPayload); } 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; } - if (!this.callPayloadIncludesParticipant(payload, meId)) { + if (!directCallPayloadIncludesAnyId(rawPayload, selfIds)) { return; } - if (payload.action === 'ring' && this.declinedCallIds.has(payload.callId)) { + if (rawPayload.action === 'ring' && this.declinedCallIds.has(rawPayload.callId)) { return; } + const payload = normalizeDirectCallPayloadSelfAliases(rawPayload, meId, selfIds); const participants = this.callParticipantsFromPayload(payload); const existing = this.sessionById(payload.callId); const incomingSession = this.createSession({ @@ -826,11 +837,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 { const names = Object.values(session.participants) .map((participant) => participant.profile.displayName || participant.profile.username || participant.userId); @@ -1056,6 +1062,19 @@ export class DirectCallService { return user ? this.userKey(user) : null; } + /** Every id that can address the local user, including provisioned signal-server actor ids. */ + private selfIdentityIds(): ReadonlySet { + 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 { const user = this.currentUser(); diff --git a/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.spec.ts b/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.spec.ts index 0589d6b..06d9222 100644 --- a/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.spec.ts +++ b/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.spec.ts @@ -1,8 +1,11 @@ +import type { DirectCallEventPayload } from '../../../../shared-kernel'; import type { DirectCallSession } from '../models/direct-call.model'; import { + directCallPayloadIncludesAnyId, findDirectCallParticipantEntry, findDirectCallParticipantEntryForUser, - isDirectCallParticipantJoined + isDirectCallParticipantJoined, + normalizeDirectCallPayloadSelfAliases } from './direct-call-participant-identity.rules'; function createSession(participants: DirectCallSession['participants']): DirectCallSession { @@ -77,4 +80,58 @@ describe('direct-call-participant-identity.rules', () => { oderId: 'bob-foreign' }, ['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' + } + ] + }; +} diff --git a/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.ts b/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.ts index f8a05b9..0d356cc 100644 --- a/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.ts +++ b/toju-app/src/app/domains/direct-call/domain/logic/direct-call-participant-identity.rules.ts @@ -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'; type UserIdentityFields = Pick; @@ -86,3 +86,52 @@ export function isDirectCallParticipantJoined( ): boolean { 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, + ids: ReadonlySet +): 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 +): DirectCallEventPayload { + const participantIds = [ + ...new Set(payload.participantIds.map((participantId) => + (selfIds.has(participantId) ? canonicalId : participantId))) + ]; + const seenParticipantIds = new Set(); + 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 + }; +} -- 2.54.0 From edc4d935d86f87035aa76c78a1afa8936e289b2c Mon Sep 17 00:00:00 2001 From: Myx Date: Tue, 14 Jul 2026 00:41:05 +0200 Subject: [PATCH 07/11] chore: Fix app --- agents-docs/FEATURES.md | 17 +- agents-docs/LESSONS.md | 7 + agents-docs/features/app-i18n.md | 18 ++ agents-docs/features/attachments.md | 118 ++++++++++ agents-docs/features/authentication.md | 107 ++++++++- agents-docs/features/custom-emoji.md | 141 ++++++++---- agents-docs/features/desktop-local-api.md | 53 +++++ agents-docs/features/direct-messaging.md | 29 +++ agents-docs/features/game-activity.md | 54 +++++ agents-docs/features/invites-join-requests.md | 65 ++++++ agents-docs/features/klipy-gifs.md | 44 ++++ .../features/link-preview-media-proxy.md | 46 ++++ agents-docs/features/message-integrity.md | 30 ++- agents-docs/features/messaging.md | 209 ++++++++++++++++++ agents-docs/features/mobile-capacitor.md | 41 +++- agents-docs/features/plugins.md | 70 ++++++ agents-docs/features/push-notifications.md | 53 +++++ agents-docs/features/server-directory.md | 96 ++++++++ agents-docs/features/server-discovery.md | 15 +- agents-docs/features/signal-server-tag.md | 32 ++- agents-docs/features/signaling.md | 152 +++++++++++++ agents-docs/features/voice-webrtc.md | 60 +++++ .../android/app/src/main/AndroidManifest.xml | 7 + .../res/drawable-hdpi/ic_stat_metoyou.png | Bin 0 -> 241 bytes .../res/drawable-mdpi/ic_stat_metoyou.png | Bin 0 -> 180 bytes .../res/drawable-xhdpi/ic_stat_metoyou.png | Bin 0 -> 319 bytes .../res/drawable-xxhdpi/ic_stat_metoyou.png | Bin 0 -> 476 bytes .../res/drawable-xxxhdpi/ic_stat_metoyou.png | Bin 0 -> 633 bytes toju-app/capacitor.config.ts | 4 +- toju-app/public/i18n/catalog/call.json | 8 +- toju-app/public/i18n/catalog/mobile.json | 1 + toju-app/public/i18n/en.json | 9 +- toju-app/src/app/domains/README.md | 7 +- toju-app/src/app/domains/attachment/README.md | 3 +- .../attachment-download.service.spec.ts | 33 +++ .../services/attachment-download.service.ts | 7 + .../logic/attachment-export.rules.spec.ts | 31 +++ .../domain/logic/attachment-export.rules.ts | 23 ++ ...apacitor-attachment-export.service.spec.ts | 121 ++++++++++ .../capacitor-attachment-export.service.ts | 81 +++++++ .../capacitor-attachment-file-store.spec.ts | 1 + ...capacitor-attachment-filesystem.adapter.ts | 3 + .../feature/login/login.component.html | 4 +- .../feature/register/register.component.html | 4 +- toju-app/src/app/domains/chat/README.md | 8 + .../chat-messages.component.html | 2 +- .../chat-message-overlays.component.html | 4 +- .../src/app/domains/custom-emoji/README.md | 46 ++++ .../services/direct-call.service.spec.ts | 96 +++++++- .../services/direct-call.service.ts | 31 ++- .../incoming-call-modal.component.html | 4 +- .../src/app/domains/direct-message/README.md | 6 + .../services/direct-message.service.ts | 11 + .../feature/dm-chat/dm-chat.component.html | 2 +- .../src/app/domains/game-activity/README.md | 41 ++++ .../effects/notifications.effects.ts | 2 +- .../facades/notifications.facade.ts | 8 +- .../services/notifications.service.spec.ts | 17 ++ .../services/notifications.service.ts | 69 +++++- .../domain/logic/notification.logic.spec.ts | 86 ++++++- .../domain/logic/notification.logic.ts | 47 +++- .../notifications-settings.component.ts | 2 +- .../desktop-notification.service.spec.ts | 70 ++++++ .../services/desktop-notification.service.ts | 7 + toju-app/src/app/domains/plugins/README.md | 5 + .../profile-avatar-editor.component.html | 2 +- .../app/domains/server-directory/README.md | 9 + .../floating-voice-controls.component.html | 2 +- .../floating-voice-controls.component.ts | 4 + .../voice-controls.component.html | 44 ++-- .../voice-controls.component.ts | 21 +- .../private-call-controls.component.html | 28 +-- .../private-call-controls.component.ts | 1 + .../direct-call/private-call.component.html | 9 + .../direct-call/private-call.component.ts | 22 +- .../voice-workspace.component.html | 2 +- .../voice-workspace.component.ts | 4 + .../high-memory-alert-modal.component.html | 2 +- .../capacitor-mobile-notifications.adapter.ts | 40 ++++ .../web/web-mobile-notifications.adapter.ts | 16 ++ .../mobile/contracts/mobile.contracts.ts | 2 + .../ensure-mobile-capture-permissions.spec.ts | 10 + .../logic/message-notification.rules.spec.ts | 44 ++++ .../logic/message-notification.rules.ts | 33 +++ ...mobile-android-launcher-icon.rules.spec.ts | 44 +++- .../mobile-android-launcher-icon.rules.ts | 8 + .../mobile-media-permission.rules.spec.ts | 12 +- .../logic/mobile-media-permission.rules.ts | 13 +- .../mobile-voice-foreground-session.spec.ts | 76 +++++++ .../logic/mobile-voice-foreground-session.ts | 49 ++++ .../mobile-app-lifecycle.service.spec.ts | 94 ++++++++ .../services/mobile-app-lifecycle.service.ts | 15 +- .../services/mobile-notifications.service.ts | 8 + .../realtime/media/media.manager.ts | 4 + .../debug-console.component.html | 2 +- ...screen-share-quality-dialog.component.html | 4 +- .../screen-share-source-picker.component.html | 2 +- tools/generate-android-app-icons.mjs | 39 +++- 98 files changed, 2878 insertions(+), 155 deletions(-) create mode 100644 agents-docs/features/attachments.md create mode 100644 agents-docs/features/desktop-local-api.md create mode 100644 agents-docs/features/direct-messaging.md create mode 100644 agents-docs/features/game-activity.md create mode 100644 agents-docs/features/invites-join-requests.md create mode 100644 agents-docs/features/klipy-gifs.md create mode 100644 agents-docs/features/link-preview-media-proxy.md create mode 100644 agents-docs/features/messaging.md create mode 100644 agents-docs/features/plugins.md create mode 100644 agents-docs/features/push-notifications.md create mode 100644 agents-docs/features/server-directory.md create mode 100644 agents-docs/features/signaling.md create mode 100644 agents-docs/features/voice-webrtc.md create mode 100644 toju-app/android/app/src/main/res/drawable-hdpi/ic_stat_metoyou.png create mode 100644 toju-app/android/app/src/main/res/drawable-mdpi/ic_stat_metoyou.png create mode 100644 toju-app/android/app/src/main/res/drawable-xhdpi/ic_stat_metoyou.png create mode 100644 toju-app/android/app/src/main/res/drawable-xxhdpi/ic_stat_metoyou.png create mode 100644 toju-app/android/app/src/main/res/drawable-xxxhdpi/ic_stat_metoyou.png create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.spec.ts create mode 100644 toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.ts create mode 100644 toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.spec.ts create mode 100644 toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.ts create mode 100644 toju-app/src/app/domains/custom-emoji/README.md create mode 100644 toju-app/src/app/domains/game-activity/README.md create mode 100644 toju-app/src/app/domains/notifications/infrastructure/services/desktop-notification.service.spec.ts create mode 100644 toju-app/src/app/infrastructure/mobile/logic/message-notification.rules.spec.ts create mode 100644 toju-app/src/app/infrastructure/mobile/logic/message-notification.rules.ts create mode 100644 toju-app/src/app/infrastructure/mobile/logic/mobile-voice-foreground-session.spec.ts create mode 100644 toju-app/src/app/infrastructure/mobile/logic/mobile-voice-foreground-session.ts create mode 100644 toju-app/src/app/infrastructure/mobile/services/mobile-app-lifecycle.service.spec.ts diff --git a/agents-docs/FEATURES.md b/agents-docs/FEATURES.md index 756def3..c870c42 100644 --- a/agents-docs/FEATURES.md +++ b/agents-docs/FEATURES.md @@ -9,14 +9,27 @@ It must stay accurate as new features are introduced, renamed, merged, or remove ## 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. +- [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. - [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. +- [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. -- [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. +- [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//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//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/.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. diff --git a/agents-docs/LESSONS.md b/agents-docs/LESSONS.md index 9dfe6ae..6f38e01 100644 --- a/agents-docs/LESSONS.md +++ b/agents-docs/LESSONS.md @@ -25,6 +25,13 @@ Durable rules for AI agents working on this project. Read this file at session s ## 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`. diff --git a/agents-docs/features/app-i18n.md b/agents-docs/features/app-i18n.md index da1535d..1a0e2a6 100644 --- a/agents-docs/features/app-i18n.md +++ b/agents-docs/features/app-i18n.md @@ -1,7 +1,14 @@ # 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. +## 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 - 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.service.spec.ts` - `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 | diff --git a/agents-docs/features/attachments.md b/agents-docs/features/attachments.md new file mode 100644 index 0000000..e38be94 --- /dev/null +++ b/agents-docs/features/attachments.md @@ -0,0 +1,118 @@ +# 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//…` 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. +- "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-13 | Capacitor download/export to public `Documents` via `CapacitorAttachmentExportService` | +| 2026-07-05 | Expanded to full contract style | diff --git a/agents-docs/features/authentication.md b/agents-docs/features/authentication.md index b4b24e4..35f49dd 100644 --- a/agents-docs/features/authentication.md +++ b/agents-docs/features/authentication.md @@ -1,6 +1,14 @@ # 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 @@ -8,8 +16,8 @@ Session-token authentication for the signaling server and product client. |---|---|---| | Signaling server REST (mutations) | `Authorization: Bearer ` | 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 WebSocket | `identify.token` | Connections must identify before any other message type | -| Electron Local API | Separate in-memory bearer tokens | Proxies login to allowed signaling servers only | +| 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 — see [desktop-local-api.md](desktop-local-api.md) | | Product client local DB | OS user account | SQLite and attachments are plaintext at rest | ## Client logout @@ -36,13 +44,81 @@ Session-token authentication for the signaling server and product client. ## 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`) -- `PUT /api/requests/:id` -- Plugin-support mutations under `/api/servers/:serverId/plugins/*` -- `/api/users/device-tokens/*` -- `POST /api/users/logout` +### Users (`/api/users`) + +| Method | Path | Auth | +|--------|------|------| +| 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 @@ -135,3 +211,16 @@ 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. - 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. + +## 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-05 | Expanded protected-route inventory; clarified signing-key registration scope; cross-links | diff --git a/agents-docs/features/custom-emoji.md b/agents-docs/features/custom-emoji.md index f22638b..f1a5e3f 100644 --- a/agents-docs/features/custom-emoji.md +++ b/agents-docs/features/custom-emoji.md @@ -2,64 +2,125 @@ > **Area:** custom-emoji > **Status:** Active -> **Last updated:** 2026-06-05 +> **Last updated:** 2026-07-05 ## 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 -- Own custom emoji asset validation, local persistence, user-saved library membership, shortcut ranking, and peer-to-peer asset sync. -- Expose a shared picker consumed by chat message reactions and the chat composer. -- Keep usage ranking local to the current user; usage counts are not synced. -- Does not store custom emoji on the signaling server. +- Validate uploads (size, MIME), persist image assets locally, and track per-user **saved library** membership. +- Rank shortcuts by local usage (not synced across devices). +- Sync assets P2P (`custom-emoji-*` envelopes) and proactively push referenced emoji when sending messages. +- 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. -- **Known custom emoji**: A synced asset available for message rendering and forwarding, but not shown in the current user's picker unless saved. -- **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. -- **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. +- Message send/edit transport → [messaging.md](messaging.md). +- Profile avatar bytes → `toju-app/src/app/domains/profile-avatar/README.md`. +- Server-side storage (none). -## 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:`); 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, 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. -- 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:`, 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. +**Handshake:** on peer connect both sides send summaries; receiver requests stale/missing ids; owner sends manifest then chunked payloads via buffered sends. -## 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). -- 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:`), which is what keeps the picker user-bound even on a shared client database. +**Inline threshold:** assets ≤ `CUSTOM_EMOJI_INLINE_MAX_JSON_BYTES` (48 KiB) ship in one `custom-emoji-full`; larger assets use manifest + chunks. + +**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:` | +| Electron | SQLite `custom_emojis` (shared desktop DB) | same localStorage key | +| Capacitor | SQLite `custom_emojis` in `metoyou__` | 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 -- 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. -- Assets sync only to already connected peers; the signaling server does not persist or proxy emoji images. \ No newline at end of file +## Security considerations + +- 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 | diff --git a/agents-docs/features/desktop-local-api.md b/agents-docs/features/desktop-local-api.md new file mode 100644 index 0000000..04de8f0 --- /dev/null +++ b/agents-docs/features/desktop-local-api.md @@ -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 | diff --git a/agents-docs/features/direct-messaging.md b/agents-docs/features/direct-messaging.md new file mode 100644 index 0000000..ce1f2aa --- /dev/null +++ b/agents-docs/features/direct-messaging.md @@ -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 | diff --git a/agents-docs/features/game-activity.md b/agents-docs/features/game-activity.md new file mode 100644 index 0000000..e403370 --- /dev/null +++ b/agents-docs/features/game-activity.md @@ -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 5–60 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 | diff --git a/agents-docs/features/invites-join-requests.md b/agents-docs/features/invites-join-requests.md new file mode 100644 index 0000000..8a615ff --- /dev/null +++ b/agents-docs/features/invites-join-requests.md @@ -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 | diff --git a/agents-docs/features/klipy-gifs.md b/agents-docs/features/klipy-gifs.md new file mode 100644 index 0000000..44eb134 --- /dev/null +++ b/agents-docs/features/klipy-gifs.md @@ -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 | diff --git a/agents-docs/features/link-preview-media-proxy.md b/agents-docs/features/link-preview-media-proxy.md new file mode 100644 index 0000000..c946808 --- /dev/null +++ b/agents-docs/features/link-preview-media-proxy.md @@ -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 | diff --git a/agents-docs/features/message-integrity.md b/agents-docs/features/message-integrity.md index 7c82c7c..ce0fce1 100644 --- a/agents-docs/features/message-integrity.md +++ b/agents-docs/features/message-integrity.md @@ -1,6 +1,14 @@ # 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 @@ -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 | | 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::`) | 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 | | `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 diff --git a/agents-docs/features/messaging.md b/agents-docs/features/messaging.md new file mode 100644 index 0000000..016aa08 --- /dev/null +++ b/agents-docs/features/messaging.md @@ -0,0 +1,209 @@ +# 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` = 1_000_000 (safety ceiling for pathological rooms). +- Sync polling: 10 s when catching up, 15 min after a clean cycle (`SYNC_POLL_FAST_MS` / `SYNC_POLL_SLOW_MS`). + +--- + +## 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-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) | diff --git a/agents-docs/features/mobile-capacitor.md b/agents-docs/features/mobile-capacitor.md index 3348c94..dd87142 100644 --- a/agents-docs/features/mobile-capacitor.md +++ b/agents-docs/features/mobile-capacitor.md @@ -31,10 +31,6 @@ npm run cap:sync npm run cap:open:android 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) npm run cap:build:android 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 ``` +### 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`). ### CI (Gitea) @@ -85,13 +85,15 @@ Re-run `npm run cap:assets:android` whenever `images/icon-new-rounded.png` chang | 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` | +| 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 | | 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 | | 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` | -| 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 | +| 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 | | 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) | @@ -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 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. -- **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 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+) | | `POST_NOTIFICATIONS` | Incoming/active call notifications | | `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. @@ -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_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 POST /api/users/device-tokens/:userId/dispatch +Authorization: Bearer { "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 -`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_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. - Per-user database files: `metoyou__` 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. +- **Custom emoji assets** persist in the `custom_emojis` table (`CapacitorDatabaseService.saveCustomEmoji` / `getCustomEmojis` / `deleteCustomEmoji`). +- **Message revisions** persist in `meta` under keys `message-revision::` (JSON payload). See [message-integrity.md](message-integrity.md) and [custom-emoji.md](custom-emoji.md). ## 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. ## Safe area (Android) @@ -267,10 +278,16 @@ Phase 3 delivered: 3. iOS CallKit bridge (partial) via `MetoyouMobile` plugin and `MobileCallKitService`. 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. -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: - Wire CallKit answer/end actions back into `DirectCallService`. - 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 | diff --git a/agents-docs/features/plugins.md b/agents-docs/features/plugins.md new file mode 100644 index 0000000..0fb750d --- /dev/null +++ b/agents-docs/features/plugins.md @@ -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///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 | diff --git a/agents-docs/features/push-notifications.md b/agents-docs/features/push-notifications.md new file mode 100644 index 0000000..90e0466 --- /dev/null +++ b/agents-docs/features/push-notifications.md @@ -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 | diff --git a/agents-docs/features/server-directory.md b/agents-docs/features/server-directory.md new file mode 100644 index 0000000..9d8f89d --- /dev/null +++ b/agents-docs/features/server-directory.md @@ -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 | diff --git a/agents-docs/features/server-discovery.md b/agents-docs/features/server-discovery.md index 48cf87c..b6866ef 100644 --- a/agents-docs/features/server-discovery.md +++ b/agents-docs/features/server-discovery.md @@ -2,7 +2,7 @@ > **Area:** server-directory > **Status:** Active -> **Last updated:** 2025-02-14 +> **Last updated:** 2026-07-05 ## Overview @@ -67,13 +67,24 @@ Both endpoints live in `server/src/routes/servers.ts` and **must be registered b ## Client internals - `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. - `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`. - 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 `` 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 `` + `[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 `` + `[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 `` 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 - 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` +- 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 | diff --git a/agents-docs/features/signal-server-tag.md b/agents-docs/features/signal-server-tag.md index f9a59ea..5382a4f 100644 --- a/agents-docs/features/signal-server-tag.md +++ b/agents-docs/features/signal-server-tag.md @@ -1,10 +1,18 @@ # 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). +## 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/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 @@ -12,11 +20,27 @@ Users registered on a signal server can show that server's display tag on their ## 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 - 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. -- 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 | diff --git a/agents-docs/features/signaling.md b/agents-docs/features/signaling.md new file mode 100644 index 0000000..b567cc0 --- /dev/null +++ b/agents-docs/features/signaling.md @@ -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 | diff --git a/agents-docs/features/voice-webrtc.md b/agents-docs/features/voice-webrtc.md new file mode 100644 index 0000000..d030cf1 --- /dev/null +++ b/agents-docs/features/voice-webrtc.md @@ -0,0 +1,60 @@ +# 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). + +## 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-05 | Initial cross-context voice/WebRTC contract | diff --git a/toju-app/android/app/src/main/AndroidManifest.xml b/toju-app/android/app/src/main/AndroidManifest.xml index b03d540..33220fb 100644 --- a/toju-app/android/app/src/main/AndroidManifest.xml +++ b/toju-app/android/app/src/main/AndroidManifest.xml @@ -59,4 +59,11 @@ + + + diff --git a/toju-app/android/app/src/main/res/drawable-hdpi/ic_stat_metoyou.png b/toju-app/android/app/src/main/res/drawable-hdpi/ic_stat_metoyou.png new file mode 100644 index 0000000000000000000000000000000000000000..e473d01196b9df14e1f686532faac42221a5eba1 GIT binary patch literal 241 zcmeAS@N?(olHy`uVBq!ia0vp^Dj>|k1|%Oc%$NbBI14-?iy0W0Uw|;<*6N^apx|Op z7srr_Id3OB@*Pp&VSfI9{6tnHa|#6pe=i7TXu$f#_*oMhS{<#AWBwC#oFV@`bOB_PHt(JX}6JE8uxFUC?%+<>k3vZ$9j0 z^sF)NQrf@WTTVAcYi~@^F|D0Uf$GzH7G#!Ac=>NS+qs>Kq)t?}XF5FYnkMn!jA6q6 a4!zJqTeT(YZd?W0$l&Sf=d#Wzp$Pyj)k81< literal 0 HcmV?d00001 diff --git a/toju-app/android/app/src/main/res/drawable-xhdpi/ic_stat_metoyou.png b/toju-app/android/app/src/main/res/drawable-xhdpi/ic_stat_metoyou.png new file mode 100644 index 0000000000000000000000000000000000000000..55516cd29d68cbfb3627ca3a85e90d783e25ae57 GIT binary patch literal 319 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA1|-9oezpTC&H|6fVg?507a+{IwK^ypDEQIS z#WAE}&f6J|d@T+fEWiKHU$=Lb?-kjMHXkt|zqBQ*8GE@doLrg5$iwhg&q|Ku}5 z#c8Xe8JHdRcc0<-`09}9s@T14xt;G9IeiIhSehjIeaglN*9?Xqhxs%ra;*)`9Lhk$DVn tzQDCAEruP;nkyGOHR$4S@Jzv94Cgf8%&ot~JqPG{22WQ%mvv4FO#l&_c$@$L literal 0 HcmV?d00001 diff --git a/toju-app/android/app/src/main/res/drawable-xxhdpi/ic_stat_metoyou.png b/toju-app/android/app/src/main/res/drawable-xxhdpi/ic_stat_metoyou.png new file mode 100644 index 0000000000000000000000000000000000000000..17c780674b887ebd1c8a8e10a879390e7f0c1d6c GIT binary patch literal 476 zcmeAS@N?(olHy`uVBq!ia0vp^9w5xY1|&n@ZgvM!oCO|{#S9G0FF=@aYjsdI0|R59 zr;B4q#hkY@4)!%02sr=!Z~u00&QdvzMg!wA?dVUeUY|ZmX=r&UJ#}ZFc=$7~kYkU6 zO=U|8yJ6D=*(3YnAKgjnQ2_F`ON8YAu4Ds?-bp%P+%d0y_X);~I7^1JyQ?1tKIwj$ zux8F5TfZQ=!qUb)#~pjNE(i|^+UGXGSt(;8N0dsFSmy#)r4z0Kc@1yoyqDl!*HrL0 z=6OU|Q^X&;s~?x1WZmd-PJ6CSSyS2P;3k6|%@5Qvrk;w8u)No?K-+TnvzLqJ^&HJ} z4B!0g&$~rs=jWe|S6gBI>gO8PgBj;Ie)WHm+#YTR5FAD)k-PS@q`S z9Ob3}jvAKpZI#DZ7fSql6LIv1kfX*PR;}Po>%1Hn_&?C%ND6$K{ZgnUe!^v44(CNt zKh;?ldS2o9zC@vBwoI#njfm;FRYEPZ7p3%MIYx8@72o7&%6`gVvR!oI``i&SFrrx z5ZK%DnQcb=k)JG$v5N`zt#LD~&WG{t*wo>_X-dPw z2hXPMYi;l|x|hPu7#oJ_nY6xZ1QnfIq03v7Eg^ zdeYvl4E_=Srt0Ni7kr@n;9Kw)GsF1{PBG3~c9~}>lUqal%6~pRHp^QZ1iOFQhn}wd zG+X_-kMIYT@^#l291WS5>~-MecOOv)H}1`{j7Ke*&Zs@Jci=Xh%K5^~Kr)aijd#60 z+y3ISFIF@+oJ#!abbx1_8B?0~1^smWjeocpLz`D~9+#fBk}1t|$EBZ&2UtRE8(p@n zYPjmUV%KJtH5!h)IU`(K(xwSqh-{g}a-z2BZG)IX1dDCCG$WJCh0WVU7EC!>F1A2P z@Qcl9&I<~HCjUP%eQ{zryJsrH+busrSzm}tn)uIQcpD&d;Nek5nK;U+zw9iL=Ns=X S-~}cd1_n=8KbLh*2~7YH@DR)Z literal 0 HcmV?d00001 diff --git a/toju-app/capacitor.config.ts b/toju-app/capacitor.config.ts index 1e0d71c..167b5c6 100644 --- a/toju-app/capacitor.config.ts +++ b/toju-app/capacitor.config.ts @@ -13,8 +13,8 @@ const config: CapacitorConfig = { style: 'DARK' }, LocalNotifications: { - smallIcon: 'ic_stat_icon_config_sample', - iconColor: '#488AFF', + smallIcon: 'ic_stat_metoyou', + iconColor: '#4A217A', sound: 'call.wav' }, PushNotifications: { diff --git a/toju-app/public/i18n/catalog/call.json b/toju-app/public/i18n/catalog/call.json index d0d4868..f92b4bc 100644 --- a/toju-app/public/i18n/catalog/call.json +++ b/toju-app/public/i18n/catalog/call.json @@ -43,7 +43,13 @@ }, "errors": { "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." } } } diff --git a/toju-app/public/i18n/catalog/mobile.json b/toju-app/public/i18n/catalog/mobile.json index 10bb5a4..d0fb579 100644 --- a/toju-app/public/i18n/catalog/mobile.json +++ b/toju-app/public/i18n/catalog/mobile.json @@ -24,6 +24,7 @@ "notifications": { "incomingCallsChannel": "Incoming calls", "activeCallsChannel": "Active calls", + "messagesChannel": "Messages", "answer": "Answer", "decline": "Decline", "mute": "Mute", diff --git a/toju-app/public/i18n/en.json b/toju-app/public/i18n/en.json index efbdac5..050e41f 100644 --- a/toju-app/public/i18n/en.json +++ b/toju-app/public/i18n/en.json @@ -127,7 +127,13 @@ }, "errors": { "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": { @@ -517,6 +523,7 @@ "notifications": { "incomingCallsChannel": "Incoming calls", "activeCallsChannel": "Active calls", + "messagesChannel": "Messages", "answer": "Answer", "decline": "Decline", "mute": "Mute", diff --git a/toju-app/src/app/domains/README.md b/toju-app/src/app/domains/README.md index 0bbd47b..f5d9b1c 100644 --- a/toju-app/src/app/domains/README.md +++ b/toju-app/src/app/domains/README.md @@ -29,21 +29,26 @@ infrastructure adapters and UI. 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) +- [attachment/README.md](attachment/README.md) - [authentication/README.md](authentication/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-call/README.md](direct-call/README.md) - [experimental-media/README.md](experimental-media/README.md) +- [game-activity/README.md](game-activity/README.md) - [notifications/README.md](notifications/README.md) - [plugins/README.md](plugins/README.md) - [profile-avatar/README.md](profile-avatar/README.md) - [screen-share/README.md](screen-share/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-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 Every domain follows the same internal layout: diff --git a/toju-app/src/app/domains/attachment/README.md b/toju-app/src/app/domains/attachment/README.md index 873f389..6991129 100644 --- a/toju-app/src/app/domains/attachment/README.md +++ b/toju-app/src/app/domains/attachment/README.md @@ -28,7 +28,8 @@ attachment/ │ ├── infrastructure/ │ ├── 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/ │ └── attachment-storage.util.ts sanitizeAttachmentRoomName, resolveAttachmentStorageBucket │ diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-download.service.spec.ts b/toju-app/src/app/domains/attachment/application/services/attachment-download.service.spec.ts index 2bd4da0..97d76da 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-download.service.spec.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-download.service.spec.ts @@ -9,8 +9,15 @@ import { import { DOCUMENT } from '@angular/common'; 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 { 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'; describe('AttachmentDownloadService', () => { @@ -21,8 +28,11 @@ describe('AttachmentDownloadService', () => { let documentStub: Document; let saveExistingFileAs: ReturnType; let saveFileAs: ReturnType; + let exportToDevice: ReturnType; beforeEach(() => { + isCapacitorNativeRuntimeMock.mockReturnValue(false); + exportToDevice = vi.fn(async () => true); saveExistingFileAs = vi.fn(async () => ({ saved: true, cancelled: false })); saveFileAs = vi.fn(async () => ({ saved: true, cancelled: false })); @@ -53,6 +63,7 @@ describe('AttachmentDownloadService', () => { providers: [ AttachmentDownloadService, { provide: ElectronBridgeService, useValue: electronBridge }, + { provide: CapacitorAttachmentExportService, useValue: { exportToDevice } }, { provide: DOCUMENT, useValue: documentStub } ] }); @@ -78,6 +89,28 @@ describe('AttachmentDownloadService', () => { 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 () => { const service = createService(); const attachment: Attachment = { diff --git a/toju-app/src/app/domains/attachment/application/services/attachment-download.service.ts b/toju-app/src/app/domains/attachment/application/services/attachment-download.service.ts index 4e7f7d3..7e72338 100644 --- a/toju-app/src/app/domains/attachment/application/services/attachment-download.service.ts +++ b/toju-app/src/app/domains/attachment/application/services/attachment-download.service.ts @@ -2,12 +2,15 @@ import { DOCUMENT } from '@angular/common'; import { Injectable, inject } from '@angular/core'; 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 type { Attachment } from '../../domain/models/attachment.model'; +import { CapacitorAttachmentExportService } from '../../infrastructure/services/capacitor-attachment-export.service'; @Injectable({ providedIn: 'root' }) export class AttachmentDownloadService { private readonly electronBridge = inject(ElectronBridgeService); + private readonly capacitorExport = inject(CapacitorAttachmentExportService); private readonly document = inject(DOCUMENT); async downloadToUserLocation(attachment: Attachment): Promise { @@ -15,6 +18,10 @@ export class AttachmentDownloadService { return false; } + if (isCapacitorNativeRuntime()) { + return this.capacitorExport.exportToDevice(attachment); + } + const electronApi = this.electronBridge.getApi(); const diskPath = resolveAttachmentDiskPath(attachment); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.spec.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.spec.ts new file mode 100644 index 0000000..e68d15f --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.spec.ts @@ -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'); + }); +}); diff --git a/toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.ts b/toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.ts new file mode 100644 index 0000000..e3c2c8d --- /dev/null +++ b/toju-app/src/app/domains/attachment/domain/logic/attachment-export.rules.ts @@ -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() ?? ''; +} diff --git a/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.spec.ts b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.spec.ts new file mode 100644 index 0000000..c17cdc5 --- /dev/null +++ b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.spec.ts @@ -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 { + 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; + + 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); + }); +}); diff --git a/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.ts b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.ts new file mode 100644 index 0000000..047c177 --- /dev/null +++ b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-export.service.ts @@ -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 { + 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 { + try { + const response = await fetch(objectUrl); + const buffer = await response.arrayBuffer(); + + return encodeUint8ArrayToBase64(new Uint8Array(buffer)); + } catch { + return null; + } + } +} diff --git a/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-file-store.spec.ts b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-file-store.spec.ts index ca34716..555a021 100644 --- a/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-file-store.spec.ts +++ b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-file-store.spec.ts @@ -82,6 +82,7 @@ function createFakeFilesystem() { adapter: { filesystem, directory: 'DATA', + exportDirectory: 'DOCUMENTS', convertFileSrc: (url: string) => url.replace('file://', 'capacitor://localhost/_capacitor_file_') } }; diff --git a/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-filesystem.adapter.ts b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-filesystem.adapter.ts index debdbff..7e16770 100644 --- a/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-filesystem.adapter.ts +++ b/toju-app/src/app/domains/attachment/infrastructure/services/capacitor-attachment-filesystem.adapter.ts @@ -10,6 +10,8 @@ type CapacitorCoreModule = typeof import('@capacitor/core'); export interface CapacitorAttachmentFilesystem { filesystem: CapacitorFilesystemModule['Filesystem']; 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; } @@ -42,6 +44,7 @@ async function resolveCapacitorAttachmentFilesystem(): Promise coreModule.Capacitor.convertFileSrc(url) }; } catch { diff --git a/toju-app/src/app/domains/authentication/feature/login/login.component.html b/toju-app/src/app/domains/authentication/feature/login/login.component.html index 8afc675..af64cad 100644 --- a/toju-app/src/app/domains/authentication/feature/login/login.component.html +++ b/toju-app/src/app/domains/authentication/feature/login/login.component.html @@ -1,5 +1,5 @@ -
-
+
+
-
+
+
-
+
-
+
-
+