Skip to content

TW-2912 Allow mobile clear cache#2917

Merged
hoangdat merged 3 commits intomainfrom
TW-2912/Mobile-clear-cache
Mar 27, 2026
Merged

TW-2912 Allow mobile clear cache#2917
hoangdat merged 3 commits intomainfrom
TW-2912/Mobile-clear-cache

Conversation

@tddang-linagora
Copy link
Copy Markdown
Collaborator

@tddang-linagora tddang-linagora commented Mar 16, 2026

Ticket

Resolved

Mobile

storage-mobile.mp4

Responsive

storage-responsive.mov

Summary by CodeRabbit

  • New Features

    • Added a "Data and Storage" settings screen (mobile only) showing phone storage usage, per-category breakdown, progress indicator, available space, mascot header, and a responsive styled container.
    • Clear cache flow with scanning state, confirmation prompt, and success notification.
    • New English localization strings for the above UI (with size/percent placeholders).
  • Bug Fixes

    • Removed duplicate document file-type entry.
  • Tests

    • Added unit tests for storage calculations and file-category classification.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2003045a-fae1-42dc-8eee-ae87d30d8918

📥 Commits

Reviewing files that changed from the base of the PR and between 4156e31 and ca7607d.

⛔ Files ignored due to path filters (1)
  • pubspec.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • assets/l10n/intl_en.arb
  • lib/config/go_routes/go_router.dart
  • lib/di/global/get_it_initializer.dart
  • lib/pages/settings_dashboard/settings/settings.dart
  • pubspec.yaml
✅ Files skipped from review due to trivial changes (2)
  • pubspec.yaml
  • lib/config/go_routes/go_router.dart
🚧 Files skipped from review as they are similar to previous changes (3)
  • lib/di/global/get_it_initializer.dart
  • lib/pages/settings_dashboard/settings/settings.dart
  • assets/l10n/intl_en.arb

Walkthrough

Adds a mobile-only "Data and storage" settings screen and related navigation, localization entries, and assets. Introduces storage scanning and calculation utilities, a storage-scanner service using isolates, GetIt registration for the scanner, UI view/controller/widgets for presenting storage usage and clearing cache, a StorageCategory enum with classification logic, unit tests for calculators and scanner mapping, and a new dependency to query device storage.

Possibly related PRs

  • linagora/twake-on-matrix PR 2887: Touches the same image asset reference and localization file changes.
  • linagora/twake-on-matrix PR 2911: Modifies the same localization key (leaveChatTitle) in assets/l10n/intl_en.arb.
  • linagora/twake-on-matrix PR 2916: Also updates localization ARB files and metadata overlapping with this PR's i18n changes.

Suggested reviewers

  • dab246
  • 9clg6
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete. It only includes Ticket and Resolved sections with video links but is missing Root cause, Solution, Impact description, Test recommendations, and Pre-merge sections. Provide a complete PR description following the template: add Root cause (if applicable), Solution (describing implementation details), Impact description, Test recommendations, and Pre-merge checklist items.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'TW-2912 Allow mobile clear cache' directly matches the changeset, which implements a cache-clearing feature for mobile devices.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch TW-2912/Mobile-clear-cache

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

This PR has been deployed to https://linagora.github.io/twake-on-matrix/2917

@hoangdat
Copy link
Copy Markdown
Member

@coderabbitai please review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 17, 2026

@hoangdat Sure, I'll review the changes in this PR now!

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
lib/pages/settings_dashboard/settings/settings.dart (1)

264-265: Use AppRoutePaths.dataAndStorageFull here instead of another string literal.

This duplicates the new constant from lib/config/go_routes/app_route_paths.dart:7-8, so the navigation target can drift from the router definition.

♻️ Suggested cleanup
+import 'package:fluffychat/config/go_routes/app_route_paths.dart';
+
-        final result = await context.push('/rooms/dataAndStorage');
+        final result = await context.push(AppRoutePaths.dataAndStorageFull);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/pages/settings_dashboard/settings/settings.dart` around lines 264 - 265,
Replace the hard-coded route string used when handling
SettingEnum.dataAndStorage with the route constant
AppRoutePaths.dataAndStorageFull: in the switch branch that currently calls
context.push('/rooms/dataAndStorage') (the SettingEnum.dataAndStorage case),
change the push target to use AppRoutePaths.dataAndStorageFull so navigation
uses the centralized route constant defined in app_route_paths.dart and cannot
drift from the router definition.
lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_view.dart (1)

85-113: Consider using design system colors instead of hardcoded hex values.

The view uses LinagoraSysColors and LinagoraRefColors throughout, but falls back to hardcoded colors for the progress indicator (lines 92-93) and label text (lines 103, 108). Using the design system consistently would improve maintainability and theme support.

Example using design system colors
                 ClipRRect(
                   borderRadius: BorderRadius.circular(999),
                   child: LinearProgressIndicator(
                     value: controller.isScanning
                         ? null
                         : controller.storageUsageRatio,
                     minHeight: 8,
-                    backgroundColor: const Color(0xFFEEEEEE),
-                    color: const Color(0xFF006DE2),
+                    backgroundColor: sysColors.surfaceVariant,
+                    color: sysColors.primary,
                   ),
                 ),
                 const SizedBox(height: 8),
                 Row(
                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                   children: [
                     Text(
                       l10n.twake,
                       style: textTheme.labelSmall?.copyWith(
-                        color: const Color(0xFF636363),
+                        color: refColors.tertiary[30],
                       ),
                     ),
                     Text(
                       l10n.available,
                       style: textTheme.labelSmall?.copyWith(
-                        color: const Color(0xFF636363),
+                        color: refColors.tertiary[30],
                       ),
                     ),
                   ],
                 ),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_view.dart`
around lines 85 - 113, The hardcoded colors used in the progress bar and label
texts should be replaced with the design system colors; update the
LinearProgressIndicator (inside the ClipRRect) to use the appropriate
LinagoraSysColors/LinagoraRefColors token(s) instead of Color(0xFFEEEEEE) and
Color(0xFF006DE2), and replace the label text color usages (the two text widgets
using textTheme.labelSmall) to use the design system color token instead of
Color(0xFF636363); locate these in the ClipRRect -> LinearProgressIndicator and
the two Text widgets (l10n.twake and l10n.available) and swap the hardcoded
Color(...) instances for the corresponding LinagoraSysColors or
LinagoraRefColors constants so theming/maintainability is preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/config/go_routes/go_router.dart`:
- Line 48: The router currently registers the '/rooms/dataAndStorage' route
unconditionally which will crash on web because SettingsDataAndStorage imports
dart:io and package:storage_space; update the GoRouter registration code that
creates the redirect/route for '/rooms/dataAndStorage' to only register (or
return the mobile-specific redirect) when PlatformInfos.isMobile is true (use
the same guard as in settings.dart); if PlatformInfos.isMobile is false, omit
the route or return a safe fallback redirect so web does not resolve the page.

In
`@lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_scanner.dart`:
- Around line 16-26: The current try/catch around the whole directory scan
swallows directory-level errors and returns a partial result; instead, let
directory-level failures surface and only catch per-entity errors inside the
loop: remove or rethrow the outer catch so errors from
Directory(dirPath).list(...) bubble up to the caller (scanDirectory), and wrap
the body that handles each entity (the is! File check,
StorageCategory.fromFile(entity.path) and entity.lengthSync()) in a small
try/catch that on error skips that file (continue) and optionally records/logs
the failure; keep updates to the result map (result[category.name] = ...) only
when the per-file processing succeeds.
- Around line 35-40: The code currently awaits events.first twice (creating a
race where the second message can be lost); replace the dual await on the
broadcast stream with a StreamQueue to keep a single listener alive across both
isolate messages: construct a StreamQueue from receivePort.asBroadcastStream()
(e.g. final queue = StreamQueue(events)), then await queue.next for the SendPort
(assign to isolateSendPort) and await queue.next again for the Map (convert to
Map<String,int>), and finally cancel the queue and close the ReceivePort; update
usages around receivePort/events/isolateSendPort to use this queue-based
sequencing so no messages are dropped.

In
`@lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage.dart`:
- Around line 76-87: The clear-cache routine currently deletes the whole
temporary directory and can remove files in use by the preview flow; update
_clearCacheDir to avoid disrupting active previews by either (A) prompting the
user with a confirmation/warning before clearing (add a UI confirmation call
from the settings flow that explains active previews may be affected), or (B)
skipping currently-used preview files by integrating a usage check from the
preview logic: expose a method like isPreviewFileInUse(String path) from the
preview mixin/manager (refer to handle_download_and_preview_file_mixin and its
tempDirPath usage) and during _clearCacheDir iteration only delete files for
which isPreviewFileInUse returns false (log/skipped files). Also ensure
_getCacheCategories and any cache-scan logic account for skipped files so sizes
remain accurate when files are excluded. Implement one of these fixes and add a
short user-facing note in the settings UI if you choose the skip behavior.
- Around line 108-127: The _clearCacheDir method shows
l10n.cacheClearedSuccessfully even when deletion fails because exceptions are
only logged; change the flow to track success and only show the snack on
success: inside _clearCacheDir (function name) introduce a local bool (e.g.,
success = true) set to false in the catch block where Logs().e(...) is called,
or rethrow/return early on failure, and move the TwakeSnackBar.show(...) call so
it only runs when success is true and context.mounted; ensure setState still
runs as needed only after a successful clear or adjust state updates to reflect
failure appropriately.

---

Nitpick comments:
In
`@lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_view.dart`:
- Around line 85-113: The hardcoded colors used in the progress bar and label
texts should be replaced with the design system colors; update the
LinearProgressIndicator (inside the ClipRRect) to use the appropriate
LinagoraSysColors/LinagoraRefColors token(s) instead of Color(0xFFEEEEEE) and
Color(0xFF006DE2), and replace the label text color usages (the two text widgets
using textTheme.labelSmall) to use the design system color token instead of
Color(0xFF636363); locate these in the ClipRRect -> LinearProgressIndicator and
the two Text widgets (l10n.twake and l10n.available) and swap the hardcoded
Color(...) instances for the corresponding LinagoraSysColors or
LinagoraRefColors constants so theming/maintainability is preserved.

In `@lib/pages/settings_dashboard/settings/settings.dart`:
- Around line 264-265: Replace the hard-coded route string used when handling
SettingEnum.dataAndStorage with the route constant
AppRoutePaths.dataAndStorageFull: in the switch branch that currently calls
context.push('/rooms/dataAndStorage') (the SettingEnum.dataAndStorage case),
change the push target to use AppRoutePaths.dataAndStorageFull so navigation
uses the centralized route constant defined in app_route_paths.dart and cannot
drift from the router definition.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 174cd193-cc80-4f03-964d-8aa636841ec6

📥 Commits

Reviewing files that changed from the base of the PR and between 574496c and beb84e7.

⛔ Files ignored due to path filters (1)
  • pubspec.lock is excluded by !**/*.lock
📒 Files selected for processing (15)
  • assets/l10n/intl_en.arb
  • lib/config/go_routes/app_route_paths.dart
  • lib/config/go_routes/go_router.dart
  • lib/domain/model/preview_file/supported_preview_file_types.dart
  • lib/pages/settings_dashboard/settings/settings.dart
  • lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage.dart
  • lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_calculator.dart
  • lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_constants.dart
  • lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_scanner.dart
  • lib/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_view.dart
  • lib/pages/settings_dashboard/settings_style/settings_style_twake_view.dart
  • lib/presentation/enum/settings/settings_enum.dart
  • pubspec.yaml
  • test/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_calculator_test.dart
  • test/pages/settings_dashboard/settings_data_and_storage/settings_data_and_storage_scanner_test.dart

@hoangdat
Copy link
Copy Markdown
Member

hoangdat commented Mar 17, 2026

@tddang-linagora we should to calculate the size of files in ApplicationSupport or ApplicationDocuments.
Moreover, if we prevent user clear database, we should find the way to filter it out and still remove other things in ApplicationSupport or ApplicationDocuments.

Comment on lines +16 to +27
static String formatBytes(double bytes) {
if (bytes >= 1024 * 1024 * 1024) {
return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
}
if (bytes >= 1024 * 1024) {
return '${(bytes / (1024 * 1024)).toStringAsFixed(0)} MB';
}
if (bytes >= 1024) {
return '${(bytes / 1024).toStringAsFixed(0)} KB';
}
return '${bytes.toStringAsFixed(0)} B';
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we dont have any 3rd party lib for this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To get the right format "number{space}unit"? No.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be in a seperated Util class i think
And comments to make it understandable by people who don't understand how it works

@tddang-linagora
Copy link
Copy Markdown
Collaborator Author

@tddang-linagora we should to calculate the size of files in ApplicationSupport or ApplicationDocuments. Moreover, if we prevent user clear database, we should find the way to filter it out and still remove other things in ApplicationSupport or ApplicationDocuments.

We don't use ApplicationSupport to save cache. Every cache saved in ApplicationDocuments is inside a directory named by the eventId it belongs. If we don't know the cached eventId, we cannot clear the cache in this directory. Nuking it like "Temporary" directory will break the app, force the user to re-login.

@hoangdat
Copy link
Copy Markdown
Member

@tddang-linagora please rebase

nqhhdev
nqhhdev previously approved these changes Mar 24, 2026
@tddang-linagora tddang-linagora force-pushed the TW-2912/Mobile-clear-cache branch from 02aa8d7 to 7023ad1 Compare March 24, 2026 04:30
@tddang-linagora tddang-linagora changed the base branch from sprint/march26 to main March 24, 2026 04:30
@tddang-linagora tddang-linagora dismissed nqhhdev’s stale review March 24, 2026 04:30

The base branch was changed.

@hoangdat hoangdat merged commit a65ee53 into main Mar 27, 2026
9 checks passed
@hoangdat hoangdat deleted the TW-2912/Mobile-clear-cache branch March 27, 2026 09:36
github-actions bot added a commit that referenced this pull request Mar 27, 2026
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.

4 participants