Skip to content

New QMS - #68

Open
va1mont wants to merge 12 commits into
SubvertDev:developfrom
va1mont:feature/new-qms
Open

va1mont wants to merge 12 commits into
SubvertDev:developfrom
va1mont:feature/new-qms

Conversation

@va1mont

@va1mont va1mont commented Dec 5, 2026 •

Copy link
Copy Markdown

QMS переписан с нуля: быстрый, без ExyteChat, с кэшем и очередью отправки. Альтернатива #66: тот дорабатывает текущую реализацию, этот переписывает её целиком.

Что сделано

  • Парсеры QMS на Decodable без force-cast'ов: битый ответ даёт ошибку, а не краш.
  • QMSStore (actor) — диалоги в памяти и на диске (Caches/QMS/<userId>/, до 300 последних сообщений). Диалог открывается сразу из кэша, свежие сообщения подтягиваются фоном. Страницы склеиваются по id; если новая страница не стыкуется с известными сообщениями, старые выбрасываются, чтобы не показать дыру. Синхронизации одного диалога склеиваются: сокет, возврат в приложение и отправка во время запроса дают максимум один дополнительный запрос.
  • QMSListStore — то же для списка собеседников. Раскрытые диалоги хранятся по id пользователя, поэтому не схлопываются при пересортировке списка.
  • Лента на UICollectionView с diffable data source и SwiftUI-ячейками вместо ExyteChat:
    • позиция не прыгает при подгрузке старых сообщений;
    • лента прижимается к низу при новых сообщениях и клавиатуре;
    • разделители по дням, группировка по отправителю;
    • статусы «отправляется / ошибка / отправлено / прочитано»;
    • в контекстном меню поднимается только пузырь, а не вся строка.
  • Отправка: сообщение появляется сразу. При ошибке остаётся в ленте с «Повторить» и «Удалить». Если приложение убили во время отправки, после перезапуска сообщение помечается ошибкой.
  • Вложения: скрепка и UploadBoxFeature (флаг isQms, файлы уходят в QMS-хранилище). Картинки показываются целиком и открываются в галерее со всеми картинками диалога. Файлы — карточкой с иконкой по типу, именем и размером.
  • BB-блоки (цитаты, код, спойлеры) через TopicView. Рендер в фоне с кэшем, чтобы лента не тормозила.
  • Новое сообщение в открытом чате приходит само (событие сокета с флагом 2).
  • Кэши QMS очищаются при выходе из аккаунта и очистке кэша в настройках.
  • ExyteChat удалён из зависимостей.

Проверено

Xcode 27.2, симулятор iPhone 18 Pro (iOS 27.2), реальный аккаунт и живой собеседник:

  • отправка текста, картинки и файла, ошибка отправки, повтор, восстановление после перезапуска;
  • подгрузка старых сообщений, приход нового сообщения в открытый чат, автообновление списка;
  • открытие из кэша без сети, тёмная тема, BB-цитаты и код;
  • пуш на экране блокировки и баннером, переход в чат по нажатию;
  • выключение QMS в настройках уведомлений: пуш не приходит, сообщение доходит.

Unit-тесты (Swift Testing, 45 штук): парсеры, QMSStore, QMSListStore, сборка ленты и рендер. Запуск: xcodebuild test -scheme QMSClient -only-testing:QMSClientTests (аналогично ParsingClient, QMSFeature).

Не проверено

  • iOS 16–17 (проверялось только на iOS 27).
  • Нажатие на пуш на экране блокировки: симулятор не передаёт его в приложение.

Не входит

Индикатор «печатает» (событие с флагом 101).

va1mont and others added 12 commits December 5, 2026 00:26
- Parse QMS chat, list and user responses with Decodable instead of
  force casts, malformed responses now throw ParsingError
- Add ParsingClientTests with QMS parser tests
- Don't force unwrap chat and user session in QMSFeature, don't mark
  chat as read when it failed to load
- Reload chat right after sending instead of waiting for socket event
- Fix attachment link range for file names with emoji

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- QMSStore actor keeps dialog snapshots in memory and on disk
  (Caches/QMS/<userId>/<dialogId>.json, last 300 messages), so a dialog
  opens instantly from cache and refreshes in background
- Pages are merged by message id; a full latest page after a gap drops
  stale messages instead of showing a hole
- Concurrent syncs of a dialog (socket events, scene activation, send)
  are coalesced into at most one extra request; older pages are loaded once
- QMSFeature observes the store instead of merging pages itself; long
  running effects are cancellable so repeated onAppear doesn't duplicate them
- Failed background refresh of a shown chat no longer shows an alert
- QMS cache is removed on logout and on cache clearing
- Add QMSClientTests for merge, store and file cache

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- QMSChatCollectionView: diffable data source with self-sizing
  UIHostingConfiguration cells; keeps the visible message in place when
  older pages are prepended, sticks to the bottom on new messages and
  keyboard, interactive keyboard dismiss, copy context menu
- Feed rows (day headers, sender groups, avatars, read status) are built
  by QMSChatItemsBuilder off the main thread; BB rendering is cached per
  message text in QMSMessageRenderer instead of running on every redraw
- New input bar with multiline field, scroll to bottom button
- Remove ExyteChat package
- Add QMSFeatureTests for items builder and renderer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Message rows report their bubble frame, and the context menu uses it as
the visible path of the targeted preview instead of the whole full width
row. The screen background goes under the preview since bubble color
is translucent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- QMSStore.send shows the message in the dialog right away with
  sending state; on failure it stays as failed with retry and discard,
  after success it is replaced by the real message on the next sync
- Outgoing messages are saved with the dialog cache; messages that were
  sending when the app closed come back as failed, so nothing is resent
  without the user knowing
- Chat feed shows sending and failed states, tap on a failed message
  retries it, context menu has Retry and Delete
- Attach button opens UploadBox with QMS storage (isQms), uploaded files
  are sent with the message as attachment ids
- Add tests for the queue and outgoing rows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- QMSListStore keeps the list in memory and on disk, so the list opens
  instantly and refreshes in background; dialogs of a partner are kept
  when the list response comes without them
- List syncs are coalesced, repeated loads of a partner's dialogs share
  one request
- QMSListFeature observes the store; long-running effects are
  cancellable, so returning from a chat no longer adds another unread
  subscription
- Expanded partners are tracked by user id instead of row index, so the
  right groups stay expanded after the list is reordered
- Failure to load one partner's dialogs no longer turns the whole screen
  into an error, and a failed refresh keeps the cached list
- List cache is removed on logout and on cache clearing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Messages with quotes, code, spoilers and other BB blocks are built into
TopicNodeBuilder nodes in background, together with formatted text, and
cached per message. Such messages are drawn with TopicView like forum
posts; plain formatted messages keep the fast Text path. Attachments
referenced in the text are passed to the builder, the rest stay as
download links above the text.

Based on the BB rendering from SubvertDev#66.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Flag 2 means the last API request was this chat, so the chat is most
likely open, yet the event was dropped and a new message from the
partner didn't show up until the next sync. Now it emits the same chat
event as flag 1; unread state still isn't touched for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Images open in the gallery with all images of the dialog.
Split chat item models, feed builder and renderer into separate files.
The composer is a UITextView: TextField doesn't expose the selection
before iOS 18, and tags have to wrap it. Tags are applied by the text
view itself, so keys typed before the state catches up aren't lost.
The panel sits under the field, above it the selection edit menu
covers the buttons.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant