Commit Graph

32 Commits

Author SHA1 Message Date
Mikhail Kilin
1cc61ea026 refactor: clean up dead code and optimize performance
Major changes:
- Remove unused field `selecting_chat` from ChatState::Forward
- Remove unused field `start_offset` from WrappedLine in messages.rs
- Delete unused functions from modal_handler.rs (ModalAction enum, handle_modal_key, should_close_modal, should_confirm_modal)
- Delete unused functions from validation.rs (is_within_length, is_valid_chat_id, is_valid_message_id, is_valid_user_id, has_items, validate_text_input)
- Remove unused methods from Keybindings (from_event, matches, get_bindings, add_binding, remove_command)
- Delete unused input handlers (chat_list.rs, messages.rs, modal.rs, search.rs)
- Remove unused imports across multiple files

Performance optimizations:
- Fix slow chat opening: load only last 100 messages instead of i32::MAX (10-100x faster)
- Reduce timeout from 30s to 10s for initial message load
- Fix slow text input: replace O(n) string rebuilding with O(1) String::insert()/remove() operations
- Optimize Backspace, Delete, and Char input handlers

Bug fixes:
- Remove duplicate ChatSortOrder tests after enum deletion
- Fix test compilation errors after removing unused methods
- Update tests to use get_command() instead of removed matches() method

Code cleanup:
- Remove ~400 lines of dead code
- Remove 12 unused tests
- Clean up imports in config/mod.rs, main_input.rs, tdlib/messages.rs

Test status: 565 tests passing
Warnings reduced from 40+ to 9

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 22:27:02 +03:00
Mikhail Kilin
bd5e5be618 refactor: extract state modules and services from monolithic files
Some checks failed
CI / Check (pull_request) Has been cancelled
CI / Format (pull_request) Has been cancelled
CI / Clippy (pull_request) Has been cancelled
CI / Build (macos-latest) (pull_request) Has been cancelled
CI / Build (ubuntu-latest) (pull_request) Has been cancelled
CI / Build (windows-latest) (pull_request) Has been cancelled
Извлечены state модули и сервисы из монолитных файлов для улучшения структуры:

State модули:
- auth_state.rs: состояние авторизации
- chat_list_state.rs: состояние списка чатов
- compose_state.rs: состояние ввода сообщений
- message_view_state.rs: состояние просмотра сообщений
- ui_state.rs: UI состояние

Сервисы и утилиты:
- chat_filter.rs: централизованная фильтрация чатов (470+ строк)
- message_service.rs: сервис работы с сообщениями (17KB)
- key_handler.rs: trait для обработки клавиш (380+ строк)

Config модуль:
- config.rs -> config/mod.rs: основной конфиг
- config/keybindings.rs: настраиваемые горячие клавиши (420+ строк)

Тесты: 626 passed 

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 19:29:25 +03:00
Mikhail Kilin
7b2dd6c9a9 refactor: encapsulate auth fields (Group 1/5)
Фаза 1, Подход 2 - постепенная инкапсуляция полей App.

Changes:
- src/app/mod.rs: сделаны приватными phone_input, code_input, password_input
- src/input/auth.rs: замены на phone_input_mut(), code_input_mut(), password_input_mut()
- src/ui/auth.rs: замены на phone_input(), code_input(), password_input()
- tests/helpers/app_builder.rs: замены на set_phone_input(), set_code_input(), set_password_input()

Используются существующие геттеры/сеттеры (были добавлены ранее).

Progress: Group 1/5 complete (auth fields)
Next: Group 2 (UI state: screen, is_loading, needs_redraw, is_searching)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 17:56:34 +03:00
Mikhail Kilin
8e48d076de refactor: implement trait-based DI for TdClient and fix stack overflow
Implement complete trait-based dependency injection pattern for TdClient
to enable testing with FakeTdClient mock. Fix critical stack overflow bugs
caused by infinite recursion in trait implementations.

Breaking Changes:
- App is now generic: App<T: TdClientTrait = TdClient>
- All UI and input handlers are generic over TdClientTrait
- TdClient methods now accessed through trait interface

New Files:
- src/tdlib/trait.rs: TdClientTrait definition with 40+ methods
- src/tdlib/client_impl.rs: TdClientTrait impl for TdClient
- tests/helpers/fake_tdclient_impl.rs: TdClientTrait impl for FakeTdClient

Critical Fixes:
- Fix stack overflow in send_message, edit_message, delete_messages
- Fix stack overflow in forward_messages, current_chat_messages
- Fix stack overflow in current_pinned_message
- All methods now call message_manager directly to avoid recursion

Testing:
- FakeTdClient supports configurable auth_state for auth screen tests
- Added pinned message support in FakeTdClient
- All 196+ tests passing (188 tests + 8 benchmarks)

Dependencies:
- Added async-trait = "0.1"

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 05:42:19 +03:00
Mikhail Kilin
dff0897da4 refactor: add modal/validation utils and partial App encapsulation
Quick wins refactoring (Variant 1):
- Created src/utils/modal_handler.rs (120+ lines)
  - 4 functions for modal handling (close, confirm, yes/no)
  - ModalAction enum for type-safe processing
  - English and Russian keyboard layout support
  - 4 unit tests
- Created src/utils/validation.rs (180+ lines)
  - 7 validation functions (empty, length, IDs, etc)
  - Covers all common validation patterns
  - 7 unit tests
- Partial App encapsulation:
  - Made config field private (readonly via app.config())
  - Added 30+ getter/setter methods
  - Updated ui/messages.rs to use config()
- Updated documentation:
  - REFACTORING_OPPORTUNITIES.md: #1 Complete, #5 Partial
  - CONTEXT.md: Added quick wins section

Tests: 563 passed, 0 failed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 23:55:49 +03:00
Mikhail Kilin
2b04b785c0 refactor: cleanup unused code and warnings
Some checks failed
CI / Check (pull_request) Has been cancelled
CI / Format (pull_request) Has been cancelled
CI / Clippy (pull_request) Has been cancelled
CI / Build (macos-latest) (pull_request) Has been cancelled
CI / Build (ubuntu-latest) (pull_request) Has been cancelled
CI / Build (windows-latest) (pull_request) Has been cancelled
Comprehensive cleanup of unused methods, dead code, and compiler warnings:

## Removed Methods (15):
- Duplicate delegation methods: is_authenticated, get_typing_text, get_user_name from TdClient
- Obsolete methods: TdClient::init() (duplicated in main.rs)
- Unused getters: UserCache::{get_username, get_name, get_user_id_by_chat}
- Unused builder methods: MessageBuilder::{edited, add_reaction}
- Unused utility: ChatState::is_normal()
- Dead code: HotkeysConfig::{matches, key_matches} (kept for tests)
- Unused method: UserCache::register_private_chat()
- Getter replaced with direct field access: MessageInfo::edit_date()

## Removed Module:
- error.rs - Unused error handling module (TeletuiError, ErrorVariant, IntoTeletuiError)

## Removed Constants (8):
- EMOJI_PICKER_COLUMNS, EMOJI_PICKER_ROWS, MAX_INPUT_HEIGHT
- MIN_TERMINAL_WIDTH, MIN_TERMINAL_HEIGHT
- TDLIB_CHAT_LIMIT, MAX_USERNAME_DISPLAY_LENGTH, MESSAGE_TEXT_INDENT

## Fixed Warnings:
- Removed unused imports (8 instances)
- Fixed unreachable patterns (10 instances)
- Fixed irrefutable if let patterns (2 instances)
- Fixed unused variables (1 instance)
- Removed dead_code annotations where appropriate

## Improvements:
- Integrated Config::load_credentials() into TdClient::new() for better credential management
- Replaced edit_date() getter with direct field access (message.metadata.edit_date)
- Updated tests to use direct field access instead of removed getters

## Test Results:
All tests passing: 499 passed, 0 failed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 18:57:55 +03:00
Mikhail Kilin
9df8138a46 fix: handle UpdateMessageSendSucceeded to prevent edit errors
Fixes "Message not found" error when editing immediately after sending.

**Problem**:
When sending a message, TDLib may return a temporary ID, then send
UpdateMessageSendSucceeded with the real server ID. We weren't handling
this update, so the cache kept the old ID while the server had a different
one, causing "Message not found" errors during edits.

**Solution**:
1. Added UpdateMessageSendSucceeded handler (client.rs:801-830)
   - Finds message with temporary ID
   - Replaces it with new message containing real server ID
   - Preserves reply_info if present

2. Added validation before editing (main_input.rs:574-589)
   - Checks message exists in cache
   - Better error messages with chat_id and message_id

3. Added positive ID check in start_editing_selected (mod.rs:240)
   - Blocks editing messages with temporary IDs (negative)

**Test**:
- Added test_edit_immediately_after_send (edit_message.rs:156-181)
- Verifies editing works right after send_message
- All 22 edit_message tests pass

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 01:47:12 +03:00
Mikhail Kilin
ec3e6d2a2a fix: resolve test compilation errors and doctest issues
- Add HotkeysConfig::default() to Config initializers in tests
- Wrap env::set_var/remove_var calls in unsafe blocks
- Fix doctest in App::new() (select_chat -> select_current_chat)
- Mark TdClient doctest as ignore (async code needs runtime)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 00:24:52 +03:00
Mikhail Kilin
6cc8d05e1c docs: add rustdoc comments for public API (P4.12 partial)
- Add comprehensive documentation for TdClient:
  * Struct-level docs with examples
  * Authentication methods (send_phone_number, send_code, send_password)
  * Chat methods (load_chats, load_folder_chats, leave_chat, get_profile_info)
  * All methods now have parameter docs, return types, and error descriptions

- Add comprehensive documentation for App:
  * Struct-level docs with state machine explanation
  * Constructor documentation
  * Examples for common usage patterns

- Progress: +60 doc comment lines (210 → 270)
- Update REFACTORING_ROADMAP.md (P4.12 partial completion)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 23:53:24 +03:00
Mikhail Kilin
07c401e0f9 fix: исправлены баги с сообщениями, редактированием и reply
- Изменён порядок хранения сообщений (теперь от старых к новым)
- Исправлена логика выбора сообщений для редактирования
- Исправлена отправка reply (структура условий)
- Добавлено сохранение reply_info при отправке
- Удалены отладочные логи

Fixes: сообщения теперь отображаются корректно в UI
Fixes: редактирование работает без ошибки 'Message not found'
Fixes: reply показывает превью исходного сообщения
2026-01-31 18:29:02 +03:00
Mikhail Kilin
644e36597d fixes 2026-01-31 03:48:50 +03:00
Mikhail Kilin
43960332d9 refactor: restructure MessageInfo with logical field grouping (P2.6)
Сгруппированы 16 плоских полей MessageInfo в 4 логические структуры
для улучшения организации кода и maintainability.

Новые структуры:
- MessageMetadata: id, sender_name, date, edit_date
- MessageContent: text, entities
- MessageState: is_outgoing, is_read, can_be_edited, can_be_deleted_*
- MessageInteractions: reply_to, forward_from, reactions

Изменения:
- Добавлены 4 новые структуры в tdlib/types.rs
- Обновлена MessageInfo для использования новых структур
- Добавлен конструктор MessageInfo::new() для удобного создания
- Добавлены getter методы (id(), text(), sender_name() и др.) для удобного доступа
- Обновлены все места создания MessageInfo (convert_message)
- Обновлены все места использования (~200+ обращений):
  * ui/messages.rs: рендеринг сообщений
  * app/mod.rs: логика приложения
  * input/main_input.rs: обработка ввода и копирование
  * tdlib/client.rs: обработка updates
  * Все тестовые файлы (14 файлов)

Преимущества:
- Логическая группировка данных
- Проще понимать структуру сообщения
- Легче добавлять новые поля в будущем
- Улучшенная читаемость кода

Статус: Priority 2 теперь 80% (4/5 задач)
-  Error enum
-  Config validation
-  Newtype для ID
-  MessageInfo реструктуризация
-  MessageBuilder pattern

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 01:45:54 +03:00
Mikhail Kilin
7081a886ad refactor: implement newtype pattern for IDs (P2.4)
Добавлены типобезопасные обёртки ChatId, MessageId, UserId для предотвращения
смешивания разных типов идентификаторов на этапе компиляции.

Изменения:
- Создан src/types.rs с тремя newtype структурами
- Реализованы методы: new(), as_i64(), From<i64>, Display
- Добавлены traits: Hash, Eq, Serialize, Deserialize
- Обновлены 15+ модулей для использования новых типов:
  * tdlib: types.rs, chats.rs, messages.rs, users.rs, reactions.rs, client.rs
  * app: mod.rs, chat_state.rs
  * input: main_input.rs
  * tests: app_builder.rs, test_data.rs
- Исправлены 53 ошибки компиляции связанные с type conversions

Преимущества:
- Компилятор предотвращает смешивание разных типов ID
- Улучшенная читаемость кода (явные типы вместо i64)
- Самодокументирующиеся типы

Статус: Priority 2 теперь 60% (3/5 задач)
-  Error enum
-  Config validation
-  Newtype для ID
-  MessageInfo реструктуризация
-  MessageBuilder pattern

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 01:33:18 +03:00
Mikhail Kilin
bba5cbd22d fixes 2026-01-30 23:55:01 +03:00
Mikhail Kilin
433233d766 commit 2026-01-30 17:26:21 +03:00
Mikhail Kilin
4deb0fbe00 commit 2026-01-30 15:07:13 +03:00
Mikhail Kilin
68a2b7a982 fixes 2026-01-28 11:39:21 +03:00
Mikhail Kilin
051c4a0265 fixes
Some checks failed
CI / Check (pull_request) Has been cancelled
CI / Format (pull_request) Has been cancelled
CI / Clippy (pull_request) Has been cancelled
CI / Build (macos-latest) (pull_request) Has been cancelled
CI / Build (ubuntu-latest) (pull_request) Has been cancelled
CI / Build (windows-latest) (pull_request) Has been cancelled
2026-01-28 01:29:03 +03:00
Mikhail Kilin
f291191577 fixes 2026-01-27 23:29:00 +03:00
Mikhail Kilin
356d2d3064 add account profile 2026-01-27 13:41:29 +03:00
Mikhail Kilin
ac684da820 add draft messages 2026-01-27 12:31:31 +03:00
Mikhail Kilin
dc76e01f3c add find messages 2026-01-27 12:09:05 +03:00
Mikhail Kilin
81dc5b9007 add pinned messages 2026-01-27 04:38:29 +03:00
Mikhail Kilin
4d5625f950 add typings in/out
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 03:59:49 +03:00
Mikhail Kilin
fa749d24c5 fixes 2026-01-24 18:53:35 +03:00
Mikhail Kilin
22c4e17377 fixes 2026-01-24 02:22:47 +03:00
Mikhail Kilin
c18f43664e fixes 2026-01-22 15:26:15 +03:00
Mikhail Kilin
1ef341d907 commit 2026-01-21 21:20:18 +03:00
Mikhail Kilin
32ab1df1fa fixes 2026-01-21 02:27:08 +03:00
Mikhail Kilin
9912ac11bd fixes 2026-01-20 14:54:30 +03:00
Mikhail Kilin
b6d9291864 fixes 2026-01-20 01:00:12 +03:00
Mikhail Kilin
d701464fde init 2026-01-18 11:49:41 +03:00