Skip to content

V- Modal AI: Visual Video / Image Search - Flutter Video SDK

Release Flutter SDK from 1e4c9d590661782c733b6119a1acf76cb6b79670

vmodal-release-app2af9c7cae2a0
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 6cacb94..e8d5666 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -6,9 +6,9 @@ description = "Internal implementation plans contain documented credential-patte
paths = ['''(^|/)uinterface/sdk_flutter/docs/dev_plan(_step)?\.md$''', '''^docs/dev_plan(_step)?\.md$''']
[[allowlists]]
-description = "Unpublished Flutter task plan contains a documented credential-pattern example"
+description = "Unpublished Flutter task plans contain documented credential-pattern examples"
targetRules = ["generic-api-key"]
-paths = ['''^docs/todo/dev_plan\.md$''']
+paths = ['''^docs/todo/(done/)?dev_plan\.md$''']
[[allowlists]]
description = "Generated Flutter build outputs are excluded from source secret detection"
diff --git a/.pubignore b/.pubignore
index 879fc6f..f573e5b 100644
--- a/.pubignore
+++ b/.pubignore
@@ -7,7 +7,7 @@ coverage/
docs/todo/
docs/dev_plan.md
docs/dev_plan_step.md
-docs_sdk/
+docs/
docs.py
release/
test/routes_gen_test.dart
@@ -17,3 +17,8 @@ tool/routes_manifest.dart
utils.py
SOURCE_MANIFEST.sha256
*.iml
+!lib/
+!lib/**
+AGENTS.md
+README_PRIVATE.md
+example/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b3e752..4548748 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,21 @@
+----------------------------------------------------------
+----------------------------------------------------------
+date: 2026-09-30
+commit_hash: pending
+title: Harden the account-scoped Framebase example
+summary:
+ - Added opaque server-issued library scopes, typed credential failures with bounded recovery, and versioned in-memory credential contracts.
+ - Added typed video search hits, stable asset matching, lifecycle cancellation, and explicit local/cloud/index retention behavior.
+ - Added previewed full-library deletion, immutable production pin guidance, and regression coverage for the complete user lifecycle.
+
+----------------------------------------------------------
+date: 2026-09-27
+commit_hash: pending
+title: Repair pub.dev Dartdoc archive
+summary:
+ - Explicitly retain the package public library tree during publication.
+ - Verify the uploaded pub.dev archive contains the Dart entrypoint.
+
----------------------------------------------------------
date: 2026-09-24
commit_hash: pending
@@ -22,6 +40,12 @@ summary:
- Restored the omitted Sightline application sources in the public SDK export.
- Added dependency, analysis, formatting, test, and manifest coverage for example 04.
+## 1.2.3
+
+- Reissued the package after explicitly retaining the public `lib/` tree in
+ the publish manifest, so pub.dev can discover and document
+ `vmodal_sdk_flutter`.
+
## 1.2.2
- Configured the public pub.dev workflow to initialize GitHub Actions OIDC
diff --git a/README.md b/README.md
index a4ff864..b6bd470 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,7 @@
|---|---|---|
| 💬 | **Discord support** | [Join the V-Modal AI Discord](https://discord.gg/XGxgBQqkaY) |
| 📚 | **SDK documentation** | [Read the Flutter SDK reference](https://v-modal.github.io/vmodal_sdk_flutter/) |
+| 📦 | **pub.dev package** | [Install vmodal_sdk_flutter](https://pub.dev/packages/vmodal_sdk_flutter) |
| 📱 | **Demo app and community** | [Visit r/v_modal on Reddit](https://www.reddit.com/r/v_modal/) |
| 🔑 | **Get an API key** | [Request a VModal API key](https://v-modal.com/page/contact.ts) |
@@ -82,16 +83,30 @@ next command I should run.
-The public package source is available on GitHub. Add it to your app:
+For production, prefer the exact published pub.dev version when it is
+available:
+
+```yaml
+dependencies:
+ vmodal_sdk_flutter: 1.2.3
+```
+
+For a Git install, pin an immutable public revision. Use the version tag only
+after a pub.dev release has actually created it:
```yaml
dependencies:
vmodal_sdk_flutter:
git:
url: https://github.com/v-modal/vmodal_sdk_flutter.git
- ref: main
+ ref: v1.2.3
```
+The default source-only public workflow does not create that tag. For such a
+release, replace the `ref` above with the full 40-character commit SHA from the
+public repository. The `main` branch is suitable for evaluation and development
+only; it is not a production pin.
+
Then run:
```bash
@@ -140,11 +155,20 @@ final results = await favorites.search(
);
print('${results.cntActual} moments found');
-for (final moment in results.data) {
- print(moment);
+for (final hit in results.videoHits) {
+ print(
+ '${hit.assetId ?? 'legacy asset'} · ${hit.fileName ?? 'unnamed'} · '
+ '${hit.playbackOffsetMs ?? 'unknown'} ms · distance ${hit.distance}',
+ );
}
```
+`VideoSearchHit.distance` is the raw lower-is-better distance; it is not a
+similarity or confidence score. `assetId` remains `null` when an older server
+does not return `asset_id`—the SDK never invents stable identity from a
+filename, path, frame identifier, or timestamp. The original entries remain
+available through `results.data` and each hit's `raw` map for compatibility.
+
Collection access is key-scoped. A logical name copied from another account or
environment can return HTTP 404 even when the search route is healthy. Use
`ScopedSearchOptions(versionLancedb: version)` when your application tracks a
diff --git a/RELEASE_METADATA b/RELEASE_METADATA
index dfbe2e1..094287c 100644
--- a/RELEASE_METADATA
+++ b/RELEASE_METADATA
@@ -1 +1 @@
-Source-vmx-api: 417ffba7190934c2883bbaee4266d1aece2645c9
+Source-vmx-api: 1e4c9d590661782c733b6119a1acf76cb6b79670
diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256
index e809440..6b1c8c1 100644
--- a/SOURCE_MANIFEST.sha256
+++ b/SOURCE_MANIFEST.sha256
@@ -1,20 +1,20 @@
e789cd4d1bed8a78ec8014c5c5913e300f81b63ea56a56aacb0dfec3b5e7ce2b ./.flutter-version
a3e3ce18f80b46587bcd529d13e456d10d97dd5e4a3f15e8e1a18894961120b1 ./.github/workflows/publish.yml
-f8944a946de6f0d751d0de3277b9fd65150a26bac629030ac10c8c9772c06574 ./.gitleaks.toml
-5115d06bd9913f466d50fcbf8ad8890372349060c54a4581f3481ea084cfdec6 ./.pubignore
-b455e46613099c45774f1836bdaed834ab6af8aff8a3784e4f872c7f583a7922 ./CHANGELOG.md
+992d54be0fbdaf0ef52be1bb80a3985af67defed270f4343aa9ee27465f6a49e ./.gitleaks.toml
+efaab625b09d5b5bb80352b0586e4f81764914a1aff24164e338b6a95fee5973 ./.pubignore
+5b29f2e6863615d3ed18f9a464c06ce1e4832b9b2103b159573edcf31caff090 ./CHANGELOG.md
37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 ./LICENSE
-534637dca830a792f7e4bec16dddfea86c37f59e67e6e95c4651c9bd0ae0052b ./README.md
-24f62d19b9b31ba66c5424da526f9d8c7e391dc6e0302e6822768190a46c42d8 ./RELEASE_METADATA
+24f8ccbc0f0ffaf43dff1c74c4712fbe3141bf3fc834f092646d39ca3402fd22 ./README.md
+08ebe9e7d7841b3a238e386a1f85230dc6cfbf1a9efcbf1f8ef0fa44a36e08b8 ./RELEASE_METADATA
def7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 ./analysis_options.yaml
5aeee476843e07c110c4525685fb6b875fa28824e26eae514f345d593126df48 ./build.sh
4f18642680fb433554a5523d00bd99e0d650af340bcaebe628f59f63ac84e458 ./dartdoc_options.yaml
75461620cf3a062f4dad10e034952b82cca461b483788de1f46c539aca8b0f0f ./doc/manage_api_key.md
a66d39da0983a994474fa516f81fd41bbb131efbd69c955891a41781a76daf24 ./doc/performance.md
-c8376ed2786fd58778016d72dda4371a97231c94a47aded142133557582b3425 ./doc/release.md
-616b3b20c5166ed48e1d6d8ba48bf34f1cad7c11dcd88ad8276c416faf30200b ./doc/sdk_contract.md
-797404fa5975951d5ddb0ee4fde4db16d6ece935c530adcd4ad5591a2fd7ef06 ./doc/sdk_doc.md
-c0f878afdfd9f8b9914d60ce1c7bc15a54d2c8631826a3a6d17907d4c2ada846 ./doc/search_app.md
+c59892e1edadebe19a9bc5211f6d6a2f38ad0aece15d6505f8237405f152896e ./doc/release.md
+97c81876aa73762589a794c6d89592dd5500f9b196bf3d8a8b0e5171425a5b48 ./doc/sdk_contract.md
+98db54c31211074fa4176208662dd5b9e09e6d724a6dab2b22fc90b138a9f9e6 ./doc/sdk_doc.md
+4aad6c643677dbefdd7fd7ac1aef865dd8c1640a6d98292facb28bcdcc8904a0 ./doc/search_app.md
7b0acfc01cfa4c8bf3af8aeb19741e65b8e9406935d9ab8e0f4cb84547483e55 ./doc/transcode_360.md
e246ed229511a24a1ee7e98529c203ef90d1d352290ce8486caebe05683db3a0 ./env.sh
c5ce516b547327aab5b6fa27a523d4c76e66294ada3248b293c54b9595cd3a87 ./example/01_full_app/.metadata
@@ -269,7 +269,7 @@ c783830af58111d94c3e78a705865468fa3ba8f59cc5bef833404d7ac3567119 ./example/05_f
4ecc92b82356d3fc31b7573caa8b9608dafb3af44dfe6f99b9f3ab93b4693500 ./example/05_framebase_userlogin/.metadata
bc001543e1418412ce7879a5c46d40ef1b3c485d8ba2b9a343bf7104b17e360c ./example/05_framebase_userlogin/LICENSE
559a8b6846e28399e68511e778cb7ea4b0390cf38fd87a9936414711bca72947 ./example/05_framebase_userlogin/MEDIA_SOURCES.md
-ad239ca9daa04dc03101bb4fda630d560560c93efc193498fb809e064d0c2cc6 ./example/05_framebase_userlogin/README.md
+581c40688b944e039a33899303faf8fd7344663c5118773c722bbf899716a082 ./example/05_framebase_userlogin/README.md
e0ea485cfdbc3e12b93efb8679a5ea73ebfe20ea4ca0c473dc594fc2fb274ed5 ./example/05_framebase_userlogin/analysis_options.yaml
6939878d0e417b29be6738e9c57772fc8a22a9aab5db39ae7fa867848d09d089 ./example/05_framebase_userlogin/android/app/build.gradle.kts
4e4a0e0726baf45d2d878ea5d0e0666e08ea6e9dbdc33ecd2a74a3525cf5ba51 ./example/05_framebase_userlogin/android/app/src/debug/AndroidManifest.xml
@@ -337,79 +337,80 @@ fd367b6c43006d61b730f674970dd48b9f662c8f2264e52ffc1558102a2c9f2d ./example/05_f
1a8d11d01d1cc92c650c9c9ed35299240052d4683a15a719a2315ef44185e074 ./example/05_framebase_userlogin/ios/Runner/Runner-Bridging-Header.h
add68b905971dedfcc0d0b5b7118030de5925ba8c081ad9815463699e3a444ad ./example/05_framebase_userlogin/ios/Runner/SceneDelegate.swift
5e8f4908dacea6f29b2a790e4d38bf5fded69096063f9a27a2f21584d62b30c0 ./example/05_framebase_userlogin/ios/RunnerTests/RunnerTests.swift
-9970e371aa042196c5b632e83411dc081768256c35d168a892738365f8ad1459 ./example/05_framebase_userlogin/lib/data/archive_controller.dart
-dba0ac7c273f4c53187df1d4aa5a0709e87bab7b191dbee9f806f99f1569f780 ./example/05_framebase_userlogin/lib/data/search_gateway.dart
-83d703a4176d34d35472475bf37ccb38c30d655ce23a7f060db213c921248328 ./example/05_framebase_userlogin/lib/main.dart
-1f7958647977c5a6d8cc3b1b1f0079d8a5e4140a7e22544d7e830c40d176360f ./example/05_framebase_userlogin/lib/user/auth_adapter.dart
-4af30076d205211ac289d75fc583cdb37fcb937db4c79edc4f63e3ac579e5e06 ./example/05_framebase_userlogin/lib/user/login_page.dart
+33ac5f6b1c52ca80d0e7a53539881a565cf8cc7a3f69ce945bfcf832bf706607 ./example/05_framebase_userlogin/lib/data/archive_controller.dart
+996a045adfd44031d6e1a6ba5a962525791e0e6bfa0ad0232f2c223e902fc90b ./example/05_framebase_userlogin/lib/data/search_gateway.dart
+b1771f392ee3f7b13f2d50c03a7f5533f66eb83c019c1e376cdb94e9673285b3 ./example/05_framebase_userlogin/lib/main.dart
+79223e647a2f81538c58b21856ee5a231a3bd4e45dfcd3ba784405d4f0fd0ac9 ./example/05_framebase_userlogin/lib/user/auth_adapter.dart
+c2ec078652813b9c8a875e436e29cc92c64f564aac1e96d7ed215e24ed43c006 ./example/05_framebase_userlogin/lib/user/library_scope.dart
+2ac441b32baf95eeaba9f53afc297016af9a3389cbc26b4a3c702a0c602d817c ./example/05_framebase_userlogin/lib/user/login_page.dart
d34a3e5ea1783adcaeac1bb3abb9c0760b7d2355279b9e442e78d93c70c0c728 ./example/05_framebase_userlogin/lib/user/mock_firebase_auth.dart
-5541327a114d32d64c874363767a7f2a627cbf4afe6834381dc786e0f451a5a1 ./example/05_framebase_userlogin/lib/user/user_collection.dart
-ce54d214a484937abf6f3de7b10283ce8fc51276bef7540985d12d0322de481c ./example/05_framebase_userlogin/lib/user/user_session_controller.dart
-60cdc7deba6d5bfd88abbdfb2738ecb25ed2ce4586e8a7193d7d43c5394e4ff8 ./example/05_framebase_userlogin/lib/user/vmodal_credential.dart
+c39791c305e72ea92656df28f490f613330b79e8ccce46e14e6b5858dd4b9f7c ./example/05_framebase_userlogin/lib/user/user_session_controller.dart
+94f19c14a447d8a6840173b7d2bd518c1456972883893ef4c3f65c153b5017b3 ./example/05_framebase_userlogin/lib/user/vmodal_credential.dart
38915e998b313d617db841f46ae5bf293a06bc813791ec3adb7dfd245ec549c1 ./example/05_framebase_userlogin/pubspec.lock
d127d3f4cd96b63ab036c263e488f8af91a5140be12768b0e3cd0904193676d5 ./example/05_framebase_userlogin/pubspec.yaml
5ac0550b52416cec8dd4f01d0cf8622dc696a235502aedbb7a291a13594eac02 ./example/05_framebase_userlogin/readme_assets/library.png
1af691525fbc6b8c558690bdc651d0bfc76b09116caa59835f27d552b456239e ./example/05_framebase_userlogin/readme_assets/playback.png
1fc9b69f52a19ed05d741b4cf71bea35daac8b684977fb73909c97a65b0f9d24 ./example/05_framebase_userlogin/readme_assets/search.png
-8b4e372b59e32cdc5e56a3cf823cf5d265262a73dacd750bf1e8798846c3fd29 ./example/05_framebase_userlogin/test/archive_controller_test.dart
-8d3c3ce3e9edb1e69bbea021ec4d0bdb5a0b7d574b87f791b48d0ecbbfc4ea20 ./example/05_framebase_userlogin/test/search_gateway_test.dart
-ccf1fb18ee188b3bd966d5ec0f2ad45ad1ad90ff46ebbafb3822bf1195cd2497 ./example/05_framebase_userlogin/test/user_collection_test.dart
-dac923d9ef8ee95a08920037e07ec43ad7b2da12996a8aaf273bb443c0bc477f ./example/05_framebase_userlogin/test/user_session_controller_test.dart
-ea227c1405876c237e4c88c851ce8223456e56999a98b1b39109a45a616689e0 ./example/05_framebase_userlogin/test/widget_test.dart
+89b8437232d2fcdef45c8b658fba2785541528e705bc6d88ce567b1b0e86137d ./example/05_framebase_userlogin/test/archive_controller_test.dart
+6a12566076d8e0493fc73589445f256739d6fcd882fc62dd0aae2aa6de51ed94 ./example/05_framebase_userlogin/test/library_scope_test.dart
+7d4e31013658ad77d3392a169c1038e99d0229bb0ed3213706559a7510964171 ./example/05_framebase_userlogin/test/search_gateway_test.dart
+417dac72f4059de5a71a1cdec4daf62c5f2f047eb006512b3f1d140cf4e63da8 ./example/05_framebase_userlogin/test/user_session_controller_test.dart
+1faebf8598db4d0ea84a98439fa06fcf59b6841d1f7dc49d724e70f7816430a5 ./example/05_framebase_userlogin/test/widget_test.dart
bb2e66ce21a066b5331a8c6ee665f1a4d2fcb3451cde5ce2ba0e6fe492344ac0 ./example/readme.md
23756b83470b1f25f6a7e6b5a6270f123a5224e49fd8e2eda36001358951b688 ./install.sh
7becacd31a8d134fa435b39cd819798d5fbf58f89b9f30c50362e2dcf757aaed ./lib/src/adaptive_upload.dart
9464fff0c519a1ce70cddefb3e3eaa95d07b97ccdaf5b8381c01d7c88767ae83 ./lib/src/api_key_provider.dart
-91395c928fd85760bed8584f21c26d89bcabe4da79e39d7dac9e25ed2363b1de ./lib/src/client.dart
+9c8a5a834352d6c417fb1fd9793f427252fced588ff3e126493ea6f9c80cf474 ./lib/src/client.dart
56854450130793060945446c9d4f812dab1ef80de83c51db5f9f4fdc13851c9d ./lib/src/collection_uploads.dart
3591a3bfd33164aadcd65b5d5b02bafc5f36b577a304a0e87bec8fb7ac34bb8b ./lib/src/config.dart
d3e03d9a72a499659c70f2296115d1d3138b9370a017e027d8255f85f7fb1c5c ./lib/src/content_scope.dart
873d969cfed5c725d34df0fd0c8769462b56992cf523710fcf741a81fa1bbcad ./lib/src/errors.dart
027174edd680e69e067453695f62680fd90b16c78f74a6999ab926cd2fd257dc ./lib/src/http.dart
-3c026d1046fd2380d25b82f252fd3e75967a773adff4c1aed749a7d6cf139432 ./lib/src/models.dart
+edd4993e3f56b492b19430a6eb52646d52052a8b8b9a98d7bce784da41195ef9 ./lib/src/models.dart
1612baa4be9d9f1489673ea1368698209fbca9199e9f927a114d696a413deb09 ./lib/src/resources.dart
43770c621bffccf69eacebd1e3b297503ca288093c848f0e8ccbd118d7f0d88a ./lib/src/routes.dart
27056230065682f3ea3aa747c39c08950dcdca87387f4733adfad18f4b345b06 ./lib/src/routes.g.dart
42331852249c8f99874a5e3889c752fd344ad8a5301ede246d5a4fbccb4191f2 ./lib/src/transcode.dart
362f472ea7ed5ec09dc0272239865ac12100a8c2fa3f73f45ccfeaedebe77395 ./lib/src/transport.dart
8a9ab7a18da892c10f4004d0188f71cf60c31d3207b08617d70f0a7e4fde4d0e ./lib/src/upload.dart
-6c80bc04d98a46141c0066655b95d89c26fbfa155fe07cdbd2b6062a6dd2ac71 ./lib/src/utils.dart
-e4413678ceb7bdfc1f6aaa241c53d8ba2033fc5171dd0a30030b62946d14008e ./lib/src/vmodal.dart
+655a7627df6b9db8059dadd5a7f61c796e8e8da39b7210ce291ac9189027a7fd ./lib/src/utils.dart
+fded09f674653828d4cc95bceacac01018d4783cc584ef8eb816edb25e1f8831 ./lib/src/vmodal.dart
14f02410389d19abb09ca40ff69c6267f3ad0b8b40ab115aa6e2c76bf43bfeef ./lib/vmodal_sdk_flutter.dart
72fff91181fd3e25fd9afd766930a67025205b61096fd35c55cbdd9a3178ecf0 ./pubspec.lock
-5bdde8cb1c29076e2c3f9ac308f3786b3355873666f7d5c5384acb45ebe8701d ./pubspec.yaml
+b71f6aaaac229ea700bda226ee1dd3cf53e549a1d7ef8f03399b6c75086ad78b ./pubspec.yaml
387ec75b8a58410c403abd622bc6627d194a2fa4b839c549600cc0ea28b50f67 ./readme_assets/app1.png
ecf9d38677ac502250e93353ce7784aa8685c725e73e5dcfc744a1f9d4eb0651 ./readme_assets/app2.png
93db32456ccda95d5b5bfea658e6e1b8088dc65f0166517e5b1a46bf54028405 ./readme_assets/app3.png
5ecf57fdb27bab2ba7966384beefe5c4641a257e4bfd3c9cbeb2c7f3d18fb08d ./readme_assets/app5.png
a80b38547f5d9ca1874f60e71c648e3fc12ab5f7cb88d1bead6d5b863d3c0245 ./readme_assets/dev_homepage.jpg
c56419d129059b64551e06f074e88ef62676f25938dc2a1fe28a6ab3f2ba8547 ./readme_assets/logo_vmodal_owl.jpeg
-478b9ab42059ecf4b2bca27378a35a97b807877293ed43a66115169bb08451cc ./release_note.md
+efec1544082870ed0079302d6ed6d266b5ce543bb42fa44042c385a343e894d2 ./release_note.md
3198051c448338c5331baef7e17ff32bfbaf1265b59543a8aca2baf57513feed ./run.sh
-fa80897bb2a4214cdc1d54c82b369c05f1d1c726f7f61ca1b18d59d9f335735b ./security_check.sh
+bb5948fd73afd0adfbc1fa34addb946ae688fc8e03f4c54a17c4b067f0679b3d ./security_check.sh
75d9810c9d50fd1224462aba8d2d1669cbfa094bd9cc0e5275f3a6a9f1364cb5 ./test.sh
be59599b9ba77d031e9b4bad7f8d5c59efd2687888c5b73be4fbea115902106b ./test/adaptive_upload_test.dart
002abcc5d95c0cf20375adefe4ee2472581a615e64f5726bf361dd5c679cdea7 ./test/auth_http_test.dart
51001c445940a527271418f3eded8af669dd1eb6c450504e9dd1f12ec16d66a0 ./test/cctv_contract_test.dart
3cb772c473b1657f2aaeebd8281e4d9cfee1aaa10b70badb70a1df8d5d7bc389 ./test/client_test.dart
56eb465d0c149368f68dce9d54e48ad8f61476b912525d5783fac7de7b7c2943 ./test/config_routes_test.dart
-4b9358bc8c8eb76b84dffc1c85d699169d890b4878af967f490bcddfcd6bd869 ./test/docs_reference_test.dart
+4d65cc6e6f2bcfb1d0fc42bc38e0106daf46c0de8e5c4c53c7a997df3f9a7bab ./test/docs_reference_test.dart
b45470d8e7674bcb87828a8dcf231ac29afb4418774972c66e60cea9788270db ./test/errors_leak_test.dart
d132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.dart
0a1394c90829b91541aa01e9786e3195aae04fc49a7b92775dbf404bf2802107 ./test/fakes_test.dart
14368b598ece0ce9b2e249148a10a92f2c80e38427c077013a1515826f4365bd ./test/fixtures/routes_contract.json
593b356ac3431de80e03e7a0e2f1df0d29589140f44746468213c1cac1c35bbe ./test/multipart_upload_test.dart
-348b9581f6262acaaf96012a3d57685b0b45c3663c1497f14135663de7a60954 ./test/new_api_surface_test.dart
-5209e29aefbfb5ecf855979754ec760578c4fa0c73d616394e05f85945c594c7 ./test/regression_manifest_test.dart
-8c87a4645a2e329477d070277f64b617da14ac90163bb734fbb5326c1a97a5c3 ./test/resources_models_test.dart
+1247019fcd0549fab4bb48fa9aeee438ea288cc1e73561c46ca7dd6598170d14 ./test/new_api_surface_test.dart
+ee8fbc92ad32387a834cb9f1fd082487e765409337e381c8f87fbaa8f6ac6249 ./test/readme_pin_test.dart
+24526adae4d56282d2780d5653727a62ebca6fcfdf1be89486ac374bf9d0e6ba ./test/regression_manifest_test.dart
+5f049dd64b419a6afa46b548cdaba8d1101dd66501cede4425f02ed956b9a669 ./test/resources_models_test.dart
8619ce113bb8669612f9a2a16b1b334ac68435c5972e84828a789511467fcb77 ./test/shell_scripts_test.dart
efe4f1158e7d4b9ca8e57f3538ce296279817292a4356c1399cf5f2cbae4c52d ./test/transcode_upload_test.dart
b94c0fef25560e387c4de5de0e4032fce73aa22b23a4bf38594ea6ff241d914c ./test/transport_test.dart
c4aa3c091992668ee531412a7fc783106769df7d75147eb06271492027b0c100 ./test/upload_test.dart
-7aa795ad3c78116f1805b97d6e5b01c2e35b49aff5eda6e1f0db2b891d8f9ec5 ./test/workflow_layout_test.dart
+a5b7f52cd2560df794b75574180134a2ccf1c1b814c7b5eb495a29150c892f89 ./test/workflow_layout_test.dart
406de1350b79662fcaf007cb0cacd7a6b71b83815dc7cd3c7b561fcfba5600a3 ./tool/check_route_sync.dart
d5f5f9246656a5c275c5ab5863dbf3945d8ef6b1c9042c9d1912cfafce93646f ./tool/flutter_checksums.txt
24ea8e3013e0ed3531ff2aa3c86ad5332bf315d3d26f6a0814d2d6c84c5dade2 ./tool/live_cctv_test.dart
d09e2ee68e0e238b86e54a8248a0da92db81c953ce691628708bffd63fa3e737 ./tool/live_test.dart
d0eb57dd08a93b8afe4dc8f078db8b7ba7bdfc926292c2cff183c6489104c776 ./tool/perf_benchmark.dart
-685ff82afcd1d4696b52ac7e790756414b0d3c4b2e0b4ce177b5ec75c2792c83 ./tool/release_manifest.dart
+a87f6dfd6208d9ff926a1bddacff5506cb5e3f8f0d80ac160f1da39837b052bf ./tool/release_manifest.dart
diff --git a/doc/release.md b/doc/release.md
index 209c7f4..bb9afc0 100644
--- a/doc/release.md
+++ b/doc/release.md
@@ -12,14 +12,18 @@ collection. It remains outside `test.sh all` and the Flutter release workflow;
run it explicitly against a backend that has the CCTV search contract deployed.
The release workflow is manually dispatched during development. Exact-candidate
-`RELEASE_SHA` checkout and `git rev-parse` verification lines are retained as
-comments so they can be restored later, but they do not gate the fast release
-path. Jobs use the normal workflow checkout, while GitHub's built-in
-`GITHUB_SHA` is recorded in artifacts, public commits, tags, and documentation
-metadata for traceability. A secret-detection job scans the Flutter SDK tree
-and source publication waits for secret detection, offline tests, Android and
-iOS builds, the live test, and the tested package artifact. Protected release approval remains
-disabled during this development mode. Optional pub.dev publication is
+`ref` overrides remain commented, so jobs use the normal workflow checkout and
+do not enforce a separate `git rev-parse` guard on the fast release path. The
+workflow explicitly maps `github.sha` to `RELEASE_SHA`; release artifacts,
+public commits, tags, and documentation metadata record that value for
+traceability. Workflow steps only orchestrate named functions from a
+monorepo-owned release helper; that private CI helper is not part of the
+standalone SDK export. Its workspace, runner-temporary directory, publication
+input, repository targets, URLs, and secrets remain explicit in the workflow
+for debugging. A secret-detection job scans the Flutter SDK tree and source
+publication waits for secret detection, offline tests, Android and iOS builds,
+the live test, and the tested package artifact. Protected release approval
+remains disabled during this development mode. Optional pub.dev publication is
triggered only by the exported version tag and uses OIDC trusted publishing; no
long-lived pub token is stored.
@@ -32,14 +36,14 @@ fake auth and transport. Its real Firebase and credential issuer integration
requires separate device verification once that server contract exists.
After the tested SDK source is published, the same workflow installs the pinned
-Flutter toolchain, regenerates `docs_sdk` from the public Dart library, and
+Flutter toolchain, regenerates `doc` from the public Dart library, and
publishes the immutable class/method reference to the `gh-pages` branch of the
existing public repository `v-modal/vmodal_sdk_flutter`. Generation removes
only Dartdoc Implementation sections, validates required public symbols, and
fails when backend hosts, route prefixes, or implementation-only types appear.
The workflow pushes that branch directly, without opening a pull request, and
configures GitHub Pages for branch-based (`legacy`) publishing. It verifies the
-recorded `GITHUB_SHA` at `https://v-modal.github.io/vmodal_sdk_flutter/`. The
+recorded `RELEASE_SHA` at `https://v-modal.github.io/vmodal_sdk_flutter/`. The
deployment depends on both source publication and the active
secret-detection job. The private monorepo maintainer handbook owns the local
generation commands because the generator is intentionally absent from the
@@ -47,4 +51,7 @@ standalone public package.
Multipart is excluded from production live claims until all five backend routes
are verified. A failed publication is fixed forward with a new version after the
-entire candidate pipeline passes again.
+entire candidate pipeline passes again. Before publishing, the package dry-run
+must list `lib/vmodal_sdk_flutter.dart`; the release workflow also verifies
+that the uploaded pub.dev archive contains that entrypoint, otherwise pub.dev
+cannot build the SDK's Dartdoc library.
diff --git a/doc/sdk_contract.md b/doc/sdk_contract.md
index ee80c0f..a82aaf1 100644
--- a/doc/sdk_contract.md
+++ b/doc/sdk_contract.md
@@ -48,6 +48,29 @@ or API-key-provider contract. `VmodalClient` remains public and compatible.
`VModal.fromClient` transfers lifecycle ownership, so the project is the object
that must be closed.
+## Typed video-search results
+
+`SearchResponse.videoHits` is an additive typed view of map-shaped entries in
+the unchanged `SearchResponse.data` list. It preserves map-entry order, ignores
+non-map entries, and retains every original field through `VideoSearchHit.raw`.
+
+| Field | Canonical wire field | Meaning |
+|---|---|---|
+| `assetId` | `asset_id` | Nullable stable source-asset identity |
+| `fileName` | `file_name` | Nullable normalized basename for display and legacy lookup |
+| `playbackOffsetMs` | `playback_offset_ms` | Nullable elapsed milliseconds from source-video start |
+| `distance` | `distance` | Nullable raw lower-is-better distance |
+| `previewImageUrl` | `preview_image_url` | Nullable absolute HTTPS or relative signed image route |
+
+Legacy filename/path, seconds, relative-millisecond, `score`/`_distance`, and
+image URL aliases remain accepted. Invalid, blank, negative, non-finite, and
+epoch-like playback values become null rather than throwing. `score_ui`,
+similarity, and confidence are not distance and are never transformed into it.
+Missing `asset_id` is never synthesized from an item ID, filename, path,
+stream, or timestamp. `VideoUploadResponse.assetId` follows the same
+canonical-only identity rule, allowing applications to persist upload identity
+and reconnect later search hits without weakening legacy compatibility.
+
## CCTV timestamp and metadata contract
`VideoUploadOptions` carries `videoFilename`, `metadataText`, repeated
diff --git a/doc/sdk_doc.md b/doc/sdk_doc.md
index 84593c3..0d1b1b7 100644
--- a/doc/sdk_doc.md
+++ b/doc/sdk_doc.md
@@ -3,7 +3,7 @@
The generated class and method reference is published at
`https://v-modal.github.io/vmodal_sdk_flutter/` and is built from the public
Dart declarations in `lib/vmodal_sdk_flutter.dart`. The monorepo release
-pipeline builds the Pages artifact in `docs_sdk/`; that generated tree is not
+pipeline builds the Pages artifact in `doc/`; that generated tree is not
part of the standalone package. Backend hosts, wire paths, and implementation
bodies are intentionally excluded; mobile applications should use the typed
resources described there.
diff --git a/doc/search_app.md b/doc/search_app.md
index 36f009c..52ab70f 100644
--- a/doc/search_app.md
+++ b/doc/search_app.md
@@ -25,23 +25,41 @@ Use `versionLancedb` in `ScopedSearchOptions` when your application tracks a
specific index version. Collection and stream cannot be overridden per search,
so overlapping searches retain the organization with which they started.
-Search hits contain stored image coordinates, not public image URLs. Convert
-each usable hit into one bulk lookup record with these fields:
+Use `result.videoHits` as the recommended parsing path. Each `VideoSearchHit`
+exposes nullable `assetId`, `fileName`, `playbackOffsetMs`, `distance`, and
+`previewImageUrl` fields while retaining the complete service map in `raw`:
+
+```dart
+for (final hit in result.videoHits) {
+ final seconds = hit.playbackOffsetMs == null
+ ? null
+ : hit.playbackOffsetMs! / 1000;
+ print('${hit.assetId} ${hit.fileName} $seconds ${hit.distance}');
+}
+```
+
+`playbackOffsetMs` is elapsed time from the beginning of the source video.
+`distance` is the raw lower-is-better distance, not similarity or confidence.
+`assetId` is stable only when the server supplies canonical `asset_id`; legacy
+responses legitimately expose a null identity.
+
+When `previewImageUrl` is present, validate it at the application boundary and
+reuse it. Otherwise convert each usable typed hit into one bulk lookup record
+with these fields:
```text
mode vid_file
group_name selected authenticated collection
modality image
stream_name hit stream, or selected stream as fallback
-filename basename of the first supported filename/path field
-ts_unix_13digits normalized timestamp, when present
+filename hit.fileName
+ts_unix_13digits zero-padded hit.playbackOffsetMs, when present
```
-The supported filename fields, in order, are `filename`,
-`filename_sanitized`, `video_filename`, `video`, `source_path`, and `path`.
-Normalize timestamps from `ts_unix_13digits`, `ts_unix`, or `timestamp_ms`:
-truncate values longer than 13 digits, multiply 10-digit seconds by 1000, and
-left-pad other nonblank numeric values to 13 digits.
+For backward compatibility, `result.data` remains unchanged and callers may
+still inspect raw maps. The typed model already handles the documented legacy
+filename, seconds, relative-millisecond, score, and preview aliases. New code
+should not repeat those aliases or derive a filename from `item_id`.
Image URL resolution remains an advanced low-level resource. When a result
flow needs it, create `VmodalClient` first, pass it to `VModal.fromClient`, and
diff --git a/example/05_framebase_userlogin/README.md b/example/05_framebase_userlogin/README.md
index 649f83f..e038dda 100644
--- a/example/05_framebase_userlogin/README.md
+++ b/example/05_framebase_userlogin/README.md
@@ -1,9 +1,10 @@
# Framebase user library
-This Flutter example gives each signed-in user a separate street-video library.
-It shows where app sign-in, a VMODAL credential, SDK requests, local video files,
-and search results meet. The video screens come from the original Framebase
-example; this version adds a signed-out entry screen and per-user state.
+This Flutter example opens the one opaque street-video library scope selected by
+a trusted credential issuer for the signed-in user. It shows where app sign-in,
+a VMODAL credential, SDK requests, local video files, and search results meet.
+The video screens come from the original Framebase example; this version adds a
+signed-out entry screen and scope-isolated state.
## Screenshots
@@ -40,17 +41,20 @@ flowchart TD
B -- No --> C[Show sign-in screen with no VMODAL request]
B -- Yes --> D[Ask app adapter for Firebase ID token]
C -->|Configured fake account signs in| D
- D --> E[App credential source returns VMODAL key and user IDs]
- E --> F{UID, expiry, permission, and owner checks pass?}
- F -- No --> G[Show access error or retry]
- F -- Yes --> H[Open this user's local archive and library]
+ D --> E[Trusted issuer verifies Firebase token server-side]
+ E --> F[Issuer returns scope-bound VMODAL credential]
+ F --> G{Client contract checks pass?}
+ G -- No --> H[Show access error or retry]
+ G -- Yes --> I[Gateway enforces owner, scope, grants, and expiry]
+ I --> J[Open the scope-isolated client session]
```
`UserSessionController` validates the credential's Firebase UID, expiry,
-`library:read` permission, and stable user IDs. `SearchGateway.connect()` calls
-`auth.me()` to confirm that the VMODAL key belongs to the expected VMODAL user.
-Only then does the app show the library. Firebase Auth does not issue the VMODAL
-key: an app-owned credential source must supply it.
+`library:read` permission, stable VMODAL owner, and stable opaque scope.
+`SearchGateway.connect()` calls `auth.me()` to confirm that the VMODAL key
+resolves to the expected VMODAL user. These fail-closed checks control client UI
+and session state; they are not the authorization boundary. Firebase Auth does
+not issue the VMODAL key: a trusted app-owned credential issuer must supply it.
## 2. API access and account changes
@@ -59,23 +63,92 @@ flowchart TD
A[Read or write action] --> B{Permission allows action?}
B -- No --> C[Keep action unavailable]
B -- Yes --> D[Ensure credential is fresh]
- D -->|Expires within 1 minute| E[Acquire renewed credential and rotate in-memory key]
+ D -->|Expires within 1 minute| E[Retry typed temporary failures with bounded backoff]
D -->|Still valid| F[SDK request]
- E --> F
- F --> G[VMODAL collection scoped to this user]
- G -->|401 or 403| H[Cancel work and clear key and archive state]
- I[Sign out or switch account] --> H
- H --> J[Close session and hide library]
+ E -->|Refresh succeeds| F
+ E -->|Temporary failures exhausted| L[Keep resources but gate operations until manual retry]
+ F --> G[Send issuer scope_id unchanged as collection selector]
+ G --> H[Gateway authorizes bearer, scope, operation, and resource owner]
+ H -->|401 or 403| I[Cancel work and clear key and archive state]
+ J[Sign out or switch account] --> I
+ I --> K[Close session and hide library]
```
-Collection operations target `framebase_streets__user_<collection_user_id>`;
-upload, indexing, and search use stream `street_study`. Reads need
-`library:read`; uploads and index preparation need
-`library:write`. The archive controller checks permissions, and the gateway
-fixes the collection scope for SDK calls. A rejected or
-expired credential closes access; sign-out also stops work and clears the
-in-memory key. The next account gets its own archive under
-`accounts/<collection_user_id>/` in application support.
+The issuer returns `scope_id`, an opaque exact backend `group_name`. The app
+does not prepend a project, append a user ID, split it, or infer identity or
+permissions from it. It accepts only a nonempty `[A-Za-z0-9_]+` value of at
+most 80 characters for safe request and directory reuse; this is syntax
+validation, not authorization. Upload, indexing, search, discovery matching,
+jobs, and image lookup reuse that exact immutable value. The stream remains
+`street_study`. The archive controller uses the same value only as
+`accounts/<scope_id>/` in application support.
+
+The version-1 issuer envelope is:
+
+```json
+{
+ "version": 1,
+ "session_id": "<opaque issuer session identifier>",
+ "issued_at": "2030-01-01T00:00:00Z",
+ "expires_at": "2030-01-01T00:05:00Z",
+ "api_token": "<short-lived VMODAL bearer>",
+ "firebase_uid": "<verified Firebase subject>",
+ "vmodal_user_id": "<auth.me user_id>",
+ "scope_id": "<opaque backend collection identifier>",
+ "allowed": true,
+ "permissions": ["library:read", "library:write"]
+}
+```
+
+`version` identifies this example-owned envelope contract. `session_id` is an
+opaque issuer value: the app does not derive identity, scope, grants, or
+authorization from it. It may rotate during refresh because no stability
+contract is defined for it. `issued_at` and `expires_at` must be parseable UTC
+times with `issued_at` strictly earlier than `expires_at`.
+
+On refresh, only `vmodal_user_id` and `scope_id` must remain unchanged. A
+change tears down the session instead of rotating the in-memory key. `allowed`
+and `permissions` remain client-visible hints used for fail-closed UI gating.
+The gateway is authoritative.
+
+Credential refresh retries only typed temporary identity or issuer failures,
+with three total attempts and bounded backoff. If those attempts are exhausted,
+the current provider, gateway, credential scope, and archive remain in memory,
+but new read and write operations stay gated until manual retry succeeds.
+Firebase identity expiry, credential denial, final VMODAL `401` or `403`, and
+invalid credential contracts are terminal and clear the key and archive. SDK
+read retries remain governed by `SdkConfig.maxRetries`; writes are not replayed.
+
+When the app becomes `paused`, `hidden`, or `detached`, it cancels the active
+upload or local index wait and invalidates the active search so late progress
+or results cannot repopulate hidden UI. A brief `inactive` interruption does
+not cancel work. Returning to `resumed` never replays an upload, search,
+mutation, or index submission. A submitted server index job may continue; its
+`pendingJob` stays in the manifest and the user explicitly chooses **Resume**
+to poll it again.
+
+### Server requirements: the authorization boundary
+
+The credential issuer must verify the Firebase ID token server-side and derive
+`firebase_uid`; it must not trust a UID or requested scope supplied by the
+mobile app. It must issue a stable, syntax-compatible scope. The VMODAL gateway
+must then:
+
+- Bind the bearer to `(vmodal_user_id, scope_id, permissions, expires_at)` and
+ return `403` for any other collection, including requests from a modified
+ client.
+- Require `library:read` for read routes and `library:write` (or a narrower
+ future grant) for upload, indexing, deletion, and other mutations.
+- Filter collection discovery so a bearer sees only its allowed collections,
+ and make `auth.me()` resolve to the envelope's `vmodal_user_id`.
+- Ownership-check selector-less resources. A job ID, asset/image lookup, or
+ signed-upload completion owned by another scope or principal must return
+ `403` or a non-enumerating `404`.
+
+`MockVmodalCredentialSource` and the offline transports demonstrate client
+behavior only. They do not prove server enforcement. This repository still has
+no production Firebase adapter, Firebase token verifier, credential issuer, or
+collection-scoped token endpoint.
## 3. Video upload, search, and playback
@@ -97,7 +170,90 @@ version. Results use bulk image URL lookup and image download; tapping a result
opens the local source video at its returned timestamp. Imported MP4s and the
`archive.json` manifest stay in the active account's local directory. Credentials,
search responses, signed URLs, and downloaded images are never persisted. The
-app does not delete remote videos.
+app keeps local and cloud retention separate.
+
+Modern upload and search responses reconnect a result to its local
+`ArchiveClip` through the server-issued `assetId`, which is persisted in the
+archive manifest. Filename matching remains only a compatibility fallback when
+either the saved clip or a legacy search response lacks canonical asset
+identity. Two different non-null asset IDs never match merely because their
+filenames are the same.
+
+### Upload identity and deduplication
+
+The example skips manifest rows already marked `uploaded`, persists the
+canonical server `asset_id`, and reconnects search results by that ID. This
+avoids ordinary repeats from the same manifest, but it is not a once-only
+upload guarantee. An ambiguous upload failure remains unknown completion: the
+app does not mark the clip uploaded or reuse an ID unless the server confirms
+it authoritatively.
+
+Robust retry and cross-device deduplication require a backend-supported,
+scope-bound idempotency contract—for example, a stable app asset ID or content
+digest accepted by upload finalization, with a response returning the existing
+or new canonical `asset_id`. The key must be scoped at least to the authorized
+principal and opaque `scope_id`; a digest alone must never authorize or expose
+another user's asset. Filenames, local paths, `UploadSource.sourceId`,
+`versionTag`, multipart checkpoint keys, ETags, and search result IDs are not
+undocumented server dedup keys. Such a contract must first be added to the
+Python reference SDK and then synchronized across SDKs before Flutter uses it.
+
+## 4. Storage, sign-out, and deletion
+
+**Sign out** is session teardown, not deletion. It cancels local work, clears
+the in-memory API key and client, and hides the active library. It does not
+unlink an MP4, remove `archive.json`, or send collection/index deletion calls.
+Signing back into the same issued scope restores that scope's local manifest.
+
+All credential material stays in `UserSessionController` memory only. This
+includes the live credential object, `api_token`, `version`, `session_id`,
+`issued_at`, `expires_at`, identity fields, and grants. `archive.json` is an
+allowlisted media/work manifest containing clips, canonical remote asset IDs,
+the pending index job, and bounded events. It never serializes the credential
+envelope, bearer, signed URLs, or search responses. Sign-out, account switch,
+and terminal auth failure clear the provider and credential from memory.
+
+This example intentionally adds no secure-storage, shared-preferences, or
+refresh-token cache. If background processing is approved later, its platform
+execution, least credential material, expiry and revocation, logout cleanup,
+account isolation, and migration need a separate design; the foreground bearer
+must not be silently persisted.
+
+Local data under `accounts/<scope_id>/` persists until the user explicitly
+removes a device copy, uninstalls the app or triggers platform cleanup, or the
+operating system evicts application storage where applicable. An imported
+local-only clip is removed from the manifest when its MP4 is removed. If the
+clip was uploaded, local removal retains a cloud-only manifest row and its
+server-issued `asset_id`, so search identity remains correct. The cloud copy
+stays searchable. Bundled source media remains packaged with the app.
+
+**Storage & deletion** separates the three retention domains:
+
+| Domain | Explicit action | Result |
+| --- | --- | --- |
+| Device MP4 and manifest | Remove device copy | Removes only the imported local MP4; an uploaded cloud copy remains |
+| Cloud raw video and metadata | Delete cloud library | Deletes the complete issued collection; device MP4s remain |
+| Derived search index | Delete cloud library | Deleted with the collection's `scope: all`; no extra index-delete call is made |
+
+Complete cloud deletion first previews, then requires a second confirmation.
+Both requests use the credential-issued opaque `scope_id` unchanged as
+`group_name`, `mode: vid_file`, and `scope: all` through
+`DELETE /api/external/v1/collection/delete`. Preview sends `dry_run: true` and
+`confirm: false`; commit sends `dry_run: false` and `confirm: true`. A successful
+commit clears saved upload/asset identity and the discovered index version, but
+keeps every local MP4 so it can be prepared again.
+
+The public API does not expose an asset-, filename-, or stream-item-scoped
+remote delete route. This example therefore never labels local removal as
+remote video deletion and never misuses collection or index deletion to remove
+one video. Cloud data persists until explicit complete-library deletion or a
+server-side policy outside this example.
+
+Deletion commits are never retried automatically. A `409` asks the user to
+wait for cloud processing. Network or server failures keep local remote-state
+flags conservative because completion is unknown. If the server confirms
+deletion but the local manifest cannot be saved, the UI reports cloud success
+and the local reconciliation problem separately; device videos remain.
## Code map
@@ -105,9 +261,10 @@ app does not delete remote videos.
| --- | --- |
| [`lib/user/auth_adapter.dart`](lib/user/auth_adapter.dart), [`lib/user/mock_firebase_auth.dart`](lib/user/mock_firebase_auth.dart) | App-owned auth interface and offline fake |
| [`lib/user/vmodal_credential.dart`](lib/user/vmodal_credential.dart) | Credential envelope, validation, and source interface |
+| [`lib/user/library_scope.dart`](lib/user/library_scope.dart) | Exact opaque-scope syntax validation |
| [`lib/user/user_session_controller.dart`](lib/user/user_session_controller.dart) | Session states, refresh, account switch, and teardown |
| [`lib/data/search_gateway.dart`](lib/data/search_gateway.dart) | Owner check and scoped VMODAL SDK calls |
-| [`lib/data/archive_controller.dart`](lib/data/archive_controller.dart) | Per-user local files, upload, indexing, and search |
+| [`lib/data/archive_controller.dart`](lib/data/archive_controller.dart) | Per-scope local files, upload, indexing, and search |
| [`lib/main.dart`](lib/main.dart) | Signed-out and library screens |
## Verify
@@ -122,10 +279,25 @@ flutter_bin="$(bash ../../install.sh flutter_bin)"
"$flutter_bin" test
```
-The offline tests cover auth states, scopes, refresh, account switching,
-archive separation, result mapping, and UI gating. Device testing with two
-real accounts, a trusted issuer, and a gateway-accepted key remains the
-production integration step.
+The offline tests cover credential parsing and validation, exact selector
+propagation, scope immutability, auth states, refresh, account switching,
+archive separation, local/cloud retention, previewed collection deletion,
+result mapping, and UI gating. They are not an authorization test.
+
+Production readiness requires this live negative authorization test with two
+real issuer-created users A and B:
+
+1. A's bearer can read and write A's issued `scope_id` according to its grants.
+2. A raw request modified to use B's `scope_id` with A's bearer returns `403`
+ and performs no mutation.
+3. A's bearer receives `403` or a non-enumerating `404` for B's job ID and
+ B-owned asset, image, and signed-upload resources.
+4. A read-only bearer receives `403` for upload, indexing, and mutation against
+ its own scope.
+5. Discovery with A's bearer does not return B's scope.
+
+If the deployed issuer and gateway cannot pass all five checks, this example is
+not production-complete. Client-side Flutter validation is not a substitute.
The bundled footage and its license are documented in
[MEDIA_SOURCES.md](MEDIA_SOURCES.md).
diff --git a/example/05_framebase_userlogin/lib/data/archive_controller.dart b/example/05_framebase_userlogin/lib/data/archive_controller.dart
index 76ca63b..e6a1928 100644
--- a/example/05_framebase_userlogin/lib/data/archive_controller.dart
+++ b/example/05_framebase_userlogin/lib/data/archive_controller.dart
@@ -18,15 +18,19 @@ class ArchiveClip {
required this.asset,
required this.poster,
this.path,
+ this.remoteAssetId,
this.uploaded = false,
this.bundled = true,
});
final String id, title, location, asset, poster;
final double duration;
String? path;
+ String? remoteAssetId;
bool uploaded;
final bool bundled;
String get filename => '$id.mp4';
+ bool get hasLocalCopy => path != null;
+ bool get remoteOnly => !bundled && path == null && uploaded;
Map<String, Object?> toJson() => {
'id': id,
'title': title,
@@ -35,6 +39,7 @@ class ArchiveClip {
'asset': asset,
'poster': poster,
'path': path,
+ 'remoteAssetId': remoteAssetId,
'uploaded': uploaded,
'bundled': bundled,
};
@@ -46,9 +51,41 @@ class ArchiveClip {
asset: r['asset'] as String,
poster: r['poster'] as String,
path: r['path'] as String?,
+ remoteAssetId: _archiveAssetId(r['remoteAssetId']),
uploaded: r['uploaded'] == true,
bundled: r['bundled'] == true,
);
+
+ ArchiveClip copy() => ArchiveClip.fromJson(toJson());
+}
+
+String? _archiveAssetId(Object? value) {
+ if (value is! String) return null;
+ final clean = value.trim();
+ return clean.isEmpty ? null : clean;
+}
+
+enum LocalRemovalResult { removed, partial, unavailable }
+
+enum CloudDeletionResult { deleted, partial, failed }
+
+class LibraryDeletionPreview {
+ const LibraryDeletionPreview({
+ required this.removedBytes,
+ required this.sqlRowsDeleted,
+ required this.executionTimeMs,
+ });
+
+ final int removedBytes;
+ final int sqlRowsDeleted;
+ final double executionTimeMs;
+}
+
+class _ArchiveSnapshot {
+ _ArchiveSnapshot(this.clips, this.pendingJob, this.events);
+ final List<ArchiveClip> clips;
+ final String pendingJob;
+ final List<ArchiveEvent> events;
}
List<ArchiveClip> streetClips() => [
@@ -110,12 +147,15 @@ class ArchiveController extends ChangeNotifier {
int _searchGeneration = 0;
int _generation = 0;
bool _disposed = false;
- String _collectionUserId = '';
+ String _scopeId = '';
bool canRead = false, canWrite = false;
Future<void> _saveQueue = Future<void>.value();
+ final Map<String, _ArchiveSnapshot> _pendingReconciliation = {};
bool get connected => _gateway != null;
bool get ready => connected && indexVersion != null;
bool get hasPendingUploads => clips.any((c) => !c.uploaded);
+ bool get canDeleteCloudLibrary =>
+ connected && canWrite && !busy && pendingJob.isEmpty;
void emit() {
if (!_disposed) notifyListeners();
@@ -127,14 +167,14 @@ class ArchiveController extends ChangeNotifier {
}
Future<void> activate(
- String collectionUserId,
+ String scopeId,
SearchGateway gateway, {
required bool canRead,
required bool canWrite,
}) async {
deactivate();
final generation = _generation;
- _collectionUserId = collectionUserId;
+ _scopeId = scopeId;
this.canRead = canRead;
this.canWrite = canWrite;
_gateway = gateway;
@@ -142,7 +182,7 @@ class ArchiveController extends ChangeNotifier {
try {
final root = supportDirectory ?? await getApplicationSupportDirectory();
if (generation != _generation) return;
- _directory = Directory('${root.path}/accounts/$collectionUserId');
+ _directory = Directory('${root.path}/accounts/$scopeId');
if (persist) {
final state = File('${_directory!.path}/archive.json');
if (await state.exists()) {
@@ -155,11 +195,13 @@ class ArchiveController extends ChangeNotifier {
)
.toList();
if (generation != _generation) return;
+ for (final clip in saved) {
+ if (clip.path != null && !File(clip.path!).existsSync()) {
+ clip.path = null;
+ }
+ }
clips = saved
- .where(
- (c) =>
- c.bundled || (c.path != null && File(c.path!).existsSync()),
- )
+ .where((c) => c.bundled || c.path != null || c.uploaded)
.toList();
if (clips.isEmpty) clips = streetClips();
pendingJob = data['pendingJob'] as String? ?? '';
@@ -176,6 +218,21 @@ class ArchiveController extends ChangeNotifier {
}
}
}
+ final reconciliation = _pendingReconciliation[scopeId];
+ if (reconciliation != null && generation == _generation) {
+ clips = reconciliation.clips.map((c) => c.copy()).toList();
+ pendingJob = reconciliation.pendingJob;
+ events
+ ..clear()
+ ..addAll(reconciliation.events);
+ try {
+ await _saveStrict(_directory!, clips, pendingJob, events);
+ _pendingReconciliation.remove(scopeId);
+ } on Object {
+ notice =
+ 'Cloud status is restored in memory but could not be saved locally.';
+ }
+ }
} on Object {
notice =
'Local archive could not be restored. Built-in clips are available.';
@@ -191,7 +248,7 @@ class ArchiveController extends ChangeNotifier {
invalidateSearch();
_gateway = null;
_directory = null;
- _collectionUserId = '';
+ _scopeId = '';
canRead = false;
canWrite = false;
clips = streetClips();
@@ -208,28 +265,62 @@ class ArchiveController extends ChangeNotifier {
}
Future<void> save() {
- if (!persist || _directory == null || _collectionUserId.isEmpty) {
+ if (!persist || _directory == null || _scopeId.isEmpty) {
return Future<void>.value();
}
// Snapshot and serialize writes so progress events cannot truncate each other.
// Never serialize the client, key, response rows or signed URLs.
- final snapshot = jsonEncode({
- 'clips': clips.map((c) => c.toJson()).toList(),
- 'pendingJob': pendingJob,
- 'events': events.take(40).map((e) => e.toJson()).toList(),
- });
+ final snapshot = _manifestJson(clips, pendingJob, events);
final path = '${_directory!.path}/archive.json';
- _saveQueue = _saveQueue.then((_) async {
- try {
- await File(path).parent.create(recursive: true);
- await File(path).writeAsString(snapshot, flush: true);
- } on Object {
- /* Optional history must not cancel network work. */
- }
+ final write = _saveQueue.catchError((_) {}).then((_) async {
+ if (_disposed) return;
+ await _writeManifest(path, snapshot);
+ });
+ _saveQueue = write.catchError((_) {
+ /* Optional history must not cancel network work. */
});
return _saveQueue;
}
+ String _manifestJson(
+ List<ArchiveClip> savedClips,
+ String savedJob,
+ List<ArchiveEvent> savedEvents,
+ ) => jsonEncode({
+ 'clips': savedClips.map((c) => c.toJson()).toList(),
+ 'pendingJob': savedJob,
+ 'events': savedEvents.take(40).map((e) => e.toJson()).toList(),
+ });
+
+ Future<void> _writeManifest(String path, String snapshot) async {
+ final target = File(path);
+ await target.parent.create(recursive: true);
+ final temp = File('$path.${DateTime.now().microsecondsSinceEpoch}.tmp');
+ try {
+ await temp.writeAsString(snapshot, flush: true);
+ await temp.rename(path);
+ } on Object {
+ if (await temp.exists()) await temp.delete();
+ rethrow;
+ }
+ }
+
+ Future<void> _saveStrict(
+ Directory directory,
+ List<ArchiveClip> savedClips,
+ String savedJob,
+ List<ArchiveEvent> savedEvents,
+ ) async {
+ if (!persist) return;
+ final snapshot = _manifestJson(savedClips, savedJob, savedEvents);
+ final path = '${directory.path}/archive.json';
+ final write = _saveQueue
+ .catchError((_) {})
+ .then((_) => _writeManifest(path, snapshot));
+ _saveQueue = write.catchError((_) {});
+ await write;
+ }
+
void record(String title, String detail, {bool error = false}) {
events.insert(0, ArchiveEvent(title, detail, error: error));
if (events.length > 40) events.removeLast();
@@ -244,7 +335,7 @@ class ArchiveController extends ChangeNotifier {
if (!clip.bundled) {
throw const FileSystemException('Recording no longer available');
}
- if (_directory == null || _collectionUserId.isEmpty) {
+ if (_directory == null || _scopeId.isEmpty) {
throw const FileSystemException('No active library');
}
final file = File('${_directory!.path}/${clip.filename}');
@@ -260,6 +351,78 @@ class ArchiveController extends ChangeNotifier {
return file;
}
+ Future<LocalRemovalResult> removeLocalCopy(ArchiveClip clip) async {
+ final directory = _directory;
+ final scope = _scopeId;
+ final generation = _generation;
+ final path = clip.path;
+ if (directory == null ||
+ scope.isEmpty ||
+ busy ||
+ pendingJob.isNotEmpty ||
+ clip.bundled ||
+ path == null ||
+ !clips.contains(clip)) {
+ return LocalRemovalResult.unavailable;
+ }
+ final target = File(path);
+ try {
+ final rootPath = await directory.resolveSymbolicLinks();
+ final targetPath = await target.resolveSymbolicLinks();
+ final prefix = rootPath.endsWith(Platform.pathSeparator)
+ ? rootPath
+ : '$rootPath${Platform.pathSeparator}';
+ if (!targetPath.startsWith(prefix) ||
+ generation != _generation ||
+ scope != _scopeId ||
+ directory.path != _directory?.path) {
+ notice = 'The video could not be removed from this device.';
+ emit();
+ return LocalRemovalResult.unavailable;
+ }
+ await target.delete();
+ } on Object {
+ if (generation == _generation && scope == _scopeId) {
+ notice = 'The video could not be removed from this device.';
+ emit();
+ }
+ return LocalRemovalResult.unavailable;
+ }
+
+ if (generation != _generation || scope != _scopeId) {
+ return LocalRemovalResult.removed;
+ }
+ if (clip.uploaded) {
+ clip.path = null;
+ } else {
+ clips.remove(clip);
+ }
+ invalidateSearch();
+ events.insert(
+ 0,
+ ArchiveEvent(
+ 'Device copy removed',
+ clip.uploaded
+ ? '${clip.title} · cloud copy kept'
+ : '${clip.title} · local-only recording removed',
+ ),
+ );
+ if (events.length > 40) events.removeLast();
+ notice = clip.uploaded
+ ? 'Device copy removed. The cloud copy remains searchable.'
+ : 'Video removed from this device.';
+ emit();
+ try {
+ await _saveStrict(directory, clips, pendingJob, events);
+ return LocalRemovalResult.removed;
+ } on Object {
+ notice =
+ 'The video was removed, but the local library status could not be saved.';
+ emit();
+ return LocalRemovalResult.partial;
+ }
+ }
+
Future<void> importFile(String path, double duration) async {
if (!canWrite || _directory == null) return;
final generation = _generation;
@@ -287,9 +450,17 @@ class ArchiveController extends ChangeNotifier {
record('Recording added', '$sourceName · stored on device only');
}
- ArchiveClip? clipFor(String filename) {
- final clean = basename(filename).toLowerCase();
+ ArchiveClip? clipFor(VideoSearchHit hit) {
+ final assetId = hit.assetId;
+ if (assetId != null) {
+ for (final clip in clips) {
+ if (clip.remoteAssetId == assetId) return clip;
+ }
+ }
+ final clean = basename(hit.fileName ?? '').toLowerCase();
+ if (clean.isEmpty) return null;
for (final clip in clips) {
+ if (assetId != null && clip.remoteAssetId != null) continue;
if (clean == clip.id.toLowerCase() ||
clean == clip.filename.toLowerCase() ||
clean.startsWith('${clip.id.toLowerCase()}.')) {
@@ -299,6 +470,142 @@ class ArchiveController extends ChangeNotifier {
return null;
}
+ Future<LibraryDeletionPreview?> previewCloudLibraryDeletion() async {
+ final gateway = _gateway;
+ if (gateway == null || !canDeleteCloudLibrary) return null;
+ final generation = _generation;
+ final scope = _scopeId;
+ busy = true;
+ phase = 'Checking cloud library';
+ notice = '';
+ invalidateSearch();
+ final token = CancellationToken();
+ _work = token;
+ emit();
+ try {
+ final response = await gateway.previewLibraryDeletion(token);
+ token.throwIfCanceled();
+ _validateDeletion(response, 'dry_run', scope);
+ final raw = response.raw;
+ return LibraryDeletionPreview(
+ removedBytes: _safeInt(raw['removed_bytes']),
+ sqlRowsDeleted: _safeInt(raw['sql_rows_deleted']),
+ executionTimeMs: _safeDouble(raw['execution_time_ms']),
+ );
+ } on Object catch (error) {
+ if (generation == _generation && scope == _scopeId) {
+ notice = error is MalformedResponse
+ ? 'The deletion preview could not be verified. Nothing was deleted.'
+ : _cloudDeletionError(error, preview: true);
+ emit();
+ }
+ return null;
+ } finally {
+ if (generation == _generation && scope == _scopeId) {
+ busy = false;
+ phase = '';
+ _work = null;
+ emit();
+ }
+ }
+ }
+
+ Future<CloudDeletionResult> deleteCloudLibrary() async {
+ final gateway = _gateway;
+ final directory = _directory;
+ if (gateway == null || directory == null || !canDeleteCloudLibrary) {
+ return CloudDeletionResult.failed;
+ }
+ final generation = _generation;
+ final scope = _scopeId;
+ final savedClips = clips.map((c) => c.copy()).toList();
+ final savedEvents = List<ArchiveEvent>.from(events);
+ busy = true;
+ phase = 'Deleting cloud library';
+ notice = '';
+ invalidateSearch();
+ final token = CancellationToken();
+ _work = token;
+ emit();
+ try {
+ final response = await gateway.deleteLibrary(token);
+ _validateDeletion(response, 'ok', scope);
+
+ for (final clip in savedClips) {
+ clip.uploaded = false;
+ clip.remoteAssetId = null;
+ }
+ savedClips.removeWhere((clip) => !clip.bundled && clip.path == null);
+ savedEvents.insert(
+ 0,
+ ArchiveEvent(
+ 'Cloud library deleted',
+ 'All cloud videos, metadata, and search indexes removed; device videos kept',
+ ),
+ );
+ if (savedEvents.length > 40) savedEvents.removeLast();
+ gateway.version = null;
+
+ final current = generation == _generation && scope == _scopeId;
+ if (current) {
+ clips = savedClips;
+ events
+ ..clear()
+ ..addAll(savedEvents);
+ pendingJob = '';
+ indexVersion = null;
+ activeQuery = '';
+ batch = null;
+ notice = 'Cloud library deleted. Videos on this device were kept.';
+ emit();
+ }
+ try {
+ await _saveStrict(directory, savedClips, '', savedEvents);
+ _pendingReconciliation.remove(scope);
+ return CloudDeletionResult.deleted;
+ } on Object {
+ _pendingReconciliation[scope] = _ArchiveSnapshot(
+ savedClips.map((c) => c.copy()).toList(),
+ '',
+ List<ArchiveEvent>.from(savedEvents),
+ );
+ if (current) {
+ notice =
+ 'Cloud library was deleted, but local status could not be saved. Your device videos were kept.';
+ emit();
+ }
+ return CloudDeletionResult.partial;
+ }
+ } on Object catch (error) {
+ if (generation == _generation && scope == _scopeId) {
+ notice = _cloudDeletionError(error);
+ emit();
+ }
+ return CloudDeletionResult.failed;
+ } finally {
+ if (generation == _generation && scope == _scopeId) {
+ busy = false;
+ phase = '';
+ _work = null;
+ emit();
+ }
+ }
+ }
+
+ void _validateDeletion(
+ DeleteCollectionResponse response,
+ String expectedStatus,
+ String scope,
+ ) {
+ final raw = response.raw;
+ if ('${raw['status'] ?? ''}' != expectedStatus ||
+ raw.containsKey('group_name') && '${raw['group_name']}' != scope ||
+ raw.containsKey('mode') && '${raw['mode']}' != 'vid_file' ||
+ raw.containsKey('scope') && '${raw['scope']}' != 'all') {
+ throw const MalformedResponse('Unverified collection deletion');
+ }
+ }
+
Future<void> uploadAndIndex() async {
final gateway = _gateway;
if (gateway == null || busy || !canWrite) return;
@@ -330,6 +637,7 @@ class ArchiveController extends ChangeNotifier {
final result = await task.result;
token.throwIfCanceled();
if (!result.uploaded) throw const TransportException();
+ if (result.assetId != null) clip.remoteAssetId = result.assetId;
clip.uploaded = true;
record(
'Uploaded',
@@ -522,6 +830,27 @@ String safeError(Object error) {
return 'The operation could not finish. Check the connection and try again.';
}
+int _safeInt(Object? value) =>
+ value is num ? value.toInt() : int.tryParse('$value') ?? 0;
+
+double _safeDouble(Object? value) =>
+ value is num ? value.toDouble() : double.tryParse('$value') ?? 0;
+
+String _cloudDeletionError(Object error, {bool preview = false}) {
+ if (error is SdkException && error.statusCode == 409) {
+ return 'Cloud processing is still running. Wait for it to finish, then retry.';
+ }
+ if (error is SdkException &&
+ error.statusCode == 500 &&
+ '${error.body}'.toLowerCase().contains('partial delete failure')) {
+ return 'Cloud deletion may be incomplete. Local videos were kept. Reconnect and verify before retrying.';
+ }
+ if (preview) {
+ return 'The deletion preview could not be verified. Nothing was deleted.';
+ }
+ return 'Cloud deletion could not be confirmed. Local videos were kept. Reconnect and verify before retrying.';
+}
+
String timeLabel(double seconds) {
final value = seconds.isFinite ? seconds.floor().clamp(0, 86400) : 0;
return '${(value ~/ 60).toString().padLeft(2, '0')}:${(value % 60).toString().padLeft(2, '0')}';
diff --git a/example/05_framebase_userlogin/lib/data/search_gateway.dart b/example/05_framebase_userlogin/lib/data/search_gateway.dart
index 3cbd78e..5bbc97d 100644
--- a/example/05_framebase_userlogin/lib/data/search_gateway.dart
+++ b/example/05_framebase_userlogin/lib/data/search_gateway.dart
@@ -3,95 +3,32 @@ import 'dart:convert';
import 'dart:typed_data';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
-import '../user/user_collection.dart';
+import '../user/library_scope.dart';
-const archiveStream = userStream;
-
-String firstText(Map<String, Object?> row, List<String> fields) {
- for (final field in fields) {
- final text = '${row[field] ?? ''}'.trim();
- if (text.isNotEmpty) return text;
- }
- return '';
-}
+const archiveStream = 'street_study';
String basename(String path) => path.replaceAll('\\', '/').split('/').last;
-String hitFilename(Map<String, Object?> row) {
- final name = firstText(row, const [
- 'filename',
- 'filename_sanitized',
- 'video_filename',
- 'video',
- 'source_path',
- 'path',
- 'title',
- ]);
- if (name.isNotEmpty) return basename(name);
- var id = firstText(row, const ['item_id']);
- final stream = firstText(row, const ['stream', 'stream_name']);
- final ts = firstText(row, const ['ts_unix', 'ts_unix_13digits']);
- if (stream.isNotEmpty && id.startsWith('$stream-')) {
- id = id.substring(stream.length + 1);
- }
- if (ts.isNotEmpty && id.endsWith('-$ts')) {
- id = id.substring(0, id.length - ts.length - 1);
- }
- return basename(id);
-}
-
-String timestamp13(Map<String, Object?> row) {
- final text = firstText(row, const [
- 'ts_unix_13digits',
- 'ts_unix',
- 'timestamp_ms',
- ]);
- final value = num.tryParse(text);
- if (value == null || !value.isFinite || value < 0) return '';
- final digits = value.toInt().toString();
- if (digits.length >= 13) return digits.substring(0, 13);
- if (digits.length == 10) return '${value.toInt() * 1000}';
- return digits.padLeft(13, '0');
-}
-
-double? hitSeconds(Map<String, Object?> row) {
- for (final field in [
- 'video_time_seconds',
- 'timestamp_seconds',
- 'time_seconds',
- 'start_seconds',
- 'offset_seconds',
- 'seconds',
- 'time_sec',
- ]) {
- final n = num.tryParse('${row[field]}');
- if (n != null && n.isFinite && n >= 0) return n.toDouble();
- }
- // The live video index returns zero-padded relative milliseconds in ts_unix.
- // Epoch values are deliberately not interpreted as playback positions.
- final ms = num.tryParse(
- firstText(row, const ['ts_unix_13digits', 'ts_unix', 'timestamp_ms']),
- );
- if (ms != null && ms.isFinite && ms >= 0 && ms < 86400000) return ms / 1000;
- return null;
-}
-
class FrameMatch {
- const FrameMatch({
- required this.row,
- required this.filename,
- required this.timestamp,
- this.imageUrl,
- this.imageBytes,
- this.seconds,
- });
- final Map<String, Object?> row;
- final String filename;
- final String timestamp;
+ const FrameMatch({required this.hit, this.imageUrl, this.imageBytes});
+ final VideoSearchHit hit;
final String? imageUrl;
final Uint8List? imageBytes;
- final double? seconds;
- double? get distance => num.tryParse('${row['score']}')?.toDouble();
+ String? get assetId => hit.assetId;
+ String get fileName => hit.fileName ?? '';
+ String get sourceKey => hit.assetId ?? hit.fileName ?? '';
+ double? get seconds =>
+ hit.playbackOffsetMs == null ? null : hit.playbackOffsetMs! / 1000;
+ double? get distance => hit.distance;
+}
+
+bool trustedPreviewUrl(String value) {
+ final uri = Uri.tryParse(value);
+ return uri != null &&
+ (uri.scheme == 'https' ||
+ (!uri.hasScheme &&
+ !uri.hasAuthority &&
+ uri.path == '/api/external/v1/image/get_image'));
}
class SearchBatch {
@@ -114,10 +51,10 @@ class SearchBatch {
class SearchGateway {
SearchGateway(
this.keys,
- String collectionUserId, {
+ String scopeId, {
VmodalTransport? transport,
Future<void> Function()? ensureFresh,
- }) : collection = encodedUserCollection(collectionUserId),
+ }) : collection = validateLibraryScope(scopeId),
// ignore: prefer_initializing_formals
_ensureFresh = ensureFresh {
client = VmodalClient(
@@ -181,6 +118,32 @@ class SearchGateway {
);
}
+ Future<DeleteCollectionResponse> previewLibraryDeletion(
+ CancellationToken cancellation,
+ ) => _call(
+ () => client.collections.delete(
+ groupName: collection,
+ mode: 'vid_file',
+ scope: 'all',
+ dryRun: true,
+ confirm: false,
+ cancellation: cancellation,
+ ),
+ );
+
+ Future<DeleteCollectionResponse> deleteLibrary(
+ CancellationToken cancellation,
+ ) => _call(
+ () => client.collections.delete(
+ groupName: collection,
+ mode: 'vid_file',
+ scope: 'all',
+ dryRun: false,
+ confirm: true,
+ cancellation: cancellation,
+ ),
+ );
+
Future<UploadTask<VideoUploadResponse>> upload(File file) async {
await _fresh();
return client.collections.videoUpload(
@@ -242,34 +205,40 @@ class SearchGateway {
),
);
final searchMs = timer.elapsedMilliseconds;
- final rows = response.data
- .whereType<Map>()
- .map((r) => r.map((k, v) => MapEntry('$k', v)))
- .toList();
// Enforce the displayed cutoff defensively on returned rows as well.
// A client-filtered result is distinct from the raw server result count.
- final usable = rows.where((r) {
- final distance = num.tryParse('${r['score']}');
- return hitFilename(r).isNotEmpty &&
- distance != null &&
- distance.isFinite &&
- distance <= maxDistance;
+ final usable = response.videoHits.where((hit) {
+ final distance = hit.distance;
+ return (hit.assetId ?? hit.fileName ?? '').trim().isNotEmpty &&
+ (distance == null || distance <= maxDistance);
}).toList();
final urls = <int, String>{};
final imageBytes = <int, Uint8List>{};
- if (usable.isNotEmpty) {
+ for (var i = 0; i < usable.length; i++) {
+ final preview = usable[i].previewImageUrl;
+ if (preview != null && trustedPreviewUrl(preview)) urls[i] = preview;
+ }
+ final lookupIndexes = <int>[
+ for (var i = 0; i < usable.length; i++)
+ if (usable[i].previewImageUrl == null &&
+ (usable[i].fileName?.isNotEmpty ?? false))
+ i,
+ ];
+ if (lookupIndexes.isNotEmpty) {
final resolved = await _call(
() => client.images.getUrlBulk(
- usable
+ lookupIndexes
.map(
- (row) => <String, Object?>{
+ (index) => <String, Object?>{
'mode': 'vid_file',
'group_name': collection,
'modality': 'vid_img',
'stream_name': archiveStream,
- 'filename': hitFilename(row),
- if (timestamp13(row).isNotEmpty)
- 'ts_unix_13digits': timestamp13(row),
+ 'filename': usable[index].fileName,
+ if (usable[index].playbackOffsetMs != null)
+ 'ts_unix_13digits': usable[index].playbackOffsetMs
+ .toString()
+ .padLeft(13, '0'),
},
)
.toList(),
@@ -280,52 +249,46 @@ class SearchGateway {
final row = resolved.records[i];
final rawIndex = row['input_index'];
final parsed = num.tryParse('$rawIndex');
- final index = rawIndex == null
+ final recordIndex = rawIndex == null
? i
: parsed != null && parsed.isFinite && parsed == parsed.toInt()
? parsed.toInt()
: null;
final url = '${row['url_pre_signed'] ?? ''}';
- final uri = Uri.tryParse(url);
- final valid =
- uri != null &&
- (uri.scheme == 'https' ||
- (!uri.hasScheme &&
- !uri.hasAuthority &&
- uri.path == '/api/external/v1/image/get_image'));
- if (index != null &&
- index >= 0 &&
- index < usable.length &&
+ if (recordIndex != null &&
+ recordIndex >= 0 &&
+ recordIndex < lookupIndexes.length &&
row['found'] != false &&
- valid) {
+ trustedPreviewUrl(url)) {
+ final index = lookupIndexes[recordIndex];
urls.putIfAbsent(index, () => url);
}
}
- // The beta gateway returns relative signed image routes. Its supported
- // image-byte resource resolves those without guessing an absolute origin.
- if (urls.isNotEmpty) {
- final downloaded = await _call(
- () => client.images.getImageBulkFromUrls(
- urls.values.toList(),
- cancellation: token,
- ),
- );
- final byUrl = <String, Uint8List>{};
- for (final row in downloaded.records) {
- final url = '${row['url_pre_signed'] ?? ''}';
- final encoded = '${row['content_base64'] ?? ''}';
- if (url.isNotEmpty && encoded.isNotEmpty) {
- try {
- byUrl[url] = base64Decode(encoded);
- } on FormatException {
- /* Keep a per-card placeholder. */
- }
+ }
+ // Relative signed routes are downloaded through the SDK without guessing
+ // an absolute origin. A malformed image remains local to its result card.
+ if (urls.isNotEmpty) {
+ final downloaded = await _call(
+ () => client.images.getImageBulkFromUrls(
+ urls.values.toList(),
+ cancellation: token,
+ ),
+ );
+ final byUrl = <String, Uint8List>{};
+ for (final row in downloaded.records) {
+ final url = '${row['url_pre_signed'] ?? ''}';
+ final encoded = '${row['content_base64'] ?? ''}';
+ if (url.isNotEmpty && encoded.isNotEmpty) {
+ try {
+ byUrl[url] = base64Decode(encoded);
+ } on FormatException {
+ /* Keep a per-card placeholder. */
}
}
- for (final entry in urls.entries) {
- if (byUrl[entry.value] != null) {
- imageBytes[entry.key] = byUrl[entry.value]!;
- }
+ }
+ for (final entry in urls.entries) {
+ if (byUrl[entry.value] != null) {
+ imageBytes[entry.key] = byUrl[entry.value]!;
}
}
}
@@ -334,12 +297,9 @@ class SearchGateway {
matches: [
for (var i = 0; i < usable.length; i++)
FrameMatch(
- row: usable[i],
- filename: hitFilename(usable[i]),
- timestamp: timestamp13(usable[i]),
+ hit: usable[i],
imageUrl: urls[i]?.startsWith('https://') == true ? urls[i] : null,
imageBytes: imageBytes[i],
- seconds: hitSeconds(usable[i]),
),
],
total: response.cntTotal,
diff --git a/example/05_framebase_userlogin/lib/main.dart b/example/05_framebase_userlogin/lib/main.dart
index caaa5b4..df01acf 100644
--- a/example/05_framebase_userlogin/lib/main.dart
+++ b/example/05_framebase_userlogin/lib/main.dart
@@ -38,7 +38,8 @@ class FramebaseApp extends StatefulWidget {
State<FramebaseApp> createState() => _FramebaseAppState();
}
-class _FramebaseAppState extends State<FramebaseApp> {
+class _FramebaseAppState extends State<FramebaseApp>
+ with WidgetsBindingObserver {
late final ArchiveController archive;
late final UserSessionController session;
@override
@@ -52,10 +53,22 @@ class _FramebaseAppState extends State<FramebaseApp> {
credentials: MockVmodalCredentialSource(),
archive: archive,
);
+ WidgetsBinding.instance.addObserver(this);
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (state == AppLifecycleState.paused ||
+ state == AppLifecycleState.hidden ||
+ state == AppLifecycleState.detached) {
+ archive.stopWork();
+ archive.invalidateSearch();
+ }
}
@override
void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
if (widget.session == null) session.dispose();
if (widget.controller == null) archive.dispose();
super.dispose();
@@ -280,6 +293,14 @@ class _LibraryPageState extends State<LibraryPage> {
),
);
}
+ if (value == 'storage') {
+ Navigator.push(
+ context,
+ MaterialPageRoute<void>(
+ builder: (_) => StorageDeletionPage(archive: archive),
+ ),
+ );
+ }
if (value == 'prepare' && widget.session.canWrite) {
prepareArchive(context, archive);
}
@@ -295,6 +316,10 @@ class _LibraryPageState extends State<LibraryPage> {
value: 'history',
child: Text('Sync history'),
),
+ const PopupMenuItem(
+ value: 'storage',
+ child: Text('Storage & deletion'),
+ ),
],
),
],
@@ -325,7 +350,19 @@ class _LibraryPageState extends State<LibraryPage> {
for (final clip in archive.clips)
VideoRow(
clip: clip,
- onTap: () => showRecording(context, archive, clip),
+ onTap: () {
+ if (clip.remoteOnly) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(
+ content: Text(
+ 'This video is in the cloud but is not stored on this device.',
+ ),
+ ),
+ );
+ } else {
+ showRecording(context, archive, clip);
+ }
+ },
),
if (archive.busy) ...[
const SizedBox(height: 12),
@@ -494,7 +531,9 @@ class VideoRow extends StatelessWidget {
padding: const EdgeInsets.only(bottom: 14),
child: Semantics(
button: true,
- label: 'Play ${clip.title}',
+ label: clip.remoteOnly
+ ? '${clip.title}, cloud only, not on this device'
+ : 'Play ${clip.title}',
child: ClipRRect(
borderRadius: BorderRadius.circular(18),
child: AspectRatio(
@@ -539,7 +578,9 @@ class VideoRow extends StatelessWidget {
),
const SizedBox(height: 5),
Text(
- city(clip),
+ clip.remoteOnly
+ ? 'Cloud only · Not on this device'
+ : city(clip),
style: const TextStyle(
fontSize: 12,
color: Color(0xFFDFE5DF),
@@ -564,8 +605,10 @@ class VideoRow extends StatelessWidget {
width: .7,
),
),
- child: const Icon(
- Icons.play_arrow_rounded,
+ child: Icon(
+ clip.remoteOnly
+ ? Icons.cloud_done_outlined
+ : Icons.play_arrow_rounded,
color: Colors.white,
size: 24,
),
@@ -637,7 +680,7 @@ class TimeBadge extends StatelessWidget {
Map<String, List<FrameMatch>> groupMoments(List<FrameMatch> hits) {
final groups = <String, List<FrameMatch>>{};
for (final hit in hits) {
- final moments = groups.putIfAbsent(hit.filename, () => []);
+ final moments = groups.putIfAbsent(hit.sourceKey, () => []);
final t = hit.seconds;
if (moments.any(
(m) => t != null && m.seconds != null && (t - m.seconds!).abs() < 6,
@@ -833,7 +876,10 @@ class _SearchPageState extends State<SearchPage> {
),
for (final entry in groups.entries) ...[
Text(
- archive.clipFor(entry.key)?.title ?? entry.key,
+ archive.clipFor(entry.value.first.hit)?.title ??
+ (entry.value.first.fileName.isNotEmpty
+ ? entry.value.first.fileName
+ : entry.key),
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
@@ -841,9 +887,9 @@ class _SearchPageState extends State<SearchPage> {
),
const SizedBox(height: 4),
Text(
- archive.clipFor(entry.key) == null
+ archive.clipFor(entry.value.first.hit) == null
? 'Not stored on this device'
- : city(archive.clipFor(entry.key)!),
+ : city(archive.clipFor(entry.value.first.hit)!),
style: const TextStyle(color: secondary, fontSize: 13),
),
const SizedBox(height: 12),
@@ -867,8 +913,10 @@ class _SearchPageState extends State<SearchPage> {
key: Key('moment_${entry.key}_$i'),
hit: entry.value[i],
onTap: () {
- final clip = archive.clipFor(entry.key);
- if (clip != null) {
+ final clip = archive.clipFor(
+ entry.value[i].hit,
+ );
+ if (clip != null && !clip.remoteOnly) {
showRecording(
context,
archive,
@@ -880,7 +928,7 @@ class _SearchPageState extends State<SearchPage> {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
- 'This video is not stored on this device.',
+ 'This video is in the cloud but is not stored on this device.',
),
),
);
@@ -1048,6 +1096,50 @@ class _RecordingSheetState extends State<RecordingSheet> {
}
}
+ Future<void> removeLocalCopy() async {
+ final uploaded = widget.clip.uploaded;
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Remove device copy?'),
+ content: Text(
+ uploaded
+ ? 'This removes only the copy on this device. The cloud copy remains searchable until you delete the complete cloud library.'
+ : 'This removes the copy on this device and removes this local-only video from the library.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('confirm_remove_local_copy'),
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Remove device copy'),
+ ),
+ ],
+ ),
+ );
+ if (confirmed != true || !mounted) return;
+ final messenger = ScaffoldMessenger.of(context);
+ final old = player;
+ old?.removeListener(refresh);
+ await old?.pause();
+ await old?.dispose();
+ player = null;
+ final result = await widget.archive.removeLocalCopy(widget.clip);
+ if (!mounted) return;
+ if (result == LocalRemovalResult.unavailable) {
+ setState(
+ () => error = 'The video could not be removed from this device.',
+ );
+ unawaited(load());
+ return;
+ }
+ Navigator.pop(context);
+ messenger.showSnackBar(SnackBar(content: Text(widget.archive.notice)));
+ }
+
void refresh() {
if (mounted) setState(() {});
}
@@ -1130,6 +1222,23 @@ class _RecordingSheetState extends State<RecordingSheet> {
),
if (error != null)
Padding(padding: const EdgeInsets.all(16), child: Text(error!)),
+ if (!widget.clip.bundled && widget.clip.path != null)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton.icon(
+ key: const Key('remove_local_copy'),
+ onPressed:
+ widget.archive.busy ||
+ widget.archive.pendingJob.isNotEmpty
+ ? null
+ : removeLocalCopy,
+ icon: const Icon(Icons.delete_outline),
+ label: const Text('Remove device copy'),
+ style: TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
if (p != null) ...[
if (widget.moments.length > 1) ...[
const SizedBox(height: 16),
@@ -1313,6 +1422,139 @@ class WorkStatus extends StatelessWidget {
);
}
+class StorageDeletionPage extends StatelessWidget {
+ const StorageDeletionPage({super.key, required this.archive});
+ final ArchiveController archive;
+
+ Future<void> deleteCloudLibrary(BuildContext context) async {
+ final previewApproved = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Delete cloud library?'),
+ content: const Text(
+ 'This affects all cloud videos, metadata, and search indexes in this issued library scope. Videos stored on this device remain.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Preview deletion'),
+ ),
+ ],
+ ),
+ );
+ if (previewApproved != true || !context.mounted) return;
+ final preview = await archive.previewCloudLibraryDeletion();
+ if (!context.mounted) return;
+ if (preview == null) {
+ ScaffoldMessenger.of(
+ context,
+ ).showSnackBar(SnackBar(content: Text(archive.notice)));
+ return;
+ }
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Deletion preview'),
+ content: Text(
+ 'Cloud data selected: ${preview.removedBytes} bytes\n'
+ 'Metadata rows selected: ${preview.sqlRowsDeleted}\n'
+ 'Preview time: ${preview.executionTimeMs.toStringAsFixed(0)} ms\n\n'
+ 'Deleting removes the complete cloud library and search indexes. Device videos remain.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('confirm_delete_cloud_library'),
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Delete cloud library'),
+ ),
+ ],
+ ),
+ );
+ if (confirmed != true || !context.mounted) return;
+ await archive.deleteCloudLibrary();
+ if (!context.mounted) return;
+ ScaffoldMessenger.of(
+ context,
+ ).showSnackBar(SnackBar(content: Text(archive.notice)));
+ }
+
+ @override
+ Widget build(BuildContext context) => AnimatedBuilder(
+ animation: archive,
+ builder: (context, _) => Scaffold(
+ appBar: AppBar(title: const Text('Storage & deletion')),
+ body: ListView(
+ padding: const EdgeInsets.all(24),
+ children: [
+ const Text(
+ 'Your videos have three separate retention domains:',
+ style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
+ ),
+ const SizedBox(height: 16),
+ const ListTile(
+ contentPadding: EdgeInsets.zero,
+ leading: Icon(Icons.phone_android),
+ title: Text('Device MP4 and manifest'),
+ subtitle: Text(
+ 'Kept until explicit local removal, app uninstall or platform cleanup, or operating-system storage eviction where applicable.',
+ ),
+ ),
+ const ListTile(
+ contentPadding: EdgeInsets.zero,
+ leading: Icon(Icons.cloud_outlined),
+ title: Text('Cloud video and metadata'),
+ subtitle: Text(
+ 'Removing a device copy does not remove its uploaded cloud copy.',
+ ),
+ ),
+ const ListTile(
+ contentPadding: EdgeInsets.zero,
+ leading: Icon(Icons.manage_search),
+ title: Text('Derived search index'),
+ subtitle: Text(
+ 'Complete cloud deletion also removes the searchable index.',
+ ),
+ ),
+ const SizedBox(height: 12),
+ const Text(
+ 'Signing out keeps videos on this device and in the cloud.',
+ ),
+ const SizedBox(height: 20),
+ if (archive.pendingJob.isNotEmpty)
+ const Text(
+ 'Cloud processing is still running. Wait for it to finish before deletion.',
+ ),
+ if (archive.busy) WorkStatus(archive: archive),
+ FilledButton.icon(
+ key: const Key('delete_cloud_library'),
+ onPressed: archive.canDeleteCloudLibrary
+ ? () => deleteCloudLibrary(context)
+ : null,
+ icon: const Icon(Icons.delete_forever_outlined),
+ label: const Text('Delete cloud library'),
+ style: FilledButton.styleFrom(
+ backgroundColor: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ const SizedBox(height: 8),
+ const Text(
+ 'Stopping the wait cannot undo a deletion already committed by the server.',
+ style: TextStyle(color: secondary, fontSize: 12),
+ ),
+ ],
+ ),
+ ),
+ );
+}
+
class HistoryPage extends StatelessWidget {
const HistoryPage({super.key, required this.archive});
final ArchiveController archive;
@@ -1377,7 +1619,7 @@ Future<void> showSearchDetails(
),
const SizedBox(height: 16),
const Text(
- 'Nearby frames from the same video are combined in the results. Distance is similarity, not confidence.',
+ 'Nearby frames from the same video are combined in the results. Distance is lower-is-better; it is not similarity or confidence.',
),
],
],
diff --git a/example/05_framebase_userlogin/lib/user/auth_adapter.dart b/example/05_framebase_userlogin/lib/user/auth_adapter.dart
index 2881199..215757e 100644
--- a/example/05_framebase_userlogin/lib/user/auth_adapter.dart
+++ b/example/05_framebase_userlogin/lib/user/auth_adapter.dart
@@ -7,6 +7,18 @@ class AppUser {
String get displayName => label ?? email ?? uid;
}
+/// The Firebase identity cannot be renewed without authenticating again.
+class FirebaseIdentityExpired implements Exception {
+ const FirebaseIdentityExpired();
+}
+
+/// Firebase token acquisition failed because of a temporary provider issue.
+class FirebaseIdentityTransient implements Exception {
+ const FirebaseIdentityTransient();
+}
+
+/// App implementations must translate provider-specific token failures into
+/// [FirebaseIdentityExpired] or [FirebaseIdentityTransient].
abstract interface class FirebaseAuthAdapter {
Stream<AppUser?> get users;
Future<void> signIn(String email, String password);
diff --git a/example/05_framebase_userlogin/lib/user/library_scope.dart b/example/05_framebase_userlogin/lib/user/library_scope.dart
new file mode 100644
index 0000000..b8263f4
--- /dev/null
+++ b/example/05_framebase_userlogin/lib/user/library_scope.dart
@@ -0,0 +1,15 @@
+final _validLibraryScope = RegExp(r'^[A-Za-z0-9_]+$');
+
+String validateLibraryScope(Object? scope) {
+ if (scope is! String ||
+ scope.isEmpty ||
+ scope.length > 80 ||
+ !_validLibraryScope.hasMatch(scope)) {
+ throw const InvalidLibraryScope();
+ }
+ return scope;
+}
+
+class InvalidLibraryScope implements Exception {
+ const InvalidLibraryScope();
+}
diff --git a/example/05_framebase_userlogin/lib/user/login_page.dart b/example/05_framebase_userlogin/lib/user/login_page.dart
index 1c0291f..c724a03 100644
--- a/example/05_framebase_userlogin/lib/user/login_page.dart
+++ b/example/05_framebase_userlogin/lib/user/login_page.dart
@@ -40,18 +40,30 @@ class _LoginPageState extends State<LoginPage> {
const LinearProgressIndicator(),
const SizedBox(height: 16),
const Text('Loading your library…'),
- ] else if (state == SessionState.denied ||
+ ] else if (state == SessionState.recoverable ||
+ state == SessionState.denied ||
state == SessionState.error) ...[
Text(widget.session.message),
const SizedBox(height: 16),
- FilledButton(
- onPressed: widget.session.retry,
- child: const Text('Retry'),
- ),
- TextButton(
- onPressed: widget.session.signOut,
- child: const Text('Sign out'),
- ),
+ if (widget.session.failureKind ==
+ SessionFailureKind.firebaseIdentityExpired ||
+ widget.session.failureKind ==
+ SessionFailureKind.vmodalUnauthorized)
+ FilledButton(
+ onPressed: widget.session.signOut,
+ child: const Text('Sign in again'),
+ )
+ else ...[
+ if (widget.session.canRetry)
+ FilledButton(
+ onPressed: widget.session.retry,
+ child: const Text('Retry'),
+ ),
+ TextButton(
+ onPressed: widget.session.signOut,
+ child: const Text('Sign out'),
+ ),
+ ],
] else ...[
const Text(
'Sign in to your street library',
@@ -126,6 +138,10 @@ class ProfileSheet extends StatelessWidget {
'Upload and prepare: ${session.canWrite ? 'allowed' : 'unavailable'}',
),
const SizedBox(height: 16),
+ const Text(
+ 'Signing out keeps videos on this device and in the cloud.',
+ ),
+ const SizedBox(height: 12),
FilledButton(
key: const Key('sign_out'),
onPressed: () {
diff --git a/example/05_framebase_userlogin/lib/user/user_collection.dart b/example/05_framebase_userlogin/lib/user/user_collection.dart
deleted file mode 100644
index 905e04b..0000000
--- a/example/05_framebase_userlogin/lib/user/user_collection.dart
+++ /dev/null
@@ -1,19 +0,0 @@
-import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
-
-const userProject = 'framebase_streets';
-const userStream = 'street_study';
-final _validId = RegExp(r'^[A-Za-z0-9_]+$');
-
-String userCollection(String id) {
- if (id.isEmpty || !_validId.hasMatch(id) || id.contains('__')) {
- throw const ValidationException('Invalid collection user ID');
- }
- final name = 'user_$id';
- if ('${userProject}__$name'.length > 80) {
- throw const ValidationException('Collection user ID is too long');
- }
- return name;
-}
-
-String encodedUserCollection(String id) =>
- '${userProject}__${userCollection(id)}';
diff --git a/example/05_framebase_userlogin/lib/user/user_session_controller.dart b/example/05_framebase_userlogin/lib/user/user_session_controller.dart
index b886591..86821fc 100644
--- a/example/05_framebase_userlogin/lib/user/user_session_controller.dart
+++ b/example/05_framebase_userlogin/lib/user/user_session_controller.dart
@@ -8,12 +8,29 @@ import '../data/search_gateway.dart';
import 'auth_adapter.dart';
import 'vmodal_credential.dart';
-enum SessionState { loading, signedOut, resolving, ready, denied, error }
+enum SessionState {
+ loading,
+ signedOut,
+ resolving,
+ ready,
+ recoverable,
+ denied,
+ error,
+}
+
+enum SessionFailureKind {
+ transient,
+ firebaseIdentityExpired,
+ credentialDenied,
+ vmodalUnauthorized,
+ vmodalForbidden,
+ contract,
+}
typedef GatewayFactory =
SearchGateway Function(
MutableApiKeyProvider provider,
- String collectionUserId,
+ String scopeId,
Future<void> Function() ensureFresh,
);
@@ -24,21 +41,38 @@ class UserSessionController extends ChangeNotifier {
required this.archive,
GatewayFactory? gatewayFactory,
DateTime Function()? clock,
+ Future<void> Function(Duration)? delay,
}) : gatewayFactory =
gatewayFactory ??
((provider, id, fresh) =>
SearchGateway(provider, id, ensureFresh: fresh)),
- clock = clock ?? DateTime.now {
+ clock = clock ?? DateTime.now,
+ delay = delay ?? Future<void>.delayed {
_subscription = auth.users.listen(_onUser);
}
+ static const _transientMessage =
+ 'Connection interrupted. Retry to reconnect your library.';
+ static const _identityMessage = 'Your sign-in expired. Sign in again.';
+ static const _deniedMessage = 'Access to this library is unavailable.';
+ static const _unauthorizedMessage =
+ 'Your library session expired. Sign in again.';
+ static const _contractMessage =
+ 'The library connection is not configured correctly.';
+ static const _backoff = [
+ Duration(milliseconds: 250),
+ Duration(milliseconds: 500),
+ ];
+
final FirebaseAuthAdapter auth;
final VmodalCredentialSource credentials;
final ArchiveController archive;
final GatewayFactory gatewayFactory;
final DateTime Function() clock;
+ final Future<void> Function(Duration) delay;
late final StreamSubscription<AppUser?> _subscription;
SessionState state = SessionState.loading;
+ SessionFailureKind? failureKind;
AppUser? user;
VmodalCredential? _credential;
MutableApiKeyProvider? _provider;
@@ -50,6 +84,7 @@ class UserSessionController extends ChangeNotifier {
int _generation = 0;
bool _disposed = false;
+ bool get canRetry => failureKind == SessionFailureKind.transient;
bool get canRead =>
state == SessionState.ready &&
(_credential?.permissions.contains('library:read') ?? false);
@@ -80,6 +115,7 @@ class UserSessionController extends ChangeNotifier {
if (next?.uid == user?.uid && state != SessionState.loading) return;
_teardown();
user = next;
+ failureKind = null;
message = '';
state = next == null ? SessionState.signedOut : SessionState.resolving;
_notify();
@@ -89,25 +125,64 @@ class UserSessionController extends ChangeNotifier {
bool _current(AppUser account, int generation) =>
!_disposed && generation == _generation && user?.uid == account.uid;
+ Future<VmodalCredential> _acquire(
+ AppUser account,
+ int generation, {
+ VmodalCredential? previous,
+ }) async {
+ Object? failure;
+ for (var attempt = 0; attempt < 3; attempt++) {
+ if (!_current(account, generation)) {
+ throw failure ?? const CredentialDenied();
+ }
+ try {
+ final firebaseToken = await auth.idToken(account);
+ if (!_current(account, generation)) {
+ throw const CredentialDenied();
+ }
+ final credential = await credentials.acquire(account, firebaseToken);
+ if (!_current(account, generation)) {
+ throw const CredentialDenied();
+ }
+ credential.validate(account, clock(), previous: previous);
+ return credential;
+ } on FirebaseIdentityTransient catch (error) {
+ failure = error;
+ } on CredentialTransient catch (error) {
+ failure = error;
+ }
+ if (attempt == 2) throw failure;
+ if (!_current(account, generation)) throw failure;
+ await delay(_backoff[attempt]);
+ if (!_current(account, generation)) throw failure;
+ }
+ throw failure!;
+ }
+
Future<void> _resolve(AppUser account, int generation) async {
SearchGateway? next;
try {
- final firebaseToken = await auth.idToken(account);
- if (!_current(account, generation)) return;
- final credential = await credentials.acquire(account, firebaseToken);
+ final credential = await _acquire(account, generation);
if (!_current(account, generation)) return;
- credential.validate(account, clock());
final provider = MutableApiKeyProvider(credential.apiToken!);
_provider = provider;
_credential = credential;
- next = gatewayFactory(
- provider,
- credential.collectionUserId!,
- ensureFresh,
- );
+ next = gatewayFactory(provider, credential.scopeId!, ensureFresh);
next.onAccessFailure = (status) {
if (_current(account, generation)) {
- _fail(status == 403 ? SessionState.denied : SessionState.error);
+ if (status == 403) {
+ _fail(
+ SessionState.denied,
+ SessionFailureKind.vmodalForbidden,
+ _deniedMessage,
+ );
+ } else {
+ _fail(
+ SessionState.error,
+ SessionFailureKind.vmodalUnauthorized,
+ _unauthorizedMessage,
+ );
+ }
}
};
await next.connect(credential.vmodalUserId!);
@@ -117,30 +192,72 @@ class UserSessionController extends ChangeNotifier {
}
gateway = next;
await archive.activate(
- credential.collectionUserId!,
+ credential.scopeId!,
next,
canRead: credential.permissions.contains('library:read'),
canWrite: credential.permissions.contains('library:write'),
);
if (!_current(account, generation)) return;
state = SessionState.ready;
+ failureKind = null;
+ message = '';
_schedule();
_notify();
- } on CredentialDenied {
- if (_current(account, generation)) _fail(SessionState.denied);
+ } on FirebaseIdentityTransient {
+ if (_current(account, generation)) _recover();
if (next != null && next != gateway) await next.close();
- } on Object {
- if (_current(account, generation)) _fail(SessionState.error);
+ } on CredentialTransient {
+ if (_current(account, generation)) _recover();
+ if (next != null && next != gateway) await next.close();
+ } on Object catch (error) {
+ if (_current(account, generation)) _failFor(error);
if (next != null && next != gateway) await next.close();
}
}
- void _fail(SessionState next) {
+ void _recover() {
+ state = SessionState.recoverable;
+ failureKind = SessionFailureKind.transient;
+ message = _transientMessage;
+ _notify();
+ }
+
+ void _failFor(Object error) {
+ if (error is FirebaseIdentityExpired) {
+ _fail(
+ SessionState.error,
+ SessionFailureKind.firebaseIdentityExpired,
+ _identityMessage,
+ );
+ } else if (error is CredentialDenied) {
+ _fail(
+ SessionState.denied,
+ SessionFailureKind.credentialDenied,
+ _deniedMessage,
+ );
+ } else if (error is AuthException ||
+ error is ApiException && error.statusCode == 401) {
+ _fail(
+ SessionState.error,
+ SessionFailureKind.vmodalUnauthorized,
+ _unauthorizedMessage,
+ );
+ } else if (error is ApiException && error.statusCode == 403) {
+ _fail(
+ SessionState.denied,
+ SessionFailureKind.vmodalForbidden,
+ _deniedMessage,
+ );
+ } else {
+ _fail(SessionState.error, SessionFailureKind.contract, _contractMessage);
+ }
+ }
+
+ void _fail(SessionState next, SessionFailureKind kind, String safeMessage) {
_teardown();
state = next;
- message = next == SessionState.denied
- ? 'Access to this library is unavailable.'
- : 'Could not connect your library. Please retry.';
+ failureKind = kind;
+ message = safeMessage;
_notify();
}
@@ -148,9 +265,9 @@ class UserSessionController extends ChangeNotifier {
_timer?.cancel();
final expiry = _credential?.expiresAt;
if (expiry == null) return;
- final delay =
+ final wait =
expiry.difference(clock().toUtc()) - const Duration(seconds: 60);
- _timer = Timer(delay.isNegative ? Duration.zero : delay, () {
+ _timer = Timer(wait.isNegative ? Duration.zero : wait, () {
unawaited(ensureFresh().catchError((Object _) {}));
});
}
@@ -166,6 +283,10 @@ class UserSessionController extends ChangeNotifier {
)) {
return Future.value();
}
+ return _startRefresh(account);
+ }
+
+ Future<void> _startRefresh(AppUser account) {
final current = _refreshing;
if (current != null) return current;
final task = _refresh(account, _generation);
@@ -183,17 +304,27 @@ class UserSessionController extends ChangeNotifier {
Future<void> _refresh(AppUser account, int generation) async {
try {
- final firebaseToken = await auth.idToken(account);
- if (!_current(account, generation)) throw const CredentialDenied();
- final renewed = await credentials.acquire(account, firebaseToken);
+ final renewed = await _acquire(
+ account,
+ generation,
+ previous: _credential,
+ );
if (!_current(account, generation)) throw const CredentialDenied();
- renewed.validate(account, clock(), previous: _credential);
_provider!.rotate(renewed.apiToken!);
_credential = renewed;
+ state = SessionState.ready;
+ failureKind = null;
+ message = '';
_schedule();
_notify();
- } on Object {
- if (_current(account, generation)) _fail(SessionState.error);
+ } on FirebaseIdentityTransient {
+ if (_current(account, generation)) _recover();
+ rethrow;
+ } on CredentialTransient {
+ if (_current(account, generation)) _recover();
+ rethrow;
+ } on Object catch (error) {
+ if (_current(account, generation)) _failFor(error);
rethrow;
}
}
@@ -215,18 +346,28 @@ class UserSessionController extends ChangeNotifier {
Future<void> retry() async {
final account = user;
- if (account == null) return;
- _teardown();
+ if (account == null || failureKind != SessionFailureKind.transient) return;
+ final established = _credential != null && _provider != null;
state = SessionState.resolving;
+ failureKind = null;
message = '';
_notify();
- await _resolve(account, _generation);
+ if (!established) {
+ await _resolve(account, _generation);
+ return;
+ }
+ try {
+ await _startRefresh(account);
+ } on Object {
+ // The typed failure has already updated the recoverable or terminal UI.
+ }
}
Future<void> signOut() async {
_teardown();
user = null;
state = SessionState.signedOut;
+ failureKind = null;
message = '';
_notify();
await auth.signOut();
diff --git a/example/05_framebase_userlogin/lib/user/vmodal_credential.dart b/example/05_framebase_userlogin/lib/user/vmodal_credential.dart
index 12d6e17..0609947 100644
--- a/example/05_framebase_userlogin/lib/user/vmodal_credential.dart
+++ b/example/05_framebase_userlogin/lib/user/vmodal_credential.dart
@@ -1,54 +1,78 @@
import 'auth_adapter.dart';
-import 'user_collection.dart';
+import 'library_scope.dart';
class VmodalCredential {
const VmodalCredential({
+ required this.contractVersion,
+ required this.sessionId,
+ required this.issuedAt,
required this.apiToken,
required this.expiresAt,
required this.firebaseUid,
required this.vmodalUserId,
- required this.collectionUserId,
+ required this.scopeId,
required this.allowed,
required this.permissions,
});
- final String? apiToken, firebaseUid, vmodalUserId, collectionUserId;
- final DateTime? expiresAt;
+ final int? contractVersion;
+ final String? sessionId, apiToken, firebaseUid, vmodalUserId, scopeId;
+ final DateTime? issuedAt, expiresAt;
final bool allowed;
final Set<String> permissions;
factory VmodalCredential.fromJson(Map<String, Object?> data) {
- final raw = data['expires_at'];
+ final issued = data['issued_at'];
+ final expires = data['expires_at'];
+ final permissions = data['permissions'];
return VmodalCredential(
- apiToken: data['api_token'] as String?,
- expiresAt: raw is String ? DateTime.tryParse(raw)?.toUtc() : null,
- firebaseUid: data['firebase_uid'] as String?,
- vmodalUserId: data['vmodal_user_id'] as String?,
- collectionUserId: data['collection_user_id'] as String?,
+ contractVersion: data['version'] is int ? data['version'] as int : null,
+ sessionId: data['session_id'] is String
+ ? data['session_id'] as String
+ : null,
+ issuedAt: issued is String ? DateTime.tryParse(issued)?.toUtc() : null,
+ apiToken: data['api_token'] is String
+ ? data['api_token'] as String
+ : null,
+ expiresAt: expires is String ? DateTime.tryParse(expires)?.toUtc() : null,
+ firebaseUid: data['firebase_uid'] is String
+ ? data['firebase_uid'] as String
+ : null,
+ vmodalUserId: data['vmodal_user_id'] is String
+ ? data['vmodal_user_id'] as String
+ : null,
+ scopeId: data['scope_id'] is String ? data['scope_id'] as String : null,
allowed: data['allowed'] == true,
- permissions: (data['permissions'] as List? ?? [])
- .whereType<String>()
- .toSet(),
+ permissions: permissions is List
+ ? permissions.whereType<String>().toSet()
+ : <String>{},
);
}
void validate(AppUser user, DateTime now, {VmodalCredential? previous}) {
- if (!allowed) throw const CredentialDenied();
- if (firebaseUid != user.uid ||
+ if (!allowed || !permissions.contains('library:read')) {
+ throw const CredentialDenied();
+ }
+ try {
+ validateLibraryScope(scopeId);
+ } on InvalidLibraryScope {
+ throw const CredentialContractError();
+ }
+ if (contractVersion != 1 ||
+ sessionId == null ||
+ sessionId!.trim().isEmpty ||
+ issuedAt == null ||
+ expiresAt == null ||
+ !issuedAt!.toUtc().isBefore(expiresAt!.toUtc()) ||
+ firebaseUid != user.uid ||
vmodalUserId == null ||
- vmodalUserId!.isEmpty ||
- collectionUserId == null ||
+ vmodalUserId!.trim().isEmpty ||
apiToken == null ||
apiToken!.trim().isEmpty ||
- expiresAt == null ||
- !expiresAt!.isAfter(now.toUtc()) ||
+ !expiresAt!.toUtc().isAfter(now.toUtc()) ||
(previous != null &&
(previous.vmodalUserId != vmodalUserId ||
- previous.collectionUserId != collectionUserId))) {
- throw const CredentialDenied();
- }
- userCollection(collectionUserId!);
- if (!permissions.contains('library:read')) {
- throw const CredentialDenied();
+ previous.scopeId != scopeId))) {
+ throw const CredentialContractError();
}
}
}
@@ -59,6 +83,20 @@ class CredentialDenied implements Exception {
String toString() => 'Access to this library is unavailable.';
}
+class CredentialTransient implements Exception {
+ const CredentialTransient();
+}
+
+class CredentialContractError implements Exception {
+ const CredentialContractError();
+}
+
+/// Exchanges app identity for a scoped VMODAL credential.
+///
+/// Implementations report explicit policy denial as [CredentialDenied],
+/// temporary network or issuer 5xx failures as [CredentialTransient], invalid
+/// responses or configuration as [CredentialContractError], and rejected or
+/// expired Firebase identity as [FirebaseIdentityExpired].
abstract interface class VmodalCredentialSource {
Future<VmodalCredential> acquire(AppUser user, String? firebaseIdToken);
}
@@ -84,11 +122,14 @@ class MockVmodalCredentialSource implements VmodalCredentialSource {
}
const emptyCredential = <String, Object?>{
+ 'version': null,
+ 'session_id': null,
+ 'issued_at': null,
'api_token': null,
'expires_at': null,
'firebase_uid': null,
'vmodal_user_id': null,
- 'collection_user_id': null,
+ 'scope_id': null,
'allowed': false,
'permissions': <String>[],
};
diff --git a/example/05_framebase_userlogin/test/archive_controller_test.dart b/example/05_framebase_userlogin/test/archive_controller_test.dart
index 5652fd3..0ebbef4 100644
--- a/example/05_framebase_userlogin/test/archive_controller_test.dart
+++ b/example/05_framebase_userlogin/test/archive_controller_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
@@ -5,16 +6,162 @@ import 'package:framebase/data/archive_controller.dart';
import 'package:framebase/data/search_gateway.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+class UploadGateway extends SearchGateway {
+ UploadGateway()
+ : super(MutableApiKeyProvider('fixture-upload'), 'scope_upload');
+
+ @override
+ Future<UploadTask<VideoUploadResponse>> upload(File file) async =>
+ UploadTask<VideoUploadResponse>.start((cancellation, emit) async {
+ emit(UploadProgress(file.lengthSync(), file.lengthSync()));
+ return VideoUploadResponse(const <String, Object?>{
+ 'uploaded': true,
+ 'asset_id': 'asset-uploaded',
+ });
+ });
+
+ @override
+ Future<IndexationSubmitResponse> createIndex(
+ CancellationToken cancellation,
+ ) async => IndexationSubmitResponse(const <String, Object?>{
+ 'job_id': 'job-ready',
+ 'status': 'queued',
+ });
+
+ @override
+ Future<IndexationStatusResponse> indexStatus(
+ String job,
+ CancellationToken cancellation,
+ ) async => IndexationStatusResponse(const <String, Object?>{
+ 'job_id': 'job-ready',
+ 'status': 'success',
+ });
+
+ @override
+ Future<void> refreshVersion() async => version = 1;
+}
+
+class DeleteGateway extends SearchGateway {
+ DeleteGateway({this.deleteError})
+ : super(MutableApiKeyProvider('fixture-delete'), 'scope_delete');
+ final Object? deleteError;
+ int previews = 0;
+ int deletes = 0;
+
+ @override
+ Future<DeleteCollectionResponse> previewLibraryDeletion(
+ CancellationToken cancellation,
+ ) async {
+ cancellation.throwIfCanceled();
+ previews++;
+ return DeleteCollectionResponse(const <String, Object?>{
+ 'status': 'dry_run',
+ 'group_name': 'scope_delete',
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ 'removed_bytes': 12,
+ 'sql_rows_deleted': 3,
+ 'execution_time_ms': 4,
+ });
+ }
+
+ @override
+ Future<DeleteCollectionResponse> deleteLibrary(
+ CancellationToken cancellation,
+ ) async {
+ cancellation.throwIfCanceled();
+ deletes++;
+ if (deleteError case final Object error) throw error;
+ return DeleteCollectionResponse(const <String, Object?>{
+ 'status': 'ok',
+ 'group_name': 'scope_delete',
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ });
+ }
+}
+
+class DelayedDeleteGateway extends DeleteGateway {
+ final Completer<DeleteCollectionResponse> completion =
+ Completer<DeleteCollectionResponse>();
+
+ @override
+ Future<DeleteCollectionResponse> deleteLibrary(
+ CancellationToken cancellation,
+ ) {
+ deletes++;
+ return completion.future;
+ }
+}
+
+class BlockingGateway extends SearchGateway {
+ BlockingGateway()
+ : super(MutableApiKeyProvider('fixture-blocking'), 'scope_blocking') {
+ version = 1;
+ }
+
+ final uploadStarted = Completer<void>();
+ final indexStarted = Completer<void>();
+ final searchStarted = Completer<void>();
+ UploadTask<VideoUploadResponse>? activeUpload;
+
+ @override
+ Future<UploadTask<VideoUploadResponse>> upload(File file) async {
+ final task = UploadTask<VideoUploadResponse>.start((token, emit) async {
+ uploadStarted.complete();
+ await token.whenCanceled;
+ token.throwIfCanceled();
+ throw StateError('Canceled upload continued');
+ });
+ activeUpload = task;
+ return task;
+ }
+
+ @override
+ Future<IndexationSubmitResponse> createIndex(
+ CancellationToken cancellation,
+ ) async => IndexationSubmitResponse(const <String, Object?>{
+ 'job_id': 'job-continues-remotely',
+ 'status': 'queued',
+ });
+
+ @override
+ Future<IndexationStatusResponse> indexStatus(
+ String job,
+ CancellationToken cancellation,
+ ) async {
+ indexStarted.complete();
+ await cancellation.whenCanceled;
+ cancellation.throwIfCanceled();
+ throw StateError('Canceled index polling continued');
+ }
+
+ @override
+ Future<SearchBatch> search(
+ String query, {
+ CancellationToken? cancellation,
+ String? imageQuery,
+ double maxDistance = 1.5,
+ }) async {
+ searchStarted.complete();
+ await cancellation!.whenCanceled;
+ cancellation.throwIfCanceled();
+ throw StateError('Canceled search continued');
+ }
+}
+
void main() {
test(
'archive manifests and imported files stay with their account',
() async {
final root = await Directory.systemTemp.createTemp('framebase_test_');
addTearDown(() => root.delete(recursive: true));
- final a = SearchGateway(MutableApiKeyProvider('fixture-a'), 'alice');
- final b = SearchGateway(MutableApiKeyProvider('fixture-b'), 'bob');
+ const scopeA = 'scope_7K3A';
+ const scopeB = 'scope_B9Q2';
+ final a = SearchGateway(MutableApiKeyProvider('fixture-a'), scopeA);
+ final b = SearchGateway(MutableApiKeyProvider('fixture-b'), scopeB);
final c = ArchiveController(supportDirectory: root);
- await c.activate('alice', a, canRead: true, canWrite: true);
+ await c.activate(scopeA, a, canRead: true, canWrite: true);
c.clips.first.uploaded = true;
c.pendingJob = 'alice-job';
c.record('Alice upload', 'done');
@@ -22,25 +169,376 @@ void main() {
await src.writeAsBytes([1, 2, 3]);
await c.importFile(src.path, 3);
await c.save();
- expect(c.clips.last.path, startsWith('${root.path}/accounts/alice/'));
+ expect(c.clips.last.path, startsWith('${root.path}/accounts/$scopeA/'));
c.deactivate();
expect(c.events, isEmpty);
expect(c.pendingJob, isEmpty);
- await c.activate('bob', b, canRead: true, canWrite: true);
+ await c.activate(scopeB, b, canRead: true, canWrite: true);
expect(c.clips, hasLength(3));
expect(c.clips.first.uploaded, isFalse);
expect(c.pendingJob, isEmpty);
expect(c.events, isEmpty);
- await c.activate('alice', a, canRead: true, canWrite: true);
+ await c.importFile(src.path, 4);
+ expect(c.clips.last.path, startsWith('${root.path}/accounts/$scopeB/'));
+ await c.activate(scopeA, a, canRead: true, canWrite: true);
expect(c.clips, hasLength(4));
expect(c.clips.first.uploaded, isTrue);
expect(c.pendingJob, 'alice-job');
expect(c.events.any((e) => e.title == 'Alice upload'), isTrue);
- final manifest = File('${root.path}/accounts/alice/archive.json');
- expect(await manifest.readAsString(), isNot(contains('fixture-a')));
+ final manifest = File('${root.path}/accounts/$scopeA/archive.json');
+ final saved = await manifest.readAsString();
+ for (final forbidden in [
+ 'fixture-a',
+ 'api_token',
+ 'session_id',
+ 'issued_at',
+ 'expires_at',
+ ]) {
+ expect(saved, isNot(contains(forbidden)));
+ }
+ expect(await Directory('${root.path}/accounts/$scopeB').exists(), isTrue);
await a.close();
await b.close();
c.dispose();
},
);
+
+ test(
+ 'active upload, index polling, and search unwind on cancellation',
+ () async {
+ final root = await Directory.systemTemp.createTemp('framebase_cancel_');
+ addTearDown(() => root.delete(recursive: true));
+ final source = File('${root.path}/camera.mp4')
+ ..writeAsBytesSync([1, 2, 3]);
+ final gateway = BlockingGateway();
+ final c = ArchiveController(supportDirectory: root);
+ await c.activate(
+ 'scope_blocking',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ );
+ c.clips = [
+ ArchiveClip(
+ id: 'camera',
+ title: 'Camera',
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ path: source.path,
+ bundled: false,
+ ),
+ ];
+
+ final upload = c.uploadAndIndex();
+ await gateway.uploadStarted.future;
+ c.stopWork();
+ await upload;
+ expect(gateway.activeUpload!.isCanceled, isTrue);
+ expect(c.busy, isFalse);
+ expect(c.clips.single.uploaded, isFalse);
+
+ c.clips.single.uploaded = true;
+ final index = c.uploadAndIndex();
+ await gateway.indexStarted.future;
+ c.stopWork();
+ await index;
+ expect(c.busy, isFalse);
+ expect(c.pendingJob, 'job-continues-remotely');
+ expect(c.notice, contains('Indexing continues on the server'));
+
+ final search = c.search('cyclist');
+ await gateway.searchStarted.future;
+ c.invalidateSearch();
+ await search;
+ expect(c.searching, isFalse);
+ expect(c.batch, isNull);
+
+ await c.save();
+ c.dispose();
+ await gateway.close();
+ },
+ );
+
+ test('upload asset identity persists and controls archive lookup', () async {
+ final root = await Directory.systemTemp.createTemp('framebase_asset_');
+ addTearDown(() => root.delete(recursive: true));
+ final source = File('${root.path}/camera.mp4');
+ await source.writeAsBytes([1, 2, 3]);
+ final gateway = UploadGateway();
+ final controller = ArchiveController(supportDirectory: root);
+ await controller.activate('alice', gateway, canRead: true, canWrite: true);
+ controller.clips = <ArchiveClip>[
+ ArchiveClip(
+ id: 'camera',
+ title: 'Camera',
+ location: 'Test',
+ duration: 3,
+ asset: '',
+ poster: '',
+ path: source.path,
+ bundled: false,
+ ),
+ ];
+
+ await controller.uploadAndIndex();
+ expect(controller.clips.single.remoteAssetId, 'asset-uploaded');
+ controller.deactivate();
+ await controller.activate('alice', gateway, canRead: true, canWrite: true);
+ final clip = controller.clips.single;
+ expect(clip.remoteAssetId, 'asset-uploaded');
+ expect(
+ controller.clipFor(
+ VideoSearchHit(const <String, Object?>{
+ 'asset_id': 'asset-uploaded',
+ 'file_name': 'renamed.mp4',
+ }),
+ ),
+ same(clip),
+ );
+ expect(
+ controller.clipFor(
+ VideoSearchHit(const <String, Object?>{
+ 'asset_id': 'asset-other',
+ 'file_name': 'camera.mp4',
+ }),
+ ),
+ isNull,
+ );
+ expect(
+ controller.clipFor(
+ VideoSearchHit(const <String, Object?>{'file_name': 'camera.mp4'}),
+ ),
+ same(clip),
+ );
+ expect(
+ ArchiveClip.fromJson(const <String, dynamic>{
+ 'id': 'old',
+ 'title': 'Old',
+ 'location': 'Test',
+ 'duration': 1,
+ 'asset': '',
+ 'poster': '',
+ }).remoteAssetId,
+ isNull,
+ );
+ await controller.save();
+ controller.dispose();
+ await gateway.close();
+ });
+
+ test('missing paths normalize and uploaded remote rows survive', () async {
+ final root = await Directory.systemTemp.createTemp('framebase_remote_');
+ addTearDown(() => root.delete(recursive: true));
+ final gateway = SearchGateway(
+ MutableApiKeyProvider('fixture-remote'),
+ 'scope_remote',
+ );
+ final c = ArchiveController(supportDirectory: root);
+ await c.activate('scope_remote', gateway, canRead: true, canWrite: true);
+ c.clips = [
+ ArchiveClip(
+ id: 'remote',
+ title: 'Remote',
+ location: 'Test',
+ duration: 2,
+ asset: '',
+ poster: '',
+ path: '${root.path}/missing.mp4',
+ remoteAssetId: 'asset-remote',
+ uploaded: true,
+ bundled: false,
+ ),
+ ArchiveClip(
+ id: 'gone',
+ title: 'Gone',
+ location: 'Test',
+ duration: 2,
+ asset: '',
+ poster: '',
+ path: '${root.path}/also-missing.mp4',
+ bundled: false,
+ ),
+ ];
+ await c.save();
+ c.deactivate();
+ await c.activate('scope_remote', gateway, canRead: true, canWrite: true);
+ expect(c.clips, hasLength(1));
+ expect(c.clips.single.path, isNull);
+ expect(c.clips.single.remoteOnly, isTrue);
+ expect(
+ c.clipFor(VideoSearchHit(const {'asset_id': 'asset-remote'})),
+ same(c.clips.single),
+ );
+ c.dispose();
+ await gateway.close();
+ });
+
+ test('local removal stays contained and keeps cloud identity', () async {
+ final root = await Directory.systemTemp.createTemp('framebase_remove_');
+ addTearDown(() => root.delete(recursive: true));
+ final gateway = SearchGateway(
+ MutableApiKeyProvider('fixture-remove'),
+ 'scope_remove',
+ );
+ final c = ArchiveController(supportDirectory: root);
+ await c.activate('scope_remove', gateway, canRead: true, canWrite: true);
+ final account = Directory('${root.path}/accounts/scope_remove');
+ await account.create(recursive: true);
+ final local = File('${account.path}/local.mp4')..writeAsBytesSync([1]);
+ final remote = File('${account.path}/remote.mp4')..writeAsBytesSync([2]);
+ final outside = File('${root.path}/outside.mp4')..writeAsBytesSync([3]);
+ ArchiveClip clip(String id, String path, {bool uploaded = false}) =>
+ ArchiveClip(
+ id: id,
+ title: id,
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ path: path,
+ remoteAssetId: uploaded ? 'asset-$id' : null,
+ uploaded: uploaded,
+ bundled: false,
+ );
+
+ final localClip = clip('local', local.path);
+ final remoteClip = clip('remote', remote.path, uploaded: true);
+ final staleClip = clip('stale', outside.path);
+ c.clips = [localClip, remoteClip, staleClip];
+ expect(await c.removeLocalCopy(staleClip), LocalRemovalResult.unavailable);
+ expect(await outside.exists(), isTrue);
+ expect(await c.removeLocalCopy(localClip), LocalRemovalResult.removed);
+ expect(await local.exists(), isFalse);
+ expect(c.clips, isNot(contains(localClip)));
+ expect(await c.removeLocalCopy(remoteClip), LocalRemovalResult.removed);
+ expect(await remote.exists(), isFalse);
+ expect(remoteClip.path, isNull);
+ expect(remoteClip.uploaded, isTrue);
+ expect(remoteClip.remoteAssetId, 'asset-remote');
+ c.dispose();
+ await gateway.close();
+ });
+
+ test('preview is non-mutating and commit keeps device videos', () async {
+ final root = await Directory.systemTemp.createTemp('framebase_delete_');
+ addTearDown(() => root.delete(recursive: true));
+ final gateway = DeleteGateway()..version = 7;
+ final c = ArchiveController(supportDirectory: root);
+ await c.activate('scope_delete', gateway, canRead: true, canWrite: true);
+ final account = Directory('${root.path}/accounts/scope_delete');
+ await account.create(recursive: true);
+ final file = File('${account.path}/kept.mp4')..writeAsBytesSync([1, 2]);
+ ArchiveClip uploaded(String id, {String? path}) => ArchiveClip(
+ id: id,
+ title: id,
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ path: path,
+ remoteAssetId: 'asset-$id',
+ uploaded: true,
+ bundled: false,
+ );
+
+ c.clips = [uploaded('kept', path: file.path), uploaded('remote')];
+ c.indexVersion = 7;
+ final preview = await c.previewCloudLibraryDeletion();
+ expect(preview?.removedBytes, 12);
+ expect(c.clips, hasLength(2));
+ expect(c.clips.every((item) => item.uploaded), isTrue);
+ expect(await c.deleteCloudLibrary(), CloudDeletionResult.deleted);
+ expect(gateway.previews, 1);
+ expect(gateway.deletes, 1);
+ expect(await file.exists(), isTrue);
+ expect(c.clips, hasLength(1));
+ expect(c.clips.single.id, 'kept');
+ expect(c.clips.single.uploaded, isFalse);
+ expect(c.clips.single.remoteAssetId, isNull);
+ expect(c.indexVersion, isNull);
+ c.dispose();
+ await gateway.close();
+ });
+
+ test('known late success reconciles only its captured scope', () async {
+ final root = await Directory.systemTemp.createTemp('framebase_late_');
+ addTearDown(() => root.delete(recursive: true));
+ final a = DelayedDeleteGateway();
+ final b = SearchGateway(MutableApiKeyProvider('fixture-b'), 'scope_b');
+ final c = ArchiveController(supportDirectory: root);
+ await c.activate('scope_delete', a, canRead: true, canWrite: true);
+ final account = Directory('${root.path}/accounts/scope_delete');
+ await account.create(recursive: true);
+ final file = File('${account.path}/kept.mp4')..writeAsBytesSync([1]);
+ c.clips = [
+ ArchiveClip(
+ id: 'kept',
+ title: 'Kept',
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ path: file.path,
+ remoteAssetId: 'asset-kept',
+ uploaded: true,
+ bundled: false,
+ ),
+ ];
+ await c.save();
+ final deletion = c.deleteCloudLibrary();
+ await Future<void>.delayed(Duration.zero);
+ await c.activate('scope_b', b, canRead: true, canWrite: true);
+ expect(c.clips, hasLength(3));
+ a.completion.complete(
+ DeleteCollectionResponse(const {
+ 'status': 'ok',
+ 'group_name': 'scope_delete',
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ }),
+ );
+ expect(await deletion, CloudDeletionResult.deleted);
+ expect(c.clips, hasLength(3));
+ expect(c.clips.any((item) => item.id == 'kept'), isFalse);
+
+ await c.activate('scope_delete', a, canRead: true, canWrite: true);
+ expect(c.clips.single.id, 'kept');
+ expect(c.clips.single.uploaded, isFalse);
+ expect(c.clips.single.remoteAssetId, isNull);
+ expect(await file.exists(), isTrue);
+ c.dispose();
+ await a.close();
+ await b.close();
+ });
+
+ test('failed cloud commit keeps conservative remote state', () async {
+ final root = await Directory.systemTemp.createTemp('framebase_fail_');
+ addTearDown(() => root.delete(recursive: true));
+ final gateway = DeleteGateway(
+ deleteError: const ApiException('active', statusCode: 409),
+ );
+ final c = ArchiveController(supportDirectory: root);
+ await c.activate('scope_delete', gateway, canRead: true, canWrite: true);
+ c.clips = [
+ ArchiveClip(
+ id: 'remote',
+ title: 'Remote',
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ remoteAssetId: 'asset-remote',
+ uploaded: true,
+ bundled: false,
+ ),
+ ];
+ expect(await c.deleteCloudLibrary(), CloudDeletionResult.failed);
+ expect(c.clips.single.uploaded, isTrue);
+ expect(c.clips.single.remoteAssetId, 'asset-remote');
+ expect(c.notice, contains('still running'));
+ c.dispose();
+ await gateway.close();
+ });
}
diff --git a/example/05_framebase_userlogin/test/library_scope_test.dart b/example/05_framebase_userlogin/test/library_scope_test.dart
new file mode 100644
index 0000000..20b66b3
--- /dev/null
+++ b/example/05_framebase_userlogin/test/library_scope_test.dart
@@ -0,0 +1,35 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:framebase/user/library_scope.dart';
+
+void main() {
+ test('opaque scope is returned byte-for-byte without a legacy prefix', () {
+ const scope = 'scope_7K3A';
+ expect(validateLibraryScope(scope), same(scope));
+ expect(validateLibraryScope(scope), scope);
+ expect(scope, isNot(startsWith('framebase_streets__user_')));
+ });
+
+ test('invalid scopes fail closed without trimming or sanitizing', () {
+ for (final scope in [
+ null,
+ '',
+ ' ',
+ ' scope_7K3A',
+ 'scope_7K3A ',
+ 'scope/7K3A',
+ '../scope_7K3A',
+ 'scope-7K3A',
+ 'scope.7K3A',
+ 'scope:7K3A',
+ 'scopé_7K3A',
+ 'a' * 81,
+ ]) {
+ expect(
+ () => validateLibraryScope(scope),
+ throwsA(isA<InvalidLibraryScope>()),
+ reason: 'invalid scope: $scope',
+ );
+ }
+ expect(validateLibraryScope('a' * 80), 'a' * 80);
+ });
+}
diff --git a/example/05_framebase_userlogin/test/search_gateway_test.dart b/example/05_framebase_userlogin/test/search_gateway_test.dart
index c14af44..21b8afd 100644
--- a/example/05_framebase_userlogin/test/search_gateway_test.dart
+++ b/example/05_framebase_userlogin/test/search_gateway_test.dart
@@ -1,16 +1,19 @@
import 'dart:convert';
+import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:framebase/data/search_gateway.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
-import 'package:framebase/user/user_collection.dart';
-final accountCollection = encodedUserCollection('alice');
+const accountScope = 'scope_7K3A';
SearchGateway testGateway(QueueTransport transport) => SearchGateway(
MutableApiKeyProvider('test-only-placeholder'),
- 'alice',
+ accountScope,
transport: transport,
);
+String requestText(VmodalRequest request) =>
+ '${request.uri} ${request.jsonBody ?? ''}';
+
class QueueTransport implements VmodalTransport {
QueueTransport(this.responses);
final List<Map<String, Object?>> responses;
@@ -44,7 +47,7 @@ void main() {
'data': [
{
'mode': 'vid_file',
- 'group_name': accountCollection,
+ 'group_name': accountScope,
'lancedb_versions': ['v2', 'v4'],
},
],
@@ -56,8 +59,17 @@ void main() {
await gateway.connect('account-1');
expect(gateway.accountId, 'account-1');
+ expect(gateway.collection, accountScope);
expect(gateway.version, 4);
expect(transport.requests, hasLength(3));
+ expect(
+ transport.requests.last.uri.queryParameters['group_name'],
+ accountScope,
+ );
+ expect(
+ transport.requests.map(requestText).join(' '),
+ isNot(contains('framebase_streets__user_')),
+ );
await gateway.close();
},
);
@@ -112,7 +124,7 @@ void main() {
final gateway = testGateway(transport);
gateway.version = 2;
final result = await gateway.search('crosswalk', maxDistance: .85);
- expect(result.matches.map((m) => m.filename), [
+ expect(result.matches.map((m) => m.fileName), [
'first',
'second',
'missing',
@@ -124,13 +136,10 @@ void main() {
expect(result.matches[0].seconds, 6);
expect(result.serverMs, 42.5);
final body = transport.requests.first.jsonBody as Map;
- expect(body['group_name'], accountCollection);
+ expect(body['group_name'], accountScope);
expect(body['stream_name'], archiveStream);
expect(body['image_emb_score_min'], .85);
- expect(
- transport.requests[1].jsonBody.toString(),
- contains(accountCollection),
- );
+ expect(transport.requests[1].jsonBody.toString(), contains(accountScope));
expect(
transport.requests[1].jsonBody.toString(),
contains(archiveStream),
@@ -141,6 +150,83 @@ void main() {
},
);
+ test(
+ 'typed previews skip resolution and canonical offsets drive selectors',
+ () async {
+ const route = '/api/external/v1/image/get_image';
+ const direct = 'https://images.test/direct.jpg';
+ final transport = QueueTransport([
+ {
+ 'data': [
+ {
+ 'asset_id': 'asset-direct',
+ 'file_name': 'direct.mp4',
+ 'playback_offset_ms': 12000,
+ 'distance': .4,
+ 'preview_image_url': direct,
+ },
+ {
+ 'asset_id': 'asset-offset',
+ 'file_name': 'offset.mp4',
+ 'playback_offset_ms': 35000,
+ 'distance': .5,
+ },
+ {
+ 'asset_id': 'asset-epoch',
+ 'file_name': 'epoch.mp4',
+ 'ts_unix': '1788510000000',
+ 'distance': .6,
+ },
+ ],
+ 'cnt_total': 3,
+ },
+ {
+ 'records': [
+ {
+ 'input_index': 0,
+ 'found': true,
+ 'url_pre_signed': '$route?test=offset',
+ },
+ {'input_index': 1, 'found': false},
+ ],
+ },
+ {
+ 'records': [
+ {
+ 'url_pre_signed': direct,
+ 'content_base64': base64Encode([1]),
+ },
+ {
+ 'url_pre_signed': '$route?test=offset',
+ 'content_base64': base64Encode([2]),
+ },
+ ],
+ },
+ ]);
+ final gateway = testGateway(transport);
+ final result = await gateway.search('street', maxDistance: .85);
+
+ expect(result.matches.map((match) => match.assetId), [
+ 'asset-direct',
+ 'asset-offset',
+ 'asset-epoch',
+ ]);
+ expect(result.matches[0].imageUrl, direct);
+ expect(result.matches[0].imageBytes, [1]);
+ expect(result.matches[1].seconds, 35);
+ expect(result.matches[1].imageBytes, [2]);
+ expect(result.matches[2].seconds, isNull);
+ expect(transport.requests, hasLength(3));
+ final lookup = transport.requests[1].jsonBody as Map;
+ final records = lookup['records'] as List;
+ expect(records, hasLength(2));
+ expect(records.toString(), isNot(contains('direct.mp4')));
+ expect((records[0] as Map)['ts_unix_13digits'], '0000000035000');
+ expect(records[1] as Map, isNot(contains('ts_unix_13digits')));
+ await gateway.close();
+ },
+ );
+
test('empty search does not request invented images', () async {
final transport = QueueTransport([
{'data': [], 'cnt_total': 0},
@@ -198,13 +284,37 @@ void main() {
expect(job.jobId, 'job-123');
expect(status.status, 'success');
final body = transport.requests.first.jsonBody as Map;
- expect(body['group_name'], accountCollection);
+ expect(body['group_name'], accountScope);
expect(body['stream_name'], archiveStream);
expect(transport.requests.last.uri.path, contains('job-123'));
await gateway.close();
},
);
+ test('upload signed request uses the exact immutable scope', () async {
+ final root = await Directory.systemTemp.createTemp('scope_upload_');
+ addTearDown(() => root.delete(recursive: true));
+ final file = File('${root.path}/clip.mp4');
+ await file.writeAsBytes([1, 2, 3]);
+ final transport = QueueTransport([
+ {'url': ''},
+ ]);
+ final gateway = testGateway(transport);
+ final task = await gateway.upload(file);
+ await expectLater(task.result, throwsA(isA<ValidationException>()));
+ expect(transport.requests, hasLength(1));
+ expect(
+ transport.requests.single.uri.queryParameters['group_name'],
+ accountScope,
+ );
+ expect(
+ requestText(transport.requests.single),
+ isNot(contains('framebase_streets__user_')),
+ );
+ expect(gateway.collection, accountScope);
+ await gateway.close();
+ });
+
test('401 reports auth failure without replaying the search', () async {
final transport = QueueTransport([
{'__status': 401, 'detail': 'expired'},
@@ -217,4 +327,99 @@ void main() {
expect(transport.requests, hasLength(1));
await gateway.close();
});
+
+ test('403 reports forbidden failure without replaying the search', () async {
+ final transport = QueueTransport([
+ {'__status': 403, 'detail': 'forbidden'},
+ ]);
+ final gateway = testGateway(transport);
+ var status = 0;
+ gateway.onAccessFailure = (value) => status = value;
+ await expectLater(gateway.search('bus'), throwsA(isA<ApiException>()));
+ expect(status, 403);
+ expect(transport.requests, hasLength(1));
+ await gateway.close();
+ });
+
+ test(
+ 'cloud deletion preview and commit use the exact issued scope',
+ () async {
+ final transport = QueueTransport([
+ {
+ 'status': 'dry_run',
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ },
+ {
+ 'status': 'ok',
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ },
+ ]);
+ final gateway = testGateway(transport);
+
+ await gateway.previewLibraryDeletion(CancellationToken());
+ await gateway.deleteLibrary(CancellationToken());
+
+ expect(transport.requests, hasLength(2));
+ expect(
+ transport.requests.map((request) => request.method),
+ everyElement('DELETE'),
+ );
+ expect(
+ transport.requests.map((request) => request.uri.path),
+ everyElement(endsWith('/api/external/v1/collection/delete')),
+ );
+ expect(transport.requests.first.jsonBody, {
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ 'dry_run': true,
+ 'confirm': false,
+ });
+ expect(transport.requests.last.jsonBody, {
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ 'dry_run': false,
+ 'confirm': true,
+ });
+ expect(requestText(transport.requests.last), isNot(contains('asset_id')));
+ expect(
+ requestText(transport.requests.last),
+ isNot(contains('stream_name')),
+ );
+ await gateway.close();
+ },
+ );
+
+ test(
+ 'cloud deletion is not replayed and honors pre-send cancellation',
+ () async {
+ final canceledTransport = QueueTransport([]);
+ final canceledGateway = testGateway(canceledTransport);
+ final canceled = CancellationToken()..cancel();
+ await expectLater(
+ canceledGateway.deleteLibrary(canceled),
+ throwsA(isA<OperationCanceled>()),
+ );
+ expect(canceledTransport.requests, isEmpty);
+ await canceledGateway.close();
+
+ for (final status in [409, 500]) {
+ final transport = QueueTransport([
+ {'__status': status, 'detail': 'failure'},
+ ]);
+ final gateway = testGateway(transport);
+ await expectLater(
+ gateway.deleteLibrary(CancellationToken()),
+ throwsA(isA<SdkException>()),
+ );
+ expect(transport.requests, hasLength(1));
+ await gateway.close();
+ }
+ },
+ );
}
diff --git a/example/05_framebase_userlogin/test/user_collection_test.dart b/example/05_framebase_userlogin/test/user_collection_test.dart
deleted file mode 100644
index 2a69136..0000000
--- a/example/05_framebase_userlogin/test/user_collection_test.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-import 'package:flutter_test/flutter_test.dart';
-import 'package:framebase/user/user_collection.dart';
-import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
-
-void main() {
- test('stable project and user scope', () {
- expect(userCollection('A_9'), 'user_A_9');
- expect(encodedUserCollection('A_9'), 'framebase_streets__user_A_9');
- expect(encodedUserCollection('A_9'), encodedUserCollection('A_9'));
- });
- test('invalid IDs cannot collide or exceed the backend limit', () {
- for (final id in ['', 'a-b', 'a.b', 'a b', 'a__b', ' a', 'é']) {
- expect(
- () => userCollection(id),
- throwsA(isA<ValidationException>()),
- reason: 'invalid ID: $id',
- );
- }
- const prefix = 'framebase_streets__user_';
- final maxId = 'a' * (80 - prefix.length);
- expect(encodedUserCollection(maxId).length, 80);
- expect(
- () => userCollection('${maxId}a'),
- throwsA(isA<ValidationException>()),
- );
- });
-}
diff --git a/example/05_framebase_userlogin/test/user_session_controller_test.dart b/example/05_framebase_userlogin/test/user_session_controller_test.dart
index 25b0a13..5fe551d 100644
--- a/example/05_framebase_userlogin/test/user_session_controller_test.dart
+++ b/example/05_framebase_userlogin/test/user_session_controller_test.dart
@@ -11,39 +11,108 @@ import 'package:framebase/user/vmodal_credential.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
class SessionGateway extends SearchGateway {
- SessionGateway(super.keys, super.collectionUserId, this.owner);
+ SessionGateway(super.keys, super.scopeId, this.owner, [this.connectError]);
final String owner;
+ final Object? connectError;
+ int destructiveCalls = 0;
@override
Future<void> connect(String expectedUserId) async {
+ if (connectError case final Object error) throw error;
if (expectedUserId != owner) throw const AuthException('Wrong owner');
accountId = owner;
}
+
+ @override
+ Future<DeleteCollectionResponse> previewLibraryDeletion(
+ CancellationToken cancellation,
+ ) async {
+ destructiveCalls++;
+ return DeleteCollectionResponse(const {'status': 'dry_run'});
+ }
+
+ @override
+ Future<DeleteCollectionResponse> deleteLibrary(
+ CancellationToken cancellation,
+ ) async {
+ destructiveCalls++;
+ return DeleteCollectionResponse(const {'status': 'ok'});
+ }
+}
+
+class TrackingArchive extends ArchiveController {
+ TrackingArchive({required Directory supportDirectory})
+ : super(persist: false, supportDirectory: supportDirectory);
+ String activatedScope = '';
+ int activations = 0;
+
+ @override
+ Future<void> activate(
+ String scopeId,
+ SearchGateway gateway, {
+ required bool canRead,
+ required bool canWrite,
+ }) async {
+ activatedScope = scopeId;
+ activations++;
+ await super.activate(
+ scopeId,
+ gateway,
+ canRead: canRead,
+ canWrite: canWrite,
+ );
+ }
+}
+
+class TokenAuth extends MockFirebaseAuth {
+ TokenAuth(this.tokens);
+ final List<Object> tokens;
+
+ @override
+ Future<String?> idToken(AppUser user) async {
+ final item = tokens.removeAt(0);
+ if (item is String) return item;
+ if (item is Future<String?>) return item;
+ throw item;
+ }
}
class QueueCredentials implements VmodalCredentialSource {
QueueCredentials(this.items);
- final List<Future<VmodalCredential>> items;
+ final List<Object> items;
int calls = 0;
@override
- Future<VmodalCredential> acquire(AppUser user, String? firebaseIdToken) {
+ Future<VmodalCredential> acquire(
+ AppUser user,
+ String? firebaseIdToken,
+ ) async {
calls++;
- return items.removeAt(0);
+ final item = items.removeAt(0);
+ if (item is VmodalCredential) return item;
+ if (item is Future<VmodalCredential>) return item;
+ throw item;
}
}
VmodalCredential credential(
String uid,
DateTime expiry, {
+ int? version = 1,
+ String? sessionId,
+ DateTime? issuedAt,
String? token,
String? owner,
+ String? scope,
bool allowed = true,
Set<String> grants = const {'library:read', 'library:write'},
}) => VmodalCredential(
+ contractVersion: version,
+ sessionId: sessionId ?? 'session-$uid',
+ issuedAt: issuedAt ?? expiry.subtract(const Duration(minutes: 5)),
apiToken: token ?? 'placeholder-$uid',
expiresAt: expiry,
firebaseUid: uid,
vmodalUserId: owner ?? 'vm-$uid',
- collectionUserId: uid,
+ scopeId: scope ?? 'scope_$uid',
allowed: allowed,
permissions: grants,
);
@@ -51,19 +120,53 @@ VmodalCredential credential(
Future<void> settle() => Future<void>.delayed(const Duration(milliseconds: 20));
void main() {
- test('credential rejects expiry, wrong UID, and missing grants', () {
+ test('credential parses scope and rejects invalid contracts or grants', () {
final now = DateTime.utc(2030);
const user = AppUser('alice');
+ final valid = <String, Object?>{
+ 'version': 1,
+ 'session_id': 'issuer-session-7K3A',
+ 'issued_at': '2030-01-01T00:00:00+00:00',
+ 'api_token': 'token',
+ 'expires_at': '2030-01-01T01:00:00Z',
+ 'firebase_uid': 'alice',
+ 'vmodal_user_id': 'vm-alice',
+ 'scope_id': 'scope_7K3A',
+ 'allowed': true,
+ 'permissions': ['library:read'],
+ };
+ final parsed = VmodalCredential.fromJson(valid);
+ expect(parsed.contractVersion, 1);
+ expect(parsed.sessionId, 'issuer-session-7K3A');
+ expect(parsed.issuedAt, DateTime.utc(2030));
+ expect(parsed.expiresAt, DateTime.utc(2030, 1, 1, 1));
+ expect(parsed.scopeId, 'scope_7K3A');
+ expect(() => parsed.validate(user, now), returnsNormally);
+
+ for (final invalid in <Map<String, Object?>>[
+ Map<String, Object?>.from(valid)..remove('version'),
+ {...valid, 'version': 2},
+ {...valid, 'session_id': ' '},
+ Map<String, Object?>.from(valid)..remove('issued_at'),
+ {...valid, 'issued_at': 'not-a-date'},
+ {...valid, 'issued_at': valid['expires_at']},
+ {...valid, 'issued_at': '2030-01-01T02:00:00Z'},
+ ]) {
+ expect(
+ () => VmodalCredential.fromJson(invalid).validate(user, now),
+ throwsA(isA<CredentialContractError>()),
+ );
+ }
expect(
() => credential('alice', now).validate(user, now),
- throwsA(isA<CredentialDenied>()),
+ throwsA(isA<CredentialContractError>()),
);
expect(
() => credential(
'bob',
now.add(const Duration(hours: 1)),
).validate(user, now),
- throwsA(isA<CredentialDenied>()),
+ throwsA(isA<CredentialContractError>()),
);
expect(
() => credential(
@@ -73,6 +176,77 @@ void main() {
).validate(user, now),
throwsA(isA<CredentialDenied>()),
);
+ expect(
+ () => credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ allowed: false,
+ ).validate(user, now),
+ throwsA(isA<CredentialDenied>()),
+ );
+ expect(
+ () => credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ scope: 'invalid-scope',
+ ).validate(user, now),
+ throwsA(isA<CredentialContractError>()),
+ );
+ final prior = credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ scope: 'scope_original',
+ );
+ expect(
+ () => credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ scope: 'scope_changed',
+ ).validate(user, now, previous: prior),
+ throwsA(isA<CredentialContractError>()),
+ );
+ expect(
+ () => credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ sessionId: 'rotated-session',
+ scope: 'scope_original',
+ ).validate(user, now, previous: prior),
+ returnsNormally,
+ );
+ });
+
+ test('initial resolve passes the issuer scope unchanged', () async {
+ final now = DateTime.utc(2030);
+ final root = await Directory.systemTemp.createTemp('scope_session_');
+ addTearDown(() => root.delete(recursive: true));
+ final archive = TrackingArchive(supportDirectory: root);
+ final auth = MockFirebaseAuth();
+ final source = QueueCredentials([
+ Future.value(
+ credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ scope: 'scope_7K3A',
+ ),
+ ),
+ ]);
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ gatewayFactory: (key, scope, fresh) =>
+ SessionGateway(key, scope, 'vm-alice'),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(session.state, SessionState.ready);
+ expect(session.gateway?.collection, 'scope_7K3A');
+ expect(archive.activatedScope, 'scope_7K3A');
+ session.dispose();
+ archive.dispose();
});
test('empty default and denied credential issue no gateway calls', () async {
final archive = ArchiveController(
@@ -88,7 +262,7 @@ void main() {
archive: archive,
gatewayFactory: (key, id, fresh) {
gateways++;
- return SessionGateway(key, id, 'vm-$id');
+ return SessionGateway(key, id, 'vm-alice');
},
);
expect(session.state, SessionState.loading);
@@ -196,13 +370,56 @@ void main() {
);
failed.completeError(const CredentialDenied());
await renewal;
- expect(session.state, SessionState.error);
+ expect(session.state, SessionState.denied);
+ expect(session.failureKind, SessionFailureKind.credentialDenied);
expect(() => provider.current(), throwsA(isA<AuthException>()));
session.dispose();
archive.dispose();
},
);
+ test('refresh rejects a changed scope before key rotation', () async {
+ var now = DateTime.utc(2030);
+ final source = QueueCredentials([
+ Future.value(credential('alice', now.add(const Duration(minutes: 2)))),
+ Future.value(
+ credential(
+ 'alice',
+ now.add(const Duration(minutes: 4)),
+ token: 'must-not-rotate',
+ scope: 'scope_other',
+ ),
+ ),
+ ]);
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final auth = MockFirebaseAuth();
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ gatewayFactory: (key, scope, fresh) =>
+ SessionGateway(key, scope, 'vm-alice'),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final provider = session.gateway!.keys;
+ expect(provider.current(), 'placeholder-alice');
+ now = now.add(const Duration(seconds: 70));
+ await expectLater(
+ session.ensureFresh(),
+ throwsA(isA<CredentialContractError>()),
+ );
+ expect(session.state, SessionState.error);
+ expect(() => provider.current(), throwsA(isA<AuthException>()));
+ session.dispose();
+ archive.dispose();
+ });
+
test('late account A response cannot replace account B', () async {
final now = DateTime.utc(2030);
final delayed = Completer<VmodalCredential>();
@@ -220,20 +437,23 @@ void main() {
credentials: source,
archive: archive,
clock: () => now,
- gatewayFactory: (key, id, fresh) => SessionGateway(key, id, 'vm-$id'),
+ gatewayFactory: (key, id, fresh) =>
+ SessionGateway(key, id, id == 'scope_bob' ? 'vm-bob' : 'vm-alice'),
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
auth.setUser(const AppUser('bob'));
await settle();
- expect(session.gateway?.collection, 'framebase_streets__user_bob');
+ expect(session.gateway?.collection, 'scope_bob');
+ final bobGateway = session.gateway! as SessionGateway;
delayed.complete(credential('alice', now.add(const Duration(hours: 1))));
await settle();
- expect(session.gateway?.collection, 'framebase_streets__user_bob');
+ expect(session.gateway?.collection, 'scope_bob');
await session.signOut();
expect(session.state, SessionState.signedOut);
expect(archive.clips.any((c) => c.uploaded), isFalse);
+ expect(bobGateway.destructiveCalls, 0);
session.dispose();
archive.dispose();
});
@@ -256,7 +476,8 @@ void main() {
credentials: source,
archive: archive,
clock: () => now,
- gatewayFactory: (key, id, fresh) => SessionGateway(key, id, 'vm-$id'),
+ gatewayFactory: (key, id, fresh) =>
+ SessionGateway(key, id, id == 'scope_bob' ? 'vm-bob' : 'vm-alice'),
);
await settle();
auth.setUser(const AppUser('alice'));
@@ -269,10 +490,454 @@ void main() {
await settle();
auth.setUser(const AppUser('bob'));
await settle();
- expect(session.gateway?.collection, 'framebase_streets__user_bob');
+ expect(session.gateway?.collection, 'scope_bob');
delayed.complete(credential('alice', now.add(const Duration(hours: 1))));
await old;
- expect(session.gateway?.collection, 'framebase_streets__user_bob');
+ expect(session.gateway?.collection, 'scope_bob');
+ session.dispose();
+ archive.dispose();
+ });
+
+ test(
+ 'transient refresh retries twice, stays single flight, and rotates in place',
+ () async {
+ var now = DateTime.utc(2030);
+ final delays = <Duration>[];
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ credential(
+ 'alice',
+ now.add(const Duration(minutes: 4)),
+ token: 'rotated-after-retry',
+ ),
+ ]);
+ final root = await Directory.systemTemp.createTemp('retry_success_');
+ addTearDown(() => root.delete(recursive: true));
+ final archive = TrackingArchive(supportDirectory: root);
+ final auth = MockFirebaseAuth();
+ var gateways = 0;
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) async => delays.add(value),
+ gatewayFactory: (key, scope, fresh) {
+ gateways++;
+ return SessionGateway(key, scope, 'vm-alice');
+ },
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final gateway = session.gateway!;
+ final provider = gateway.keys;
+ now = now.add(const Duration(seconds: 70));
+
+ final first = session.ensureFresh();
+ final second = session.ensureFresh();
+ await Future.wait([first, second]);
+
+ expect(source.calls, 4);
+ expect(delays, const [
+ Duration(milliseconds: 250),
+ Duration(milliseconds: 500),
+ ]);
+ expect(session.state, SessionState.ready);
+ expect(session.failureKind, isNull);
+ expect(session.gateway, same(gateway));
+ expect(session.gateway!.keys, same(provider));
+ expect(provider.current(), 'rotated-after-retry');
+ expect(archive.activations, 1);
+ expect(archive.connected, isTrue);
+ expect(gateways, 1);
+ session.dispose();
+ archive.dispose();
+ },
+ );
+
+ test('transient exhaustion preserves resources and manual retry', () async {
+ var now = DateTime.utc(2030);
+ final delays = <Duration>[];
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ ]);
+ final root = await Directory.systemTemp.createTemp('retry_manual_');
+ addTearDown(() => root.delete(recursive: true));
+ final archive = TrackingArchive(supportDirectory: root);
+ final auth = MockFirebaseAuth();
+ var gateways = 0;
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) async => delays.add(value),
+ gatewayFactory: (key, scope, fresh) {
+ gateways++;
+ return SessionGateway(key, scope, 'vm-alice');
+ },
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final gateway = session.gateway!;
+ final provider = gateway.keys;
+ now = now.add(const Duration(seconds: 70));
+
+ await expectLater(
+ session.ensureFresh(),
+ throwsA(isA<CredentialTransient>()),
+ );
+
+ expect(session.state, SessionState.recoverable);
+ expect(session.failureKind, SessionFailureKind.transient);
+ expect(session.canRetry, isTrue);
+ expect(session.gateway, same(gateway));
+ expect(session.gateway!.keys, same(provider));
+ expect(provider.current(), 'placeholder-alice');
+ expect(gateway.collection, 'scope_alice');
+ expect(archive.activatedScope, 'scope_alice');
+ expect(archive.connected, isTrue);
+ expect(session.canRead, isFalse);
+ expect(session.canWrite, isFalse);
+ expect(gateways, 1);
+ expect(archive.activations, 1);
+
+ source.items.add(
+ credential(
+ 'alice',
+ now.add(const Duration(minutes: 4)),
+ token: 'manual-retry-key',
+ ),
+ );
+ await session.retry();
+
+ expect(session.state, SessionState.ready);
+ expect(session.failureKind, isNull);
+ expect(session.gateway, same(gateway));
+ expect(provider.current(), 'manual-retry-key');
+ expect(archive.connected, isTrue);
+ expect(gateways, 1);
+ expect(archive.activations, 1);
+ expect(delays, const [
+ Duration(milliseconds: 250),
+ Duration(milliseconds: 500),
+ ]);
+ session.dispose();
+ archive.dispose();
+ });
+
+ test('initial transient exhaustion can resolve on manual retry', () async {
+ final now = DateTime.utc(2030);
+ final delays = <Duration>[];
+ final source = QueueCredentials([
+ const CredentialTransient(),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ ]);
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final auth = MockFirebaseAuth();
+ var gateways = 0;
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) async => delays.add(value),
+ gatewayFactory: (key, scope, fresh) {
+ gateways++;
+ return SessionGateway(key, scope, 'vm-alice');
+ },
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+
+ expect(session.state, SessionState.recoverable);
+ expect(session.failureKind, SessionFailureKind.transient);
+ expect(session.gateway, isNull);
+ expect(archive.connected, isFalse);
+ expect(gateways, 0);
+
+ source.items.add(credential('alice', now.add(const Duration(hours: 1))));
+ await session.retry();
+
+ expect(session.state, SessionState.ready);
+ expect(session.failureKind, isNull);
+ expect(session.gateway, isNotNull);
+ expect(archive.connected, isTrue);
+ expect(gateways, 1);
+ expect(delays, const [
+ Duration(milliseconds: 250),
+ Duration(milliseconds: 500),
+ ]);
+ session.dispose();
+ archive.dispose();
+ });
+
+ test('terminal refresh failures do not retry and fail closed', () async {
+ Future<void> check(
+ Object error,
+ SessionState expectedState,
+ SessionFailureKind expectedKind,
+ ) async {
+ var now = DateTime.utc(2030);
+ final delays = <Duration>[];
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ error,
+ ]);
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final auth = MockFirebaseAuth();
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) async => delays.add(value),
+ gatewayFactory: (key, scope, fresh) =>
+ SessionGateway(key, scope, 'vm-alice'),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final provider = session.gateway!.keys;
+ now = now.add(const Duration(seconds: 70));
+
+ await expectLater(session.ensureFresh(), throwsA(same(error)));
+
+ expect(delays, isEmpty);
+ expect(session.state, expectedState);
+ expect(session.failureKind, expectedKind);
+ expect(session.canRetry, isFalse);
+ expect(session.gateway, isNull);
+ expect(archive.connected, isFalse);
+ expect(() => provider.current(), throwsA(isA<AuthException>()));
+ session.dispose();
+ archive.dispose();
+ }
+
+ await check(
+ const FirebaseIdentityExpired(),
+ SessionState.error,
+ SessionFailureKind.firebaseIdentityExpired,
+ );
+ await check(
+ const CredentialDenied(),
+ SessionState.denied,
+ SessionFailureKind.credentialDenied,
+ );
+ await check(
+ const CredentialContractError(),
+ SessionState.error,
+ SessionFailureKind.contract,
+ );
+ });
+
+ test('VMODAL 401 and 403 stay distinct at connect and after ready', () async {
+ Future<void> checkConnect(
+ Object error,
+ SessionState expectedState,
+ SessionFailureKind expectedKind,
+ ) async {
+ final now = DateTime.utc(2030);
+ final delays = <Duration>[];
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(hours: 1))),
+ ]);
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final auth = MockFirebaseAuth();
+ MutableApiKeyProvider? provider;
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) async => delays.add(value),
+ gatewayFactory: (key, scope, fresh) {
+ provider = key;
+ return SessionGateway(key, scope, 'vm-alice', error);
+ },
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(delays, isEmpty);
+ expect(session.state, expectedState);
+ expect(session.failureKind, expectedKind);
+ expect(session.gateway, isNull);
+ expect(archive.connected, isFalse);
+ expect(() => provider!.current(), throwsA(isA<AuthException>()));
+ session.dispose();
+ archive.dispose();
+ }
+
+ await checkConnect(
+ const AuthException('expired'),
+ SessionState.error,
+ SessionFailureKind.vmodalUnauthorized,
+ );
+ await checkConnect(
+ const ApiException('forbidden', statusCode: 403),
+ SessionState.denied,
+ SessionFailureKind.vmodalForbidden,
+ );
+
+ Future<void> checkCallback(
+ SdkException error,
+ SessionState expectedState,
+ SessionFailureKind expectedKind,
+ ) async {
+ final now = DateTime.utc(2030);
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(hours: 1))),
+ ]);
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final auth = MockFirebaseAuth();
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ gatewayFactory: (key, scope, fresh) =>
+ SessionGateway(key, scope, 'vm-alice'),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final gateway = session.gateway!;
+ final provider = gateway.keys;
+ gateway.reportFailure(error);
+ expect(session.state, expectedState);
+ expect(session.failureKind, expectedKind);
+ expect(session.gateway, isNull);
+ expect(archive.connected, isFalse);
+ expect(() => provider.current(), throwsA(isA<AuthException>()));
+ session.dispose();
+ archive.dispose();
+ }
+
+ await checkCallback(
+ const AuthException('expired'),
+ SessionState.error,
+ SessionFailureKind.vmodalUnauthorized,
+ );
+ await checkCallback(
+ const ApiException('forbidden', statusCode: 403),
+ SessionState.denied,
+ SessionFailureKind.vmodalForbidden,
+ );
+ });
+
+ test('Firebase identity expiry from the adapter does not back off', () async {
+ var now = DateTime.utc(2030);
+ final expired = FirebaseIdentityExpired();
+ final auth = TokenAuth(['initial', expired]);
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ ]);
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final delays = <Duration>[];
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) async => delays.add(value),
+ gatewayFactory: (key, scope, fresh) =>
+ SessionGateway(key, scope, 'vm-alice'),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final provider = session.gateway!.keys;
+ now = now.add(const Duration(seconds: 70));
+ await expectLater(session.ensureFresh(), throwsA(same(expired)));
+ expect(delays, isEmpty);
+ expect(session.state, SessionState.error);
+ expect(session.failureKind, SessionFailureKind.firebaseIdentityExpired);
+ expect(() => provider.current(), throwsA(isA<AuthException>()));
+ expect(archive.connected, isFalse);
+ session.dispose();
+ archive.dispose();
+ });
+
+ test('account switch during retry backoff cannot mutate old state', () async {
+ var now = DateTime.utc(2030);
+ final waiting = Completer<void>();
+ final delays = <Duration>[];
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ const CredentialTransient(),
+ credential('bob', now.add(const Duration(hours: 1))),
+ ]);
+ final root = await Directory.systemTemp.createTemp('retry_switch_');
+ addTearDown(() => root.delete(recursive: true));
+ final archive = TrackingArchive(supportDirectory: root);
+ final auth = MockFirebaseAuth();
+ final session = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (value) {
+ delays.add(value);
+ return waiting.future;
+ },
+ gatewayFactory: (key, scope, fresh) => SessionGateway(
+ key,
+ scope,
+ scope == 'scope_bob' ? 'vm-bob' : 'vm-alice',
+ ),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final oldGateway = session.gateway!;
+ final oldProvider = oldGateway.keys;
+ now = now.add(const Duration(seconds: 70));
+ final oldRefresh = expectLater(
+ session.ensureFresh(),
+ throwsA(isA<CredentialTransient>()),
+ );
+ await settle();
+ expect(delays, const [Duration(milliseconds: 250)]);
+
+ auth.setUser(const AppUser('bob'));
+ await settle();
+ expect(session.state, SessionState.ready);
+ expect(session.gateway?.collection, 'scope_bob');
+ expect(archive.activatedScope, 'scope_bob');
+ waiting.complete();
+ await oldRefresh;
+
+ expect(session.state, SessionState.ready);
+ expect(session.failureKind, isNull);
+ expect(session.gateway?.collection, 'scope_bob');
+ expect(archive.activatedScope, 'scope_bob');
+ expect(session.gateway, isNot(same(oldGateway)));
+ expect(() => oldProvider.current(), throwsA(isA<AuthException>()));
session.dispose();
archive.dispose();
});
diff --git a/example/05_framebase_userlogin/test/widget_test.dart b/example/05_framebase_userlogin/test/widget_test.dart
index 57df2d7..a1bcd84 100644
--- a/example/05_framebase_userlogin/test/widget_test.dart
+++ b/example/05_framebase_userlogin/test/widget_test.dart
@@ -5,30 +5,89 @@ import 'package:framebase/main.dart';
import 'package:framebase/data/archive_controller.dart';
import 'package:framebase/data/search_gateway.dart';
import 'package:framebase/user/auth_adapter.dart';
+import 'package:framebase/user/login_page.dart';
import 'package:framebase/user/mock_firebase_auth.dart';
import 'package:framebase/user/user_session_controller.dart';
import 'package:framebase/user/vmodal_credential.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
class FakeGateway extends SearchGateway {
- FakeGateway(super.keys, super.collectionUserId);
+ FakeGateway(super.keys, super.scopeId);
@override
Future<void> connect(String expectedUserId) async {
accountId = expectedUserId;
version = 1;
}
+
+ @override
+ Future<DeleteCollectionResponse> previewLibraryDeletion(
+ CancellationToken cancellation,
+ ) async => DeleteCollectionResponse({
+ 'status': 'dry_run',
+ 'group_name': collection,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ 'removed_bytes': 20,
+ 'sql_rows_deleted': 2,
+ });
+
+ @override
+ Future<DeleteCollectionResponse> deleteLibrary(
+ CancellationToken cancellation,
+ ) async => DeleteCollectionResponse({
+ 'status': 'ok',
+ 'group_name': collection,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ });
+}
+
+class LifecycleArchive extends ArchiveController {
+ LifecycleArchive() : super(persist: false);
+ int stopCalls = 0;
+ int invalidateCalls = 0;
+
+ @override
+ void stopWork() {
+ stopCalls++;
+ super.stopWork();
+ }
+
+ @override
+ void invalidateSearch() {
+ invalidateCalls++;
+ super.invalidateSearch();
+ }
}
VmodalCredential fixture() => VmodalCredential(
+ contractVersion: 1,
+ sessionId: 'widget-session',
+ issuedAt: DateTime.now().toUtc(),
apiToken: 'test-only-placeholder',
expiresAt: DateTime.now().toUtc().add(const Duration(hours: 1)),
firebaseUid: 'alice',
vmodalUserId: 'vmodal-alice',
- collectionUserId: 'alice',
+ scopeId: 'scope_7K3A',
allowed: true,
permissions: {'library:read', 'library:write'},
);
+FrameMatch frameMatch({
+ required String name,
+ required int offsetMs,
+ double distance = .7,
+ String? assetId,
+}) {
+ final raw = <String, Object?>{
+ 'file_name': name,
+ 'playback_offset_ms': offsetMs,
+ 'distance': distance,
+ };
+ if (assetId != null) raw['asset_id'] = assetId;
+ return FrameMatch(hit: VideoSearchHit(raw));
+}
+
void main() {
testWidgets(
'search starts with two moments per video and expands on request',
@@ -37,12 +96,7 @@ void main() {
c.batch = SearchBatch(
matches: [
for (final second in [0, 10, 20, 30, 40])
- FrameMatch(
- row: const {'score': .7},
- filename: 'neighborhood_crossing',
- timestamp: '$second',
- seconds: second.toDouble(),
- ),
+ frameMatch(name: 'neighborhood_crossing', offsetMs: second * 1000),
],
total: 5,
serverMs: 10,
@@ -79,6 +133,52 @@ void main() {
session.dispose();
c.dispose();
});
+ testWidgets('lifecycle exit cancels work without replay on resume', (
+ tester,
+ ) async {
+ final c = LifecycleArchive();
+ final session = UserSessionController(
+ auth: MockFirebaseAuth(),
+ credentials: MockVmodalCredentialSource(),
+ archive: c,
+ );
+ await tester.pumpWidget(FramebaseApp(controller: c, session: session));
+ await tester.pumpAndSettle();
+ final stopped = c.stopCalls;
+ final invalidated = c.invalidateCalls;
+
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await tester.pump();
+ expect(c.stopCalls, stopped);
+ expect(c.invalidateCalls, invalidated);
+
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
+ await tester.pump();
+ expect(c.stopCalls, stopped + 1);
+ expect(c.invalidateCalls, invalidated + 1);
+
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
+ await tester.pump();
+ expect(c.stopCalls, stopped + 2);
+ expect(c.invalidateCalls, invalidated + 2);
+
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
+ await tester.pump();
+ expect(c.stopCalls, stopped + 3);
+ expect(c.invalidateCalls, invalidated + 3);
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(c.stopCalls, stopped + 3);
+ expect(c.invalidateCalls, invalidated + 3);
+ expect(c.busy, isFalse);
+ expect(c.searching, isFalse);
+
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ c.dispose();
+ });
testWidgets('sign in exposes library and sign out clears it', (tester) async {
final c = ArchiveController(
persist: false,
@@ -171,40 +271,255 @@ void main() {
session.dispose();
c.dispose();
});
+ testWidgets('recoverable session shows safe retry and sign-out actions', (
+ tester,
+ ) async {
+ final c = ArchiveController(persist: false);
+ final session = UserSessionController(
+ auth: MockFirebaseAuth(),
+ credentials: MockVmodalCredentialSource(),
+ archive: c,
+ );
+ await tester.pump();
+ session.state = SessionState.recoverable;
+ session.failureKind = SessionFailureKind.transient;
+ session.message =
+ 'Connection interrupted. Retry to reconnect your library.';
+
+ await tester.pumpWidget(MaterialApp(home: LoginPage(session: session)));
+
+ expect(find.text(session.message), findsOneWidget);
+ expect(find.text('Retry'), findsOneWidget);
+ expect(find.text('Sign out'), findsOneWidget);
+ expect(find.textContaining('CredentialTransient'), findsNothing);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ c.dispose();
+ });
+ testWidgets('expired identity and VMODAL 401 show sign in again', (
+ tester,
+ ) async {
+ for (final kind in [
+ SessionFailureKind.firebaseIdentityExpired,
+ SessionFailureKind.vmodalUnauthorized,
+ ]) {
+ final c = ArchiveController(persist: false);
+ final session = UserSessionController(
+ auth: MockFirebaseAuth(initial: const AppUser('alice')),
+ credentials: MockVmodalCredentialSource(),
+ archive: c,
+ );
+ await tester.pump();
+ session.state = SessionState.error;
+ session.failureKind = kind;
+ session.message = kind == SessionFailureKind.firebaseIdentityExpired
+ ? 'Your sign-in expired. Sign in again.'
+ : 'Your library session expired. Sign in again.';
+
+ await tester.pumpWidget(MaterialApp(home: LoginPage(session: session)));
+
+ expect(find.text(session.message), findsOneWidget);
+ expect(find.text('Sign in again'), findsOneWidget);
+ expect(find.text('Retry'), findsNothing);
+ await tester.tap(find.text('Sign in again'));
+ await tester.pumpAndSettle();
+ expect(session.state, SessionState.signedOut);
+ expect(find.byKey(const Key('sign_in')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ c.dispose();
+ }
+ });
+ testWidgets('denial, VMODAL 403, and contract failures cannot retry', (
+ tester,
+ ) async {
+ for (final kind in [
+ SessionFailureKind.credentialDenied,
+ SessionFailureKind.vmodalForbidden,
+ SessionFailureKind.contract,
+ ]) {
+ final c = ArchiveController(persist: false);
+ final session = UserSessionController(
+ auth: MockFirebaseAuth(),
+ credentials: MockVmodalCredentialSource(),
+ archive: c,
+ );
+ await tester.pump();
+ session.state = kind == SessionFailureKind.contract
+ ? SessionState.error
+ : SessionState.denied;
+ session.failureKind = kind;
+ session.message = kind == SessionFailureKind.contract
+ ? 'The library connection is not configured correctly.'
+ : 'Access to this library is unavailable.';
+
+ await tester.pumpWidget(MaterialApp(home: LoginPage(session: session)));
+
+ expect(find.text(session.message), findsOneWidget);
+ expect(find.text('Retry'), findsNothing);
+ expect(find.text('Sign out'), findsOneWidget);
+ expect(find.textContaining('raw issuer detail'), findsNothing);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ c.dispose();
+ }
+ });
test(
'nearby moments collapse per video while relevance order is preserved',
() {
- FrameMatch hit(String name, double time) => FrameMatch(
- row: const {'score': .7},
- filename: name,
- timestamp: '$time',
- seconds: time,
- );
final grouped = groupMoments([
- hit('one', 35),
- hit('one', 36),
- hit('two', 35),
- hit('one', 22),
- hit('one', 23),
+ frameMatch(name: 'one-a.mp4', offsetMs: 35000, assetId: 'asset-one'),
+ frameMatch(name: 'one-b.mp4', offsetMs: 36000, assetId: 'asset-one'),
+ frameMatch(name: 'two.mp4', offsetMs: 35000, assetId: 'asset-two'),
+ frameMatch(name: 'one-a.mp4', offsetMs: 22000, assetId: 'asset-one'),
+ frameMatch(name: 'one-b.mp4', offsetMs: 23000, assetId: 'asset-one'),
]);
- expect(grouped.keys, ['one', 'two']);
- expect(grouped['one']!.map((m) => m.seconds), [35, 22]);
- expect(grouped['two'], hasLength(1));
+ expect(grouped.keys, ['asset-one', 'asset-two']);
+ expect(grouped['asset-one']!.map((m) => m.seconds), [35, 22]);
+ expect(grouped['asset-two'], hasLength(1));
},
);
test('relative video timestamps and score meaning', () {
- expect(timestamp13({'ts_unix': '0000000035000'}), '0000000035000');
- expect(hitSeconds({'ts_unix': '0000000035000'}), 35);
- expect(hitSeconds({'ts_unix': '1788510000000'}), isNull);
- expect(hitSeconds({'ts_unix': '-5'}), isNull);
- const hit = FrameMatch(
- row: {'score': .92, 'score_ui': 1.0},
- filename: 'test',
- timestamp: '0',
+ final hit = FrameMatch(
+ hit: VideoSearchHit(const <String, Object?>{
+ 'file_name': 'test',
+ 'playback_offset_ms': 35000,
+ 'score': .92,
+ 'score_ui': 1.0,
+ }),
);
+ expect(hit.seconds, 35);
expect(hit.distance, .92);
+ expect(
+ VideoSearchHit(const <String, Object?>{
+ 'ts_unix': '1788510000000',
+ }).playbackOffsetMs,
+ isNull,
+ );
expect(timeLabel(75), '01:15');
expect(indexDone('success'), isTrue);
expect(indexFailed('failed'), isTrue);
});
+
+ testWidgets('storage deletion previews before final confirmation', (
+ tester,
+ ) async {
+ final c = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final gateway = FakeGateway(
+ MutableApiKeyProvider('fixture-delete'),
+ 'scope_7K3A',
+ );
+ await c.activate('scope_7K3A', gateway, canRead: true, canWrite: true);
+ await tester.pumpWidget(MaterialApp(home: StorageDeletionPage(archive: c)));
+ expect(
+ find.text('Signing out keeps videos on this device and in the cloud.'),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('delete_cloud_library')));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(find.text('Delete cloud library?'), findsOneWidget);
+ expect(
+ find.textContaining('Videos stored on this device remain'),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Preview deletion'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(find.text('Deletion preview'), findsOneWidget);
+ expect(find.textContaining('20 bytes'), findsOneWidget);
+ expect(
+ find.byKey(const Key('confirm_delete_cloud_library')),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('confirm_delete_cloud_library')));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(c.notice, 'Cloud library deleted. Videos on this device were kept.');
+ c.dispose();
+ await gateway.close();
+ });
+
+ testWidgets('uploaded local removal explains cloud retention', (
+ tester,
+ ) async {
+ final root = Directory.systemTemp.createTempSync('widget_remove_');
+ addTearDown(() => root.deleteSync(recursive: true));
+ final file = File('${root.path}/clip.mp4')..writeAsBytesSync([1]);
+ final c = ArchiveController(persist: false);
+ final clip = ArchiveClip(
+ id: 'clip',
+ title: 'Clip',
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ path: file.path,
+ remoteAssetId: 'asset-clip',
+ uploaded: true,
+ bundled: false,
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: RecordingSheet(archive: c, clip: clip),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const Key('remove_local_copy')));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(
+ find.textContaining('cloud copy remains searchable'),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Cancel'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(file.existsSync(), isTrue);
+ c.dispose();
+ });
+
+ testWidgets('remote-only row never opens local playback', (tester) async {
+ final c = ArchiveController(persist: false);
+ final session = UserSessionController(
+ auth: MockFirebaseAuth(),
+ credentials: MockVmodalCredentialSource(),
+ archive: c,
+ );
+ await tester.pump();
+ c.clips = [
+ ArchiveClip(
+ id: 'remote',
+ title: 'Remote',
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ remoteAssetId: 'asset-remote',
+ uploaded: true,
+ bundled: false,
+ ),
+ ];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: LibraryPage(controller: c, session: session),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Cloud only'), findsOneWidget);
+ await tester.tap(find.byType(VideoRow));
+ await tester.pump();
+ expect(
+ find.text('This video is in the cloud but is not stored on this device.'),
+ findsOneWidget,
+ );
+ expect(find.byType(RecordingSheet), findsNothing);
+ session.dispose();
+ c.dispose();
+ });
}
diff --git a/lib/src/client.dart b/lib/src/client.dart
index 4e6da0c..2b3e166 100644
--- a/lib/src/client.dart
+++ b/lib/src/client.dart
@@ -7,7 +7,7 @@ import 'transport.dart';
import 'upload.dart';
/// Version of the Dart SDK contract represented by this package.
-const String vmodalSdkVersion = '1.2.2';
+const String vmodalSdkVersion = '1.2.3';
/// Owns configuration, transports, and feature resources for one app session.
///
diff --git a/lib/src/models.dart b/lib/src/models.dart
index d5ffc92..65dc227 100644
--- a/lib/src/models.dart
+++ b/lib/src/models.dart
@@ -421,17 +421,114 @@ class HealthResponse extends JsonBackedResponse {
final Object? dependencies;
}
+/// Typed fields for one video-search hit.
+///
+/// Unknown and future service fields remain available through [raw]. A missing
+/// [assetId] is not inferred from a filename, path, item identifier, or time.
+class VideoSearchHit extends JsonBackedResponse {
+ VideoSearchHit(super.raw)
+ : assetId = stringValueOrNull(raw['asset_id']),
+ fileName = _videoHitFileName(raw),
+ playbackOffsetMs = _videoHitPlaybackOffsetMs(raw),
+ distance = _videoHitDistance(raw),
+ previewImageUrl = _firstVideoHitText(raw, const <String>[
+ 'preview_image_url',
+ 'image_url',
+ 'thumbnail_url',
+ ]);
+
+ /// Stable source-asset identity, when supplied by the server.
+ final String? assetId;
+
+ /// Display and legacy-compatibility basename, not stable identity.
+ final String? fileName;
+
+ /// Elapsed milliseconds from the beginning of the source video.
+ final int? playbackOffsetMs;
+
+ /// Raw lower-is-better search distance.
+ final double? distance;
+
+ /// Optional absolute or relative preview-image URL.
+ final String? previewImageUrl;
+}
+
+String? _firstVideoHitText(Map<String, Object?> raw, List<String> fields) {
+ for (final field in fields) {
+ final value = stringValueOrNull(raw[field]);
+ if (value != null) return value;
+ }
+ return null;
+}
+
+String? _videoHitFileName(Map<String, Object?> raw) {
+ final value = _firstVideoHitText(raw, const <String>[
+ 'file_name',
+ 'filename',
+ 'filename_sanitized',
+ 'video_filename',
+ 'video',
+ 'source_path',
+ 'path',
+ 'title',
+ ]);
+ if (value == null) return null;
+ return stringValueOrNull(value.replaceAll('\\', '/').split('/').last);
+}
+
+int? _videoHitPlaybackOffsetMs(Map<String, Object?> raw) {
+ final canonical = intValueOrNull(raw['playback_offset_ms']);
+ if (canonical != null && canonical >= 0) return canonical;
+
+ for (final field in const <String>[
+ 'video_time_seconds',
+ 'timestamp_seconds',
+ 'time_seconds',
+ 'start_seconds',
+ 'offset_seconds',
+ 'seconds',
+ 'time_sec',
+ ]) {
+ final seconds = doubleValueOrNull(raw[field]);
+ final milliseconds = seconds == null ? null : seconds * 1000;
+ if (milliseconds != null && milliseconds.isFinite && milliseconds >= 0) {
+ return milliseconds.round();
+ }
+ }
+ for (final field in const <String>[
+ 'ts_unix_13digits',
+ 'ts_unix',
+ 'timestamp_ms',
+ ]) {
+ final milliseconds = intValueOrNull(raw[field]);
+ if (milliseconds != null && milliseconds >= 0 && milliseconds < 86400000) {
+ return milliseconds;
+ }
+ }
+ return null;
+}
+
+double? _videoHitDistance(Map<String, Object?> raw) {
+ for (final field in const <String>['distance', 'score', '_distance']) {
+ final value = doubleValueOrNull(raw[field]);
+ if (value != null && value >= 0) return value;
+ }
+ return null;
+}
+
/// Search results, counts, and execution timing.
class SearchResponse extends JsonBackedResponse {
SearchResponse(super.raw)
: data = raw['data'] is List
? List<Object?>.from(raw['data']! as List)
: <Object?>[],
+ videoHits = objectList(raw['data']).map(VideoSearchHit.new).toList(),
cntActual = intValue(raw['cnt_actual']),
cntTotal = intValue(raw['cnt_total']),
executionTimeMs = doubleValue(raw['execution_time_ms']);
final List<Object?> data;
+ final List<VideoSearchHit> videoHits;
final int cntActual;
final int cntTotal;
final double executionTimeMs;
@@ -573,7 +670,8 @@ class UploadResponse extends JsonBackedResponse {
/// Detailed result of one signed video upload.
class VideoUploadResponse extends JsonBackedResponse {
VideoUploadResponse(super.raw)
- : userId = '${raw['user_id'] ?? ''}',
+ : assetId = stringValueOrNull(raw['asset_id']),
+ userId = '${raw['user_id'] ?? ''}',
key = '${raw['key'] ?? ''}',
url = '${raw['url'] ?? ''}',
method = '${raw['method'] ?? 'PUT'}',
@@ -601,6 +699,9 @@ class VideoUploadResponse extends JsonBackedResponse {
temporaryFileDeleted = raw['temporary_file_deleted'] == true,
temporaryFileReused = raw['temporary_file_reused'] == true;
+ /// Stable uploaded-asset identity, when supplied by finalization.
+ final String? assetId;
+
final String userId;
final String key;
final String url;
diff --git a/lib/src/utils.dart b/lib/src/utils.dart
index e0e3929..f02a7b1 100644
--- a/lib/src/utils.dart
+++ b/lib/src/utils.dart
@@ -134,6 +134,30 @@ int intValue(Object? value) {
return 0;
}
+String? stringValueOrNull(Object? value) {
+ if (value == null) return null;
+ final text = '$value'.trim();
+ return text.isEmpty ? null : text;
+}
+
+int? intValueOrNull(Object? value) {
+ if (value is int) return value;
+ if (value is num && value.isFinite && value == value.roundToDouble()) {
+ return value.toInt();
+ }
+ if (value is String) return int.tryParse(value.trim());
+ return null;
+}
+
+double? doubleValueOrNull(Object? value) {
+ if (value is num && value.isFinite) return value.toDouble();
+ if (value is String) {
+ final parsed = double.tryParse(value.trim());
+ return parsed != null && parsed.isFinite ? parsed : null;
+ }
+ return null;
+}
+
double doubleValue(Object? value) {
if (value is num && value.isFinite) return value.toDouble();
if (value is String) {
diff --git a/lib/src/vmodal.dart b/lib/src/vmodal.dart
index 63a6c7e..077927c 100644
--- a/lib/src/vmodal.dart
+++ b/lib/src/vmodal.dart
@@ -302,7 +302,7 @@ final class ScopedSearchOptions {
this.queryMetadataText,
this.imageQuery,
this.mode = 'vid_file',
- this.searchSources = const <String>['ocr', 'asr', 'image'],
+ this.searchSources = const <String>['image'],
this.searchCombineMode = 'union',
this.startDate,
this.endDate,
diff --git a/pubspec.yaml b/pubspec.yaml
index de4bb4b..5f3a67a 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,6 +1,6 @@
name: vmodal_sdk_flutter
description: Typed VModal API client for Flutter applications on Android and iOS.
-version: 1.2.2
+version: 1.2.3
license: MIT
repository: https://github.com/v-modal/vmodal_sdk_flutter
issue_tracker: https://github.com/v-modal/vmodal_sdk_flutter/issues
diff --git a/release_note.md b/release_note.md
index 06043a8..c3c1a2b 100644
--- a/release_note.md
+++ b/release_note.md
@@ -1,14 +1,7 @@
----------------------------------------------------------
-date: 2026-09-01
-origin_commit: 9ace1fb2ad558d5061b18eb1185cce9af9bd3d9e
-title: Flutter SDK v1.2.2 CCTV timestamp and metadata contract
+date: 2026-09-27
+origin_commit: pending
+title: Flutter SDK v1.2.3 Dartdoc package archive repair
summary:
- - Added caller-selected CCTV video filenames, metadata text, repeated metadata tags, offset-aware start datetimes, and reprocessing options for direct and signed uploads.
- - Preserved the CCTV contract across single, multipart, resumed, bulk, adaptive, and transcoded upload paths, including the original public filename.
- - Added canonical timestamp response accessors for normalized start datetime, UTC epoch milliseconds, and timestamp source.
- - Added metadata-text and absolute-time video search support with timezone validation, paired date bounds, scoped API propagation, and legacy compatibility.
- - Added a compile-checked CCTV example covering authentication, collection and index-job discovery, timestamped upload, index creation, polling, and absolute-time search.
- - Reissued the release with a reproducible public-source manifest that tracks SDK and example lockfiles before tag verification and pub.dev publication.
- - Configured public pub.dev publishing to initialize GitHub Actions OIDC before upload, preventing interactive login during release automation.
- - Added offline contract, multipart wire, transcode, workflow, and explicit CCTV live tests, plus synchronized documentation and generated Dart reference pages.
- - Released the public Flutter SDK source and documentation after analysis, SDK/example tests, security scanning, package validation, Android/iOS builds, and the production lifecycle passed.
+ - Reissued the package with explicit public `lib/` include rules so pub.dev's archive retains the Dart entrypoint for dartdoc.
+ - Added a regression assertion for the library include rules and release guidance that requires the package dry-run to list the entrypoint.
diff --git a/security_check.sh b/security_check.sh
index cfc4acf..09517b3 100755
--- a/security_check.sh
+++ b/security_check.sh
@@ -26,7 +26,10 @@ sdk_security_workflow() {
grep -Eq 'environment:[[:space:]]+pub\.dev' "$public"
grep -Eq 'environment:[[:space:]]+sdk-flutter-production' "$internal"
grep -Eq 'persist-credentials:[[:space:]]+false' "$internal" "$public"
- grep -Fq 'run: bash security_check.sh secrets' "$internal"
+ grep -Fq 'ga_release.sh" ga_secret_detection' "$internal"
+ ! grep -Fq 'run: |' "$internal"
+ grep -Fq 'RELEASE_SHA: ${{ github.sha }}' "$internal"
+ grep -Fq 'GA_RELEASE_DIR: ${{ runner.temp }}' "$internal"
grep -Fq 'needs: [secret_detection, offline_test, example_android, example_ios, live_test, pub_package]' "$internal"
! grep -Fq 'Security scan disabled for development' "$internal"
! grep -Fq -- '--log-opts=' "$internal"
diff --git a/test/docs_reference_test.dart b/test/docs_reference_test.dart
index 14052aa..ca75eda 100644
--- a/test/docs_reference_test.dart
+++ b/test/docs_reference_test.dart
@@ -3,7 +3,7 @@ import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
-final docsRoot = Directory('docs_sdk');
+final docsRoot = Directory('doc');
final internalDocs = docsRoot.existsSync() && File('docs.py').existsSync();
final requiredDocs = <String>[
@@ -146,7 +146,7 @@ void main() {
expect(text, isNot(contains('swagger')), reason: path);
expect(text, isNot(contains('openapi')), reason: path);
expect(text, isNot(contains('docs_swagger')), reason: path);
- expect(text, contains('docs_sdk'), reason: path);
+ expect(text, contains('doc'), reason: path);
}
});
}
diff --git a/test/new_api_surface_test.dart b/test/new_api_surface_test.dart
index 809c9b0..cd53ac3 100644
--- a/test/new_api_surface_test.dart
+++ b/test/new_api_surface_test.dart
@@ -406,8 +406,10 @@ void main() {
expect(api.requests, hasLength(2));
expect(requestValues(api.requests[0])['group_name'], 'app__user_1');
expect(requestValues(api.requests[0])['stream_name'], 'camera');
+ expect(requestValues(api.requests[0])['search_sources'], <String>['image']);
expect(requestValues(api.requests[1])['group_name'], 'app__user_2');
expect(requestValues(api.requests[1])['stream_name'], 'favorites');
+ expect(requestValues(api.requests[1])['search_sources'], <String>['image']);
waits['second']!.complete(
jsonResponse('{"data":[],"cnt_actual":2,"cnt_total":2}'),
diff --git a/test/readme_pin_test.dart b/test/readme_pin_test.dart
new file mode 100644
index 0000000..8f933da
--- /dev/null
+++ b/test/readme_pin_test.dart
@@ -0,0 +1,25 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ test('public production installation uses immutable version pins', () {
+ final readme = File('README.md').readAsStringSync();
+ final pubspec = File('pubspec.yaml').readAsStringSync();
+ final section = RegExp(
+ r'## Start in minutes([\s\S]*?)## Search video',
+ ).firstMatch(readme)?.group(1);
+
+ expect(section, isNotNull);
+ expect(section, isNot(contains('ref: main')));
+ expect(section, contains('main` branch is suitable for evaluation'));
+ expect(section, contains('full 40-character commit SHA'));
+
+ final version = RegExp(
+ r'^version:\s*([^\s]+)',
+ multiLine: true,
+ ).firstMatch(pubspec)!.group(1);
+ final tag = RegExp(r'ref:\s*v([^\s]+)').firstMatch(section!)?.group(1);
+ if (tag != null) expect(tag, version);
+ });
+}
diff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dart
index a35a4cf..06ab699 100644
--- a/test/regression_manifest_test.dart
+++ b/test/regression_manifest_test.dart
@@ -85,6 +85,8 @@ void main() {
);
if (Directory('docs').existsSync()) {
expect(File('tool/live_test.dart').existsSync(), isTrue);
+ }
+ if (File('test/routes_gen_test.dart').existsSync()) {
expect(File('tool/gen_routes.dart').existsSync(), isTrue);
expect(File('tool/routes_manifest.dart').existsSync(), isTrue);
}
@@ -120,7 +122,7 @@ void main() {
final text = File('.pubignore').readAsStringSync();
for (final path in <String>[
'docs/todo/',
- 'docs_sdk/',
+ 'docs/',
'docs.py',
'utils.py',
'test/routes_gen_test.dart',
@@ -129,6 +131,9 @@ void main() {
]) {
expect(text, contains(path), reason: path);
}
+ for (final path in <String>['!lib/', '!lib/**']) {
+ expect(text, contains(path), reason: path);
+ }
expect(text, isNot(contains('dartdoc_options.yaml')));
expect(text, isNot(contains('release_note.md')));
});
@@ -200,10 +205,10 @@ void main() {
'example/05_framebase_userlogin/lib/data/search_gateway.dart',
'example/05_framebase_userlogin/lib/data/archive_controller.dart',
'example/05_framebase_userlogin/test/user_session_controller_test.dart',
- 'doc/search_app.md',
- 'doc/sdk_doc.md',
- 'doc/manage_api_key.md',
- 'doc/sdk_contract.md',
+ 'docs/search_app.md',
+ 'docs/sdk_doc.md',
+ 'docs/manage_api_key.md',
+ 'docs/sdk_contract.md',
]) {
expect(File('${dir.path}/$path').existsSync(), isTrue, reason: path);
}
@@ -211,7 +216,7 @@ void main() {
'${dir.path}/example/01_full_app/README.md',
).readAsStringSync();
final searchGuide = File(
- '${dir.path}/doc/search_app.md',
+ '${dir.path}/docs/search_app.md',
).readAsStringSync();
expect(exampleReadme, contains('client.images.getUrlBulk'));
expect(exampleReadme, contains('responsive result grid'));
@@ -236,8 +241,8 @@ void main() {
'example/05_framebase_userlogin/.dart_tool',
'example/05_framebase_userlogin/build',
'example/05_framebase_userlogin/android/local.properties',
- 'doc/todo/sdk_doc.md',
- 'docs_sdk',
+ 'docs/todo/sdk_doc.md',
+ 'doc',
'docs.py',
'utils.py',
'test/routes_gen_test.dart',
diff --git a/test/resources_models_test.dart b/test/resources_models_test.dart
index d514221..640cd66 100644
--- a/test/resources_models_test.dart
+++ b/test/resources_models_test.dart
@@ -352,6 +352,125 @@ void main() {
expect(groups.findGroup('travel', mode: 'img_file'), isNull);
});
+ test('canonical video hits expose typed fields and preserve raw data', () {
+ final raw = <String, Object?>{
+ 'asset_id': 'asset-7',
+ 'file_name': 'camera.mp4',
+ 'playback_offset_ms': '35000',
+ 'distance': '0.42',
+ 'preview_image_url': '/api/external/v1/image/get_image?sig=test',
+ 'extension_field': <String>['kept'],
+ };
+ final hit = VideoSearchHit(raw);
+ expect(hit.assetId, 'asset-7');
+ expect(hit.fileName, 'camera.mp4');
+ expect(hit.playbackOffsetMs, 35000);
+ expect(hit.distance, .42);
+ expect(hit.previewImageUrl, '/api/external/v1/image/get_image?sig=test');
+ expect(hit.raw, same(raw));
+ expect(hit.raw['extension_field'], <String>['kept']);
+ expect(
+ VideoSearchHit(const <String, Object?>{
+ 'playback_offset_ms': 1200,
+ }).playbackOffsetMs,
+ 1200,
+ );
+ });
+
+ test(
+ 'search response adds ordered map-only video hits without changing data',
+ () {
+ final rows = <Object?>[
+ <String, Object?>{'asset_id': 'first'},
+ 'unchanged scalar',
+ <Object?, Object?>{'asset_id': 'second'},
+ ];
+ final response = SearchResponse(<String, Object?>{'data': rows});
+ expect(response.data, rows);
+ expect(response.data[1], 'unchanged scalar');
+ expect(response.videoHits.map((hit) => hit.assetId), ['first', 'second']);
+ },
+ );
+
+ test(
+ 'legacy video hit aliases normalize filename time distance and preview',
+ () {
+ final hit = VideoSearchHit(const <String, Object?>{
+ 'source_path': r'C:\archive\camera.mp4',
+ 'timestamp_seconds': '35.1256',
+ 'score': .73,
+ 'image_url': 'https://images.test/frame.jpg',
+ });
+ expect(hit.fileName, 'camera.mp4');
+ expect(hit.playbackOffsetMs, 35126);
+ expect(hit.distance, .73);
+ expect(hit.previewImageUrl, 'https://images.test/frame.jpg');
+ expect(
+ VideoSearchHit(const <String, Object?>{'score': .92}).distance,
+ .92,
+ );
+ expect(
+ VideoSearchHit(const <String, Object?>{'score_ui': .98}).distance,
+ isNull,
+ );
+ },
+ );
+
+ test(
+ 'malformed video hit fields stay null and identity is never invented',
+ () {
+ for (final raw in <Map<String, Object?>>[
+ <String, Object?>{'ts_unix': '1788510000000'},
+ <String, Object?>{'playback_offset_ms': -1},
+ <String, Object?>{'playback_offset_ms': 1.5},
+ <String, Object?>{'playback_offset_ms': 'bad'},
+ <String, Object?>{'playback_offset_ms': double.infinity},
+ ]) {
+ expect(VideoSearchHit(raw).playbackOffsetMs, isNull);
+ }
+ for (final value in <Object?>[-1, 'bad', double.nan, double.infinity]) {
+ expect(
+ VideoSearchHit(<String, Object?>{'distance': value}).distance,
+ isNull,
+ );
+ }
+ final blank = VideoSearchHit(const <String, Object?>{
+ 'asset_id': ' ',
+ 'path': 'folder/',
+ 'preview_image_url': '',
+ 'item_id': 'frame-123',
+ });
+ expect(blank.assetId, isNull);
+ expect(blank.fileName, isNull);
+ expect(blank.previewImageUrl, isNull);
+ expect(
+ VideoSearchHit(const <String, Object?>{
+ 'item_id': 'frame-123',
+ 'filename': 'camera.mp4',
+ }).assetId,
+ isNull,
+ );
+ },
+ );
+
+ test('video upload asset identity is canonical-only', () {
+ expect(
+ VideoUploadResponse(const <String, Object?>{
+ 'asset_id': 'asset-uploaded',
+ }).assetId,
+ 'asset-uploaded',
+ );
+ expect(
+ VideoUploadResponse(const <String, Object?>{
+ 'filename': 'camera.mp4',
+ 'video_filename': 'camera.mp4',
+ 'key': 'uploads/camera.mp4',
+ 'dest_path': 'bucket/camera.mp4',
+ }).assetId,
+ isNull,
+ );
+ });
+
test('gateway bulk image payload removes nested identity fields', () async {
final fake = FakeTransport()..addResponse(jsonResponse('{"records":[]}'));
final client = VmodalClient(
diff --git a/test/workflow_layout_test.dart b/test/workflow_layout_test.dart
index e0154da..97b7d05 100644
--- a/test/workflow_layout_test.dart
+++ b/test/workflow_layout_test.dart
@@ -12,6 +12,7 @@ final publicFile = File('release/public_publish.yml').existsSync()
? File('release/public_publish.yml')
: File('.github/workflows/publish.yml');
final public = publicFile.readAsStringSync();
+final release = File('ga_release.sh').readAsStringSync();
final androidProperties = File(
'example/01_full_app/android/gradle.properties',
).readAsStringSync();
@@ -22,7 +23,7 @@ final examplePubspec = File(
'example/01_full_app/pubspec.yaml',
).readAsStringSync();
-void checkWorkflow(String main, String tagged) {
+void checkWorkflow(String main, String script, String tagged) {
const releaseOnly =
"if: \${{ github.event_name == 'workflow_dispatch' && !inputs.publish_sdk_docs_only && (inputs.publish_sdk_flutter || inputs.publish_pub_dev) }}";
const publishDocs =
@@ -39,15 +40,33 @@ void checkWorkflow(String main, String tagged) {
expect(main, contains('default: true'));
expect(main, contains('group: sdk_flutter_release_\${{ github.ref }}'));
expect(main, contains('WORKDIR: uinterface/sdk_flutter'));
- expect(main, contains('# RELEASE_SHA: \${{ github.sha }}'));
- expect(main, isNot(contains('\n RELEASE_SHA: \${{ github.sha }}')));
- expect(main, isNot(contains('\n ref: \${{ env.RELEASE_SHA }}')));
+ expect(main, contains('GA_WORKSPACE: \${{ github.workspace }}'));
+ expect(main, contains('RELEASE_SHA: \${{ github.sha }}'));
+ expect(main, contains('PUBLIC_REPOSITORY: v-modal/vmodal_sdk_flutter'));
+ expect(main, contains('DOCS_REPOSITORY: v-modal/vmodal_sdk_flutter'));
+ expect(
+ main,
+ contains('DOCS_URL: https://v-modal.github.io/vmodal_sdk_flutter'),
+ );
+ expect(main, contains('GA_RELEASE_DIR: \${{ runner.temp }}'));
+ expect(main, contains('VMODAL_ENV: prd'));
expect(
main,
- isNot(
- contains('\n test "\$(git rev-parse HEAD)" = "\$RELEASE_SHA"'),
+ contains(
+ 'VMODAL_API_KEY: \${{ secrets.TEST_CLIENT_CLERK_USER_API_TOKEN }}',
),
);
+ expect(main, contains('RELEASE_TOKEN: \${{ secrets.GH_TOKEN }}'));
+ expect(main, contains('GH_TOKEN: \${{ secrets.GH_TOKEN }}'));
+ expect(main, contains('PUBLISH_PUB_DEV: \${{ inputs.publish_pub_dev }}'));
+ expect(main, isNot(contains('\n ref: \${{ env.RELEASE_SHA }}')));
+ expect(main, isNot(contains('run: |')));
+
+ final runs = RegExp(r'^\s+run:\s*(.+)$', multiLine: true).allMatches(main);
+ expect(runs, isNotEmpty);
+ for (final run in runs) {
+ expect(run.group(1), contains('ga_release.sh'));
+ }
expect(
main,
contains('secret_detection:\n $publishDocs\n runs-on: ubuntu-latest'),
@@ -81,7 +100,6 @@ void checkWorkflow(String main, String tagged) {
'[secret_detection, offline_test, example_android, example_ios, live_test, pub_package]',
),
);
- expect(main, contains('pub.dev publication requires source export.'));
expect(
main,
contains(
@@ -89,46 +107,53 @@ void checkWorkflow(String main, String tagged) {
),
);
expect(main, contains('environment: sdk-flutter-production'));
- expect(main, contains('gitleaks_'));
- expect(main, contains('--source "\$WORKDIR"'));
- expect(main, contains('run: bash security_check.sh secrets'));
- expect(main, contains('cd example/05_framebase_userlogin'));
- expect(main, contains('flutter_bin)" analyze'));
- expect(main, contains('flutter_bin)" test'));
+ expect(main, contains('ga_release.sh" ga_secret_detection'));
+ expect(main, contains('ga_release.sh" ga_offline_test'));
+ expect(main, contains('ga_release.sh" ga_example_android'));
+ expect(main, contains('ga_release.sh" ga_example_ios'));
+ expect(main, contains('ga_release.sh" ga_live_test "\$GITHUB_STEP_SUMMARY"'));
+ expect(main, contains('ga_release.sh" ga_source_package'));
+ expect(main, contains('ga_release.sh" ga_public_publish'));
+ expect(main, contains('ga_release.sh" ga_docs_build'));
+ expect(main, contains('ga_release.sh" ga_docs_publish'));
+ expect(main, contains('ga_release.sh" ga_pub_dev_verify'));
expect(main, isNot(contains('--log-opts=')));
- expect(main, contains('SHA256SUMS'));
- expect(main, contains('SOURCE_MANIFEST.sha256'));
+
+ expect(script, contains('ga_secret_detection()'));
+ expect(script, contains('bash security_check.sh secrets'));
+ expect(script, contains('ga_offline_test()'));
+ expect(script, contains('cd example/05_framebase_userlogin'));
+ expect(script, contains('flutter_bin)" analyze'));
+ expect(script, contains('flutter_bin)" test'));
+ expect(script, contains('ga_source_package()'));
+ expect(script, contains('SHA256SUMS'));
+ expect(script, contains('SOURCE_MANIFEST.sha256'));
expect(
- main,
+ script,
contains('run tool/release_manifest.dart export "\$export_dir"'),
);
- expect(main, contains('sha256sum --check SOURCE_MANIFEST.sha256'));
- expect(
- main,
- contains('git ls-files --error-unmatch install.sh build.sh run.sh test.sh'),
- );
+ expect(script, contains('sha256sum --check SOURCE_MANIFEST.sha256'));
expect(
- main,
+ script,
contains(
'sha256sum example/01_full_app/build/app/outputs/flutter-apk/app-debug.apk',
),
);
- expect(main, contains("find example/01_full_app/build/ios -name '*.app'"));
+ expect(script, contains("find example/01_full_app/build/ios -name '*.app'"));
expect(
- main,
+ script,
contains(
'sha256sum example/05_framebase_userlogin/build/app/outputs/flutter-apk/app-debug.apk',
),
);
expect(
- main,
+ script,
contains("find example/05_framebase_userlogin/build/ios -name '*.app'"),
);
- expect(main, isNot(contains('sha256sum example/build/')));
- expect(main, isNot(contains('find example/build/ios')));
- expect(main, contains('RELEASE_TOKEN: \${{ secrets.GH_TOKEN }}'));
+ expect(script, isNot(contains('sha256sum example/build/')));
+ expect(script, isNot(contains('find example/build/ios')));
expect(main, isNot(contains('FLUTTER_SDK_APP_')));
- expect(main, contains('git push --atomic'));
+ expect(script, contains('git push --atomic'));
expect(
main,
contains(
@@ -147,69 +172,69 @@ void checkWorkflow(String main, String tagged) {
'publish_sdk_docs:\n needs: sdk_docs_artifact\n $publishBuiltDocs',
),
);
- expect(main, contains('python "\$WORKDIR/docs.py" generate'));
- expect(main, contains('python "\$WORKDIR/docs.py" check'));
- expect(main, contains('bash "\$WORKDIR/install.sh" install'));
+ expect(script, contains('python "\$GA_SCRIPT_DIR/docs.py" generate'));
+ expect(script, contains('python "\$GA_SCRIPT_DIR/docs.py" check'));
+ expect(script, contains('bash "\$GA_SCRIPT_DIR/install.sh" install'));
expect(
- main,
+ script,
contains('python -m pip install --disable-pip-version-check fire==0.7.1'),
);
- expect(main, contains('path: \${{ env.WORKDIR }}/docs_sdk'));
+ expect(main, contains('path: \${{ env.WORKDIR }}/doc'));
expect(
main,
contains('sdk-flutter-docs-\${{ github.run_id }}-\${{ github.sha }}'),
);
- expect(main, contains('"\$WORKDIR/docs_sdk/index.html"'));
- expect(main, contains('"\$WORKDIR/docs_sdk/index.json"'));
+ expect(script, contains('"\$GA_SCRIPT_DIR/doc/index.html"'));
+ expect(script, contains('"\$GA_SCRIPT_DIR/doc/index.json"'));
expect(
- main,
- contains('"\$WORKDIR/docs_sdk/vmodal_sdk_flutter/VmodalClient-class.html"'),
+ script,
+ contains(
+ '"\$GA_SCRIPT_DIR/doc/vmodal_sdk_flutter/VmodalClient-class.html"',
+ ),
);
for (final name in <String>['VModal', 'VModalProject', 'VModalScope']) {
expect(
- main,
- contains('"\$WORKDIR/docs_sdk/vmodal_sdk_flutter/$name-class.html"'),
+ script,
+ contains('"\$GA_SCRIPT_DIR/doc/vmodal_sdk_flutter/$name-class.html"'),
);
expect(
- main,
- contains(
- '"\$RUNNER_TEMP/sdk-docs-site/vmodal_sdk_flutter/$name-class.html"',
- ),
+ script,
+ contains('"\$site_dir/vmodal_sdk_flutter/$name-class.html"'),
);
}
expect(main, isNot(contains('PyYAML')));
expect(main, isNot(contains('openapi-spec-validator')));
expect(main.toLowerCase(), isNot(contains('swagger')));
expect(main, contains('include-hidden-files: true'));
- expect(main, contains('DOCS_REPOSITORY: v-modal/vmodal_sdk_flutter'));
- expect(
- main,
- contains('DOCS_URL: https://v-modal.github.io/vmodal_sdk_flutter'),
- );
- expect(main, isNot(contains('gh repo create "\$DOCS_REPOSITORY"')));
- expect(main, contains('git push origin HEAD:gh-pages'));
- expect(main, contains('build_type:"legacy"'));
- expect(main, contains('repos/\$DOCS_REPOSITORY/pages'));
- expect(main, contains('"\$DOCS_URL/RELEASE_SHA"'));
- expect(main, contains('for attempt in {1..30}'));
- expect(main, contains('https://pub.dev/api/packages/vmodal_sdk_flutter'));
- expect(main, contains('dartdoc_options.yaml'));
- expect(main, contains('README.md release_note.md CHANGELOG.md'));
- expect(main, contains("--exclude='todo'"));
- expect(
- main,
- contains(
- 'git add -f pubspec.lock example/01_full_app/pubspec.lock '
- 'example/02_users/pubspec.lock example/03_cctv/pubspec.lock',
- ),
- );
+ expect(script, isNot(contains('gh repo create "\$DOCS_REPOSITORY"')));
+ expect(script, contains('git push origin HEAD:gh-pages'));
+ expect(script, contains('build_type:"legacy"'));
+ expect(script, contains('repos/\$DOCS_REPOSITORY/pages'));
+ expect(script, contains('"\$DOCS_URL/RELEASE_SHA"'));
+ expect(script, contains('for attempt in {1..30}'));
+ expect(script, contains('https://pub.dev/api/packages/vmodal_sdk_flutter'));
+ expect(script, contains("grep -Fx 'lib/vmodal_sdk_flutter.dart'"));
+ expect(script, contains('dartdoc_options.yaml'));
+ expect(script, contains('README.md release_note.md CHANGELOG.md'));
+ expect(script, contains("--exclude='todo'"));
+ expect(script, contains('git add -f pubspec.lock'));
expect(
- main,
+ script,
contains(
'git add -f example/05_framebase_userlogin/lib '
'example/05_framebase_userlogin/pubspec.lock',
),
);
+ expect(script, contains('ga_require_env GA_RELEASE_DIR'));
+ expect(script, contains('ga_require_env RELEASE_SHA'));
+ expect(script, contains('ga_require_env RELEASE_TOKEN'));
+ expect(script, contains('ga_require_env PUBLISH_PUB_DEV'));
+ expect(script, contains('ga_require_env GH_TOKEN'));
+ expect(script, contains('ga_require_env PUBLIC_REPOSITORY'));
+ expect(script, contains('ga_require_env DOCS_REPOSITORY'));
+ expect(script, contains('ga_require_env DOCS_URL'));
+ expect(script, isNot(contains('GITHUB_SHA')));
+ expect(script, isNot(contains('RUNNER_TEMP')));
final actions = RegExp(
r'uses:\s+[^\s]+@([^\s]+)',
@@ -229,9 +254,9 @@ void checkWorkflow(String main, String tagged) {
main.toLowerCase(),
isNot(matches(RegExp(r'maven|\bosv\b|\bsbom\b|security_policy'))),
);
- expect(main, isNot(contains('git merge')));
- expect(main, isNot(contains('git push --force')));
- expect(main, isNot(contains('--skip-validation')));
+ expect('$main\n$script', isNot(contains('git merge')));
+ expect('$main\n$script', isNot(contains('git push --force')));
+ expect('$main\n$script', isNot(contains('--skip-validation')));
expect(tagged, contains('name: publish_pub_dev'));
expect(tagged, contains("- 'v[0-9]+.[0-9]+.[0-9]+'"));
@@ -259,7 +284,7 @@ void main() {
test('release workflows enforce tested-source causality', () {
if (internal.isEmpty) return;
- checkWorkflow(internal, public);
+ checkWorkflow(internal, release, public);
});
test('floating action pin mutation fails', () {
@@ -268,7 +293,10 @@ void main() {
RegExp(r'actions/checkout@[0-9a-f]{40}'),
'actions/checkout@v4',
);
- expect(() => checkWorkflow(bad, public), throwsA(isA<TestFailure>()));
+ expect(
+ () => checkWorkflow(bad, release, public),
+ throwsA(isA<TestFailure>()),
+ );
});
test('publication shortcut mutation fails', () {
@@ -278,21 +306,30 @@ void main() {
'[secret_detection, offline_test, example_android, example_ios, live_test, pub_package]',
'publish_sdk_flutter:\n needs: offline_test',
);
- expect(() => checkWorkflow(bad, public), throwsA(isA<TestFailure>()));
+ expect(
+ () => checkWorkflow(bad, release, public),
+ throwsA(isA<TestFailure>()),
+ );
});
test('source export mutation fails', () {
if (internal.isEmpty) return;
- final bad = internal.replaceFirst(
+ final bad = release.replaceFirst(
'run tool/release_manifest.dart export "\$export_dir"',
'run tool/release_manifest.dart check',
);
- expect(() => checkWorkflow(bad, public), throwsA(isA<TestFailure>()));
+ expect(
+ () => checkWorkflow(internal, bad, public),
+ throwsA(isA<TestFailure>()),
+ );
});
test('stored publication token mutation fails', () {
if (internal.isEmpty) return;
final bad = '$public\n PUB_TOKEN: \${{ secrets.PUB_TOKEN }}\n';
- expect(() => checkWorkflow(internal, bad), throwsA(isA<TestFailure>()));
+ expect(
+ () => checkWorkflow(internal, release, bad),
+ throwsA(isA<TestFailure>()),
+ );
});
}
diff --git a/tool/release_manifest.dart b/tool/release_manifest.dart
index 8b23bcf..2faebe3 100644
--- a/tool/release_manifest.dart
+++ b/tool/release_manifest.dart
@@ -128,7 +128,7 @@ Future<void> _export(Directory root, Directory destination) async {
final docs = Directory('${root.path}/docs').existsSync() ? 'docs' : 'doc';
await _copyDirectory(
Directory('${root.path}/$docs'),
- Directory('${destination.path}/doc'),
+ Directory('${destination.path}/docs'),
excluded: const <String>{'todo'},
);
final publish = File('${root.path}/release/public_publish.yml').existsSync()