Commit Graph

137 Commits

Author SHA1 Message Date
Mikhail Kilin
ee416dff45 docs: update CONTEXT.md with refactoring progress 2026-02-03 16:33:34 +03:00
Mikhail Kilin
3edbaf2c2b refactor: extract input handlers into separate functions
Упрощение функции handle() в main_input.rs путём извлечения
обработчиков режимов в отдельные функции.

Извлечённые функции:
- handle_profile_mode() - режим профиля с модалкой выхода (~114 строк)
- handle_message_search_mode() - поиск по сообщениям (~73 строки)
- handle_pinned_mode() - закреплённые сообщения (~34 строки)
- handle_reaction_picker_mode() - выбор реакции (~79 строк)
- handle_delete_confirmation() - подтверждение удаления (~53 строки)
- handle_forward_mode() - выбор чата для пересылки (~48 строк)
- handle_chat_search_mode() - поиск по чатам (~32 строки)
- handle_escape_key() - обработка Esc (~25 строк)
- handle_message_selection() - выбор сообщения (~85 строк)

Итого извлечено: ~543 строки из основной функции handle()

Результат:
- handle() сократилась с 891 до ~350 строк (на 61%)
- Каждый режим теперь изолирован и легко тестируется
- Улучшена читаемость и maintainability кода
- Все тесты проходят успешно

Также:
- Обновлён tdlib-rs с 1.1 на 1.2.0
2026-02-03 16:32:26 +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
3c8fec7ca6 refactor: integrate validation utils and complete refactoring #1
Завершена интеграция validation utils во всех местах проверки user input:

Changes:
- src/utils/mod.rs: раскомментирован экспорт validation::*
- src/input/auth.rs: 3 замены .is_empty() -> is_non_empty()
  * phone_input validation (line 18)
  * code_input validation (line 50)
  * password_input validation (line 82)
- src/input/main_input.rs: 1 замена для message_input (line 484)
- src/main.rs: заменён последний прямой timeout на with_timeout_ignore

Documentation:
- REFACTORING_OPPORTUNITIES.md: обновлён статус категории #1
  * Отмечено как "ПОЛНОСТЬЮ ЗАВЕРШЕНО" (2026-02-02)
  * Добавлены метрики: 100% покрытие retry utils, 0 прямых timeouts
  * Обновлён план выполнения: фаза 1 завершена
- CONTEXT.md: добавлен раздел об интеграции validation utils

Result:
 Категория #1 (Дублирование кода) - ПОЛНОСТЬЮ ЗАВЕРШЕНА!
  - retry utils: 100% покрытие (8+ мест)
  - modal_handler: 2 диалога
  - validation: 4 места

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 17:38:49 +03:00
Mikhail Kilin
0768283e8a refactor: eliminate code duplication - extract helpers and use retry utils
Extracted duplicate code and unified timeout handling across the codebase.

Changes:
- Extracted open_chat_and_load_data() function (eliminates 52 lines of duplication)
- Replaced manual y/н/Enter handling with handle_yes_no() from modal_handler (2 places)
- Replaced 7 direct tokio::time::timeout calls with retry utils (auth, main_input, main)
- Added with_timeout_ignore() for non-critical operations
- Fixed modal_handler.rs bug: corrected Russian 'y' key (д → н)
- Removed unused imports in handlers/mod.rs and utils/mod.rs

Impact:
- main_input.rs: 1164 → 958 lines (-206 lines, -18%)
- Code duplication: 52 lines eliminated
- Direct timeout calls: 7 → 1 (-86%)
- DRY principle applied throughout

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 14:20:33 +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
0cd477f294 Merge pull request 'refactor: complete UI components - implement message_bubble.rs' (#17) from add_tests into main
Some checks failed
CI / Check (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Build (macos-latest) (push) Has been cancelled
CI / Build (ubuntu-latest) (push) Has been cancelled
CI / Build (windows-latest) (push) Has been cancelled
Reviewed-on: #17
2026-02-02 00:45:42 +00:00
Mikhail Kilin
ed5a4f9c72 refactor: complete UI components - implement message_bubble.rs
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
Finalize Priority 3 UI components refactoring (5/5 complete):

- Create message_bubble.rs (437 lines) with 3 rendering functions:
  * render_date_separator() - centered date separators
  * render_sender_header() - sender headers (incoming/outgoing)
  * render_message_bubble() - messages with forward/reply/reactions

- Simplify messages.rs by removing ~300 lines:
  * Use message_grouping::group_messages() for logic
  * Use UI components for rendering
  * Cleaner separation of concerns

- Update module exports and main.rs

All 196 tests passing (188 tests + 8 benchmarks). No regressions.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 03:41:03 +03:00
8855a07ccd Merge pull request 'add_tests' (#16) from add_tests into main
Some checks failed
CI / Check (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Build (macos-latest) (push) Has been cancelled
CI / Build (ubuntu-latest) (push) Has been cancelled
CI / Build (windows-latest) (push) Has been cancelled
Reviewed-on: #16
2026-02-02 00:19:58 +00:00
Mikhail Kilin
2980e52113 commit
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-02-02 03:18:55 +03:00
Mikhail Kilin
9465f067fe commit 2026-02-02 02:46:26 +03:00
Mikhail Kilin
5c92c059c9 fixes 2026-02-02 02:32:02 +03:00
Mikhail Kilin
dd4981d216 test: add comprehensive input navigation tests
Added 13 integration tests for keyboard navigation:

Arrow Keys Navigation:
- test_arrow_navigation_in_chat_list: Up/Down arrows, circular wrapping
- test_vim_navigation_in_chat_list: j/k vim-style navigation
- test_russian_keyboard_navigation: Russian layout (о/р) support
- test_enter_opens_chat: Enter to open selected chat
- test_esc_closes_chat: Esc to close open chat

Cursor Navigation in Input:
- test_cursor_navigation_in_input: Left/Right arrow keys
- test_home_end_in_input: Home/End keys
- test_backspace_with_cursor: Backspace at different positions
- test_insert_char_at_cursor_position: Insert char in middle

Message Navigation:
- test_up_arrow_selects_last_message_when_input_empty: Up arrow for message selection

Additional:
- test_circular_navigation_optional: Circular list navigation

These tests verify that the navigation functionality works correctly
through the main_input handler, protecting against future refactoring
that might break keyboard input.

All tests compile and verify actual input handling via handle_main_input().

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 00:39:47 +03:00
Mikhail Kilin
4d9d76ed23 refactor: prepare handlers structure for future input refactoring
Preparation for splitting large input file (#2):
- Created src/input/handlers/ structure (7 modules)
  - clipboard.rs (~100 lines) - clipboard operations extracted
  - global.rs (~90 lines) - global commands (Ctrl+R/S/P/F) extracted
  - Stubs: profile.rs, search.rs, modal.rs, messages.rs, chat_list.rs
- main_input.rs remains monolithic (1139 lines)
  - Attempted full migration broke navigation - rolled back
  - Handlers remain as preparation for gradual migration

Updated documentation:
- REFACTORING_OPPORTUNITIES.md: #2.1 status updated
- CONTEXT.md: Added lesson about careful refactoring

Lesson learned: Critical input logic requires careful step-by-step
refactoring with functionality verification after each step.

Tests: 563 passed, 0 failed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 00:08:56 +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
e690acfb09 test: complete Phase 4 testing - utils tests and performance benchmarks
Added 9 new unit tests for utils/formatting.rs functions:
- format_date: 4 tests (today, yesterday, old, epoch)
- format_was_online: 5 tests (just now, minutes/hours/days ago, very old)

Created 3 performance benchmark files using criterion:
- benches/group_messages.rs - message grouping benchmarks
- benches/formatting.rs - timestamp/date formatting benchmarks
- benches/format_markdown.rs - markdown parsing benchmarks

Updated documentation:
- CONTEXT.md: added Phase 4.1 (Utils) and 4.2 (Benchmarks) completion
- Total coverage: 188 tests + 8 benchmarks = 196 tests (100%)

All 565 tests passing with 100% success rate.
2026-02-01 23:04:43 +03:00
Mikhail Kilin
c6beea5608 refactor: create timeout/retry utilities to reduce code duplication (P1.1)
Created new utility modules to eliminate repeated timeout/retry patterns:
- src/utils/retry.rs: with_timeout() and with_timeout_msg() helpers
- src/utils/formatting.rs: timestamp formatting utilities (from utils.rs)
- src/utils/tdlib.rs: TDLib log configuration utilities (from utils.rs)

Refactored src/input/main_input.rs:
- Replaced 18+ instances of timeout(Duration, op).await pattern
- Simplified error handling from nested Ok(Ok(...))/Ok(Err(...))/Err(...)
  to cleaner Ok(...)/Err(...) with custom timeout messages
- Added type annotations for compiler type inference

Benefits:
- Reduced code duplication from ~20 instances to 2 utility functions
- Cleaner, more readable error handling
- Easier to maintain timeout logic in one place
- All 59 tests passing

Progress: REFACTORING_OPPORTUNITIES.md #1 (Дублирование кода) - Частично выполнено

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 19:56:33 +03:00
9cc63952f4 Merge pull request 'add_tests' (#15) from add_tests into main
Some checks failed
CI / Check (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Build (macos-latest) (push) Has been cancelled
CI / Build (ubuntu-latest) (push) Has been cancelled
CI / Build (windows-latest) (push) Has been cancelled
Reviewed-on: #15
2026-02-01 15:59:43 +00: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
f1a26b906c style: use _chat_id instead of let _ = chat_id
More idiomatic way to mark unused parameter.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:48:44 +03:00
Mikhail Kilin
c27d027ebf chore: remove dead code and unnecessary allow(dead_code) attributes
Cleaned up warnings by removing unused code:
- Removed unused format_timestamp() function from utils.rs
- Removed unused len() method from LruCache
- Removed unused date field from ForwardInfo struct
- Removed unnecessary #[allow(dead_code)] attributes from:
  * AuthState enum (actually used)
  * ChatInfo struct (actually used)
  * TdClient impl block (actually used)

This reduces code noise and makes real warnings more visible.

Changes:
- 20 lines removed
- 1 line added
- 6 files changed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:47:51 +03:00
0a4ab1b40d Merge pull request 'add_tests' (#14) from add_tests into main
Some checks failed
CI / Check (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Build (macos-latest) (push) Has been cancelled
CI / Build (ubuntu-latest) (push) Has been cancelled
CI / Build (windows-latest) (push) Has been cancelled
Reviewed-on: #14
2026-01-31 23:42:29 +00:00
Mikhail Kilin
09c5c5674e feat: add structured logging with tracing (P5.17)
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
Replaced eprintln! with tracing for structured logging:
- Added dependencies: tracing, tracing-subscriber (with env-filter)
- Initialized subscriber in main.rs with default warn level
- Replaced all eprintln! calls in src/config.rs with tracing macros:
  * warn!() for warnings (4 occurrences)
  * error!() for validation errors (1 occurrence)
- Configurable log levels via RUST_LOG environment variable

Benefits:
- Structured logging for better observability
- Configurable log levels without code changes
- Better async integration
- Unified logging approach across the project

🎉🎉🎉 REFACTORING COMPLETE: All 20/20 tasks done (100%)! 🎉🎉🎉

Priority 5: 3/3 tasks  COMPLETE
Total progress: 20/20 tasks (100%)  COMPLETE

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:29:08 +03:00
Mikhail Kilin
67739583f3 refactor: generalize LruCache to support any key type (P5.16)
Made LruCache generic over key type K, not just UserId:
- LruCache<V> → LruCache<K, V>
- Added trait bounds: K: Eq + Hash + Clone + Copy
- Updated UserCache field types:
  * user_usernames: LruCache<UserId, String>
  * user_names: LruCache<UserId, String>
  * user_statuses: LruCache<UserId, UserOnlineStatus>

Benefits:
- Reusable cache implementation for any key types
- Type-safe caching
- No additional dependencies

Progress: Priority 5: 2/3 tasks, Total: 18/20 (90%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:26:03 +03:00
Mikhail Kilin
56bddabbe1 feat: add optional feature flags for clipboard and url-open (P5.15)
Implemented feature flags to make dependencies optional:
- clipboard feature: controls arboard dependency
- url-open feature: controls open dependency
- Both enabled by default for backward compatibility

Changes:
- Cargo.toml: Added [features] section with optional deps
- src/input/main_input.rs: Conditional compilation for open::that() and copy_to_clipboard()
- tests/copy.rs: Clipboard tests only compile with feature enabled
- Graceful degradation: user-friendly error messages when features disabled

Benefits:
- Smaller binary size when features disabled
- Modular functionality
- Better platform compatibility

Progress: Priority 5: 1/3 tasks, Total: 17/20 (85%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:23:17 +03:00
Mikhail Kilin
38b18e35ea docs: P4.14 async/await consistency - already complete! (94% total)
Verified that P4.14 - Async/await consistency is already implemented.

**Verification Results**:
 No blocking calls in async context:
- std::fs used only in Config::load() at startup (before async runtime)
- std::thread::sleep not found anywhere

 Async-friendly APIs used correctly:
- tokio::time::sleep in messages.rs for delays
- tokio::time::timeout in auth.rs, main_input.rs, main.rs
- All async operations are non-blocking

 Config operations properly organized:
- Config::load() called once in main.rs:36 BEFORE async runtime
- Synchronous initialization, not a problem

**Conclusion**: Code is already async-clean! No blocking operations in async
context. P4.14 was already completed during development.

**Progress**:
- Priority 4: 4/4 tasks COMPLETE! 🎉🎉🎉
- Total: 16/17 tasks complete (94%)

**Remaining**:
- Priority 5: Feature flags, LRU generics, CLI args (optional improvements)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:10:38 +03:00
20f1c470c4 Merge pull request 'add_tests' (#13) from add_tests into main
Some checks failed
CI / Format (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Build (macos-latest) (push) Has been cancelled
CI / Build (ubuntu-latest) (push) Has been cancelled
CI / Build (windows-latest) (push) Has been cancelled
CI / Check (push) Has been cancelled
Reviewed-on: #13
2026-01-31 23:06:22 +00:00
Mikhail Kilin
a177ab66c6 docs: update roadmap - P4.11 and P4.13 complete (88% total)
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
Updated REFACTORING_ROADMAP.md to reflect completion of P4.11 and P4.13:

**P4.11 - Unit tests**: ЗАВЕРШЕНО 100%
- Added 9 unit tests in src/utils.rs
- Coverage for time/date formatting functions
- All edge cases tested (timezones, midnight wrap, fallback)
- Total: 54 unit tests pass (was 45, +9)

**P4.13 - Config validation**: ЗАВЕРШЕНО 100%
- Validation was already implemented (config.rs:344-389)
- Added 15 comprehensive tests for full coverage
- Total: 23 config tests pass (8 existing + 15 new)

**Progress**:
- Priority 4: 3/4 tasks complete (75%)
- Total: 15/17 tasks complete (88%)

**Remaining**:
- P4.14 — Async/await consistency (last Priority 4 task)
- Priority 5: 0/3 tasks

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 02:02:09 +03:00
Mikhail Kilin
5897f6deaa test: add unit tests for utils time formatting (P4.11)
Added 9 unit tests for src/utils.rs to cover time/date formatting logic.

**Tests added**:
-  format_timestamp_with_tz with positive offset (+03:00)
-  format_timestamp_with_tz with negative offset (-05:00)
-  format_timestamp_with_tz with zero offset (UTC)
-  format_timestamp_with_tz midnight wrap (23:00 + 2h = 01:00)
-  format_timestamp_with_tz invalid timezone (fallback to +03:00)
-  get_day - extract day from timestamp
-  get_day_grouping - messages on same day
-  format_datetime - full date and time with MSK
-  parse_timezone_offset via public API

**Coverage**:
- format_timestamp_with_tz() - all edge cases
- parse_timezone_offset() - tested indirectly (private fn)
- get_day() - day calculation and grouping
- format_datetime() - partial coverage

**Result**: 54 unit tests pass (was 45, +9 new)

Related: REFACTORING_ROADMAP.md P4.11

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 01:59:47 +03:00
Mikhail Kilin
99b3b368b9 test: add comprehensive validation tests for Config (P4.13)
Added 15 tests for config validation to ensure invalid values are caught.

**What's tested**:
-  Valid default config
-  Timezone validation (must start with + or -)
-  Valid positive/negative timezones (+09:00, -05:00)
-  Invalid timezone without sign
-  Color validation (all 18 standard ratatui colors)
-  Invalid colors (rainbow, purple, pink)
-  Case-insensitive color parsing (RED, Green, YELLOW)
-  parse_color() for all variants (standard, light, gray/grey)
-  Fallback to White for invalid colors

**Coverage**:
- Config::validate() - timezone and color checks
- Config::parse_color() - all color parsing logic
- All 23 config tests pass (8 existing + 15 new)

**Note**: Validation was already implemented in config.rs:344-389
and called in load():450-456. This PR adds comprehensive test coverage.

Related: REFACTORING_ROADMAP.md P4.13

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 01:47:29 +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
c5078a54f4 docs: update roadmap - P4.12 Rustdoc complete (76% total)
Updated REFACTORING_ROADMAP.md to reflect completion of P4.12:
- Rustdoc documentation: 100% complete
- 7 modules documented with comprehensive examples
- 34 doctests added (30 ignored for async, 4 compiled)
- +900 lines of documentation
- Progress: Priority 4: 1/4, Total: 13/17 tasks (76%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 01:08:42 +03:00
Mikhail Kilin
93e43a59d0 docs: complete rustdoc documentation for all public APIs (P4.12)
Added comprehensive rustdoc documentation for all TDLib modules,
configuration, and utility functions.

TDLib modules documented:
- src/tdlib/auth.rs - AuthManager, AuthState (6 doctests)
- src/tdlib/chats.rs - ChatManager (8 doctests)
- src/tdlib/messages.rs - MessageManager (14 methods, 6 doctests)
- src/tdlib/reactions.rs - ReactionManager (3 doctests)
- src/tdlib/users.rs - UserCache, LruCache (2 doctests)

Configuration and utilities:
- src/config.rs - Config, ColorsConfig, GeneralConfig (4 doctests)
- src/formatting.rs - format_text_with_entities (2 doctests)

Documentation includes:
- Detailed descriptions of all public structs and methods
- Usage examples with code snippets
- Parameter and return value documentation
- Notes about async behavior and edge cases
- Cross-references between related functions

Total: 34 doctests (30 ignored for async, 4 compiled)
All 464 unit tests passing 

Priority 4.12 (Rustdoc) - 100% complete

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 01:03:30 +03:00
Mikhail Kilin
326bf6cc46 fix: preserve reply_to info when editing messages
When editing a message that has a reply, convert_message() creates
a new ReplyInfo with sender_name="Unknown" and text="...". This was
causing the reply info to be lost after editing.

Solution: Save the old reply_to from the original message before
replacement, and restore it if the new message has "Unknown" reply info.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 00:31:38 +03:00
Mikhail Kilin
426af96941 docs: update CONTEXT.md with Priority 3 completion
- Document P3.10 Hotkey mapping completion (9 tests)
- Document P3.9 Message grouping completion (7 tests)
- Document P4.12 Rustdoc partial progress (30%)
- Update Priority 3 status: 100% (4/4 tasks) complete
- All 464 tests passing

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 00:25:57 +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
0ae8a2fb88 fix: update UI after editing message
Issue: Message edits worked on server (other users saw changes),
but local UI didn't update - edited text wasn't visible.

Root cause: Code was updating individual fields instead of replacing
the whole message, and wasn't triggering UI redraw.

Solution:
- Replace entire message with edited_msg (not individual fields)
- Set needs_redraw = true to trigger UI update
- Remove debug logging

Now edited messages immediately appear in local UI.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 00:16:47 +03:00
Mikhail Kilin
fe924faff4 debug: add logging for edit_message to diagnose 'Message not found' error
- Log chat_id, message_id, text length before calling edit_message_text
- Log success or exact TDLib error
- This will help identify the root cause

Temporary debug commit to investigate issue.
2026-02-01 00:08:00 +03:00
Mikhail Kilin
2b18d5a481 fix: support UTF-8 characters in hotkey matching
- Fix key_matches() to use chars().count() instead of len()
- This correctly handles multi-byte UTF-8 characters (russian layout)
- All 9 config tests now pass (was 7/9, now 9/9)

Fixes:
- test_hotkeys_matches_char_keys
- test_hotkeys_matches_russian_vim_keys

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-01 00:00:00 +03:00
Mikhail Kilin
1b70b12799 docs: update CONTEXT.md with refactoring progress
- Document P3.9 (Message Grouping) completion
- Document P3.10 (Hotkey Mapping) completion
- Document P4.12 (Rustdoc) partial completion
- Priority 3: 100% complete! 🎉
- Overall refactoring: 12/17 tasks (71%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 23:53:58 +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
1629c0fc6a refactor: add hotkey mapping configuration (P3.10)
- Add HotkeysConfig structure in src/config.rs
- Implement matches(key: KeyCode, action: &str) method
- Support for 10 configurable hotkeys:
  * Navigation: up, down, left, right (vim + russian + arrows)
  * Actions: reply, forward, delete, copy, react, profile
- Add support for char keys and special keys (Up, Down, Delete, etc)
- Add default values for all hotkeys (english + russian layouts)
- Write 9 unit tests (all passing)
- Add rustdoc documentation with examples
- Update REFACTORING_ROADMAP.md (Priority 3: 4/4 tasks, 100%)
- Update CONTEXT.md with implementation details
- Overall refactoring progress: 12/17 tasks (71%)

Priority 3 is now 100% complete! 🎉

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 23:51:10 +03:00
Mikhail Kilin
0ca3da54e7 refactor: extract message grouping logic (P3.9)
- Create src/message_grouping.rs module (255 lines)
- Add MessageGroup enum (DateSeparator, SenderHeader, Message)
- Add group_messages() function for date/sender grouping
- Write 5 unit tests (all passing)
- Add full rustdoc documentation with examples
- Update REFACTORING_ROADMAP.md (Priority 3: 3/4 tasks, 75%)
- Update CONTEXT.md with refactoring progress
- Overall refactoring progress: 11/17 tasks (65%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 23:30:41 +03:00
Mikhail Kilin
c5896b7f14 tests 2026-01-31 23:02:53 +03:00
Mikhail Kilin
af3c36b9a1 docs: обновлён CONTEXT.md с описанием исправлений
Добавлено описание исправлений от 31 января (вечер):
- Исправление отображения новых сообщений
- Исправление редактирования
- Исправление reply
- Удаление отладочных логов
2026-01-31 18:38:47 +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
1bf9b3d703 docs: celebrate Priority 2 completion! 🎉
Обновлена документация для отражения ПОЛНОГО ЗАВЕРШЕНИЯ Priority 2
(все 5 задач выполнены на 100%).

Изменения:
- CONTEXT.md: отмечен Priority 2 как завершённый (100%, 5/5)
- CONTEXT.md: добавлена секция P2.7 MessageBuilder
- CONTEXT.md: обновлён раздел "Последние обновления" с празднованием
- CONTEXT.md: добавлены итоги Priority 2
- CONTEXT.md: обновлён технический долг
- REFACTORING_ROADMAP.md: отмечен P2.7 как завершённый
- REFACTORING_ROADMAP.md: добавлена детальная секция MessageBuilder
- REFACTORING_ROADMAP.md: обновлён общий прогресс (47%, 8/17 задач)

🏆 ИТОГИ PRIORITY 2 (100%):
 P2.5 — Error enum
 P2.3 — Config validation
 P2.4 — Newtype для ID
 P2.6 — MessageInfo реструктуризация
 P2.7 — MessageBuilder pattern

Статус: Priority 2 ПОЛНОСТЬЮ ЗАВЕРШЁН! 🎊
Следующий этап: Priority 3 (UI компоненты, форматирование)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 02:03:59 +03:00
Mikhail Kilin
c42976c358 refactor: add MessageBuilder with fluent API (P2.7)
Добавлен MessageBuilder для удобного создания MessageInfo с помощью
fluent API вместо вызова конструктора с 14 параметрами.

Изменения:
- Создан MessageBuilder в tdlib/types.rs с fluent API
- Реализованы методы:
  * new(id) - создание builder с обязательным ID
  * sender_name(), text(), entities(), date(), edit_date()
  * outgoing(), incoming(), read(), unread(), edited()
  * editable(), deletable_for_self(), deletable_for_all()
  * reply_to(), forward_from(), reactions(), add_reaction()
  * build() - финальное создание MessageInfo
- Обновлён convert_message() для использования builder
- Добавлен экспорт MessageBuilder в tdlib/mod.rs
- Добавлены 6 unit тестов демонстрирующих fluent API

Преимущества:
- Более читабельный код создания сообщений
- Самодокументирующийся API
- Гибкость в установке опциональных полей
- Легче добавлять новые поля в будущем

Пример использования:
```rust
let message = MessageBuilder::new(MessageId::new(123))
    .sender_name("Alice")
    .text("Hello, world!")
    .outgoing()
    .read()
    .build();
```

Статус: Priority 2 ЗАВЕРШЁН 100% (5/5 задач)! 🎉
-  Error enum
-  Config validation
-  Newtype для ID
-  MessageInfo реструктуризация
-  MessageBuilder pattern

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 02:02:07 +03:00
Mikhail Kilin
5709fab9c3 docs: update documentation for P2.6 completion
Обновлена документация для отражения завершения задачи P2.6
(реструктуризация MessageInfo).

Изменения:
- CONTEXT.md: добавлен P2.6 в завершённые задачи Priority 2
- CONTEXT.md: обновлён статус Priority 2 (80%, 4/5 задач)
- CONTEXT.md: добавлена детальная секция "Последние обновления"
- CONTEXT.md: обновлён технический долг
- REFACTORING_ROADMAP.md: отмечен P2.6 как завершённый
- REFACTORING_ROADMAP.md: обновлён общий прогресс (41%, 7/17 задач)
- REFACTORING_ROADMAP.md: добавлено "Что сделано" для P2.6

Статус: Priority 2 - 80% (4/5 задач)
Осталась последняя задача: P2.7 MessageBuilder pattern

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 01:47:51 +03:00