V- Modal AI: Visual Video / Image Search - Flutter Video SDK
Dart android-sdkflutterflutter-appflutter-packageflutter-sdkflutter-videoflutter-video-editingflutter-video-playerflutter-video-sdkflutter-videosflutter-videosdkmobile-videomobile-video-editor-sdkmobile-video-sdkvideo-editingvideo-sdkvideo-searchvideo-search-enginevideo-streaming
Release Flutter SDK from 012232d13a7b2ef8825b16b0230ecf58696ed884
vmodal-release-app84339245d613
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84263c9..2f2a868 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,3 +1,12 @@+----------------------------------------------------------+date: 2026-10-03+commit_hash: 2e046e436191798fb3d725e2a95d7077b3e8e44f+title: Publish Flutter SDK with shared Infisical credentials+summary:+ - Load live-test and public repository credentials through the shared workflow Bash helpers.+ - Publish the Flutter SDK source and generated reference documentation after release checks pass.+ - Restore tracked example library sources by correcting Flutter exceptions to the root Python packaging ignore rule.+----------------------------------------------------------date: 2026-10-02commit_hash: e02e2e15a2d2eb6af43125e89dc4e5bef904ce20diff --git a/README.md b/README.mdindex a44bc3c..62ee671 100644--- a/README.md+++ b/README.md@@ -178,8 +178,8 @@ and coalesces renewal. Close at the start of logout or account switch.This source API requires corresponding registered origin, Worker and upstreamcapabilities; it is not a claim of live deployment. See[Choose authentication](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/authentication.md),-[the backend guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/backend_authentication.md), and the independent-[backend-auth reference](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/example/06_backend_auth/README.md). The preserved+[the backend guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/auth_user_backend_mode.md), and the independent+[backend-auth reference](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/example/06_userlogin_backend_auth/README.md). The preservedFramebase user-login app remains a shared-key/local-isolation example.## Isolate signed-in app users sharing one tenant keydiff --git a/RELEASE_METADATA b/RELEASE_METADATAindex bbeb430..336a0ea 100644--- a/RELEASE_METADATA+++ b/RELEASE_METADATA@@ -1 +1 @@-Source-vmx-api: 5dd1131917e019762bd2590145e1794b5095c1db+Source-vmx-api: 012232d13a7b2ef8825b16b0230ecf58696ed884diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256index 8937570..d847bb1 100644--- a/SOURCE_MANIFEST.sha256+++ b/SOURCE_MANIFEST.sha256@@ -2,23 +2,24 @@ e789cd4d1bed8a78ec8014c5c5913e300f81b63ea56a56aacb0dfec3b5e7ce2b ./.flutter-vera3e3ce18f80b46587bcd529d13e456d10d97dd5e4a3f15e8e1a18894961120b1 ./.github/workflows/publish.yml992d54be0fbdaf0ef52be1bb80a3985af67defed270f4343aa9ee27465f6a49e ./.gitleaks.tomlefaab625b09d5b5bb80352b0586e4f81764914a1aff24164e338b6a95fee5973 ./.pubignore-abdc15ffd2312caa935bd8eeb30485b42654c146ded001997cfa240e9a77c7b2 ./CHANGELOG.md+ec2111ce70a9d716eed54174c83c8443882e699404a35c0567d3124ea09e0189 ./CHANGELOG.md37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 ./LICENSE-4a3171e141f97f254ff26643867c0ccb4a9bb4c0c53057bc439b7bae1b7190bf ./README.md-db5da40576684f0f4aa4d199a81158101f7772de2950306f557dbce7bd595918 ./RELEASE_METADATA+6c8f8c4c1337d7a56ddafd5ae35e60c31a8c0e417ecefa57b84270557950b8fb ./README.md+1b2c7ede8cc4ebcebc89f6483bd2bebefb5c52ea0b1267582eb5717ef336461a ./RELEASE_METADATAdef7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 ./analysis_options.yaml-4cbda05ee121f7d7c40278a2cdad0322299f7258ddf94c8d7035b26b23d581ca ./build.sh+82fcb500a9387b3d98417a46a57993aa4faff0701472298eb31b222c20af10b7 ./build.sh4f18642680fb433554a5523d00bd99e0d650af340bcaebe628f59f63ac84e458 ./dartdoc_options.yaml-1e7cc6b15bfd5b785478ef86b7d1dd0ecaca40385b540797662403631630dc04 ./doc/README.md-397201d1696692d0ad05c2ecf621d0e7b1c3f82b13580fd6d4858b68973d3821 ./doc/authentication.md-b93d87d3e11b0d536fdc119a21b25be0943eb22457465ba31768262611209d38 ./doc/backend_authentication.md-4d40f0045230678833e3896c810a3de2c9f9a802b4ad3aab6d278c6a46d10ff0 ./doc/component_patterns.md-c3beb6981cbaac6fd49d93abbd0dc9fd9e2b3c002ba937e5f66bbe81cf6f94cf ./doc/diagrams.md-c0bd274c1c63db332856740288b1b919106473b70bec549ded5a817adaede71b ./doc/manage_api_key.md+02ff4330d0ccc9759f6f0d2e6b6528b1c07f82df5e57bb9476ce259e12013be6 ./doc/README.md+0194e6946f57f11aea29334d3d4e731b62d5bfe315aea1e0efda75a7216491f2 ./doc/auth_user_backend_mode.md+c97c31960aa90372be07118c106aeaf67902a6dface981475b8b36b2aae1ab82 ./doc/auth_user_mobile_mode.md+1eac94fbc13e6791e7a498ab2c9f944b8e5839742f44da784bcdf810fde95c17 ./doc/authentication.md+9417c3af3d24f6ed148ccc0826e96db452e60936a60adaaa354fc9b90cdd4b1f ./doc/component_patterns.md+10d41f07a754ebd27015c9d5c601a98a35aa6f86f4e0f5de79d858a4d8621719 ./doc/diagrams.md+c97c31960aa90372be07118c106aeaf67902a6dface981475b8b36b2aae1ab82 ./doc/manage_api_key.mda66d39da0983a994474fa516f81fd41bbb131efbd69c955891a41781a76daf24 ./doc/performance.md-440332e1f43fc7e1deb8456f237a380751f6b907b2cac96951b5bcbfe2e38a02 ./doc/release.md-2ab6724728c322950ac9eed3ac280a91f7f7dde2272b8037bf74cb3d31ef679f ./doc/sdk_contract.md-db828d1510fb5490a5c88202164a3f2fddd77cce703c2de1e9c774dc553ef7f6 ./doc/sdk_doc.md+61f1c77cfcabf4586065c4a1455e7ebf3a1f265faa0d285ca9260913f7fc341c ./doc/release.md+05a73303026e37fbc0db791318426bcbe50e38eb4778c786036057e57462aafd ./doc/sdk_contract.md+8617d04f8564d2b290a7ecb3bb1cc7c7152ad7544ac4a6a3c219e1af634d1312 ./doc/sdk_doc.md6210ee89bebfcbf66e2dbfb035238420de4e10e80a3380a689653b1e45b26608 ./doc/search_app.md3271e5e49451d705345e3921393766b8b5d8b11a9cffaac0f0ecc325f5514a72 ./doc/transcode_360.mde246ed229511a24a1ee7e98529c203ef90d1d352290ce8486caebe05683db3a0 ./env.sh@@ -264,6 +265,9 @@ fd367b6c43006d61b730f674970dd48b9f662c8f2264e52ffc1558102a2c9f2d ./example/05_f1a8d11d01d1cc92c650c9c9ed35299240052d4683a15a719a2315ef44185e074 ./example/05_framebase/ios/Runner/Runner-Bridging-Header.hadd68b905971dedfcc0d0b5b7118030de5925ba8c081ad9815463699e3a444ad ./example/05_framebase/ios/Runner/SceneDelegate.swift5e8f4908dacea6f29b2a790e4d38bf5fded69096063f9a27a2f21584d62b30c0 ./example/05_framebase/ios/RunnerTests/RunnerTests.swift+8cf88ac782a45054de45866e8404b27a88f2a557ee78da7d3dc90ad59bc896c4 ./example/05_framebase/lib/data/archive_controller.dart+618e7700c2bc415e1954df8fffb4f1ccc485d0b154182db147bb751292cc1bef ./example/05_framebase/lib/data/search_gateway.dart+84450bd9576729c1cc16a7f1e793b8001885969b4ff0bb00e372508f3da1fe6f ./example/05_framebase/lib/main.dart38915e998b313d617db841f46ae5bf293a06bc813791ec3adb7dfd245ec549c1 ./example/05_framebase/pubspec.lockd127d3f4cd96b63ab036c263e488f8af91a5140be12768b0e3cd0904193676d5 ./example/05_framebase/pubspec.yaml5ac0550b52416cec8dd4f01d0cf8622dc696a235502aedbb7a291a13594eac02 ./example/05_framebase/readme_assets/library.png@@ -363,13 +367,13 @@ a51475dbc546a45bb5cbc6d85bbd39a5e84a4ca1c8c27402f4d1d7ab8c4e8e29 ./example/05_fb3f31425c264023e88a1f9ce82efdf619bb1ed80c69bcd454b11125a29f97977 ./example/05_framebase_userlogin/test/user_session_controller_test.dart8a1cd1f781e0c217df5c6676557e87ff1ebdb480b6b73e5db64a407164d661b8 ./example/05_framebase_userlogin/test/user_session_failures_test.dart5e3939495af84efeb41a736e11e3d8a9e55954da304dc16d6f646b04baa0399f ./example/05_framebase_userlogin/test/widget_test.dart-bf7d982b4aa28e125b02dbe25a861e148252b189fe03cd98519ce1d4f38fbbd4 ./example/06_backend_auth/README.md-f1aa6fde6d2fca4295953b6482ee71a530316461c24686051d63869fa5ad2522 ./example/06_backend_auth/developer_backend/session.mjs-dae89a3f907d3c79039d626a26b05e31d4dbd2aaa9bac7a9ca4d9173c3c042fd ./example/06_backend_auth/developer_backend/session_test.mjs-8e32e04701b53547c04b2b18a109a72f7fa11b448422707bc7ac9e60fd2a92a7 ./example/06_backend_auth/lib/backend_auth_example.dart-dd01a6e18a7f295b3eb5ad350366dae2ab76c9fa5fb03a79b872973b3c76eea9 ./example/06_backend_auth/pubspec.lock-1a40cfcce0bd4521ab96cefe6c5e12603989e739725fbe5ad00206942d799c7d ./example/06_backend_auth/pubspec.yaml-5e55c3d7c3a221ca7375ccdc05719a8f57b63efd051a55d375cf1861fd3efe6d ./example/06_backend_auth/test/backend_auth_example_test.dart+7195aac5574010765c87de656a766fde0b78a181f33dd9b512cd0761832e8fd1 ./example/06_userlogin_backend_auth/README.md+f1aa6fde6d2fca4295953b6482ee71a530316461c24686051d63869fa5ad2522 ./example/06_userlogin_backend_auth/developer_backend/session.mjs+dae89a3f907d3c79039d626a26b05e31d4dbd2aaa9bac7a9ca4d9173c3c042fd ./example/06_userlogin_backend_auth/developer_backend/session_test.mjs+8e32e04701b53547c04b2b18a109a72f7fa11b448422707bc7ac9e60fd2a92a7 ./example/06_userlogin_backend_auth/lib/backend_auth_example.dart+dd01a6e18a7f295b3eb5ad350366dae2ab76c9fa5fb03a79b872973b3c76eea9 ./example/06_userlogin_backend_auth/pubspec.lock+1a40cfcce0bd4521ab96cefe6c5e12603989e739725fbe5ad00206942d799c7d ./example/06_userlogin_backend_auth/pubspec.yaml+5e55c3d7c3a221ca7375ccdc05719a8f57b63efd051a55d375cf1861fd3efe6d ./example/06_userlogin_backend_auth/test/backend_auth_example_test.dartbb2e66ce21a066b5331a8c6ee665f1a4d2fcb3451cde5ce2ba0e6fe492344ac0 ./example/readme.md23756b83470b1f25f6a7e6b5a6270f123a5224e49fd8e2eda36001358951b688 ./install.sh7becacd31a8d134fa435b39cd819798d5fbf58f89b9f30c50362e2dcf757aaed ./lib/src/adaptive_upload.dart@@ -403,7 +407,7 @@ a80b38547f5d9ca1874f60e71c648e3fc12ab5f7cb88d1bead6d5b863d3c0245 ./readme_assetc56419d129059b64551e06f074e88ef62676f25938dc2a1fe28a6ab3f2ba8547 ./readme_assets/logo_vmodal_owl.jpeg87cfc21f3c3539fc539c68a534eb84760d3c297cd8989576acd55ecf035e6012 ./release_note.md3198051c448338c5331baef7e17ff32bfbaf1265b59543a8aca2baf57513feed ./run.sh-bb5948fd73afd0adfbc1fa34addb946ae688fc8e03f4c54a17c4b067f0679b3d ./security_check.sh+3bc43116838e66d0a9da33a173ebfa1b53eb41831e67e6e0b0597ab55736f4a3 ./security_check.sh75d9810c9d50fd1224462aba8d2d1669cbfa094bd9cc0e5275f3a6a9f1364cb5 ./test.shbe59599b9ba77d031e9b4bad7f8d5c59efd2687888c5b73be4fbea115902106b ./test/adaptive_upload_test.dart8d138ac9ba874307aa11cbd873eded2c913167475db550f79a697f696df1287c ./test/auth_http_test.dart@@ -419,12 +423,12 @@ d132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.d593b356ac3431de80e03e7a0e2f1df0d29589140f44746468213c1cac1c35bbe ./test/multipart_upload_test.dart1247019fcd0549fab4bb48fa9aeee438ea288cc1e73561c46ca7dd6598170d14 ./test/new_api_surface_test.dart97593b7d76911b80a27a7f2ea2bcf283986e881d2bbb1347478ef5241c6a67f9 ./test/readme_pin_test.dart-4642fb897dd0b8892e20fa1f2a85d3d6b64ccb207679cde1e8a87c287af10eea ./test/regression_manifest_test.dart+2e8dbf5de6790afb66b83b854e5b70076d3bdfc75eb9d0cf6767bcb6419e1902 ./test/regression_manifest_test.dart5f049dd64b419a6afa46b548cdaba8d1101dd66501cede4425f02ed956b9a669 ./test/resources_models_test.dart701017ce3056f071f324d8fc94ccf2b6a147a3f0abd540eda634fac450fe53e3 ./test/session_guard_test.dart113ee0888fb78edf96476ee9d2c15fba2eecedfa6ff8529a9b86d0feb44a1563 ./test/session_lifecycle_test.dart9b0eb2ce870652644e7b0e73781a1c15ccbdb60b9cb7e25bc08e9004332f587d ./test/session_storage_test.dart-6b4798bb2f7d31eac0a08141344661624141c6273efa869f509d6f0b28589456 ./test/shell_scripts_test.dart+50bf5c6cea89f619e9de842b2bd98f7c7487aeb092450b71f5d9e0e36d99dd3a ./test/shell_scripts_test.dartfd3d42374ae441045c4947152dc312020c331fbe07f197030e834e1aa7d06eb5 ./test/tenant_credentials_test.dartefe4f1158e7d4b9ca8e57f3538ce296279817292a4356c1399cf5f2cbae4c52d ./test/transcode_upload_test.dartb94c0fef25560e387c4de5de0e4032fce73aa22b23a4bf38594ea6ff241d914c ./test/transport_test.dart@@ -432,7 +436,7 @@ c4aa3c091992668ee531412a7fc783106769df7d75147eb06271492027b0c100 ./test/upload_0bf2e2c2f1476140b3bc18f978e31a5563c1d713f2b7897cab769323bcfa9155 ./test/user_provenance_test.darta379f7dc013b39e8de00fd487d979c998069c13a461a2e621ac25d18facbc5d6 ./test/user_session_acceptance_test.dart3e211aca3928fed8f0dce62a97bd08fc873c2313493d986304dfcead25c0690b ./test/user_session_test.dart-312c69e2854675a23f1849cb1d9e3f25afbcc5874795666f2bcc52bf9cb852cf ./test/workflow_layout_test.dart+5f24235f67945fa6d97c022fc13e3dd1a37c7f54089cac950c8360b6a1cd629d ./test/workflow_layout_test.dart406de1350b79662fcaf007cb0cacd7a6b71b83815dc7cd3c7b561fcfba5600a3 ./tool/check_route_sync.dartd5f5f9246656a5c275c5ab5863dbf3945d8ef6b1c9042c9d1912cfafce93646f ./tool/flutter_checksums.txt24ea8e3013e0ed3531ff2aa3c86ad5332bf315d3d26f6a0814d2d6c84c5dade2 ./tool/live_cctv_test.dartdiff --git a/build.sh b/build.shindex db77287..fc40e6e 100755--- a/build.sh+++ b/build.sh@@ -44,7 +44,7 @@ sdk_pub_get() {(cd example/03_cctv && sdk_flutter pub get)(cd example/04_example && sdk_flutter pub get)(cd example/05_framebase_userlogin && sdk_flutter pub get)- (cd example/06_backend_auth && sdk_flutter pub get)+ (cd example/06_userlogin_backend_auth && sdk_flutter pub get)}sdk_format() {@@ -52,7 +52,7 @@ sdk_format() {## Usage:bash build.sh format'- sdk_dart format --output=none --set-exit-if-changed lib test tool example/01_full_app/lib example/01_full_app/test example/02_users/lib example/02_users/test example/03_cctv/bin example/03_cctv/lib example/03_cctv/test example/04_example/lib example/04_example/test example/04_example/integration_test example/05_framebase_userlogin/lib example/05_framebase_userlogin/test example/06_backend_auth/lib example/06_backend_auth/test+ sdk_dart format --output=none --set-exit-if-changed lib test tool example/01_full_app/lib example/01_full_app/test example/02_users/lib example/02_users/test example/03_cctv/bin example/03_cctv/lib example/03_cctv/test example/04_example/lib example/04_example/test example/04_example/integration_test example/05_framebase_userlogin/lib example/05_framebase_userlogin/test example/06_userlogin_backend_auth/lib example/06_userlogin_backend_auth/test}sdk_analyze() {@@ -66,7 +66,7 @@ sdk_analyze() {(cd example/03_cctv && sdk_flutter analyze)(cd example/04_example && sdk_flutter analyze)(cd example/05_framebase_userlogin && sdk_flutter analyze)- (cd example/06_backend_auth && sdk_flutter analyze)+ (cd example/06_userlogin_backend_auth && sdk_flutter analyze)}sdk_test() {@@ -80,7 +80,7 @@ sdk_test() {(cd example/03_cctv && sdk_flutter test)(cd example/04_example && sdk_flutter test)(cd example/05_framebase_userlogin && sdk_flutter test)- (cd example/06_backend_auth && sdk_flutter test)+ (cd example/06_userlogin_backend_auth && sdk_flutter test)}sdk_example_android() {diff --git a/doc/README.md b/doc/README.mdindex 6ed3dce..181013a 100644--- a/doc/README.md+++ b/doc/README.md@@ -9,7 +9,7 @@ polling, recovery, storage, mobile lifecycle, and host acceptance tests.| Reading path | Guide || --- | --- || Direct keys, local user isolation, or server-enforced scoped tokens | [Choose authentication](authentication.md) |-| Backend endpoint, exact grants, renewal, errors and rollout | [Backend authentication](backend_authentication.md) |+| Backend endpoint, exact grants, renewal, errors and rollout | [Backend authentication](auth_user_backend_mode.md) || Ready-to-use production integration patterns | [Component patterns](component_patterns.md) || Concise tenant-scoped API orientation | [SDK guide](sdk_doc.md) || Exact sessions, permissions, provenance, storage, and response semantics | [SDK contract](sdk_contract.md) |@@ -19,7 +19,7 @@ polling, recovery, storage, mobile lifecycle, and host acceptance tests.| Streaming, concurrency, timeouts, and device measurement | [Performance](performance.md) || Tenant-scoped custom video reducer | [Transcode](transcode_360.md) || Complete session app and host adapter injection | [Framebase example](../example/05_framebase_userlogin/README.md) |-| Separate scoped callback and verified-identity backend reference | [Backend-auth reference](../example/06_backend_auth/README.md) |+| Separate scoped callback and verified-identity backend reference | [Backend-auth reference](../example/06_userlogin_backend_auth/README.md) || SDK maintainer publication and export | [Release](release.md) |Session recipes require the 1.3.0 APIs present in this source tree. Use the localdiff --git a/doc/backend_authentication.md b/doc/auth_user_backend_mode.mdsimilarity index 98%rename from doc/backend_authentication.mdrename to doc/auth_user_backend_mode.mdindex 718161d..9089226 100644--- a/doc/backend_authentication.md+++ b/doc/auth_user_backend_mode.md@@ -35,7 +35,7 @@ query or replicate the developer's user directory.## Implement your session endpointYour backend chooses its route and authentication mechanism. The independent-[Node handler reference](../example/06_backend_auth/developer_backend/session.mjs)+[Node handler reference](../example/06_userlogin_backend_auth/developer_backend/session.mjs)uses `POST /vmodal/session` with `{}` and mandatory injected identity/policyadapters. Mount the equivalent handler in your existing backend stack.@@ -249,7 +249,7 @@ throw const BackendAuthException(BackendAuthFailure.invalidResponse);Do not throw every response as a generic AuthException or expose backend bodies.The coordinator bounds transient retries and interprets authoritative identity/policy rejection separately. The-[reference adapter](../example/06_backend_auth/lib/backend_auth_example.dart)+[reference adapter](../example/06_userlogin_backend_auth/lib/backend_auth_example.dart)maps HTTP status to these classifications.### Enabled read routesdiff --git a/doc/auth_user_mobile_mode.md b/doc/auth_user_mobile_mode.mdnew file mode 100644index 0000000..a25bd96--- /dev/null+++ b/doc/auth_user_mobile_mode.md@@ -0,0 +1,171 @@+# Manage runtime credentials and app-user sessions++Choose the credential pattern first in [authentication.md](authentication.md).+This guide's tenant coordinator applies to direct API-key authentication.+For server-enforced user grants, use `VModal.connectWithBackend` and the scoped+coordinator described in [auth_user_backend_mode.md](auth_user_backend_mode.md).+Do not share a scoped credential source across users or attach it to the+tenant-wide rotation flow.++Retrieve credentials through the host's authenticated, trusted service and+keep them in memory. Direct VModal API keys identify the tenant principal; Firebase,+Clerk, or another host identity system supplies the stable app-user ID. A and B+may share one tenant key and `auth.me()` response. That response never selects+their local owner namespace or proves their content permissions. Scoped auth/me+instead adds the verified app subject/project/policy/grants and is checked+against the envelope before the backend connection becomes ready.++## Backend connection lifecycle++```dart+final backend = await VModal.connectWithBackend(+ expectedAppUserId: signedInUser.id,+ expectedProjectId: 'framebase',+ loadToken: () async => ScopedTokenEnvelope.fromJson(+ await developerApi.createVmodalSession(),+ ),+);+final library = backend.scope('my_library');+await backend.refresh(); // coalesced renewal, no mutation replay+await backend.close(); // local VModal cleanup; host owns sign-out+```++The callback verifies current host login through the developer backend on every+acquisition and returns only a short-lived VModal-signed token. Parse/identity+errors differ from temporary availability failures; see the backend guide and+the [reference adapter](../example/06_userlogin_backend_auth/lib/backend_auth_example.dart).++Shared HTTP gateway paths check readiness before taking Bearer snapshots.+Proactive renewal leeway is capped at half the lifetime. Expiry uses+`expires_at`, and renewal is coalesced. A valid token may continue during a+temporary outage; expired or rejected revisions block dispatch. Same-policy+renewal preserves session and owner; changed policy/binding requires reconnect.++Observe token-free `ready`, `refreshing`, `unavailable`, `expired`, `invalidated`+and `closed` events at the account owner. Call `close()` at the start of an+account transition and discard retired scopes/UI. Backend owner identity+includes project/service/tenant/user and excludes bearer, expiry and `jti`.++The tenant-specific sections below retain their contract. The tenant option+`retainOnRenewalFailure` is not a backend-mode fallback to broader credentials.++## Session-bound configuration++```dart+final config = SdkConfig(); // gateway mode+final namespace = SessionContext.serviceNamespaceFor(config);+final credentials = TenantCredentialSource(+ serviceNamespace: namespace,+ tenantId: tenantId,+ expectedPrincipal: tenantPrincipal,+ initialKey: runtimeTenantKey,+ renew: () async => TenantCredential(+ serviceNamespace: namespace,+ tenantId: tenantId,+ principal: tenantPrincipal,+ apiKey: await trustedIssuer.currentTenantKey(),+ ),+);+final manager = UserSessionManager(+ config: config,+ credentialSource: credentials,+);+```++The host's issuer/resolver must authenticate and validate the credential's+service/tenant/principal binding. These fields are compared locally; self-reported+labels on an arbitrary key are not proof. `session.verifyPrincipal(...)` can+add an `auth.me()` tenant-principal check. It does not identify the app user or+validate that user's mapping. Prefer authoritative integer `issuerVersion`+values when the issuer supports them; when absent, the trusted resolver must+return its currently valid key. `auth.me()` cannot order opaque keys by age.++## Coordinate tenant rotation++`credentials.renewCredential()` shares one normal renewal Future across active+matching providers. `install(TenantCredential(...))` installs a trusted external+replacement. `renewCredential(supersede: true)` deliberately fences earlier+renewal tickets. Accepted revision and request ticket checks reject late results;+authoritative issuer versions reject rollback. Commit is atomic within the+isolate, updates only live matching providers, and new sessions attach/read the+latest revision without an asynchronous gap. Closing A unsubscribes its provider+without canceling shared renewal needed by B.++```dart+credentials.install(TenantCredential(+ serviceNamespace: namespace,+ tenantId: tenantId,+ principal: tenantPrincipal,+ apiKey: replacementTenantKey,+));+```++A credential-only replacement preserves `sessionId`, stable owner/scope keys,+app user, mapping, policy, and multipart checkpoint namespace. Tenant, endpoint,+or principal changes are rejected in place: build a correctly bound source and+fresh sessions. Grant/mapping changes also require invalidation and fresh policy+resolution, even when the key or app-user ID stays equal.++By default renewal failure blocks tenant calls, retains no fallback authority,+and returns a classified `TenantAuthException`. It does not log out the host+app user or change the active owner. `retainOnRenewalFailure: true` is available+only when the host's authoritative validity policy permits using the prior key.+`revoke()` is an authoritative current-credential revocation and blocks gateway+calls; a stale request's `401` cannot revoke a newer accepted revision. Recover+the tenant connection through the trusted source rather than falling back to a+broader credential. `credentials.close()` retires the shared coordinator;+closing one user session leaves the coordinator available to another.++## Request snapshots and recovery++The HTTP layer captures a binding/revision and header snapshot at request+construction. Ordinary retries retain that snapshot. Rotation does not rewrite+an existing request. New requests read the latest committed credential. Existing+calls can finish with the prior key while the service still accepts it; every+attempt and delivery remains guarded by its original app-user lease.++An eligible active GET/HEAD read can recover from `401` at most once per logical+request by consulting the coordinator and reconstructing fresh headers. It+shares a bounded attempt budget with ordinary retries. A second denial returns+a tenant-auth error while preserving app-user identity. `403` is never a general+refresh trigger. Uploads, index submissions, deletions, and other mutations are+never automatically replayed through auth recovery; ambiguous completion remains+unknown and requires deliberate reconciliation. Multipart continuation uses only+its existing explicit status/part/resume protocol and validated owner checkpoints.++Signed URLs have independent validity and expiry. Rotating or revoking the+tenant key does not promise to revoke an already issued storage/media capability.+Never attach a replacement bearer to a signed storage request. The session guard+still blocks later local signed-upload dispatch and media delivery after logout.++## Account changes and the host boundary++Call `manager.logout()` or `manager.openResolvedSession(...)` at the start of+an identity transition. Invalidation happens before asynchronous resolution or+cleanup. Clear old displayed images, playback, navigation/restoration, and+histories; check the current view generation before applying asynchronous host+state updates. Persisted owner data may remain for a later verified activation,+but old runtime handles never become valid again. Local cache reuse requires+current policy validation.++The compatible tenant-scoped API still accepts `MutableApiKeyProvider`:++```dart+final provider = MutableApiKeyProvider(runtimeTenantKey);+final project = VModal.configure(+ projectId: 'food_app',+ apiKeyProvider: provider,+);+provider.rotate(replacementTenantKey); // later requests only+provider.close(); // permanently disables reads and rotation+await project.close();+```++`VmodalClient`/`VModalProject` bypass user-session isolation; the host must own+their complete cancellation, cache/checkpoint partitioning, and account-switch+contract. Never use `projectId` or tenant identity as proof of app-user identity.+Never commit keys, put them in assets, log them, persist them in jobs/archives,+or treat compile-time `--dart-define` values as production credential storage.++See [the SDK contract](sdk_contract.md) for result provenance, restricted media,+local storage fencing, and the shared-key modified-client limitation.diff --git a/doc/authentication.md b/doc/authentication.mdindex 593da93..e28fe21 100644--- a/doc/authentication.md+++ b/doc/authentication.md@@ -1,9 +1,10 @@# Choose authentication-The SDK supports two ways to obtain the Bearer credential used by the public-VModal gateway. Your app owns login, signup, guest identity, user permissions and+Choose one of the three integration modes below. They use two credential types:+a direct VModal API key or a VModal-issued scoped token. Your app owns end-user+login, signup, guest identity, user permissions andthe identity provider. The SDK owns VModal request credentials and connection-cleanup. Both patterns send search and media requests directly to VModal.+cleanup. All three modes send search and media requests directly to VModal.| Pattern | Credential supplied to Flutter | Server authority | Best fit || --- | --- | --- | --- |@@ -19,10 +20,20 @@ app-user boundary.This guide describes source APIs. A successful local test is not evidence thatyour public VModal deployment supports delegated access. Configure the origin,edge, registrations and upstream enforcement and complete the-[rollout checks](backend_authentication.md#deployment-and-acceptance) before+[rollout checks](auth_user_backend_mode.md#deployment-and-acceptance) beforeenabling the scoped pattern in a production app.-## Direct runtime credential+---++## 1. Direct runtime credential++**Example:** [`uinterface/sdk_flutter/example/05_framebase`](../example/05_framebase/README.md).++**End-user authentication:** This example has no separate app-user sign-in.+The user enters a VModal API key at runtime. VModal authenticates the principal+that owns that key; the key's existing authority governs cloud access.++**SDK entry point:** `MutableApiKeyProvider` and `VModal.configure`.Preserve your existing integration:@@ -51,9 +62,25 @@ keys.close();uses `projectId__collectionName`; these names organize data and do not verifyapp identity or narrow the API key's server authority.-For account-specific ownership under a shared runtime key, use-`TenantCredentialSource` and `UserSessionManager` as shown in-[manage_api_key.md](manage_api_key.md). The host resolves the verified subject+---++## 2. Direct credential with app-user sessions++**Example:** [`uinterface/sdk_flutter/example/05_framebase_userlogin`](../example/05_framebase_userlogin/README.md).++**End-user authentication:** The host app signs in the person using its own+identity provider. A trusted host issuer verifies that identity and returns a+direct VModal tenant credential together with the user's allowed library policy.+Different app users can share the same VModal key and principal.++**SDK entry point:** `TenantCredentialSource` and `UserSessionManager`, as shown+in [manage_api_key.md](manage_api_key.md).++**Access boundary:** SDK sessions isolate local account data, operations and+callbacks. Cloud access still uses the direct key's authority; the local user+policy does not turn that key into a server-enforced app-user credential.++The host resolves the verified subjectand allowed content mapping, and invalidates the outgoing session at the startof a switch. `auth.me()` and `session.verifyPrincipal(...)` check the VModalstorage principal; they do not identify the host app user in this pattern.@@ -63,7 +90,23 @@ demonstrates this host orchestration and shared-key local isolation. Its mockissuer and `api_token`/`firebase_uid` envelope are a separate contract from aVModal-issued scoped token.-## Developer-backend scoped connection+---++## 3. User backend authentication (scoped connection)++**Example:** [`uinterface/sdk_flutter/example/06_userlogin_backend_auth`](../example/06_userlogin_backend_auth/README.md).++**End-user authentication:** The host app signs in the person, then calls its+authenticated developer backend. That backend verifies the current identity,+resolves exact permissions, and obtains a short-lived scoped token from VModal.+Flutter receives the scoped envelope; the registered server key stays on the backend.++**SDK entry point:** `VModal.connectWithBackend`.++**Access boundary:** VModal and the upstream handlers enforce the token's+app-user grants on the server once the scoped deployment is configured.+See [auth_user_backend_mode.md](auth_user_backend_mode.md) for the backend+handoff, token contract, renewal and deployment checks.Sign your user in using the host app's existing identity stack, then connect:@@ -108,7 +151,7 @@ after the deployment enables and enforces that action. The initial scopedread implementation denies unsupported writes and index operations. Yourdirect tenant integration retains its existing upload/index APIs.-## Login patterns+### Host login options for user backend authentication| Host login pattern | Callback responsibility || --- | --- |@@ -122,7 +165,7 @@ Host identity tokens are not VModal credentials. Send them only to yourdeveloper backend. VModal signs its own scoped token after authenticating yourregistered backend credential; the developer does not sign VModal tokens.-## Lifetime and account changes+### Scoped connection lifetime and account changesKeep the connection at the host account lifetime and inject its `UserScope`into feature controllers. Pages dispose their own subscriptions, players and@@ -144,16 +187,18 @@ owner references, but never a bearer or envelope. Reauthorize before restoringowner data. Logout does not instantly revoke a copied token or an alreadyissued standalone signed media URL; those capabilities have separate validity.+---+## Terminology and next guides-Both authentication patterns normally use `SdkConfig.mode == 'gateway'` and+All three integration modes normally use `SdkConfig.mode == 'gateway'` and`Authorization: Bearer <credential>`. The SDK's internal-development`mode: 'direct'` / `unsafeDirect` is a different connection mode that can sendtrusted identity fields. It is not the direct authentication pattern describedhere. Mobile callers never supply `X-User-Id`, `X-Tenant-Id` or grant headers.-- [Backend setup, contracts and lifecycle](backend_authentication.md)+- [Backend setup, contracts and lifecycle](auth_user_backend_mode.md)- [Tenant key rotation and local user sessions](manage_api_key.md)- [Controller and widget integration](component_patterns.md)- [Exact ownership and resource contract](sdk_contract.md)-- [Independent backend-auth reference](../example/06_backend_auth/README.md)+- [Independent backend-auth reference](../example/06_userlogin_backend_auth/README.md)diff --git a/doc/component_patterns.md b/doc/component_patterns.mdindex 35d43e8..af1ff4f 100644--- a/doc/component_patterns.md+++ b/doc/component_patterns.md@@ -55,7 +55,7 @@ Inject `library` into the same session-bound search controller. BackendConnectioowns the manager/source lifecycle and confirms delegated binding/grants throughauth/me before return. The callback uses current host identity, maps failuresto `BackendAuthException`, and returns no master key. The separate-[backend-auth reference](../example/06_backend_auth/README.md) demonstrates+[backend-auth reference](../example/06_userlogin_backend_auth/README.md) demonstratesgeneration fencing and mandatory verified backend adapters, preserving Framebase.Scope actions determine usable recipes. Initial scoped reads support discovery,diff --git a/doc/diagrams.md b/doc/diagrams.mdindex 1922f6c..4ee9bf6 100644--- a/doc/diagrams.md+++ b/doc/diagrams.md@@ -11,7 +11,7 @@ The numbered tenant-session sequences below remain the direct-key pattern.Backend-scoped mode adds a separate credential source while reusing guardedsession operations. Both use the same public gateway. See[authentication.md](authentication.md) and-[backend_authentication.md](backend_authentication.md).+[auth_user_backend_mode.md](auth_user_backend_mode.md).```mermaidflowchart LRdiff --git a/doc/manage_api_key.md b/doc/manage_api_key.mdindex 744e1f3..a25bd96 100644--- a/doc/manage_api_key.md+++ b/doc/manage_api_key.md@@ -3,7 +3,7 @@Choose the credential pattern first in [authentication.md](authentication.md).This guide's tenant coordinator applies to direct API-key authentication.For server-enforced user grants, use `VModal.connectWithBackend` and the scoped-coordinator described in [backend_authentication.md](backend_authentication.md).+coordinator described in [auth_user_backend_mode.md](auth_user_backend_mode.md).Do not share a scoped credential source across users or attach it to thetenant-wide rotation flow.@@ -33,7 +33,7 @@ await backend.close(); // local VModal cleanup; host owns sign-outThe callback verifies current host login through the developer backend on everyacquisition and returns only a short-lived VModal-signed token. Parse/identityerrors differ from temporary availability failures; see the backend guide and-the [reference adapter](../example/06_backend_auth/lib/backend_auth_example.dart).+the [reference adapter](../example/06_userlogin_backend_auth/lib/backend_auth_example.dart).Shared HTTP gateway paths check readiness before taking Bearer snapshots.Proactive renewal leeway is capped at half the lifetime. Expiry usesdiff --git a/doc/release.md b/doc/release.mdindex 8459912..f71ffd7 100644--- a/doc/release.md+++ b/doc/release.md@@ -3,9 +3,9 @@## Scoped authentication rollout gateThe source includes `connectWithBackend` and a separate-[backend-auth reference](../example/06_backend_auth/README.md). Neither local+[backend-auth reference](../example/06_userlogin_backend_auth/README.md). Neither localfixtures nor source export establish live support. Before releasing this mode,-complete the [backend acceptance sequence](backend_authentication.md#deployment-and-acceptance):+complete the [backend acceptance sequence](auth_user_backend_mode.md#deployment-and-acceptance):registered project/key/resource authority, bounded registry distribution,origin RS256 issuance/validation, independent Worker VModal policy, and upstreamdefault-deny canonical grant enforcement. Test the real public edge chain with@@ -22,7 +22,7 @@ format, analysis and tests. Node is optional for Flutter consumers. Run thereference backend's separate offline gate explicitly with Node 22+:```bash-node --test example/06_backend_auth/developer_backend/session_test.mjs+node --test example/06_userlogin_backend_auth/developer_backend/session_test.mjs```The Dart SDK suite covers strict envelopes, auth/me agreement, expiry, renewal,@@ -51,8 +51,12 @@ public commits, tags, and documentation metadata record that value fortraceability. Workflow steps only orchestrate named functions from amonorepo-owned release helper; that private CI helper is not part of thestandalone 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+input, repository targets, and URLs remain explicit in the workflow. Credential+steps source `.github/workflows/utils.sh` and use the GitHub Actions secret+`INFISICAL_TOKEN` to load scoped Infisical keys. `GH_TOKEN` supplies public+repository and documentation publication; `TEST_CLIENT_CLERK_USER_API_TOKEN`+supplies `VMODAL_API_KEY` for live tests. The helper masks values and writes+them to `GITHUB_ENV` for subsequent steps in each job. A secret-detection job scans the Flutter SDK tree and sourcepublication waits for secret detection, offline tests, Android and iOS builds,the live test, and the tested package artifact. Protected release approvalremains disabled during this development mode. Optional pub.dev publication isdiff --git a/doc/sdk_contract.md b/doc/sdk_contract.mdindex 304e05d..ed01e5d 100644--- a/doc/sdk_contract.md+++ b/doc/sdk_contract.md@@ -75,7 +75,7 @@ Project enters backend ownership before archive/checkpoint keys are derived;direct key encoding stays compatible. Bearer, `jti` and expiry are excluded.See [authentication.md](authentication.md) for pattern choice and-[backend_authentication.md](backend_authentication.md) for envelopes,+[auth_user_backend_mode.md](auth_user_backend_mode.md) for envelopes,server-authorized actions, errors and rollout requirements.## App-user session contractdiff --git a/doc/sdk_doc.md b/doc/sdk_doc.mdindex 92c0a5c..04af403 100644--- a/doc/sdk_doc.md+++ b/doc/sdk_doc.md@@ -2,7 +2,7 @@Begin with [Choose authentication](authentication.md). Direct runtime keys keepthe setup below; backend-scoped credentials use `VModal.connectWithBackend`-and its typed callback. [Backend authentication](backend_authentication.md)+and its typed callback. [Backend authentication](auth_user_backend_mode.md)describes strict envelopes, server grants, renewal and account transitions.For account-based apps, start with [Component patterns](component_patterns.md):diff --git a/example/05_framebase/lib/data/archive_controller.dart b/example/05_framebase/lib/data/archive_controller.dartnew file mode 100644index 0000000..45ad6dc--- /dev/null+++ b/example/05_framebase/lib/data/archive_controller.dart@@ -0,0 +1,508 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:path_provider/path_provider.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'search_gateway.dart';++class ArchiveClip {+ ArchiveClip({+ required this.id,+ required this.title,+ required this.location,+ required this.duration,+ required this.asset,+ required this.poster,+ this.path,+ this.uploaded = false,+ this.bundled = true,+ });+ final String id, title, location, asset, poster;+ final double duration;+ String? path;+ bool uploaded;+ final bool bundled;+ String get filename => '$id.mp4';+ Map<String, Object?> toJson() => {+ 'id': id,+ 'title': title,+ 'location': location,+ 'duration': duration,+ 'asset': asset,+ 'poster': poster,+ 'path': path,+ 'uploaded': uploaded,+ 'bundled': bundled,+ };+ factory ArchiveClip.fromJson(Map<String, dynamic> r) => ArchiveClip(+ id: r['id'] as String,+ title: r['title'] as String,+ location: r['location'] as String,+ duration: (r['duration'] as num).toDouble(),+ asset: r['asset'] as String,+ poster: r['poster'] as String,+ path: r['path'] as String?,+ uploaded: r['uploaded'] == true,+ bundled: r['bundled'] == true,+ );+}++List<ArchiveClip> streetClips() => [+ ArchiveClip(+ id: 'neighborhood_crossing',+ title: 'Neighborhood crossing',+ location: 'San Francisco · Daylight',+ duration: 55.2,+ asset: 'assets/videos/neighborhood_crossing.mp4',+ poster: 'assets/stills/neighborhood_crossing.jpg',+ ),+ ArchiveClip(+ id: 'downtown_traffic',+ title: 'Downtown traffic',+ location: 'Singapore · Afternoon',+ duration: 15.8,+ asset: 'assets/videos/downtown_traffic.mp4',+ poster: 'assets/stills/downtown_traffic.jpg',+ ),+ ArchiveClip(+ id: 'evening_junction',+ title: 'Evening junction',+ location: 'Mexico City · Dusk',+ duration: 75,+ asset: 'assets/videos/evening_junction.mp4',+ poster: 'assets/stills/evening_junction.jpg',+ ),+];++class ArchiveEvent {+ ArchiveEvent(this.title, this.detail, {this.error = false, DateTime? time})+ : time = time ?? DateTime.now();+ final String title, detail;+ final bool error;+ final DateTime time;+ Map<String, Object?> toJson() => {+ 'title': title,+ 'detail': detail,+ 'error': error,+ 'time': time.toIso8601String(),+ };+}++class ArchiveController extends ChangeNotifier {+ ArchiveController({this.persist = true});+ final bool persist;+ List<ArchiveClip> clips = streetClips();+ final List<ArchiveEvent> events = [];+ bool initialized = false, connecting = false, busy = false, searching = false;+ String phase = '', notice = '', activeQuery = '', pendingJob = '';+ double? progress;+ SearchBatch? batch;+ int? indexVersion;+ SearchGateway? _gateway;+ Directory? _directory;+ UploadTask<VideoUploadResponse>? _upload;+ CancellationToken? _work, _queryToken;+ int _searchGeneration = 0;+ bool _disposed = false;+ String _accountId = '';+ Future<void> _saveQueue = Future<void>.value();+ bool get connected => _gateway != null;+ bool get ready => connected && indexVersion != null;+ bool get hasPendingUploads => clips.any((c) => !c.uploaded);++ void emit() {+ if (!_disposed) notifyListeners();+ }++ Future<void> initialize() async {+ if (persist) {+ try {+ _directory = await getApplicationSupportDirectory();+ final state = File('${_directory!.path}/archive.json');+ if (await state.exists()) {+ final data =+ jsonDecode(await state.readAsString()) as Map<String, dynamic>;+ final saved = (data['clips'] as List)+ .map(+ (r) =>+ ArchiveClip.fromJson(Map<String, dynamic>.from(r as Map)),+ )+ .toList();+ clips = saved+ .where(+ (c) =>+ c.bundled || (c.path != null && File(c.path!).existsSync()),+ )+ .toList();+ if (clips.isEmpty) clips = streetClips();+ pendingJob = data['pendingJob'] as String? ?? '';+ _accountId = data['accountId'] as String? ?? '';+ for (final raw in (data['events'] as List? ?? [])) {+ final r = Map<String, dynamic>.from(raw as Map);+ events.add(+ ArchiveEvent(+ r['title'] as String,+ r['detail'] as String,+ error: r['error'] == true,+ time: DateTime.parse(r['time'] as String),+ ),+ );+ }+ }+ } on Object {+ notice =+ 'Local archive could not be restored. Built-in clips are available.';+ }+ }+ initialized = true;+ emit();+ }++ Future<void> save() {+ if (!persist || _directory == null) 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,+ 'accountId': _accountId,+ 'events': events.take(40).map((e) => e.toJson()).toList(),+ });+ final path = '${_directory!.path}/archive.json';+ _saveQueue = _saveQueue.then((_) async {+ try {+ await File(path).writeAsString(snapshot, flush: true);+ } on Object {+ /* Optional history must not cancel network work. */+ }+ });+ return _saveQueue;+ }++ void record(String title, String detail, {bool error = false}) {+ events.insert(0, ArchiveEvent(title, detail, error: error));+ if (events.length > 40) events.removeLast();+ unawaited(save());+ emit();+ }++ Future<bool> connect(String key) async {+ if (busy || connecting) return false;+ connecting = true;+ notice = '';+ emit();+ SearchGateway? next;+ try {+ next = SearchGateway(key.trim());+ await next.connect();+ if (_disposed) {+ await next.close();+ return false;+ }+ invalidateSearch();+ if (_accountId.isNotEmpty && _accountId != next.accountId) {+ for (final clip in clips) {+ clip.uploaded = false;+ }+ pendingJob = '';+ events.clear();+ }+ _accountId = next.accountId;+ final previous = _gateway;+ _gateway = next;+ indexVersion = next.version;+ if (previous != null) await previous.close();+ record(+ 'Connected',+ indexVersion == null+ ? 'Authenticated. No street index yet.'+ : 'Authenticated · street index v$indexVersion available',+ );+ return true;+ } on Object catch (e) {+ await next?.close();+ notice = safeError(e);+ record('Connection failed', notice, error: true);+ return false;+ } finally {+ connecting = false;+ emit();+ }+ }++ Future<void> disconnect() async {+ if (busy || connecting) return;+ invalidateSearch();+ final old = _gateway;+ _gateway = null;+ indexVersion = null;+ await old?.close();+ notice = 'Disconnected. Recordings remain on this device.';+ emit();+ }++ Future<File> localFile(ArchiveClip clip) async {+ if (clip.path != null && await File(clip.path!).exists()) {+ return File(clip.path!);+ }+ if (!clip.bundled) {+ throw const FileSystemException('Recording no longer available');+ }+ _directory ??= await getApplicationSupportDirectory();+ final file = File('${_directory!.path}/${clip.filename}');+ if (!await file.exists()) {+ final data = await rootBundle.load(clip.asset);+ await file.writeAsBytes(+ data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),+ flush: true,+ );+ }+ clip.path = file.path;+ return file;+ }++ Future<void> importFile(String path, double duration) async {+ _directory ??= await getApplicationSupportDirectory();+ final id = 'street_${DateTime.now().millisecondsSinceEpoch}';+ final file = await File(path).copy('${_directory!.path}/$id.mp4');+ final sourceName = basename(path);+ clips.add(+ ArchiveClip(+ id: id,+ title: sourceName,+ location: 'Imported recording',+ duration: duration,+ asset: '',+ poster: '',+ path: file.path,+ bundled: false,+ ),+ );+ invalidateSearch();+ await save();+ record('Recording added', '$sourceName · stored on device only');+ }++ ArchiveClip? clipFor(String filename) {+ final clean = basename(filename).toLowerCase();+ for (final clip in clips) {+ if (clean == clip.id.toLowerCase() ||+ clean == clip.filename.toLowerCase() ||+ clean.startsWith('${clip.id.toLowerCase()}.')) {+ return clip;+ }+ }+ return null;+ }++ Future<void> uploadAndIndex() async {+ final gateway = _gateway;+ if (gateway == null || busy) return;+ busy = true;+ notice = '';+ invalidateSearch();+ final token = CancellationToken();+ _work = token;+ emit();+ try {+ for (final clip in clips.where((c) => !c.uploaded)) {+ token.throwIfCanceled();+ phase = 'Uploading ${clip.title}';+ progress = 0;+ emit();+ final file = await localFile(clip);+ token.throwIfCanceled();+ final task = gateway.upload(file);+ _upload = task;+ final watch = Stopwatch()..start();+ final subscription = task.progress.listen((p) {+ progress = p.totalBytes > 0 ? p.uploadedBytes / p.totalBytes : null;+ emit();+ });+ try {+ final result = await task.result;+ if (!result.uploaded) throw const TransportException();+ clip.uploaded = true;+ record(+ 'Uploaded',+ '${clip.title} · ${(file.lengthSync() / 1048576).toStringAsFixed(1)} MB · ${(watch.elapsedMilliseconds / 1000).toStringAsFixed(1)} s',+ );+ await save();+ } finally {+ await subscription.cancel();+ _upload = null;+ }+ }+ token.throwIfCanceled();+ phase = 'Creating visual index';+ progress = null;+ emit();+ final job = await gateway.createIndex(token);+ pendingJob = job.jobId;+ await save();+ if (pendingJob.isEmpty) {+ throw const MalformedResponse('No index job identifier');+ }+ record('Index queued', 'Visual index · ${clips.length} recordings');+ await _pollIndex(gateway, token);+ } on OperationCanceled {+ notice = pendingJob.isEmpty+ ? 'Upload canceled. Completed uploads are kept.'+ : 'Stopped waiting. Indexing continues on the server; use Resume.';+ record('Operation stopped', notice);+ } on Object catch (e) {+ notice = safeError(e);+ record('Processing failed', notice, error: true);+ } finally {+ busy = false;+ phase = '';+ progress = null;+ _work = null;+ emit();+ }+ }++ Future<void> resumeIndex() async {+ final gateway = _gateway;+ if (gateway == null || busy || pendingJob.isEmpty) return;+ busy = true;+ notice = '';+ final token = CancellationToken();+ _work = token;+ emit();+ try {+ await _pollIndex(gateway, token);+ } on OperationCanceled {+ notice = 'Stopped waiting. The server job continues.';+ } on Object catch (e) {+ notice = safeError(e);+ record('Index check failed', notice, error: true);+ } finally {+ busy = false;+ phase = '';+ _work = null;+ emit();+ }+ }++ Future<void> _pollIndex(+ SearchGateway gateway,+ CancellationToken token,+ ) async {+ final watch = Stopwatch()..start();+ for (var attempt = 0; attempt < 120; attempt++) {+ token.throwIfCanceled();+ final state = await gateway.indexStatus(pendingJob, token);+ if (indexDone(state.status)) {+ await gateway.refreshVersion();+ indexVersion = gateway.version;+ pendingJob = '';+ await save();+ notice = 'Visual index is ready. Search the street archive.';+ record(+ 'Index ready',+ 'v$indexVersion · ${(watch.elapsedMilliseconds / 1000).toStringAsFixed(1)} s waiting time',+ );+ return;+ }+ if (indexFailed(state.status)) {+ pendingJob = '';+ await save();+ throw const TransportException('Server index job failed');+ }+ phase = 'Index ${state.status} · ${watch.elapsed.inSeconds}s';+ progress = null;+ emit();+ await Future.any([+ Future<void>.delayed(const Duration(seconds: 4)),+ token.whenCanceled,+ ]);+ }+ notice = 'Still processing. Use Resume to check the server job again.';+ }++ void stopWork() {+ _work?.cancel();+ _upload?.cancel();+ }++ void invalidateSearch() {+ _searchGeneration++;+ _queryToken?.cancel();+ searching = false;+ batch = null;+ emit();+ }++ Future<void> search(String query, {double maxDistance = 1.5}) async {+ final gateway = _gateway;+ if (gateway == null ||+ indexVersion == null ||+ query.trim().isEmpty ||+ busy) {+ return;+ }+ invalidateSearch();+ final generation = _searchGeneration;+ final token = CancellationToken();+ _queryToken = token;+ searching = true;+ activeQuery = query.trim();+ notice = '';+ emit();+ try {+ final result = await gateway.search(+ activeQuery,+ cancellation: token,+ maxDistance: maxDistance,+ );+ if (_disposed || generation != _searchGeneration) return;+ batch = result;+ record(+ 'Search complete',+ '“$activeQuery” · ${result.matches.length} returned · ${result.roundTripMs} ms request · ${result.serverMs.toStringAsFixed(0)} ms server',+ );+ } on OperationCanceled {+ /* A newer query owns the screen. */+ } on Object catch (e) {+ if (generation == _searchGeneration) {+ notice = safeError(e);+ record('Search failed', notice, error: true);+ }+ } finally {+ if (generation == _searchGeneration) {+ searching = false;+ emit();+ }+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _queryToken?.cancel();+ stopWork();+ if (_gateway != null) unawaited(_gateway!.close());+ super.dispose();+ }+}++String safeError(Object error) {+ if (error is AuthException) {+ return 'Authentication failed. Check your API key and beta access.';+ }+ if (error is SdkException) return error.toString();+ if (error is FileSystemException) {+ return 'The local video could not be read. Import it again.';+ }+ return 'The operation could not finish. Check the connection and try again.';+}++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/lib/data/search_gateway.dart b/example/05_framebase/lib/data/search_gateway.dartnew file mode 100644index 0000000..a04fd8b--- /dev/null+++ b/example/05_framebase/lib/data/search_gateway.dart@@ -0,0 +1,321 @@+import 'dart:io';+import 'dart:convert';+import 'dart:typed_data';++import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++const archiveCollection = 'framebase_streets';+const archiveStream = 'street_study';++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 '';+}++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;+ final String? imageUrl;+ final Uint8List? imageBytes;+ final double? seconds;+ double? get distance => num.tryParse('${row['score']}')?.toDouble();+}++class SearchBatch {+ const SearchBatch({+ required this.matches,+ required this.total,+ required this.serverMs,+ required this.roundTripMs,+ required this.imageMs,+ });+ final List<FrameMatch> matches;+ final int total;+ final double serverMs;+ final int roundTripMs;+ final int imageMs;+}++/// One session, one application-owned collection. No credentials or signed URLs+/// are persisted. The low-level SDK is used consistently for collection selectors.+class SearchGateway {+ SearchGateway(String key, {VmodalTransport? transport})+ : keys = MutableApiKeyProvider(key) {+ client = VmodalClient(+ config: SdkConfig(+ apiKeyProvider: keys,+ timeout: const Duration(seconds: 60),+ ),+ transport: transport,+ );+ }++ final MutableApiKeyProvider keys;+ late final VmodalClient client;+ String accountId = '';+ int? version;++ Future<void> connect() async {+ final profile = await client.auth.me();+ if (profile.userId?.isNotEmpty != true) {+ throw const AuthException('No authenticated identity');+ }+ accountId = profile.userId!;+ await refreshVersion();+ }++ Future<void> refreshVersion() async {+ final groups = await client.collections.listGroups(mode: 'vid_file');+ version = groups+ .findGroup(archiveCollection, mode: 'vid_file')+ ?.latestLancedbVersion;+ }++ UploadTask<VideoUploadResponse> upload(File file) =>+ client.collections.videoUpload(+ UploadSource.fromFile(file),+ collectionName: archiveCollection,+ subCollectionName: archiveStream,+ );++ Future<IndexationSubmitResponse> createIndex(+ CancellationToken cancellation,+ ) => client.indexes.createIndex(+ IndexationSubmitRequest(+ mode: 'vid_file',+ groupName: archiveCollection,+ streamName: archiveStream,+ indexType: 'vid_img_emb',+ modality: 'vid_img_emb',+ reProcess: true,+ ),+ cancellation: cancellation,+ );++ Future<IndexationStatusResponse> indexStatus(+ String job,+ CancellationToken cancellation,+ ) => client.indexes.indexStatus(job, cancellation: cancellation);++ Future<SearchBatch> search(+ String query, {+ CancellationToken? cancellation,+ String? imageQuery,+ double maxDistance = 1.5,+ }) async {+ final token = cancellation ?? CancellationToken();+ final timer = Stopwatch()..start();+ final response = await client.searches.searchVideo(+ SearchRequest(+ queryText: query,+ imageQuery: imageQuery,+ mode: 'vid_file',+ groupName: archiveCollection,+ streamName: archiveStream,+ searchSources: const ['image'],+ limit: 30,+ imageEmbScoreMin: maxDistance,+ versionLancedb: version,+ ),+ cancellation: token,+ );+ 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;+ }).toList();+ final urls = <int, String>{};+ final imageBytes = <int, Uint8List>{};+ if (usable.isNotEmpty) {+ final resolved = await client.images.getUrlBulk(+ usable+ .map(+ (row) => <String, Object?>{+ 'mode': 'vid_file',+ 'group_name': archiveCollection,+ 'modality': 'vid_img',+ 'stream_name':+ firstText(row, const ['stream_name', 'stream']).isEmpty+ ? archiveStream+ : firstText(row, const ['stream_name', 'stream']),+ 'filename': hitFilename(row),+ if (timestamp13(row).isNotEmpty)+ 'ts_unix_13digits': timestamp13(row),+ },+ )+ .toList(),+ cancellation: token,+ );+ for (var i = 0; i < resolved.records.length; i++) {+ final row = resolved.records[i];+ final rawIndex = row['input_index'];+ final parsed = num.tryParse('$rawIndex');+ final index = 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 &&+ row['found'] != false &&+ valid) {+ 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 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]!;+ }+ }+ }+ }+ token.throwIfCanceled();+ return SearchBatch(+ matches: [+ for (var i = 0; i < usable.length; i++)+ FrameMatch(+ row: usable[i],+ filename: hitFilename(usable[i]),+ timestamp: timestamp13(usable[i]),+ imageUrl: urls[i]?.startsWith('https://') == true ? urls[i] : null,+ imageBytes: imageBytes[i],+ seconds: hitSeconds(usable[i]),+ ),+ ],+ total: response.cntTotal,+ serverMs: response.executionTimeMs,+ roundTripMs: searchMs,+ imageMs: timer.elapsedMilliseconds - searchMs,+ );+ }++ Future<void> close() async {+ keys.close();+ await client.close();+ }+}++bool indexDone(String state) => const {+ 'success',+ 'succeeded',+ 'done',+ 'completed',+ 'ok',+}.contains(state.toLowerCase());+bool indexFailed(String state) => const {+ 'failed',+ 'failure',+ 'error',+ 'cancelled',+ 'canceled',+}.contains(state.toLowerCase());diff --git a/example/05_framebase/lib/main.dart b/example/05_framebase/lib/main.dartnew file mode 100644index 0000000..9dd93a5--- /dev/null+++ b/example/05_framebase/lib/main.dart@@ -0,0 +1,1445 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui';+import 'package:file_selector/file_selector.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:video_player/video_player.dart';+import 'data/archive_controller.dart';+import 'data/search_gateway.dart';++const paper = Color(0xFFECE9E2);+const ink = Color(0xFF252C29);+const green = Color(0xFFAA4F2D);+const secondary = Color(0xFF706F67);++void main() {+ WidgetsFlutterBinding.ensureInitialized();+ SystemChrome.setSystemUIOverlayStyle(+ const SystemUiOverlayStyle(+ statusBarColor: Colors.transparent,+ statusBarIconBrightness: Brightness.dark,+ systemNavigationBarColor: paper,+ systemNavigationBarIconBrightness: Brightness.dark,+ ),+ );+ runApp(const FramebaseApp());+}++class FramebaseApp extends StatelessWidget {+ const FramebaseApp({super.key, this.controller});+ final ArchiveController? controller;+ @override+ Widget build(BuildContext context) => MaterialApp(+ title: 'Framebase',+ debugShowCheckedModeBanner: false,+ theme: ThemeData(+ useMaterial3: true,+ fontFamily: 'Instrument Sans',+ colorScheme: ColorScheme.fromSeed(+ seedColor: green,+ surface: paper,+ brightness: Brightness.light,+ ),+ scaffoldBackgroundColor: paper,+ appBarTheme: const AppBarTheme(+ systemOverlayStyle: SystemUiOverlayStyle.dark,+ backgroundColor: Colors.transparent,+ foregroundColor: ink,+ elevation: 0,+ scrolledUnderElevation: 0,+ centerTitle: false,+ titleTextStyle: TextStyle(+ color: ink,+ fontSize: 22,+ fontWeight: FontWeight.w700,+ letterSpacing: -.6,+ ),+ ),+ textTheme: const TextTheme(+ bodyMedium: TextStyle(color: ink),+ bodySmall: TextStyle(color: secondary),+ ),+ dividerTheme: const DividerThemeData(+ color: Color(0xFFDDDFD6),+ thickness: .5,+ ),+ searchBarTheme: SearchBarThemeData(+ elevation: const WidgetStatePropertyAll(0),+ backgroundColor: const WidgetStatePropertyAll(Color(0xFFDFDCD4)),+ hintStyle: const WidgetStatePropertyAll(+ TextStyle(color: secondary, fontSize: 16),+ ),+ shape: WidgetStatePropertyAll(+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),+ ),+ ),+ bottomSheetTheme: const BottomSheetThemeData(+ backgroundColor: paper,+ showDragHandle: true,+ modalBarrierColor: Color(0x66000000),+ ),+ ),+ home: LibraryPage(controller: controller),+ );+}++String city(ArchiveClip clip) => clip.location.split(' · ').first;++/// Only the toolbar and overlays blur underlying content. The library itself is flat.+class Frosted extends StatelessWidget {+ const Frosted({+ super.key,+ required this.child,+ this.dark = false,+ this.radius = 0,+ });+ final Widget child;+ final bool dark;+ final double radius;+ @override+ Widget build(BuildContext context) => ClipRRect(+ borderRadius: BorderRadius.circular(radius),+ child: BackdropFilter(+ filter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),+ child: ColoredBox(+ color: dark ? const Color(0xA6252C29) : const Color(0xDDECE9E2),+ child: child,+ ),+ ),+ );+}++class LibraryPage extends StatefulWidget {+ const LibraryPage({super.key, this.controller});+ final ArchiveController? controller;+ @override+ State<LibraryPage> createState() => _LibraryPageState();+}++class _LibraryPageState extends State<LibraryPage> {+ late final ArchiveController archive;+ @override+ void initState() {+ super.initState();+ archive = widget.controller ?? ArchiveController();+ unawaited(start());+ }++ Future<void> start() async {+ if (!archive.initialized) await archive.initialize();+ }++ @override+ void dispose() {+ if (widget.controller == null) archive.dispose();+ super.dispose();+ }++ void openSearch() => Navigator.push(+ context,+ MaterialPageRoute<void>(builder: (_) => SearchPage(archive: archive)),+ );++ Future<void> importVideo() async {+ if (archive.busy) return;+ VideoPlayerController? player;+ try {+ final file = await openFile(+ acceptedTypeGroups: [+ const XTypeGroup(+ label: 'MP4 video',+ extensions: ['mp4'],+ mimeTypes: ['video/mp4'],+ uniformTypeIdentifiers: ['public.mpeg-4'],+ ),+ ],+ );+ if (file == null) return;+ if (await file.length() > 100 * 1024 * 1024) {+ throw const FormatException();+ }+ player = VideoPlayerController.file(File(file.path));+ await player.initialize().timeout(const Duration(seconds: 15));+ await archive.importFile(+ file.path,+ player.value.duration.inMilliseconds / 1000,+ );+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(+ const SnackBar(+ content: Text(+ 'Video added. Prepare it for search when you’re ready.',+ ),+ ),+ );+ }+ } on Object {+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(+ const SnackBar(+ content: Text('Choose a playable MP4 smaller than 100 MB.'),+ ),+ );+ }+ } finally {+ await player?.dispose();+ }+ }++ @override+ Widget build(BuildContext context) => AnimatedBuilder(+ animation: archive,+ builder: (context, _) => Scaffold(+ extendBodyBehindAppBar: true,+ appBar: AppBar(+ title: const Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ BrandMark(),+ SizedBox(width: 10),+ Flexible(+ child: Text(+ 'Framebase',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ],+ ),+ flexibleSpace: const Frosted(child: SizedBox.expand()),+ actions: [+ IconButton(+ key: const Key('import'),+ tooltip: 'Add video',+ onPressed: archive.busy ? null : importVideo,+ icon: const Icon(Icons.add),+ ),+ PopupMenuButton<String>(+ key: const Key('library_menu'),+ tooltip: 'More options',+ onSelected: (value) {+ if (value == 'connection') showConnection(context, archive);+ if (value == 'history') {+ Navigator.push(+ context,+ MaterialPageRoute<void>(+ builder: (_) => HistoryPage(archive: archive),+ ),+ );+ }+ if (value == 'prepare') prepareArchive(context, archive);+ },+ itemBuilder: (_) => const [+ PopupMenuItem(+ value: 'connection',+ child: Text('Search settings'),+ ),+ PopupMenuItem(+ value: 'prepare',+ child: Text('Prepare videos for search'),+ ),+ PopupMenuItem(value: 'history', child: Text('Sync history')),+ ],+ ),+ ],+ ),+ body: ListView(+ padding: EdgeInsets.fromLTRB(+ 16,+ MediaQuery.paddingOf(context).top + kToolbarHeight + 16,+ 16,+ 96,+ ),+ children: [+ Row(+ children: [+ const Expanded(+ child: Text(+ 'Street footage',+ style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),+ ),+ ),+ Text(+ '${archive.clips.length} videos',+ style: const TextStyle(color: secondary),+ ),+ ],+ ),+ const SizedBox(height: 12),+ for (final clip in archive.clips)+ VideoRow(+ clip: clip,+ onTap: () => showRecording(context, archive, clip),+ ),+ if (archive.busy) ...[+ const SizedBox(height: 12),+ WorkStatus(archive: archive),+ ],+ if (archive.connected && !archive.ready && !archive.busy) ...[+ const SizedBox(height: 20),+ TextButton.icon(+ key: const Key('process'),+ onPressed: () => prepareArchive(context, archive),+ icon: const Icon(Icons.cloud_upload_outlined),+ label: const Text('Prepare videos for search'),+ ),+ ],+ if (archive.connected &&+ archive.ready &&+ archive.clips.any((c) => !c.bundled && !c.uploaded) &&+ !archive.busy)+ TextButton.icon(+ onPressed: () => prepareArchive(context, archive),+ icon: const Icon(Icons.cloud_upload_outlined),+ label: const Text('Prepare added videos'),+ ),+ if (archive.events.isNotEmpty && archive.events.first.error)+ Padding(+ padding: const EdgeInsets.only(top: 16),+ child: Text(+ archive.notice,+ style: TextStyle(color: Theme.of(context).colorScheme.error),+ ),+ ),+ ],+ ),+ extendBody: true,+ bottomNavigationBar: SafeArea(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),+ child: SearchDock(onTap: openSearch),+ ),+ ),+ ),+ );+}++class BrandMark extends StatelessWidget {+ const BrandMark({super.key});+ @override+ Widget build(BuildContext context) => SizedBox(+ width: 23,+ height: 23,+ child: CustomPaint(painter: _BrandPainter()),+ );+}++class _BrandPainter extends CustomPainter {+ @override+ void paint(Canvas canvas, Size size) {+ final paint = Paint()+ ..color = green+ ..strokeWidth = 2.8+ ..style = PaintingStyle.stroke;+ canvas.drawPath(+ Path()+ ..moveTo(2, 9)+ ..lineTo(2, 2)+ ..lineTo(9, 2)+ ..moveTo(14, 2)+ ..lineTo(21, 2)+ ..lineTo(21, 9)+ ..moveTo(21, 14)+ ..lineTo(21, 21)+ ..lineTo(14, 21)+ ..moveTo(9, 21)+ ..lineTo(2, 21)+ ..lineTo(2, 14),+ paint,+ );+ canvas.drawLine(const Offset(9, 8), const Offset(15, 12), paint);+ canvas.drawLine(const Offset(15, 12), const Offset(9, 16), paint);+ }++ @override+ bool shouldRepaint(covariant CustomPainter oldDelegate) => false;+}++class SearchDock extends StatelessWidget {+ const SearchDock({super.key, required this.onTap});+ final VoidCallback onTap;+ @override+ Widget build(BuildContext context) => DecoratedBox(+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(22),+ boxShadow: const [+ BoxShadow(+ color: Color(0x30212A24),+ blurRadius: 22,+ offset: Offset(0, 7),+ ),+ ],+ ),+ child: Frosted(+ dark: true,+ radius: 22,+ child: DecoratedBox(+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(22),+ border: Border.all(+ color: Colors.white.withValues(alpha: .28),+ width: .8,+ ),+ ),+ child: Material(+ color: Colors.transparent,+ child: InkWell(+ key: const Key('open_search'),+ onTap: onTap,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(20, 10, 10, 10),+ child: Row(+ children: [+ const Icon(Icons.search, color: Colors.white, size: 23),+ const SizedBox(width: 12),+ const Expanded(+ child: Text(+ 'Search your videos',+ style: TextStyle(+ fontSize: 16,+ fontWeight: FontWeight.w500,+ color: Colors.white,+ ),+ ),+ ),+ Container(+ width: 42,+ height: 42,+ decoration: BoxDecoration(+ color: const Color(0xFFE6A17F),+ borderRadius: BorderRadius.circular(13),+ ),+ child: const Icon(+ Icons.arrow_forward,+ color: ink,+ size: 21,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+}++class VideoRow extends StatelessWidget {+ const VideoRow({super.key, required this.clip, required this.onTap});+ final ArchiveClip clip;+ final VoidCallback onTap;+ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(bottom: 14),+ child: Semantics(+ button: true,+ label: 'Play ${clip.title}',+ child: ClipRRect(+ borderRadius: BorderRadius.circular(18),+ child: AspectRatio(+ aspectRatio: 1.8,+ child: Stack(+ fit: StackFit.expand,+ children: [+ ClipPoster(clip),+ const DecoratedBox(+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.topCenter,+ end: Alignment.bottomCenter,+ stops: [.4, 1],+ colors: [Colors.transparent, Color(0xD919201C)],+ ),+ ),+ ),+ Positioned(+ top: 12,+ right: 12,+ child: TimeBadge(seconds: clip.duration),+ ),+ Positioned(+ left: 16,+ bottom: 16,+ right: 70,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ clip.title,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(+ fontSize: 20,+ fontWeight: FontWeight.w600,+ letterSpacing: -.4,+ height: 1.12,+ color: Colors.white,+ ),+ ),+ const SizedBox(height: 5),+ Text(+ city(clip),+ style: const TextStyle(+ fontSize: 12,+ color: Color(0xFFDFE5DF),+ ),+ ),+ ],+ ),+ ),+ Positioned(+ right: 12,+ bottom: 12,+ child: Frosted(+ dark: true,+ radius: 13,+ child: Container(+ width: 44,+ height: 44,+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(13),+ border: Border.all(+ color: Colors.white.withValues(alpha: .3),+ width: .7,+ ),+ ),+ child: const Icon(+ Icons.play_arrow_rounded,+ color: Colors.white,+ size: 24,+ ),+ ),+ ),+ ),+ Positioned.fill(+ child: Material(+ color: Colors.transparent,+ child: InkWell(onTap: onTap),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+}++class ClipPoster extends StatelessWidget {+ const ClipPoster(this.clip, {super.key});+ final ArchiveClip clip;+ @override+ Widget build(BuildContext context) => clip.poster.isNotEmpty+ ? Image.asset(+ clip.poster,+ fit: BoxFit.cover,+ errorBuilder: (_, _, _) => const MissingFrame(),+ )+ : const MissingFrame(icon: Icons.movie_outlined);+}++class MissingFrame extends StatelessWidget {+ const MissingFrame({+ super.key,+ this.icon = Icons.image_not_supported_outlined,+ });+ final IconData icon;+ @override+ Widget build(BuildContext context) => ColoredBox(+ color: const Color(0xFFE0E3DA),+ child: Center(child: Icon(icon, color: secondary, size: 28)),+ );+}++class TimeBadge extends StatelessWidget {+ const TimeBadge({super.key, required this.seconds});+ final double seconds;+ @override+ Widget build(BuildContext context) => Frosted(+ dark: true,+ radius: 6,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4),+ child: Text(+ timeLabel(seconds),+ style: const TextStyle(+ color: Colors.white,+ fontSize: 12,+ fontWeight: FontWeight.w500,+ ),+ ),+ ),+ );+}++/// Keep relevance order, but collapse nearby frames of the same recording.+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 t = hit.seconds;+ if (moments.any(+ (m) => t != null && m.seconds != null && (t - m.seconds!).abs() < 6,+ )) {+ continue;+ }+ moments.add(hit);+ }+ return groups;+}++class SearchPage extends StatefulWidget {+ const SearchPage({super.key, required this.archive});+ final ArchiveController archive;+ @override+ State<SearchPage> createState() => _SearchPageState();+}++class _SearchPageState extends State<SearchPage> {+ final query = TextEditingController();+ bool broad = false;+ final expandedVideos = <String>{};+ ArchiveController get archive => widget.archive;+ @override+ void initState() {+ super.initState();+ query.text = archive.activeQuery;+ }++ @override+ void dispose() {+ query.dispose();+ super.dispose();+ }++ Future<void> search([String? text]) async {+ expandedVideos.clear();+ if (text != null) query.text = text;+ FocusManager.instance.primaryFocus?.unfocus();+ if (query.text.trim().isEmpty) return;+ if (archive.connecting) return;+ if (!archive.connected) {+ await showConnection(context, archive);+ if (!mounted || !archive.connected) return;+ }+ if (!archive.ready) {+ await prepareArchive(context, archive);+ return;+ }+ await archive.search(query.text, maxDistance: broad ? 1.5 : .85);+ }++ void options() => showModalBottomSheet<void>(+ context: context,+ builder: (_) => StatefulBuilder(+ builder: (ctx, update) => SafeArea(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ SwitchListTile(+ title: const Text('Include looser matches'),+ subtitle: const Text(+ 'Useful if the first search misses something.',+ ),+ value: broad,+ onChanged: (v) {+ setState(() => broad = v);+ update(() {});+ archive.invalidateSearch();+ },+ ),+ ListTile(+ leading: const Icon(Icons.info_outline),+ title: const Text('Search details'),+ onTap: () {+ Navigator.pop(ctx);+ showSearchDetails(context, archive);+ },+ ),+ const SizedBox(height: 12),+ ],+ ),+ ),+ ),+ );++ @override+ Widget build(BuildContext context) => AnimatedBuilder(+ animation: archive,+ builder: (context, _) {+ final batch = archive.batch;+ final groups = groupMoments(batch?.matches ?? []);+ return Scaffold(+ appBar: AppBar(+ automaticallyImplyLeading: false,+ toolbarHeight: 80,+ titleSpacing: 8,+ title: SearchBar(+ controller: query,+ hintText: 'Describe a moment',+ leading: IconButton(+ tooltip: 'Back to videos',+ icon: const Icon(Icons.arrow_back),+ onPressed: () => Navigator.pop(context),+ ),+ onChanged: (_) => archive.invalidateSearch(),+ onSubmitted: (_) => search(),+ trailing: [+ IconButton(+ key: const Key('run_search'),+ tooltip: archive.searching ? 'Cancel search' : 'Search',+ icon: Icon(archive.searching ? Icons.close : Icons.search),+ onPressed: archive.searching+ ? archive.invalidateSearch+ : () => search(),+ ),+ ],+ ),+ actions: [+ IconButton(+ key: const Key('search_options'),+ tooltip: 'Search options',+ onPressed: options,+ icon: const Icon(Icons.more_vert),+ ),+ ],+ ),+ body: Column(+ children: [+ if (archive.searching || archive.connecting)+ const LinearProgressIndicator(minHeight: 2),+ Expanded(+ child: ListView(+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 32),+ children: [+ if (archive.busy) WorkStatus(archive: archive),+ if (batch == null && !archive.searching) ...[+ const Padding(+ padding: EdgeInsets.symmetric(vertical: 12),+ child: Text(+ 'Try a search',+ style: TextStyle(+ fontSize: 16,+ fontWeight: FontWeight.w500,+ ),+ ),+ ),+ for (final example in [+ 'People crossing the street',+ 'A bus on a city street',+ 'Cars at an intersection',+ ])+ ListTile(+ contentPadding: EdgeInsets.zero,+ leading: const Icon(Icons.search, size: 20),+ title: Text(+ example,+ style: const TextStyle(fontSize: 15),+ ),+ trailing: const Icon(Icons.north_west, size: 18),+ onTap: () => search(example),+ ),+ ],+ if (batch != null && groups.isEmpty) ...[+ const SizedBox(height: 56),+ const Text(+ 'No matching moments',+ textAlign: TextAlign.center,+ style: TextStyle(+ fontSize: 20,+ fontWeight: FontWeight.w500,+ ),+ ),+ const SizedBox(height: 12),+ const Text(+ 'Try a different description.',+ textAlign: TextAlign.center,+ style: TextStyle(color: secondary),+ ),+ if (!broad)+ Center(+ child: TextButton(+ onPressed: () {+ setState(() => broad = true);+ search();+ },+ child: const Text('Include looser matches'),+ ),+ ),+ ],+ if (groups.isNotEmpty) ...[+ Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: Text(+ '${groups.length} ${groups.length == 1 ? 'video' : 'videos'}',+ style: const TextStyle(color: secondary),+ ),+ ),+ for (final entry in groups.entries) ...[+ Text(+ archive.clipFor(entry.key)?.title ?? entry.key,+ style: const TextStyle(+ fontSize: 18,+ fontWeight: FontWeight.w500,+ ),+ ),+ const SizedBox(height: 4),+ Text(+ archive.clipFor(entry.key) == null+ ? 'Not stored on this device'+ : city(archive.clipFor(entry.key)!),+ style: const TextStyle(color: secondary, fontSize: 13),+ ),+ const SizedBox(height: 12),+ LayoutBuilder(+ builder: (context, constraints) {+ final count = constraints.maxWidth >= 600 ? 3 : 2;+ return GridView.builder(+ shrinkWrap: true,+ physics: const NeverScrollableScrollPhysics(),+ gridDelegate:+ SliverGridDelegateWithFixedCrossAxisCount(+ crossAxisCount: count,+ mainAxisSpacing: 10,+ crossAxisSpacing: 10,+ childAspectRatio: 16 / 10,+ ),+ itemCount: expandedVideos.contains(entry.key)+ ? entry.value.length+ : entry.value.length.clamp(0, 2),+ itemBuilder: (_, i) => MomentTile(+ key: Key('moment_${entry.key}_$i'),+ hit: entry.value[i],+ onTap: () {+ final clip = archive.clipFor(entry.key);+ if (clip != null) {+ showRecording(+ context,+ archive,+ clip,+ match: entry.value[i],+ moments: entry.value,+ );+ } else {+ ScaffoldMessenger.of(context).showSnackBar(+ const SnackBar(+ content: Text(+ 'This video is not stored on this device.',+ ),+ ),+ );+ }+ },+ ),+ );+ },+ ),+ if (entry.value.length > 2)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ key: Key('expand_${entry.key}'),+ onPressed: () => setState(() {+ if (!expandedVideos.add(entry.key)) {+ expandedVideos.remove(entry.key);+ }+ }),+ child: Text(+ expandedVideos.contains(entry.key)+ ? 'Show fewer moments'+ : 'Show ${entry.value.length - 2} more moments',+ ),+ ),+ ),+ const SizedBox(height: 28),+ ],+ ],+ if (archive.notice.isNotEmpty &&+ archive.events.isNotEmpty &&+ archive.events.first.error)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 20),+ child: Text(+ archive.notice,+ style: TextStyle(+ color: Theme.of(context).colorScheme.error,+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ );+ },+ );+}++class MomentTile extends StatelessWidget {+ const MomentTile({super.key, required this.hit, required this.onTap});+ final FrameMatch hit;+ final VoidCallback onTap;+ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label:+ 'Play at ${hit.seconds == null ? 'unknown time' : timeLabel(hit.seconds!)}',+ child: ClipRRect(+ borderRadius: BorderRadius.circular(10),+ child: Stack(+ fit: StackFit.expand,+ children: [+ if (hit.imageBytes != null)+ Image.memory(+ hit.imageBytes!,+ fit: BoxFit.cover,+ errorBuilder: (_, _, _) => const MissingFrame(),+ )+ else if (hit.imageUrl != null)+ Image.network(+ hit.imageUrl!,+ fit: BoxFit.cover,+ errorBuilder: (_, _, _) => const MissingFrame(),+ )+ else+ const MissingFrame(),+ if (hit.seconds != null)+ Positioned(+ bottom: 7,+ right: 7,+ child: TimeBadge(seconds: hit.seconds!),+ ),+ Positioned.fill(+ child: Material(+ color: Colors.transparent,+ child: InkWell(onTap: onTap),+ ),+ ),+ ],+ ),+ ),+ );+}++Future<void> showRecording(+ BuildContext context,+ ArchiveController archive,+ ArchiveClip clip, {+ FrameMatch? match,+ List<FrameMatch> moments = const [],+}) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ builder: (_) => RecordingSheet(+ archive: archive,+ clip: clip,+ match: match,+ moments: moments,+ ),+);++class RecordingSheet extends StatefulWidget {+ const RecordingSheet({+ super.key,+ required this.archive,+ required this.clip,+ this.match,+ this.moments = const [],+ });+ final ArchiveController archive;+ final ArchiveClip clip;+ final FrameMatch? match;+ final List<FrameMatch> moments;+ @override+ State<RecordingSheet> createState() => _RecordingSheetState();+}++class _RecordingSheetState extends State<RecordingSheet> {+ VideoPlayerController? player;+ String? error;+ @override+ void initState() {+ super.initState();+ unawaited(load());+ }++ Future<void> load() async {+ VideoPlayerController? next;+ try {+ final file = await widget.archive.localFile(widget.clip);+ next = VideoPlayerController.file(file);+ await next.initialize().timeout(const Duration(seconds: 20));+ if (!mounted) {+ await next.dispose();+ return;+ }+ final seconds = widget.match?.seconds;+ if (seconds != null &&+ seconds <= next.value.duration.inMilliseconds / 1000) {+ await next.seekTo(Duration(milliseconds: (seconds * 1000).round()));+ }+ if (!mounted) {+ await next.dispose();+ return;+ }+ next.addListener(refresh);+ setState(() => player = next);+ } on Object {+ await next?.dispose();+ if (mounted) setState(() => error = 'This video could not be opened.');+ }+ }++ void refresh() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ player?.removeListener(refresh);+ unawaited(player?.dispose() ?? Future.value());+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final p = player;+ final length = p?.value.duration.inMilliseconds.toDouble() ?? 0;+ final position = (p?.value.position.inMilliseconds.toDouble() ?? 0).clamp(+ 0.0,+ length,+ );+ return SafeArea(+ child: SingleChildScrollView(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ widget.clip.title,+ style: const TextStyle(+ fontSize: 20,+ fontWeight: FontWeight.w500,+ ),+ ),+ const SizedBox(height: 4),+ Text(+ city(widget.clip),+ style: const TextStyle(color: secondary),+ ),+ ],+ ),+ ),+ IconButton(+ tooltip: 'Close recording',+ onPressed: () => Navigator.pop(context),+ icon: const Icon(Icons.close),+ ),+ ],+ ),+ const SizedBox(height: 20),+ ClipRRect(+ borderRadius: BorderRadius.circular(16),+ child: AspectRatio(+ aspectRatio: p?.value.aspectRatio ?? 16 / 9,+ child: Stack(+ fit: StackFit.expand,+ children: [+ if (p != null)+ VideoPlayer(p)+ else+ ClipPoster(widget.clip),+ if (p == null && error == null)+ const Center(child: CircularProgressIndicator()),+ if (p != null)+ Positioned(+ left: 8,+ right: 8,+ bottom: 8,+ child: PlaybackControls(player: p),+ ),+ ],+ ),+ ),+ ),+ if (error != null)+ Padding(padding: const EdgeInsets.all(16), child: Text(error!)),+ if (p != null) ...[+ if (widget.moments.length > 1) ...[+ const SizedBox(height: 16),+ const Text(+ 'Other moments',+ style: TextStyle(color: secondary),+ ),+ const SizedBox(height: 8),+ SizedBox(+ height: 86,+ child: ListView.separated(+ scrollDirection: Axis.horizontal,+ itemCount: widget.moments.length,+ separatorBuilder: (_, _) => const SizedBox(width: 8),+ itemBuilder: (_, i) {+ final hit = widget.moments[i];+ final active =+ hit.seconds != null &&+ (position / 1000 - hit.seconds!).abs() < 3;+ return Container(+ width: 118,+ padding: const EdgeInsets.all(2),+ decoration: BoxDecoration(+ borderRadius: BorderRadius.circular(13),+ border: Border.all(+ color: active ? green : Colors.transparent,+ width: 2,+ ),+ ),+ child: MomentTile(+ hit: hit,+ onTap: () {+ if (hit.seconds != null) {+ p.seekTo(+ Duration(+ milliseconds: (hit.seconds! * 1000).round(),+ ),+ );+ }+ },+ ),+ );+ },+ ),+ ),+ ],+ ],+ ],+ ),+ ),+ ),+ );+ }+}++class PlaybackControls extends StatelessWidget {+ const PlaybackControls({super.key, required this.player});+ final VideoPlayerController player;+ @override+ Widget build(BuildContext context) {+ final value = player.value;+ final length = value.duration.inMilliseconds.toDouble();+ final position = value.position.inMilliseconds.toDouble().clamp(+ 0.0,+ length,+ );+ return Frosted(+ dark: true,+ radius: 12,+ child: Padding(+ padding: const EdgeInsets.only(right: 10),+ child: Row(+ children: [+ IconButton(+ key: const Key('play_pause'),+ tooltip: value.isPlaying ? 'Pause' : 'Play',+ onPressed: () => value.isPlaying ? player.pause() : player.play(),+ icon: Icon(+ value.isPlaying+ ? Icons.pause_rounded+ : Icons.play_arrow_rounded,+ color: Colors.white,+ ),+ ),+ Expanded(+ child: SliderTheme(+ data: SliderTheme.of(context).copyWith(+ trackHeight: 2,+ activeTrackColor: const Color(0xFFF2B28F),+ inactiveTrackColor: Colors.white30,+ thumbColor: Colors.white,+ thumbShape: const RoundSliderThumbShape(+ enabledThumbRadius: 5,+ ),+ overlayShape: const RoundSliderOverlayShape(+ overlayRadius: 14,+ ),+ ),+ child: Slider(+ value: position,+ max: length > 0 ? length : 1,+ semanticFormatterCallback: (v) => timeLabel(v / 1000),+ onChanged: (v) =>+ player.seekTo(Duration(milliseconds: v.round())),+ ),+ ),+ ),+ Text(+ '${timeLabel(position / 1000)} / ${timeLabel(length / 1000)}',+ style: const TextStyle(+ fontSize: 11,+ color: Colors.white,+ fontFeatures: [FontFeature.tabularFigures()],+ ),+ ),+ ],+ ),+ ),+ );+ }+}++Future<void> showConnection(BuildContext context, ArchiveController archive) =>+ showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ builder: (_) => ConnectionSheet(archive: archive),+ );++class ConnectionSheet extends StatefulWidget {+ const ConnectionSheet({super.key, required this.archive});+ final ArchiveController archive;+ @override+ State<ConnectionSheet> createState() => _ConnectionSheetState();+}++class _ConnectionSheetState extends State<ConnectionSheet> {+ final input = TextEditingController();+ @override+ void dispose() {+ input.dispose();+ super.dispose();+ }++ Future<void> connect() async {+ final value = input.text.trim();+ if (value.isEmpty) return;+ input.clear();+ FocusManager.instance.primaryFocus?.unfocus();+ final ok = await widget.archive.connect(value);+ if (mounted && ok) Navigator.pop(context);+ }++ @override+ Widget build(BuildContext context) => AnimatedBuilder(+ animation: widget.archive,+ builder: (context, _) => SafeArea(+ child: SingleChildScrollView(+ padding: EdgeInsets.fromLTRB(+ 24,+ 0,+ 24,+ MediaQuery.viewInsetsOf(context).bottom + 24,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ const Text(+ 'Search settings',+ style: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),+ ),+ const SizedBox(height: 16),+ Text(+ widget.archive.connected+ ? 'Connected to the search service.'+ : 'Connect to search inside your videos.',+ ),+ const SizedBox(height: 20),+ TextField(+ key: const Key('api_key'),+ controller: input,+ obscureText: true,+ autocorrect: false,+ enableSuggestions: false,+ enableIMEPersonalizedLearning: false,+ onSubmitted: (_) => connect(),+ decoration: const InputDecoration(+ labelText: 'API key',+ border: OutlineInputBorder(),+ ),+ ),+ const SizedBox(height: 16),+ if (widget.archive.notice.isNotEmpty && !widget.archive.connected)+ Text(widget.archive.notice),+ const SizedBox(height: 8),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ if (widget.archive.connected)+ TextButton(+ onPressed: widget.archive.busy || widget.archive.connecting+ ? null+ : () async {+ await widget.archive.disconnect();+ if (context.mounted) Navigator.pop(context);+ },+ child: const Text('Disconnect'),+ ),+ const SizedBox(width: 8),+ FilledButton(+ key: const Key('connect_button'),+ onPressed: widget.archive.busy || widget.archive.connecting+ ? null+ : connect,+ child: Text(+ widget.archive.connecting ? 'Connecting…' : 'Connect',+ ),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ );+}++Future<void> prepareArchive(+ BuildContext context,+ ArchiveController archive,+) async {+ if (archive.busy) return;+ if (!archive.connected) {+ await showConnection(context, archive);+ if (!context.mounted || !archive.connected) return;+ }+ if (archive.pendingJob.isNotEmpty) {+ unawaited(archive.resumeIndex());+ return;+ }+ final count = archive.clips.where((c) => !c.uploaded).length;+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('Prepare videos for search?'),+ content: Text(+ count == 0+ ? 'Rebuild the visual index for these videos?'+ : '$count videos will be uploaded to the search service. This can take a minute.',+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: const Text('Prepare'),+ ),+ ],+ ),+ );+ if (confirmed == true) unawaited(archive.uploadAndIndex());+}++class WorkStatus extends StatelessWidget {+ const WorkStatus({super.key, required this.archive});+ final ArchiveController archive;+ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.symmetric(vertical: 12),+ child: Column(+ children: [+ LinearProgressIndicator(value: archive.progress, minHeight: 3),+ Row(+ children: [+ Expanded(+ child: Text(archive.phase, style: const TextStyle(fontSize: 13)),+ ),+ TextButton(+ onPressed: archive.stopWork,+ child: Text(+ archive.pendingJob.isEmpty ? 'Cancel' : 'Stop waiting',+ ),+ ),+ ],+ ),+ ],+ ),+ );+}++class HistoryPage extends StatelessWidget {+ const HistoryPage({super.key, required this.archive});+ final ArchiveController archive;+ @override+ Widget build(BuildContext context) => AnimatedBuilder(+ animation: archive,+ builder: (context, _) => Scaffold(+ appBar: AppBar(title: const Text('Sync history')),+ body: ListView(+ padding: const EdgeInsets.only(bottom: 24),+ children: [+ if (archive.busy)+ Padding(+ padding: const EdgeInsets.all(16),+ child: WorkStatus(archive: archive),+ ),+ if (archive.events.isEmpty)+ const Padding(+ padding: EdgeInsets.all(24),+ child: Text('No uploads or searches yet.'),+ ),+ for (final event in archive.events)+ ListTile(+ leading: Icon(+ event.error ? Icons.error_outline : Icons.check,+ size: 20,+ ),+ title: Text(event.title),+ subtitle: Text(event.detail),+ ),+ ],+ ),+ ),+ );+}++Future<void> showSearchDetails(+ BuildContext context,+ ArchiveController archive,+) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ builder: (_) {+ final batch = archive.batch;+ return SafeArea(+ child: SingleChildScrollView(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ const Text('Search details', style: TextStyle(fontSize: 22)),+ const SizedBox(height: 16),+ if (batch == null)+ const Text('Run a search first.')+ else ...[+ Text(+ 'Server results: ${batch.total}\nWithin distance filter: ${batch.matches.length}\n'+ 'Search request: ${batch.roundTripMs} ms\nServer execution: ${batch.serverMs.toStringAsFixed(0)} ms\n'+ 'Frame retrieval: ${batch.imageMs} ms',+ ),+ const SizedBox(height: 16),+ const Text(+ 'Nearby frames from the same video are combined in the results. Distance is similarity, not confidence.',+ ),+ ],+ ],+ ),+ ),+ );+ },+);diff --git a/example/06_backend_auth/README.md b/example/06_userlogin_backend_auth/README.mdsimilarity index 97%rename from example/06_backend_auth/README.mdrename to example/06_userlogin_backend_auth/README.mdindex 4e242b8..379dfbd 100644--- a/example/06_backend_auth/README.md+++ b/example/06_userlogin_backend_auth/README.md@@ -9,7 +9,7 @@ It is a host integration library, not another login UI or deployable identityprovider. Prerequisites are a verified host identity/session, an existing policystore, and a VModal deployment with registered scoped issuance and completeresource enforcement. Use [Choose authentication](../../docs/authentication.md)-and [Backend authentication](../../docs/backend_authentication.md) alongside it.+and [Backend authentication](../../docs/auth_user_backend_mode.md) alongside it.## 1. Authenticate and connect@@ -143,9 +143,9 @@ From the SDK root:```bash# The normal build gates include this reference's Dart pub_get/format/analyze/test.# The backend handler has an optional separate Node gate (no npm dependencies).-node --test example/06_backend_auth/developer_backend/session_test.mjs+node --test example/06_userlogin_backend_auth/developer_backend/session_test.mjsflutter_bin="$(bash install.sh flutter_bin)"-cd example/06_backend_auth+cd example/06_userlogin_backend_auth"$flutter_bin" pub get"$flutter_bin" analyze"$flutter_bin" testdiff --git a/example/06_backend_auth/developer_backend/session.mjs b/example/06_userlogin_backend_auth/developer_backend/session.mjssimilarity index 100%rename from example/06_backend_auth/developer_backend/session.mjsrename to example/06_userlogin_backend_auth/developer_backend/session.mjsdiff --git a/example/06_backend_auth/developer_backend/session_test.mjs b/example/06_userlogin_backend_auth/developer_backend/session_test.mjssimilarity index 100%rename from example/06_backend_auth/developer_backend/session_test.mjsrename to example/06_userlogin_backend_auth/developer_backend/session_test.mjsdiff --git a/example/06_backend_auth/lib/backend_auth_example.dart b/example/06_userlogin_backend_auth/lib/backend_auth_example.dartsimilarity index 100%rename from example/06_backend_auth/lib/backend_auth_example.dartrename to example/06_userlogin_backend_auth/lib/backend_auth_example.dartdiff --git a/example/06_backend_auth/pubspec.yaml b/example/06_userlogin_backend_auth/pubspec.yamlsimilarity index 100%rename from example/06_backend_auth/pubspec.yamlrename to example/06_userlogin_backend_auth/pubspec.yamldiff --git a/example/06_backend_auth/test/backend_auth_example_test.dart b/example/06_userlogin_backend_auth/test/backend_auth_example_test.dartsimilarity index 100%rename from example/06_backend_auth/test/backend_auth_example_test.dartrename to example/06_userlogin_backend_auth/test/backend_auth_example_test.dartdiff --git a/security_check.sh b/security_check.shindex 09517b3..cd484ac 100755--- a/security_check.sh+++ b/security_check.sh@@ -27,13 +27,16 @@ sdk_security_workflow() {grep -Eq 'environment:[[:space:]]+sdk-flutter-production' "$internal"grep -Eq 'persist-credentials:[[:space:]]+false' "$internal" "$public"grep -Fq 'ga_release.sh" ga_secret_detection' "$internal"- ! grep -Fq 'run: |' "$internal"+ grep -Fq 'infs_assign VMODAL_API_KEY TEST_CLIENT_CLERK_USER_API_TOKEN' "$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"- grep -Fq 'RELEASE_TOKEN: ${{ secrets.GH_TOKEN }}' "$internal"+ grep -Fq 'INFISICAL_TOKEN: ${{ secrets.INFISICAL_TOKEN }}' "$internal"+ grep -Fq 'infs_assign RELEASE_TOKEN GH_TOKEN' "$internal"+ grep -Fq 'token: ${{ env.GH_TOKEN }}' "$internal"+ ! grep -Fq '${{ secrets.GH_TOKEN }}' "$internal"! grep -Fq 'FLUTTER_SDK_APP_' "$internal"! grep -Eq 'git merge|git push[^\n]*--force|--skip-validation' "$internal" "$public"if grep -E 'uses:[[:space:]]+' "$internal" "$public" |diff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dartindex 5047215..74923bd 100644--- a/test/regression_manifest_test.dart+++ b/test/regression_manifest_test.dart@@ -222,13 +222,13 @@ void main() {'docs/README.md','docs/component_patterns.md','docs/authentication.md',- 'docs/backend_authentication.md',- 'example/06_backend_auth/README.md',- 'example/06_backend_auth/pubspec.yaml',- 'example/06_backend_auth/lib/backend_auth_example.dart',- 'example/06_backend_auth/test/backend_auth_example_test.dart',- 'example/06_backend_auth/developer_backend/session.mjs',- 'example/06_backend_auth/developer_backend/session_test.mjs',+ 'docs/auth_user_backend_mode.md',+ 'example/06_userlogin_backend_auth/README.md',+ 'example/06_userlogin_backend_auth/pubspec.yaml',+ 'example/06_userlogin_backend_auth/lib/backend_auth_example.dart',+ 'example/06_userlogin_backend_auth/test/backend_auth_example_test.dart',+ 'example/06_userlogin_backend_auth/developer_backend/session.mjs',+ 'example/06_userlogin_backend_auth/developer_backend/session_test.mjs',]) {expect(File('${dir.path}/$path').existsSync(), isTrue, reason: path);}@@ -239,13 +239,13 @@ void main() {'docs/README.md','docs/component_patterns.md','docs/authentication.md',- 'docs/backend_authentication.md',+ 'docs/auth_user_backend_mode.md','docs/manage_api_key.md','docs/sdk_contract.md','docs/diagrams.md','docs/release.md','README.md',- 'example/06_backend_auth/README.md',+ 'example/06_userlogin_backend_auth/README.md',]) {final content = File('${dir.path}/$guide').readAsStringSync();for (final match in RegExp(r'\]\(([^)]+)\)').allMatches(content)) {diff --git a/test/shell_scripts_test.dart b/test/shell_scripts_test.dartindex 7d557e5..e770af3 100644--- a/test/shell_scripts_test.dart+++ b/test/shell_scripts_test.dart@@ -78,12 +78,14 @@ void main() {final operation = command == 'pub_get' ? 'pub get' : command;expect(body,- contains('(cd example/06_backend_auth && sdk_flutter $operation)'),+ contains(+ '(cd example/06_userlogin_backend_auth && sdk_flutter $operation)',+ ),reason: 'Missing backend reference gate: $command',);}- expect(build, contains('example/06_backend_auth/lib'));- expect(build, contains('example/06_backend_auth/test'));+ expect(build, contains('example/06_userlogin_backend_auth/lib'));+ expect(build, contains('example/06_userlogin_backend_auth/test'));expect(build, isNot(contains('node --test')));});diff --git a/test/workflow_layout_test.dart b/test/workflow_layout_test.dartindex 1c542fe..55c951b 100644--- a/test/workflow_layout_test.dart+++ b/test/workflow_layout_test.dart@@ -52,23 +52,40 @@ void checkWorkflow(String main, String script, String tagged) {);expect(main, contains('GA_RELEASE_DIR: \${{ runner.temp }}'));expect(main, contains('VMODAL_ENV: prd'));+ expect(main, contains('INFISICAL_TOKEN: \${{ secrets.INFISICAL_TOKEN }}'));expect(main,- contains(- 'VMODAL_API_KEY: \${{ secrets.TEST_CLIENT_CLERK_USER_API_TOKEN }}',- ),+ contains('infs_assign VMODAL_API_KEY TEST_CLIENT_CLERK_USER_API_TOKEN'),+ );+ expect(main, contains('infs_assign RELEASE_TOKEN GH_TOKEN'));+ expect(main, contains('infs_assign GH_TOKEN GH_TOKEN'));+ expect(main, contains('token: \${{ env.GH_TOKEN }}'));+ expect(main, isNot(contains('\${{ secrets.GH_TOKEN }}')));+ expect(+ main,+ isNot(contains('\${{ secrets.TEST_CLIENT_CLERK_USER_API_TOKEN }}')),+ );+ expect(+ main,+ contains('source "\$GITHUB_WORKSPACE/vmx_api/.github/workflows/utils.sh"'),);- 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) {+ if (run.group(1) == '|') continue;expect(run.group(1), contains('ga_release.sh'));}+ final loads = RegExp(r'run: \|\n((?: {10}[^\n]*\n)+)').allMatches(main);+ expect(loads.length, 4);+ for (final load in loads) {+ expect(load.group(1), contains('.github/workflows/utils.sh'));+ expect(load.group(1), contains('infs_fetch_secret'));+ expect(load.group(1), contains('infs_assign'));+ expect(load.group(1), contains("trap 'unset INFISICAL_PAYLOAD' EXIT"));+ }expect(main,contains('secret_detection:\n $publishDocs\n runs-on: ubuntu-latest'),