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 e969dfe073e422ff65e618238a86398a51e94036
vmodal-release-appc40f00130313
diff --git a/README.md b/README.mdindex f61a378..c977229 100644--- a/README.md+++ b/README.md@@ -77,6 +77,12 @@ next command I should run.Get an API Key : [API Key](https://v-modal.com/page/contact.ts)+## Integrate into an existing app++Start with [the documentation index](docs/README.md) and+[ready-to-use app recipes](docs/component_patterns.md) for session ownership,+controller/widget wiring, upload/index/search, recovery, and mobile lifecycle.+## Start in minutes[SDK docs: v-modal.github.io/vmodal_sdk_flutter/](https://v-modal.github.io/vmodal_sdk_flutter/)@@ -221,8 +227,8 @@ bypass it. A modified client holding the shared tenant key can make arbitrarytenant-authorized requests; server protection requires separately verifiedapp-user authorization. The SDK cannot recall data returned while A was activeor stop work already accepted by the server. Read the-[session contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/sdk_contract.md)-and [tenant-key rotation guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/manage_api_key.md)+[session contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/sdk_contract.md)+and [tenant-key rotation guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/manage_api_key.md)before integration.## Search video with natural language@@ -346,7 +352,7 @@ Uploads use exact file ranges, awaited socket streaming, coalesced progress, andone network-concurrency budget per bulk task. For image caches, use`writeImageFromUrl` with a caller-owned sink or `saveImageFromUrl` for atomicfile replacement instead of buffering the image. See-[the performance guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/performance.md)+[the performance guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/performance.md)for limits, timeout behavior, and the benchmark command.## Designed for real mobile lifecycles@@ -462,10 +468,10 @@ Minimum toolchain: Flutter `3.44.0` and Dart `3.12.0`.- [Run the complete example app](https://github.com/v-modal/vmodal_sdk_flutter/tree/main/example/01_full_app)- [Organize global, per-user, multi-stream, and catalog indexes](https://github.com/v-modal/vmodal_sdk_flutter/tree/main/example/02_users)- [Upload timestamped CCTV footage and search an absolute time range](https://github.com/v-modal/vmodal_sdk_flutter/tree/main/example/03_cctv)-- [Read the SDK guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/sdk_doc.md)-- [Manage API keys safely](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/manage_api_key.md)-- [Build a search experience](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/search_app.md)-- [Review the API contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/sdk_contract.md)+- [Read the SDK guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/sdk_doc.md)+- [Manage API keys safely](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/manage_api_key.md)+- [Build a search experience](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/search_app.md)+- [Review the API contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/sdk_contract.md)- [Open an issue](https://github.com/v-modal/vmodal_sdk_flutter/issues)## Development@@ -498,18 +504,18 @@ The framework supports unified cross-platform logic, ensuring identical integrat* Image Recognition: Identify object patterns, text elements, and spatial relationships within static images.* Vector Indexing: Convert unstructured multimedia content into searchable mathematical representations.* Secure Authorization: Protect developer access tokens through integrated, secure API headers.-* Asynchronous Execution: Run complex indexing tasks in background threads to maintain app performance.+* Asynchronous Execution: Submit asynchronous server indexing jobs and monitor their status from the app.-Developers can quickly query their indexed catalog by passing strings or files to the search client. The SDK processes these inputs, communicates with V-Modal's specialized embedding models, and returns structured data objects. These response objects contain relevance confidence scores, metadata tags, and specific timestamps for video matches, allowing apps to jump directly to relevant frames.+Developers can quickly query their indexed catalog by passing strings or files to the search client. The SDK processes these inputs, communicates with V-Modal's specialized embedding models, and returns structured data objects. These response objects expose nullable lower-is-better distances, metadata tags, and playback offsets for video matches, allowing apps to jump directly to relevant frames.------------------------------## Evaluate Technical Architecture* Dart Native: Built natively on Dart to ensure seamless compatibility with Flutter 3.x engines.* Lightweight Footprint: Avoids heavy local binary files by offloading heavy ML math to cloud APIs.-* Reactive Model: Emits search states using streams, simplifying UI updates during long-running network requests.-* Error Resilience: Features built-in handling for network dropouts, rate limiting, and invalid API keys.+* Reactive Model: Returns search Futures and upload progress streams; app controllers publish UI state.+* Error Resilience: Retries eligible GET/HEAD failures within a bounded budget; apps handle rate limits and reconcile unknown mutation outcomes.------------------------------## Review Use Casesdiff --git a/RELEASE_METADATA b/RELEASE_METADATAindex 3e79474..c3dc451 100644--- a/RELEASE_METADATA+++ b/RELEASE_METADATA@@ -1 +1 @@-Source-vmx-api: c57d6e2a61491ae49eaba8345677fd0d08ef2dec+Source-vmx-api: e969dfe073e422ff65e618238a86398a51e94036diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256index 6de7cee..6f8ef14 100644--- a/SOURCE_MANIFEST.sha256+++ b/SOURCE_MANIFEST.sha256@@ -4,19 +4,21 @@ a3e3ce18f80b46587bcd529d13e456d10d97dd5e4a3f15e8e1a18894961120b1 ./.github/workefaab625b09d5b5bb80352b0586e4f81764914a1aff24164e338b6a95fee5973 ./.pubignoreabdc15ffd2312caa935bd8eeb30485b42654c146ded001997cfa240e9a77c7b2 ./CHANGELOG.md37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 ./LICENSE-4399569e64f4d4b73efcbcfc7e2a53e2feb175374999445819933931e38796bc ./README.md-cd94cbe58cf0c3674081d65766343d61ba9239ec51386a6b24b5aa28f1c947bd ./RELEASE_METADATA+d8707e1a8e1ad5e89183d06dde554d7daccd2b9ef0693d6090c67dea6625f163 ./README.md+a001f5aef42d295b573e8857038bf10443219759875e0c7767aae03912438188 ./RELEASE_METADATAdef7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 ./analysis_options.yaml5aeee476843e07c110c4525685fb6b875fa28824e26eae514f345d593126df48 ./build.sh4f18642680fb433554a5523d00bd99e0d650af340bcaebe628f59f63ac84e458 ./dartdoc_options.yaml+aa2787c65ea636f679723f9d6b575ce5c0d70f24e2ab3ac5823a821670b03151 ./doc/README.md+9399282ad46b1c181f92fb378ec51dc8013cd422bd90f2942dc19029fa17fcc0 ./doc/component_patterns.md+c5a4e9f35c43b80bed051903fc923a9629ee876fa1ad8d38fb3a3782338a6229 ./doc/diagrams.mde5120a94a88f2260b1d0264af7820d95a87cca8727c698f9047e1feae4d1d288 ./doc/manage_api_key.mda66d39da0983a994474fa516f81fd41bbb131efbd69c955891a41781a76daf24 ./doc/performance.mdc59892e1edadebe19a9bc5211f6d6a2f38ad0aece15d6505f8237405f152896e ./doc/release.md-97e9a1dcc98b831c5b72bfa80bd1f595fbff17266b6d42a2dd77ee75430cef20 ./doc/sdk_contract.md-98db54c31211074fa4176208662dd5b9e09e6d724a6dab2b22fc90b138a9f9e6 ./doc/sdk_doc.md-4aad6c643677dbefdd7fd7ac1aef865dd8c1640a6d98292facb28bcdcc8904a0 ./doc/search_app.md-7b0acfc01cfa4c8bf3af8aeb19741e65b8e9406935d9ab8e0f4cb84547483e55 ./doc/transcode_360.md-b7048ea33737815eeb8227a705a3629b13364ed0be0b1c74b284998d5821d372 ./doc/user_session_implementation.md+95637461214d0de45263b904eb38d702253805d989c3f07e9f896af023d915fb ./doc/sdk_contract.md+3531909fc0b44a8640155cb6fb014795950c1af393dbecd9558953b6360b384c ./doc/sdk_doc.md+6210ee89bebfcbf66e2dbfb035238420de4e10e80a3380a689653b1e45b26608 ./doc/search_app.md+3271e5e49451d705345e3921393766b8b5d8b11a9cffaac0f0ecc325f5514a72 ./doc/transcode_360.mde246ed229511a24a1ee7e98529c203ef90d1d352290ce8486caebe05683db3a0 ./env.shc5ce516b547327aab5b6fa27a523d4c76e66294ada3248b293c54b9595cd3a87 ./example/01_full_app/.metadata7b50a141c330c810a229422ca37d5ca28d34b9a9ec2ac701ec38d7bb1f49c8fb ./example/01_full_app/README.md@@ -270,7 +272,7 @@ c783830af58111d94c3e78a705865468fa3ba8f59cc5bef833404d7ac3567119 ./example/05_f4ecc92b82356d3fc31b7573caa8b9608dafb3af44dfe6f99b9f3ab93b4693500 ./example/05_framebase_userlogin/.metadatabc001543e1418412ce7879a5c46d40ef1b3c485d8ba2b9a343bf7104b17e360c ./example/05_framebase_userlogin/LICENSE559a8b6846e28399e68511e778cb7ea4b0390cf38fd87a9936414711bca72947 ./example/05_framebase_userlogin/MEDIA_SOURCES.md-61048efeb84d8df2a309039a14a3d735ba6f39f112d601d4097d7ebd79a4b281 ./example/05_framebase_userlogin/README.md+fd63eccefd17c7ff423ba6ec1e3838caa010cb59100b83be324a18356ef87588 ./example/05_framebase_userlogin/README.mde0ea485cfdbc3e12b93efb8679a5ea73ebfe20ea4ca0c473dc594fc2fb274ed5 ./example/05_framebase_userlogin/analysis_options.yaml6939878d0e417b29be6738e9c57772fc8a22a9aab5db39ae7fa867848d09d089 ./example/05_framebase_userlogin/android/app/build.gradle.kts4e4a0e0726baf45d2d878ea5d0e0666e08ea6e9dbdc33ecd2a74a3525cf5ba51 ./example/05_framebase_userlogin/android/app/src/debug/AndroidManifest.xml@@ -406,7 +408,7 @@ d132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.d593b356ac3431de80e03e7a0e2f1df0d29589140f44746468213c1cac1c35bbe ./test/multipart_upload_test.dart1247019fcd0549fab4bb48fa9aeee438ea288cc1e73561c46ca7dd6598170d14 ./test/new_api_surface_test.dart97593b7d76911b80a27a7f2ea2bcf283986e881d2bbb1347478ef5241c6a67f9 ./test/readme_pin_test.dart-4819fd5a6d02c97c0c47b137ef0a9860034929e8695325a2c6de8ad72cb41e67 ./test/regression_manifest_test.dart+60b04b0e565aa3a2928b76c36ef1f33e277f619cf1704da339f4e21ced6148b5 ./test/regression_manifest_test.dart5f049dd64b419a6afa46b548cdaba8d1101dd66501cede4425f02ed956b9a669 ./test/resources_models_test.dart701017ce3056f071f324d8fc94ccf2b6a147a3f0abd540eda634fac450fe53e3 ./test/session_guard_test.dart113ee0888fb78edf96476ee9d2c15fba2eecedfa6ff8529a9b86d0feb44a1563 ./test/session_lifecycle_test.dartdiff --git a/doc/README.md b/doc/README.mdnew file mode 100644index 0000000..6b38c1b--- /dev/null+++ b/doc/README.md@@ -0,0 +1,28 @@+# Flutter SDK documentation++For an existing Android/iOS app, start with+[Flutter app integration recipes](component_patterns.md). It covers API choice,+host activation, a complete search controller/widget, upload progress, index+polling, recovery, storage, mobile lifecycle, and host acceptance tests.++| Reading path | Guide |+| --- | --- |+| 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) |+| Tenant rotation and app-user identity transitions | [Manage API keys](manage_api_key.md) |+| Component relationships and sequences | [Diagrams](diagrams.md) |+| Advanced tenant-scoped search/image implementation | [Search app](search_app.md) |+| 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) |+| SDK maintainer publication and export | [Release](release.md) |++Session recipes require the 1.3.0 APIs present in this source tree. Use the local+dependency instructions in the recipes for reproduction; verify a public+artifact before choosing a production pin. Older 1.2.3 installation examples+refer to the earlier tenant-scoped API.++Authored guides live in `docs/`. Generated Dart API reference lives in `doc/`+and is published separately at [the SDK reference site](https://v-modal.github.io/vmodal_sdk_flutter/).+Internal planning notes are excluded from the standalone source export.diff --git a/doc/component_patterns.md b/doc/component_patterns.mdnew file mode 100644index 0000000..c88a1f2--- /dev/null+++ b/doc/component_patterns.md@@ -0,0 +1,777 @@+# Flutter app integration recipes++Use this guide to add VModal to an existing Android/iOS app. Start with a+verified host user, resolve that user's allowed library, discover existing+collections and jobs, and then attach a screen controller. Upload and index+only when the user needs new content.++The recipes target the local **1.3.0 session API**, Flutter **3.44.0+**, and+Dart **3.12.0+**. The repository pins Flutter **3.44.6**. Public package/tag+availability is not established by this guide: use the local dependency below+to reproduce these recipes. Before shipping, select an immutable public source+revision containing these symbols or a verified published compatible package.+An older `1.2.3` dependency cannot run the session recipes.++## Find the recipe you need++| Goal | Read / reuse |+| --- | --- |+| Choose sessions or tenant-scoped access | [API choice](#1-choose-the-api-and-own-its-lifetime) |+| Connect real sign-in and issuer adapters | [Activation](#2-activate-a-verified-user-and-discover-content) |+| Add a search screen without a state-management dependency | [Complete controller and widget](#3-copy-a-session-bound-search-screen) |+| Upload with progress and cancellation | [Upload recipe](#4-upload-with-owned-progress-and-cleanup) |+| Wait for an accepted index job | [Pipeline and polling](#5-orchestrate-upload-index-and-search) |+| Recover from a failed operation | [Error table](#6-map-failures-to-ui-and-permitted-recovery) |+| Switch accounts or rotate credentials | [Transition recipe](#7-handle-logout-account-switch-and-rotation) |+| Restore jobs and owner files after restart | [Storage recipe](#8-persist-owner-data-and-rebind-jobs) |+| Handle picker files, pause, and process death | [Mobile lifecycle](#9-set-mobile-file-and-interruption-policies) |+| Verify the host app before release | [Acceptance recipes](#10-test-and-release-the-host-integration) |++Canonical contracts remain in [sdk_contract.md](sdk_contract.md) and+[manage_api_key.md](manage_api_key.md). Component diagrams are in+[diagrams.md](diagrams.md). The complete working app is+[Framebase](../example/05_framebase_userlogin/README.md); its auth and issuer+implementations are mocks unless the host replaces them.++## 1. Choose the API and own its lifetime++| Integration | Use when | Host responsibility |+| --- | --- | --- |+| `UserSessionManager` → `UserSession` → `UserScope` | A signed-in user has an exact allowed library policy | Verify host identity/policy; clear app-owned UI, players, caches, and navigation on transition |+| `VModalProject` → `VModalScope` | Tenant-scoped evaluation or an app that implements its own complete isolation | Own identity fencing, cancellation, storage partitions, and every low-level resource lifecycle |+| `VmodalClient` resources | Advanced tenant operations outside the restricted session interface | Own all isolation and selector contracts; never mix these calls into a feature claiming session guarantees |++A VModal bearer authenticates the tenant. `auth.me()` reports that tenant+principal. It cannot determine which app user is signed in or which content+that user may access. Local session isolation does not establish server-side+app-user authorization under a shared tenant key; the deployment must enforce+that boundary independently where required.++### Ownership table++| Object | Lifetime | Creates / disposes it | Responsibilities |+| --- | --- | --- | --- |+| Host auth adapter and issuer client | Host connection | App composition root | Verify identity, acquire trusted credentials/policy, classify expiry/temporary failure |+| `TenantCredentialSource` | One service/tenant/principal connection | App connection owner; call `close()` | Coordinate accepted key revisions and renewal; remain available across user sessions |+| `UserSessionManager` | One active identity flow | Session coordinator; await `close()` | Activate, switch, invalidate, and close session transports |+| `UserSession` | One activation | Manager | Immutable app identity/policy; fresh runtime `sessionId` |+| `UserScope` / feature gateway | One session and exact mapping | Session coordinator / feature owner | Retain provenance across search, uploads, jobs, metadata, and media |+| Screen `ChangeNotifier` | One page or retained feature | Page or feature owner | Own debounce, tokens, query generations, progress subscriptions, and local waits |+| Widget / player | View lifetime | Owning widget | Render; dispose view resources and players |+| Archive / cache adapter | Validated stable owner/scope | Host storage owner | Validate restore, partition paths, commit through captured storage lease |++An injected shared dependency belongs to its injector. A page may dispose its+own notifier, but must not close an injected manager, source, or session that+other features use. The manager does not close the shared credential source;+the connection owner closes both when their lifetimes end.++Provider, Riverpod, or BLoC can implement the same table. None is an SDK+dependency. Keep the gateway/session out of tile constructors and network work+out of `build()`.++## 2. Activate a verified user and discover content++### Install for local integration++From your app, point to the SDK checkout with a relative path appropriate to+your directory layout:++```yaml+dependencies:+ flutter:+ sdk: flutter+ vmodal_sdk_flutter:+ path: ../vmodal_sdk_flutter+```++Run `flutter pub get` using a compatible toolchain. Within the SDK checkout,+`bash install.sh flutter_bin` locates its pinned Flutter executable. A path+dependency is a development arrangement; replace it with the verified immutable+release dependency before distributing the app.++### Define the host handoff++| Trusted input | Meaning / validation |+| --- | --- |+| Stable app-user ID | Subject verified by your host auth system; never inferred from the tenant key or user-entered collection |+| Service namespace, tenant ID, expected principal | Connection binding validated by the issuer client |+| Tenant bearer and expiry/revision | Runtime credential returned by the trusted issuer; kept out of archives |+| Exact content mapping | Logical project/collection or opaque collection ID, exact stream and mode |+| Actions and collection-wide flag | Allowed policy; write permission does not automatically grant deletion or aggregate discovery |+| Policy revision | Trusted revision, or SDK fingerprint of immutable grants/selectors |++For a concrete envelope parser and injection interfaces, reuse+[vmodal_credential.dart](../example/05_framebase_userlogin/lib/user/vmodal_credential.dart),+[auth_adapter.dart](../example/05_framebase_userlogin/lib/user/auth_adapter.dart), and+[user_session_controller.dart](../example/05_framebase_userlogin/lib/user/user_session_controller.dart).+Those are **example app components**, not SDK APIs. Implement the host auth+adapter and issuer transport; the example supplies no production verifier or+issuer URL. The issuer verifies the host token and derives its subject server-side.++Construct `TenantCredentialSource` as shown in+[manage_api_key.md](manage_api_key.md#session-bound-configuration), then inject+it into `UserSessionManager`. Use `openResolvedSession` when policy resolution+is asynchronous: it retires outgoing SDK state before awaiting the resolver.+Also fence the host resolver with an activation generation so late issuer+responses cannot install credentials or update host state for another user.++The following helper receives an already trusted resolver and a mapping from+that same policy. It performs discovery before returning the feature scope:++```dart+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++Future<UserScope> activateLibrary({+ required UserSessionManager manager,+ required Future<UserSessionPolicy> Function() resolve,+ required ContentMapping mapping,+}) async {+ final session = await manager.openResolvedSession(resolve);+ final scope = session.scope(mapping);+ await session.listCollections();+ if (!session.isActive) throw const SessionInvalidated();+ await scope.collectionInfo();+ if (!session.isActive) throw const SessionInvalidated();+ if (scope.mapping.actions.contains(UserAction.indexation)) {+ await scope.listIndexJobs();+ if (!session.isActive) throw const SessionInvalidated();+ }+ return scope;+}+```++Preconditions: grant `discover` for collection discovery, `search` for the next+recipe, and `media` for previews. Grant `indexation` only when permitted. A+scope uses the session's frozen grants even if the supplied mapping attempts to+replace them. Do not manufacture a broader mapping after a denied call.++Use `ContentMapping.logical` for a host-defined project and logical collection;+the SDK encodes `projectId__collectionName`. Use `ContentMapping.opaque` for an+issuer's exact backend collection ID; leave it unchanged. Both retain stream,+mode, and representation through every operation.++### Interpret discovery before enabling actions++| Result | UI / next action |+| --- | --- |+| No discoverable collections | Show “No available library”; resolve host provisioning/access before offering search |+| `collectionInfo()` or `latestVersion()` is null | Show “Search index unavailable”; investigate stream-specific metadata and policy |+| Existing scoped job | Show current work; monitor the live handle rather than submit another job |+| Search returns zero retained rows | Show an empty result for this query/filter; no automatic upload/index creation |+| Auth/access failure | Route to identity, tenant recovery, or denied state; not an empty library |++Aggregate collection versions require `collectionWide: true` unless discovery+returns an exact stream row. An absent stream version is not permission to+request a broader collection. Host policy controls that choice.++## 3. Copy a session-bound search screen++Copy this complete block into an app file. It uses only Flutter and public SDK+types. Pass a live `UserScope` after activation. For `vid_file`, pass a paired+offset-aware date range in `ScopedSearchOptions`; keep all selectors in the+scope. This screen displays typed filenames/distances. The media recipe below+adds images without exposing signed URLs.++```dart+import 'dart:async';+import 'package:flutter/material.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++enum SearchPhase { idle, loading, empty, ready, error, canceled }++class SearchState {+ const SearchState(this.phase, {this.result, this.message});+ final SearchPhase phase;+ final SessionSearchResponse? result;+ final String? message;+}++class LibrarySearchController extends ChangeNotifier {+ LibrarySearchController(this.scope, {required this.options});+ final UserScope scope;+ final ScopedSearchOptions options;+ SearchState state = const SearchState(SearchPhase.idle);+ Timer? _timer;+ CancellationToken? _token;+ int _generation = 0;+ bool _disposed = false;++ bool _current(int gen) => !_disposed && gen == _generation;++ void _publish(SearchState next) {+ if (_disposed) return;+ state = next;+ notifyListeners();+ }++ void queryChanged(String text) {+ if (_disposed) return;+ final gen = ++_generation;+ _timer?.cancel();+ _token?.cancel();+ final query = text.trim();+ if (query.isEmpty) {+ _publish(const SearchState(SearchPhase.idle));+ return;+ }+ _publish(const SearchState(SearchPhase.loading));+ _timer = Timer(const Duration(milliseconds: 300), () {+ unawaited(_search(query, gen));+ });+ }++ Future<void> _search(String query, int gen) async {+ if (!_current(gen)) return;+ final token = CancellationToken();+ _token = token;+ try {+ final result = await scope.search(+ query, options: options, cancellation: token,+ );+ token.throwIfCanceled();+ if (!_current(gen)) return;+ _publish(SearchState(+ result.assets.isEmpty ? SearchPhase.empty : SearchPhase.ready,+ result: result,+ ));+ } on SessionInvalidated {+ if (_current(gen)) {+ _publish(const SearchState(SearchPhase.canceled));+ }+ } on OperationCanceled {+ if (_current(gen)) {+ _publish(const SearchState(SearchPhase.canceled));+ }+ } on SdkException catch (error) {+ if (_current(gen)) {+ _publish(SearchState(SearchPhase.error, message: error.message));+ }+ } on Object {+ if (_current(gen)) {+ _publish(const SearchState(+ SearchPhase.error, message: 'Unexpected search failure',+ ));+ }+ } finally {+ if (identical(_token, token)) _token = null;+ }+ }++ void cancel() {+ if (_disposed) return;+ ++_generation;+ _timer?.cancel();+ _token?.cancel();+ _publish(const SearchState(SearchPhase.canceled));+ }++ @override+ void dispose() {+ _disposed = true;+ ++_generation;+ _timer?.cancel();+ _token?.cancel();+ super.dispose();+ }+}++class LibrarySearchPage extends StatefulWidget {+ const LibrarySearchPage({+ super.key, required this.scope, required this.options,+ });+ final UserScope scope;+ final ScopedSearchOptions options;++ @override+ State<LibrarySearchPage> createState() => _LibrarySearchPageState();+}++class _LibrarySearchPageState extends State<LibrarySearchPage> {+ late final LibrarySearchController controller;++ @override+ void initState() {+ super.initState();+ controller = LibrarySearchController(widget.scope, options: widget.options);+ }++ @override+ void dispose() {+ controller.dispose(); // This page owns only its notifier.+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => Scaffold(+ appBar: AppBar(title: const Text('Search library')),+ body: Column(children: [+ TextField(onChanged: controller.queryChanged),+ TextButton(onPressed: controller.cancel, child: const Text('Cancel')),+ Expanded(child: ListenableBuilder(+ listenable: controller,+ builder: (context, child) {+ final state = controller.state;+ switch (state.phase) {+ case SearchPhase.idle:+ return const Center(child: Text('Enter a query'));+ case SearchPhase.loading:+ return const Center(child: CircularProgressIndicator());+ case SearchPhase.empty:+ return const Center(child: Text('No matching moments'));+ case SearchPhase.error:+ return Center(child: Text(state.message ?? 'Search failed'));+ case SearchPhase.canceled:+ return const Center(child: Text('Search stopped'));+ case SearchPhase.ready:+ final hits = state.result!.videoHits;+ return ListView.builder(+ itemCount: hits.length,+ itemBuilder: (context, index) => ListTile(+ title: Text(hits[index].fileName ?? 'Unnamed asset'),+ subtitle: Text('Distance: ${hits[index].distance ?? "unknown"}'),+ ),+ );+ }+ },+ )),+ ]),+ );+}+```++**Mount contract:** key the page by runtime session identity **and** the exact+scope/options identity, so changed dependencies recreate its state. For example,+a parent that rebuilds on activation can use a `ValueKey` derived from+`scope.sessionId`, `scope.scopeKey`, and a host options revision. This recipe's+`late final` controller deliberately captures dependencies once. Replace the+route/key on account or filter-policy changes; do not update its scope in place.++Auth/tenant states belong above this feature: signed out, resolving, ready,+recoverable connection, denied, and identity expired. A production gateway can+report `401`/`403` to that coordinator as+[SearchGateway](../example/05_framebase_userlogin/lib/data/search_gateway.dart)+does, preserving the feature's failure instead of turning it into empty data.++### Why cancellation and generations both exist++The SDK session guard rejects work from an inactive session. The controller's+generation rejects older queries **inside the same active session**. The timer+reduces dispatch; the token requests local cancellation; the generation prevents+late success and late errors from replacing a newer state. Guard after every+await, including media loads, renewal callbacks, and host storage writes.++### Load a preview through its live asset++```dart+import 'dart:typed_data';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++Future<Uint8List> loadPreview(+ UserScope scope,+ SessionAsset asset,+ CancellationToken token,+) async {+ final bytes = await scope.imageBytes(+ asset, maxBytes: 2 * 1024 * 1024, cancellation: token,+ );+ token.throwIfCanceled();+ return bytes;+}+```++The 2 MiB limit is an app choice. Use `Image.memory(bytes)` only after checking+the originating query/view generation. Load a bounded number of visible tiles;+own their cancellation and cache entries. Some hits have no usable basename or+frame time, so media can be unavailable: show a placeholder and preserve the+search hit. Never obtain an arbitrary URL through a low-level client to bypass+that failure. The restricted session API keeps signed capabilities private.++Distance is nullable and lower-is-better; do not label it confidence or convert+it to a percentage. Playback offset is nullable elapsed milliseconds, not an+absolute recording timestamp. Resolve a hit to an owner-local clip by canonical+asset ID; differing non-null IDs must not match merely because filenames agree.++## 4. Upload with owned progress and cleanup++Use this helper inside a controller that owns one active task. The callback+provides the task for a cancel button before awaiting completion. `onProgress`+must check the controller's current session/view generation before publishing.+The helper releases its subscription on every exit and preserves the failure+for the owning controller to classify.++```dart+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++Future<SessionUploadResponse> uploadClip({+ required UserScope scope,+ required UploadSource source,+ required void Function(UploadTask<SessionUploadResponse>) onStarted,+ required void Function(UploadProgress) onProgress,+}) async {+ final task = scope.upload(source);+ final progress = task.progress.listen(onProgress);+ try {+ onStarted(task);+ return await task.result;+ } finally {+ task.cancel(); // Also ends unfinished work if a host callback failed.+ await progress.cancel();+ }+}+```++Controller sequence: publish uploading → retain the started task → publish+guarded byte progress → await result → check generation → record completion →+clear task reference in `finally`. Publish canceled for local cancellation and+unknown completion when a dispatched mutation has an ambiguous outcome. A+subscription callback should update state synchronously; route callback failures+through your app's error reporting rather than throwing from a stream listener.++Keep feature state immutable: phase, progress, nullable uploaded identity,+pending job, and user-facing message. Suggested pipeline phases are picking,+uploading, uploaded, indexing, ready, canceled, failed, and completionUnknown.+Keep auth recovery separate. Progress reaching 100% is not finalization success+and upload success is not index readiness.++Choose one navigation policy:++| Policy | Owner / page behavior |+| --- | --- |+| Screen-owned foreground upload | Page disposal calls `task.cancel()`; controller awaits/handles the result and cleans subscription |+| Retained foreground feature | App feature owner retains task/controller; page detaches only its view; explicit stop/logout still cancels |+| Platform background transfer | Host implements scheduling and durable recovery; a Dart Future alone supplies no process-death guarantee |++Signed single upload is the default for every size. Multipart requires explicit+`VideoUploadOptions(multipart: true)` and remains experimental; unavailable route+families fail with `FeatureDisabled`. Inject a persistent checkpoint store at the+manager if needed. Per-task stores and custom transcoders are rejected by the+restricted session interface; only `PassthroughVideoTranscoder` is supported.++## 5. Orchestrate upload, index, and search++Keep one immutable scope through the entire pipeline:++```text+verified activation → collections → existing jobs/version+ → upload when requested → completion + nullable asset+ → metadata on live proven asset when needed+ → reuse suitable job or submit index → accepted job+ → bounded local polling → discover usable version → search+```++`SessionUploadResponse.asset` is nullable. Even an asset handle may have a null+canonical `assetId`. Preserve those nulls; filenames/frame IDs do not synthesize+asset identity. Metadata/add/update calls require live scoped provenance. JSONL+metadata is bounded to 8 MiB and uses the allowlisted scalar/string-list fields+described in [the contract](sdk_contract.md#restricted-results-and-provenance).++Index submission returns acceptance, not search readiness. Reuse a suitable job+from `scope.listIndexJobs()` when policy and product behavior allow it. Creating+an index automatically on every empty search can duplicate work and widen the+feature's responsibilities.++### Bounded, cancelable local wait++The helper below uses the terminal-state classifications already used by the+Framebase gateway. Confirm the backend states used by your deployment in live+contract checks. Unknown states keep polling until the app's deadline.++```dart+import 'dart:async';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++Future<IndexationStatusResponse> waitForIndex(+ UserScope scope,+ SessionJob job,+ CancellationToken token, {+ Duration maxWait = const Duration(minutes: 2),+}) async {+ final clock = Stopwatch()..start();+ while (clock.elapsed < maxWait) {+ token.throwIfCanceled();+ final status = await scope.indexStatus(job, cancellation: token);+ token.throwIfCanceled();+ final state = status.status.toLowerCase();+ if (const {'success', 'succeeded', 'done', 'completed', 'ok'}.contains(state)) {+ return status;+ }+ if (const {'failed', 'failure', 'error', 'cancelled', 'canceled'}.contains(state)) {+ throw ApiException('Index job ended: $state');+ }+ // Short slices bound local cancellation latency between HTTP reads.+ for (var n = 0; n < 20; n++) {+ token.throwIfCanceled();+ if (clock.elapsed >= maxWait) break;+ await Future<void>.delayed(const Duration(milliseconds: 100));+ token.throwIfCanceled();+ }+ }+ throw TimeoutException('Stopped waiting locally; the server job may continue');+}+```++The deadline bounds the polling loop; a currently running status request is+additionally bounded by `SdkConfig.timeout` and its read retry budget. Thus a+request already in progress can finish after `maxWait`. If your UI needs a hard+deadline, its owner must also cancel the token with a timer and cancel that timer+in `finally`. Canceling local polling does not cancel the accepted server job.++After success, rediscover `latestVersion()` with the same scope. If unavailable,+show “Index finished; search metadata unavailable” and investigate discovery;+do not assume a nullable version means ready. Pass the discovered version and+paired dates for `vid_file` in `ScopedSearchOptions`. The host controller checks+its operation generation after the wait and discovery before enabling search.++### Resolve ambiguous mutations++| Stage / failure | Retained fact | Permitted recovery |+| --- | --- | --- |+| Local validation before SDK dispatch | No operation accepted by this attempt | Correct input/policy and deliberately start again |+| Dispatched upload/finalization times out | Completion unknown | Reconcile using documented scoped service data / supported multipart status protocol; do not infer failure from local cancel |+| Index submission response lost | Acceptance unknown | Rediscover exact scoped jobs; offer deliberate reconciliation before another submission |+| Local polling canceled/times out | Known accepted job can continue | Save durable reference; rediscover/rebind and resume waiting |+| Cloud success, archive commit failed | Remote completion known, local persistence failed | Report both stages; repair local record without replaying the remote mutation |++The generic `TransportException` alone does not prove a request was never sent.+No documented once-only upload guarantee comes from filename, hash, checkpoint,+or source ID. Do not offer a blind automatic “retry upload” for unknown completion.++### Collection deletion is a separate feature++Require `UserAction.delete` and `collectionWide: true`. Preview with+`ScopedDeleteCollectionOptions(dryRun: true)`, show collection-wide consequences,+obtain explicit host UI confirmation, then commit with+`ScopedDeleteCollectionOptions(dryRun: false, confirm: true)`. Capture the same+session and scope across preview/confirmation; recheck them before commit.+Cloud deletion does not delete owner-local MP4s. No individual remote-video+deletion API is exposed. Reconcile unknown outcomes; `409` is not permission to+replay a commit immediately. See Framebase's deletion flow for UI and archive+handling.++## 6. Map failures to UI and permitted recovery++Catch `SessionInvalidated` before `OperationCanceled` because it subclasses+cancellation. Catch credential failures before the generic `SdkException`.+Preserve the original failure for controller/repository callers, and always+release task subscriptions and timers in `finally`.++| Public failure | UI state | Next action |+| --- | --- | --- |+| `SessionInvalidated` | Retire feature; clear old results | Recreate feature only after fresh activation; never reuse handles |+| `OperationCanceled` | Normal stopped state | Explicit user restart where outcome is known; accepted mutations may continue |+| `TenantAuthException` / `AuthException` | Tenant connection recovery | Renew through trusted source; retain host user unless host identity itself is invalid |+| `ApiException` | Context-specific failure | Classify status and operation stage; preserve unknown write outcome |+| `ValidationException` | Input/policy problem | Fix contract or grant; do not repeat unchanged input |+| `TransportException` | Read failure or unknown mutation completion | Manual read retry; reconcile mutations |+| `FeatureDisabled` | Feature/media unavailable | Hide unsupported action or show placeholder; no low-level bypass |+| `ResponseTooLarge` | Resource exceeds app/SDK limit | Reduce result count/media size; avoid unbounded buffering |+| `MalformedResponse` | Service-contract failure | Record safe classification; correct contract before replaying writes |++| Status | Meaning depends on stage | Recovery rule |+| --- | --- | --- |+| `401` | Tenant bearer rejected or connection blocked | Eligible GET/HEAD can recover once within bounded attempt budget; write is not replayed |+| `403` | Access/policy denied | Resolve policy; no generic credential refresh or broader-key fallback |+| `404` | Missing collection/job/media or unavailable resource | Refresh allowed discovery or show missing media; do not mint ownership from a bare ID |+| `409` | Conflicting/busy operation | Reconcile/wait; destructive commit is not blindly repeated |+| `429` | Service rate limiting | Gate actions and use verified service retry guidance; SDK promises no generic automatic 429 recovery |+| `500/502/503/504` | Eligible read server failure | GET/HEAD may retry within configured budget; writes still require reconciliation |++Search uses POST even though the user perceives it as a read. Do not assume it+receives GET/HEAD retry or auth-recovery behavior. Request retry snapshots retain+their credential revision; eligible auth recovery reconstructs headers under the+coordinator. Other statuses/transport failures are not a blanket retry promise.++Diagnostics should record operation stage, elapsed time, exception class, status,+and runtime generation. Use a request identifier only when the actual response+contract exposes it. Do not invent a universal request-ID header or log raw+response bodies, API keys, signed URLs, or issuer envelopes. Restricted session+errors already remove raw tenant bodies and underlying capabilities.++## 7. Handle logout, account switch, and rotation++Execute this order in the host session coordinator:++1. Advance host activation/view generations and stop accepting feature actions.+2. Call `manager.logout()` or start `openResolvedSession(...)` immediately;+ outgoing SDK invalidation occurs before asynchronous cleanup/resolution.+3. Detach and dispose old feature controllers, cancel local tokens/tasks, stop+ players, clear displayed images/search/history, and replace private routes and+ restoration state. Perform these host changes before publishing new user data.+4. Retire archive writers; finish captured storage cleanup for the old owner.+5. Resolve and validate the new identity/issuer envelope under the new host+ generation; activate the exact policy, discover content, restore validated+ owner data, then publish ready.++An invalidation callback must clean up resources captured for the outgoing+session, not whatever manager session happens to be current later. Delayed A+cleanup must not dispose B's controller/player. A→B→A creates three runtime+session IDs; old A handles and callbacks do not become valid on return to A.++`TenantCredentialSource.install(...)` or `renewCredential()` replaces credentials+without changing session identity when service/tenant/principal/policy remain+equal. A changed policy requires fresh activation; a changed tenant/principal+requires a correctly bound fresh source and sessions. Host identity expiry needs+host sign-in; tenant renewal cannot repair it. A temporary tenant failure should+not automatically sign out the app user.++At final connection shutdown, await manager cleanup and close the source in a+`finally` block so a transport cleanup failure cannot leave the coordinator open.+Dispose host auth/issuer/archive components according to their ownership. Do+not close shared credentials when only one page leaves.++## 8. Persist owner data and rebind jobs++| Value | Persistent use |+| --- | --- |+| `session.context.ownerKey` | Stable service/tenant/app-user namespace |+| `scope.scopeKey` | Exact representation/collection/stream/mode namespace |+| `policyRevision` | Required restore validation; include it in result cache identity |+| `sessionId` | In-flight generation/dedup guards only; not a stable archive directory |+| API-key bytes/revision | Credentials; never an owner partition |+| `SessionAsset`, `SessionJob`, `UserScope` | Live capabilities; never serialize/reuse after activation ends |++Persist a job with `job.toDurableReference()`: allowlist `jobId`, `ownerKey`,+`scopeKey`, and `policyRevision`. After verified activation for that same owner+and policy, construct the durable reference from validated manifest data and+call `newScope.rebindJob(reference)`. Rebinding checks ownership and performs+fresh exact scoped discovery bounded to 1000 rows. A reference is not proof;+missing jobs fail closed. There is no durable asset/raw upload ID rebinding API.++Use the existing+[ArchiveController](../example/05_framebase_userlogin/lib/data/archive_controller.dart)+for the filesystem recipe: immutable captured destinations/payloads, validated+owner metadata, paths constrained to the owner directory, staged writes, and+atomic replacement through `scope.storageLease.run(...)`. Call lease `check()`+immediately before publishing a staged file. Retire a host writer when its+feature ends; do not reopen a retired writer under the same session.++SDK owner commit coordination fences older writers, including A→B→A, within+one isolate. Shared multi-isolate/process storage needs one owner isolate or+transactional locking. Never assume independent in-memory queues synchronize it.++Cache identity adds current policy and every result-affecting parameter:+query, dates, version, pagination, search sources, and media variant. In-flight+dedup also includes `sessionId`. Quarantine legacy records with unknown ownership;+do not assign them to whoever next signs in. Sign-out can preserve partitioned+files for a later verified restoration while immediately hiding them from UI.++## 9. Set mobile file and interruption policies++The SDK targets Android/iOS; Web is outside this contract. Toolchain minimums+above are package constraints, not a claim about a particular app's Android+API level or iOS deployment target. Preserve your app's native targets and+check its plugin/build requirements on device. The SDK has no picker/camera UI+and does not justify broad photo/storage/camera permissions by itself.++### Picker/camera → reopenable upload++1. Obtain the file through the host's chosen picker/camera adapter and its actual+ platform permission flow. A `content://` URI is not automatically a Dart path.+2. If access is temporary, copy it into an app-owned owner-partitioned location+ while permission is valid. Keep filename, length, and contents stable.+3. Pass the readable `File` to `UploadSource.fromFile`. The SDK can reopen ranges;+ do not pass a one-shot stream as though it supports replay/resume.+4. Keep the file until the owning task and supported resume policy release it.+ Record temporary-file ownership and clean only files this feature owns.+5. After restart, validate owner, source existence/contract, and checkpoint+ envelope before offering continuation. Process death does not settle a Dart+ Future or prove that remote finalization failed.++### Adopt an explicit lifecycle policy++| Event | Framebase policy to reuse | Host decision |+| --- | --- | --- |+| Brief inactive interruption | Keep foreground work | Avoid unnecessary cancellation for transient system UI |+| Paused/hidden/detached | Cancel upload/local job wait and invalidate search view | Choose retained work only with explicit host ownership |+| Resume | No mutation/search replay | Rediscover current state; offer explicit resume/retry |+| Page pop | End view work | Cancel screen-owned work or detach from retained feature |+| Process death | Runtime session/controllers gone | Reauthenticate, restore validated records, rebind jobs, reconcile unknown mutations |++Hook these decisions into the app's lifecycle observer; keep them outside widget+`build()`. Do not claim a Dart upload survives termination. Background scheduling+and operating-system transfer semantics are host responsibilities.++Set image byte/count limits and bound concurrent loads. Dispose players on+view/session transitions and profile real devices. See+[performance.md](performance.md) for streaming and timeout budgets.+[transcode_360.md](transcode_360.md) describes a **tenant-scoped** custom reducer:+it cannot be injected into the restricted session upload API. A host adopting+that advanced path must own native success checking, output validity, cache+identity, concurrent destinations, temporary cleanup, and isolation.++## 10. Test and release the host integration++Use the SDK's existing injected transport factories and example fixtures;+do not introduce a second fake networking stack. Manager transport factories+must return distinct gateway/signed transports for each session. Start with+[session_fixture.dart](../example/05_framebase_userlogin/test/session_fixture.dart),+[user_session_controller_test.dart](../example/05_framebase_userlogin/test/user_session_controller_test.dart),+and [search_gateway_test.dart](../example/05_framebase_userlogin/test/search_gateway_test.dart).+Keep fake keys/envelopes clearly marked as fixtures.++| Arrange / act | Assert |+| --- | --- |+| Fake verified user and allowed envelope | Activation discovers collections before index/search; exact opaque ID unchanged |+| Empty discovery, missing version, empty search | Three distinct UI states; no implicit index submission |+| Query 1 finishes after query 2 | Only query 2 changes state; late errors also ignored |+| Dispose during debounce/media await | No dispatch after debounce disposal, no late UI publish, owned subscriptions end |+| Denied action or policy | Local failure before transport; no broader mapping fallback |+| Identity expiry vs tenant renewal failure | Sign-in required only for identity failure; connection recovery retains host user |+| A→B→A with delayed responses/progress/store writes | B never displays A; new A rejects old handles; old writer cannot overwrite new owner's state |+| Upload result lost / index acceptance lost | Unknown completion retained; no automatic duplicate mutation |+| Accepted job + restart | Durable owner fields restored; fresh rebind required; changed policy rejects old reference |+| Cloud success + local commit failure | Remote success retained; local repair does not re-upload/delete again |+| Widget account transition | Old players, decoded images, navigation/restoration, and controller references removed |++From the SDK checkout, use the pinned tools to verify SDK contracts and the+reference app. These commands are existing offline tests, not backend checks:++```bash+flutter_bin="$(bash install.sh flutter_bin)"+"$flutter_bin" test test/user_session_test.dart test/session_lifecycle_test.dart \+ test/session_storage_test.dart test/tenant_credentials_test.dart \+ test/user_provenance_test.dart+cd example/05_framebase_userlogin+"$flutter_bin" analyze+"$flutter_bin" test+```++For a host app, run its own analyzer/controller/widget tests and Android/iOS+device acceptance. Separate these from live service checks proving discovery,+date filters, actual terminal states, multipart availability, and any server+app-user authorization. Offline tests cannot prove server access isolation.++### Migration and app release checklist++- Choose a verified dependency containing the public APIs used; resolve the+ lockfile and inspect the actual package, not only a README version example.+- Replace project/client selectors with a trusted `UserScope`; replace raw IDs+ and signed media URLs with live handles and `imageBytes` in session features.+- Move key replacement to the tenant source; move account/policy changes to the+ manager. Preserve canonical nullable IDs and typed distance/offset semantics.+- Validate or quarantine legacy cache/archive ownership; persist durable job+ metadata rather than old live handles.+- Inject real host auth/issuer adapters; verify exact allowed mappings and+ backend features on the intended service.+- Exercise cancellation, pause/resume, restart, account switch, renewal failure,+ and unknown mutation completion on Android/iOS devices.+- Confirm foreground/background/file-retention policy and diagnostics in the+ app. SDK publication steps remain in [release.md](release.md).++### Common implementation mistakes++| Mistake | Apply this pattern |+| --- | --- |+| Call search in `build()` or create clients per tile | Inject one scope, start work from controller actions |+| Keep a scope across account/policy change | Recreate session-bound feature; key/replace the route |+| Use query cancellation without latest-result guard | Advance generation on query/cancel/dispose and check after await |+| Cancel token and report remote write rolled back | Record accepted/unknown outcome; reconcile |+| Treat tenant auth failure as host logout | Separate connection and identity state machines |+| Save API keys or runtime session IDs as archive identity | Use validated stable owner/scope/policy metadata |+| Show low-level signed URLs in a session feature | Use live `SessionAsset` and scoped media bytes |+| Treat upload complete or job accepted as searchable | Wait for terminal result and rediscover usable index version |++Documentation basis: local source and existing Framebase implementation reviewed+on 2026-10-02. This guide describes reusable app patterns; it does not claim a+production issuer, public package publication, device certification, or live+backend acceptance has been supplied by the example.diff --git a/doc/diagrams.md b/doc/diagrams.mdnew file mode 100644index 0000000..63a1632--- /dev/null+++ b/doc/diagrams.md@@ -0,0 +1,245 @@+# Flutter component couplings++These diagrams describe the gateway-mode SDK and its opt-in app-user session+API in the 1.3.0 source interface. The host app owns sign-in, trusted identity+and policy resolution, and visible UI state. The SDK owns session guards,+resource operations, transport, and tenant credential coordination.++## 1. App, user auth, VModal auth, and SDK layers++```mermaid+flowchart TB+ User["App user"] --> UI++ subgraph App["App layer - Flutter host"]+ UI["Screens, navigation, players"]+ Controller["App session controller"]+ HostStore["Owner archives and UI caches"]+ UI --> Controller+ Controller --> HostStore+ end++ subgraph HostAuth["User auth - host integration"]+ Identity["Firebase, Clerk, or another identity provider"]+ Issuer["Trusted host issuer / policy resolver"]+ Identity -->|"Verified app identity at issuer"| Issuer+ end++ subgraph SDK["SDK layer - vmodal_sdk_flutter"]+ Manager["UserSessionManager"]+ Session["UserSession + immutable SessionContext"]+ Scope["UserScope + ContentMapping"]+ Credentials["TenantCredentialSource"]+ Client["Private VmodalClient and resources"]+ HTTP["VmodalHttp + Routes + guarded transports"]+ Manager --> Session+ Session --> Scope+ Scope --> Client+ Credentials -->|"Session-bound API-key provider"| Client+ Client --> HTTP+ end++ subgraph Service["VModal service layer"]+ Gateway["users_api - tenant bearer verification and proxy"]+ Backend["Search, collection, index, and media services"]+ Storage["Object storage - signed capabilities"]+ Gateway -->|"Trusted tenant identity and routed request"| Backend+ Backend --> Storage+ end++ Controller -->|"Host sign-in"| Identity+ Controller -->|"Authenticated credential and policy request"| Issuer+ Issuer -->|"Stable appUserId and allowed mappings via host"| Controller+ Controller -->|"Resolved UserSessionPolicy"| Manager+ Issuer -->|"Tenant key and verified binding via host"| Credentials+ Controller -->|"Session-bound operations"| Scope+ Scope -->|"SessionStorageLease for host commits"| HostStore+ HTTP -->|"Authorization: Bearer tenant key"| Gateway+ HTTP -->|"Signed upload bytes; no tenant bearer"| Storage+ Scope -->|"Restricted results and image bytes"| UI+```++The identity provider and issuer are host integrations. The+[Framebase userlogin example](../example/05_framebase_userlogin/README.md) has+mock adapters; a production issuer must verify the host identity and resolve+its authorized content policy. It is not an SDK login endpoint.++| Identity / selector | Supplied by | Meaning |+| --- | --- | --- |+| `appUserId` | Authenticated host | Stable app user; A and B remain different even with one tenant key |+| `tenantId`, expected principal, API key | Trusted tenant issuer | VModal connection binding; `auth.me()` checks the tenant principal |+| `sessionId` | SDK on every activation | Runtime lease for requests, callbacks, and live resource handles |+| `ContentMapping` | Trusted host policy | Exact collection, stream, mode, actions, and collection-wide permission |+| `ownerKey`, `scopeKey`, `policyRevision` | SDK context / trusted policy | Stable storage partition and policy validation |++App-user identity is separate from `SdkConfig.userId`, gateway identity+headers, and collection names. The gateway derives its identity from the+tenant bearer. Under a shared key, local SDK policy does not establish+server-side app-user authorization.++## 2. Sign-in and session activation++```mermaid+sequenceDiagram+ autonumber+ actor User as App user+ participant App as Host app+ participant Auth as Host identity provider+ participant Issuer as Trusted issuer / resolver+ participant Keys as TenantCredentialSource+ participant Manager as UserSessionManager+ participant Session as UserSession+ participant Gateway as VModal users_api++ User->>App: Sign in+ App->>Auth: Authenticate+ Auth-->>App: Stable app identity and host credential+ App->>Issuer: Request tenant credential and content policy+ Issuer->>Auth: Verify host credential / identity+ Auth-->>Issuer: Verified app-user subject+ Issuer-->>App: Tenant binding, key, exact mappings, policy+ App->>Keys: Create source with service / tenant / principal binding+ App->>Manager: openResolvedSession(resolver)+ Manager->>Manager: Invalidate outgoing session before awaiting resolver+ Manager->>App: Invoke policy resolver+ App-->>Manager: UserSessionPolicy from trusted host resolution+ Manager->>Keys: Attach fresh session provider at current revision+ Manager->>Session: Create fresh sessionId, guard, private client / transports+ Manager-->>App: Active session (latest activation ticket only)+ opt Optional tenant-principal verification+ App->>Session: verifyPrincipal(expectedPrincipal)+ Session->>Gateway: auth.me() with tenant bearer+ Gateway-->>Session: Tenant principal profile+ Session-->>App: Expected principal verified+ end+ App->>Session: listCollections(), then scope(allowedMapping)+ Session-->>App: Restricted discovery and immutable UserScope+```++For account changes, begin `openResolvedSession` before asynchronous identity+or mapping resolution. The diagram's first credential acquisition assumes an+initial activation. `openUserSession` is available when the host already has+the verified policy. `auth.me()` verifies neither the app-user ID nor its+allowed mapping.++## 3. Data requests, signed uploads, and media++```mermaid+flowchart LR+ App["App operation"] --> Scope["UserScope - frozen selectors and actions"]+ Scope --> Guard["Capture originating session lease and inputs"]+ Guard --> Resource["Existing SDK resources and upload helpers"]+ Resource --> HTTP["VmodalHttp - credential/header snapshot"]+ HTTP --> Gateway["users_api - verify tenant bearer"]+ Gateway --> Backend["Routed data service"]+ Backend --> Response["Results, job / asset identity, or signed upload grant"]+ Response --> Delivery["Lease check + restricted result / provenance validation"]+ Delivery --> App++ Response -->|"Signed upload grant"| PUT["Guarded signed-upload transport"]+ PUT -->|"PUT bytes with signed grant; no tenant bearer"| Storage["Object storage"]+ Storage -->|"Upload completion"| Finalize["Guarded finalization via gateway resources"]+ Finalize --> HTTP++ App -->|"imageBytes(live SessionAsset)"| Media["Scope validates handle and resolves media privately"]+ Media --> Download["Guarded media download; no tenant bearer on signed URL"]+ Download -->|"Bytes through originating lease"| App+```++Session checks cover preparation, sends, retries, signed phases, response+chunks, completion, and progress callbacks. `SessionAsset` and `SessionJob`+handles belong to the originating live session and scope. Signed URLs remain+private in the restricted interface and have independent expiry. A server+operation already accepted can continue after local cancellation.++The compatible `VModalProject` / `VModalScope` and direct `VmodalClient` APIs+delegate to the same resources but bypass app-user session guarantees. Their+host must manage account cancellation, storage partitioning, and UI cleanup.++## 4. Account switch and logout++```mermaid+sequenceDiagram+ autonumber+ participant App as Host app / view generation+ participant Manager as UserSessionManager+ participant A as Session A and scopes+ participant IO as Pending A work+ participant UI as Images / players / navigation+ participant B as Fresh session B++ App->>Manager: openResolvedSession(resolve B) or logout()+ Manager->>Manager: Advance activation ticket, set current to null+ Manager->>A: Invalidate synchronously+ A->>A: Retire lease, close provider, detach internal state+ A->>IO: Cancel registered work and retire storage writers+ A-->>App: onInvalidated(A)+ App->>UI: Advance view generation and clear A-owned visible state+ IO-->>A: Late A response or progress+ A->>A: Reject delivery under expired lease+ A->>IO: Finish instance-owned transport / storage cleanup+ opt Account switch+ Manager->>App: Resolve B's verified identity and policy+ App-->>Manager: UserSessionPolicy for B+ Manager->>B: Create fresh sessionId, provider, client, and transports+ Manager-->>App: Publish B if activation ticket is still current+ App->>UI: Render B after session / view-generation check+ end+```++A → B → A creates three runtime sessions. Returning to A may reuse validated+owner storage, but cannot reactivate old scopes or handles. Cleanup remains+bound to the outgoing instance even if a callback opens a newer session.+Logout invalidates SDK user data; the host also owns identity-provider sign-out+and cleanup of data already displayed or copied.++## 5. Tenant-key rotation and stable storage ownership++```mermaid+flowchart TB+ Trigger["Trusted replacement or coordinated renewal"] --> Source["TenantCredentialSource"]+ Source --> Validate["Check service / tenant / principal binding,<br/>renewal ticket, accepted revision, issuer version when supplied"]+ Validate --> Commit["Atomically accept credential revision"]+ Commit --> Provider["Update live matching session providers"]+ Provider --> NewRequest["New request captures latest key and revision"]+ OldRequest["Already constructed request"] --> Snapshot["Retains original headers and credential snapshot"]++ Source --> Failure["Renewal failure or revocation: block tenant calls by default"]+ Failure --> Recovery["Host tenant-connection recovery; app-user identity retained"]+ NewRequest --> Denied["401 on eligible active GET / HEAD"]+ Denied --> Once["At most one auth recovery; rebuild headers within attempt budget"]+ Once --> Source++ Context["Stable SessionContext"] --> Owner["ownerKey = service namespace + tenantId + appUserId"]+ Owner --> ScopeKey["scopeKey adds representation + collection + stream + mode"]+ ScopeKey --> Store["Owner / scope storage + policy validation"]+ Store --> Checkpoints["SDK multipart checkpoint envelopes"]+ Store --> Archive["Host archives via SessionStorageLease"]+ Context --> Lifetime["Credential-only rotation preserves sessionId and policy"]+```++Keys and credential revisions are excluded from stable owner/scope keys.+Host cache entries additionally include policy and result-affecting parameters;+in-flight deduplication includes `sessionId`. Writer retirement and serialized+commits fence older activations within one isolate.++Tenant, endpoint, principal, or content-policy changes require fresh sessions;+changed connection bindings also require a correctly bound credential source.+Mutations are never automatically replayed through auth recovery, and `403` is+not a general refresh trigger. Key rotation does not revoke previously issued+signed capabilities.++## Implementation and contract references++- [Session contracts, provenance, and storage](sdk_contract.md)+- [Tenant credential coordination and recovery](manage_api_key.md)+- [Framebase host integration and issuer envelope](../example/05_framebase_userlogin/README.md)+- [Session manager, context, policy, and scopes](../lib/src/user_session.dart)+- [Tenant credential source and providers](../lib/src/api_key_provider.dart)+- [Session and storage guards](../lib/src/session_guard.dart)+- [Client composition](../lib/src/client.dart) and [shared HTTP](../lib/src/http.dart)++The host issuer must authorize each app user independently. A modified client+with a shared tenant key can call any resource that key authorizes. Server+enforcement therefore needs verified app-user identity and per-resource policy;+the SDK's local isolation alone does not supply that server contract.diff --git a/doc/sdk_contract.md b/doc/sdk_contract.mdindex edc5c65..fdef1f3 100644--- a/doc/sdk_contract.md+++ b/doc/sdk_contract.md@@ -209,8 +209,8 @@ history, and copied/downloaded files at identity transitions. The SDK exposessession invalidation; it cannot manage these host-owned surfaces.Tenant renewal and bounded read recovery are documented in-[Manage API keys](manage_api_key.md). Implemented block and verification notes-are in [User-session implementation](user_session_implementation.md).+[Manage API keys](manage_api_key.md). Ready-to-use controller, upload, storage,+and lifecycle recipes are in [Component patterns](component_patterns.md).## Typed video-search resultsdiff --git a/doc/sdk_doc.md b/doc/sdk_doc.mdindex 0d1b1b7..825b6e2 100644--- a/doc/sdk_doc.md+++ b/doc/sdk_doc.md@@ -1,5 +1,11 @@# SDK guide+For account-based apps, start with [Component patterns](component_patterns.md):+activate a verified app-user session, discover its allowed library, and inject+the resulting `UserScope` into a feature controller. The examples below use the+compatible **tenant-scoped** API, whose host owns isolation and lifecycle.+See the [documentation index](README.md) for the recommended reading paths.+The generated class and method reference is published at`https://v-modal.github.io/vmodal_sdk_flutter/` and is built from the publicDart declarations in `lib/vmodal_sdk_flutter.dart`. The monorepo releasediff --git a/doc/search_app.md b/doc/search_app.mdindex 52ab70f..8159acc 100644--- a/doc/search_app.md+++ b/doc/search_app.md@@ -1,5 +1,11 @@# Search application integration+This guide uses the advanced **tenant-scoped** project/client and signed-image+path. For an account-based app, use the complete+[session-bound controller/widget recipe](component_patterns.md#3-copy-a-session-bound-search-screen)+and live `SessionAsset` media through `UserScope.imageBytes`. Do not mix raw+selectors or arbitrary signed URLs into a feature relying on session isolation.+Keep the project above individual pages so navigation does not close sharednetwork state. Retain an immutable scope in the page controller, provider,BLoC, or notifier:diff --git a/doc/transcode_360.md b/doc/transcode_360.mdindex e46d4f6..846b96c 100644--- a/doc/transcode_360.md+++ b/doc/transcode_360.md@@ -1,5 +1,12 @@# Pre-upload 360px video transcode+This custom-reducer recipe applies to **tenant-scoped** uploads. Restricted+`UserScope.upload` accepts only `PassthroughVideoTranscoder` and rejects custom+transcoders. See [mobile file and interruption policies](component_patterns.md#9-set-mobile-file-and-interruption-policies)+for the session path. Treat the reducer snippet as an adapter starting point:+before production use, check native execution success, output validity, cache+identity, concurrent destination handling, and temporary-file ownership.+The SDK can reduce a video to a smaller resolution (longer side = 360px) *before*uploading, to cut upload bytes. The core package stays free of native code: it owns onlythe `VideoTranscoder` interface and the upload lifecycle. **By default there is nodiff --git a/doc/user_session_implementation.md b/doc/user_session_implementation.mddeleted file mode 100644index bbe3de4..0000000--- a/doc/user_session_implementation.md+++ /dev/null@@ -1,71 +0,0 @@-# App-user session implementation notes--Date: 2026-10-02--The nine requested specification blocks are implemented as an opt-in gateway-interface. Existing tenant-scoped wire APIs remain compatible. The specification-is a design input; this authored note and [SDK contract](sdk_contract.md) describe-the actual supported interface.--| Block | Implemented boundary | Verification focus |-| --- | --- | --- |-| 1. Credential model and guarantee | Shared tenant auth separated from stable host app-user identity; documented modified-client limitation | Same-key A/B tests; same tenant principal |-| 2. Tenant configuration / context | `TenantCredentialSource`, immutable `SessionContext`, policy fingerprints, revisions and renewal tickets | Coalesced/out-of-order renewal, external installs, rotation without identity change |-| 3. Session API | `UserSessionManager`, `UserSession`, `UserScope`, logical/opaque `ContentMapping` | Frozen mappings, exact selectors, private clients/providers/transports |-| 4. Central guard | Session/operation lease checks through preparation, retries, signed phases, response and listener delivery | Prompt cancellation with uncooperative I/O; caller token ownership; paused streams |-| 5. Resource identifiers / discovery | Live asset/job handles, restricted fields/counts/errors, durable job rebinding, bounded JSONL provenance | Cross-owner batches, unknown IDs, nested data, stream-only aggregate discovery |-| 6. Account switch / logout | Synchronous invalidation, latest activation ticket, instance-owned idempotent cleanup | A→B→A, late activation, reentrant callbacks, cleanup failure |-| 7. Cache / storage | Owner/policy multipart envelopes, serialized writer fences, public host storage lease | Identical upload contracts, same-owner reopen, stale save/remove, policy narrowing |-| 8. Reuse / host integration | Existing resources/transports reused; Framebase session gateway and exact owner archives | Host identity transitions, safe image bytes, no tenant-key-derived archive |-| 9. Acceptance tests | Focused same-key/session/rotation/storage tests plus existing SDK and example suites | SDK isolation asserted separately from server authorization |--## Docs impact checklist--- Subject changed: tenant credential versus app-user identity; runtime lifecycle,- rotation, provenance/discovery, owner storage, host UI handoff, source release.-- Updated: root README, `sdk_contract.md`, `manage_api_key.md`, Framebase userlogin- README, and this implementation note.-- Neighboring references checked: public API exports, config/provider/session/- guard/resource implementations, Framebase credential/controller/gateway/archive- contracts, existing package-install and source-publication guidance.-- Removed stale claims in touched docs: `auth.me()` as app-user owner, guaranteed- per-user bearer authorization under a shared tenant key, scope-only archives,- write grants implying collection-wide deletion, unrestricted session result- URLs, and tenant `401` meaning Firebase logout.-- Existing low-level examples remain labeled tenant-scoped; they bypass the- session guarantees. Published pub.dev `1.2.3`/tag install examples remain- distinct from the new 1.3.0 source-only interface.--## Validation and publication--Local gates from the SDK root are `bash build.sh pub_get`, `bash build.sh format`,-`bash build.sh analyze`, `bash test.sh all`, and the pinned Dart command-`run tool/check_route_sync.dart`. They cover every SDK/example test suite,-formatting, analysis, package export, secret checks, simulation, and upstream-route synchronization. GitHub Actions separately gates Android/iOS builds and-the production live lifecycle before public publication. Focused session/guard/provider/-storage and Framebase suites cover deterministic account-switch and rotation-races. These are offline SDK-flow checks, not evidence of server-side app-user-authorization.--Final local results: all 207 SDK tests and all five example suites pass, including-53 Framebase tests. Formatting and analysis pass across the SDK and examples;-all 42 upstream route operations match. Package validation reports zero warnings,-secret detection reports zero leaks, simulation passes, and generated reference-validation verifies 1,011 sanitized source sections. The public revision is-recorded by the release change and GitHub Actions run. Public source publication uses-`.github/workflows/sdk_flutter_test_release.yml`; only its successful export-establishes the released public commit. This task does not publish a pub.dev-package or create a pub.dev version tag.--Storage coordination is guaranteed within one isolate. Shared files across-isolates/processes require one storage owner or a transactional lock. Signed-capabilities have independent revocation/expiry. Host UI caches, navigation,-players, copied files, and already delivered data require host cleanup; server-work already accepted remains owned by its originating user.--Framebase clears decoded image caches and replaces its navigation tree using-the SDK runtime session identity. Recording sheets retire their player on-invalidation; file selection and confirmation dialogs capture that same-identity before awaiting so a later activation cannot consume an earlier view's-decision.diff --git a/example/05_framebase_userlogin/README.md b/example/05_framebase_userlogin/README.mdindex d16aa13..d959295 100644--- a/example/05_framebase_userlogin/README.md+++ b/example/05_framebase_userlogin/README.md@@ -71,6 +71,110 @@ service namespace and tenant/principal binding, then opens a SDK session withthe Firebase UID as `appUserId`. `SearchGateway.connect()` uses`session.verifyPrincipal(...)` for the optional tenant-principal check.+### User-auth components and responsibilities++There are two authentication contexts. Firebase identifies the person using+the app; the VModal bearer identifies the tenant principal making cloud calls.+The trusted issuer connects the verified person to an allowed library policy.+For example, Firebase users A and B can receive the same `api_token` and+`vmodal_user_id`, but different `firebase_uid` and `scope_id` values. Their+SDK sessions and local archives remain separate.++| Component | Owner / location | Responsibility |+| --- | --- | --- |+| `FirebaseAuthAdapter` | Host app; [auth_adapter.dart](lib/user/auth_adapter.dart) | Implements `signIn`, `signOut`, nullable `users` events, and `idToken(AppUser)`. Translates token-acquisition failures into `FirebaseIdentityExpired` or `FirebaseIdentityTransient`. |+| Trusted issuer / policy resolver | Host backend; production integration required | Verifies the Firebase token, derives the authenticated UID, authorizes library access, and returns the bound tenant credential, exact scope, permissions, and expiry. It is the authority for the envelope. |+| `VmodalCredentialSource` | Host issuer client; [vmodal_credential.dart](lib/user/vmodal_credential.dart) | Implements `acquire(AppUser, String? firebaseIdToken)` against the trusted issuer and classifies identity rejection, policy denial, temporary failure, and invalid responses. This example supplies a mock implementation. |+| `VmodalCredential` | App contract model; same file | Parses the version-1 envelope and validates UID agreement, required fields, scope syntax, permission, expiry, and tenant/principal continuity during renewal. These local checks do not verify a Firebase token or establish server authorization. |+| `UserSessionController` | App orchestration; [user_session_controller.dart](lib/user/user_session_controller.dart) | Subscribes to identity changes, retires outgoing data state, acquires and validates credentials, builds SDK policy, connects the library, and exposes readiness/failure state to the UI. Owns renewal scheduling, bounded issuer retries, and activation-generation checks. |+| `TenantCredentialSource` | SDK; [api_key_provider.dart](../../lib/src/api_key_provider.dart) | Coordinates accepted tenant-key revisions and renewal across live session providers. Checks service/tenant/principal binding and fences stale renewal results. It supplies credentials to transport; it does not sign in the app user. |+| `UserSessionManager`, `UserSession`, `UserScope` | SDK; [user_session.dart](../../lib/src/user_session.dart) | Freeze the resolved app-user identity and content policy, create a fresh runtime session, and guard requests, callbacks, handles, and storage leases against invalidation. |+| `SearchGateway` | App cloud adapter; [search_gateway.dart](lib/data/search_gateway.dart) | Wraps session-bound library operations, calls the host freshness callback, verifies the tenant principal during `connect`, and reports `401`/`403` to the controller. This Dart class is distinct from the remote VModal gateway. |+| `ArchiveController` | App storage; [archive_controller.dart](lib/data/archive_controller.dart) | Activates only the resolved owner's archive, validates persisted ownership/policy, commits through the scope's storage lease, and retires local work when deactivated. |+| `FramebaseApp` and its views | App UI; [main.dart](lib/main.dart) | Display sign-in/recovery/denial states, clear decoded image caches on runtime-session changes, replace navigation state, and fence dialogs, playback, and asynchronous view updates. |++`VmodalCredentialSource` and `TenantCredentialSource` are separate objects.+The first retrieves the host envelope; the second manages the accepted VModal+key inside the SDK. Neither replaces the host identity provider. The remote+VModal gateway verifies the tenant bearer and routes cloud calls; `auth.me()`+reports that principal rather than the Firebase user.++Email/password belong to the host sign-in flow. The Firebase ID token goes+to the issuer client, while SDK gateway calls use the tenant VModal bearer.+`auth.me()` does not exchange a Firebase token, and neither issuer nor runtime+session IDs are bearer credentials. Credentials remain in memory and are+excluded from the owner archive.++### Activation handoff++1. The UI calls `UserSessionController.signIn`. The auth adapter performs+ sign-in and emits the resulting `AppUser` through `users`.+2. On an identity change, the controller advances its generation, invalidates+ the outgoing SDK session, and deactivates the archive before awaiting new+ credentials. A null user leaves the app signed out.+3. The controller obtains `auth.idToken(user)`, calls+ `credentials.acquire(user, token)`, and validates the returned envelope+ against that same user and the current clock. Late results from an older+ generation cannot activate a library.+4. The controller configures the tenant source and opens a SDK session using+ the verified UID as `appUserId`. It converts issuer permissions into a+ frozen opaque mapping for the exact `scope_id` and `street_study` stream.+5. `SearchGateway.connect(vmodal_user_id)` verifies the tenant principal and+ discovers usable index metadata and, when permitted, jobs. The archive+ then activates with the SDK's service/tenant/app-user/policy context.+6. Only after connection and archive activation complete does the controller+ publish `SessionState.ready`. UI read/write controls also check the+ envelope's corresponding permission.++The issuer's `session_id` identifies its envelope. The SDK's `sessionId`+identifies one runtime activation, while the controller's generation fences+its own asynchronous work. Stable Firebase UID and owner keys identify+persisted data. These values serve different lifecycle responsibilities.++### Expiry, failures, and sign-out ownership++The controller schedules renewal 60 seconds before envelope expiry, and+`SearchGateway` checks `ensureFresh()` before cloud operations. A renewal+acquires a current Firebase token and a fresh issuer envelope. An unchanged+policy installs through the tenant source; a changed scope or permission set+retires the outgoing session and resolves a new one.++| Event | Controller behavior | Integration responsibility |+| --- | --- | --- |+| Temporary Firebase token or issuer failure | Up to three acquisition attempts, with 250 ms and 500 ms backoff; exhaustion enters `recoverable` and gates operations | Adapter/source must use the typed transient exceptions; UI offers `retry()` |+| Rejected or expired Firebase identity | Deactivates private data and enters `error` with `firebaseIdentityExpired` | Host requires fresh sign-in; tenant-key rotation cannot repair app identity |+| Issuer policy denial or VModal `403` | Deactivates private data and enters `denied` | Host resolves authorization with the issuer; a broader key is not a fallback |+| Invalid envelope, UID mismatch, or invalid connection contract | Deactivates private data and enters `error` with `contract` | Correct the adapter/issuer contract before allowing library activation |+| VModal `401` / tenant-auth failure | Enters tenant-connection recovery while retaining the authenticated Firebase UID; retry renews an established connection or resolves a fresh one | Keep tenant recovery separate from Firebase sign-out; mutations are not automatically replayed |+| Explicit sign-out | Retires SDK/archive state and publishes `signedOut` before awaiting `auth.signOut()` | Auth adapter ends host sign-in; UI clears visible state; owner-local files remain available for later verified restoration |++### Connecting production user auth++The default app constructs `MockFirebaseAuth` and+`MockVmodalCredentialSource`. The auth mock returns no ID token and performs+no real password verification; the credential mock only returns queued+fixtures. Mock success demonstrates the local flow, not verified identity.++Implement the two host interfaces, then inject them into+`UserSessionController(auth: ..., credentials: ..., archive: ...)` and pass+that controller to `FramebaseApp(session: ..., controller: ...)`, using the+same archive instance. A production credential source must require a usable+host token and obtain the envelope from the trusted issuer; an arbitrary+caller-supplied UID is not identity proof. No production issuer URL, Firebase+configuration, or server verifier is supplied by this example.++When the embedding host supplies these controllers, it owns their disposal;+`FramebaseApp` disposes only instances it creates itself. The session+controller's `dispose()` retires SDK state, closes the tenant coordinator,+cancels its auth subscription, and closes the auth adapter. The host must+also dispose its archive controller.++See [component coupling diagrams](../../docs/diagrams.md),+[the session contract](../../docs/sdk_contract.md), and+[tenant credential management](../../docs/manage_api_key.md) for the SDK+boundaries. Server enforcement requirements are described below under+[SDK isolation and server authorization](#sdk-isolation-and-server-authorization).+## 2. Discover collections and indexing work`scope_id` stays unchanged as backend `group_name`; the app never prefixes it@@ -201,8 +305,8 @@ bind an app-user identity to requests can expect A's raw request for B's resourcto return `403` or a non-enumerating `404`. This same-key example and its offlinetests demonstrate SDK isolation, not those server authorization guarantees.-See [the SDK contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/sdk_contract.md)-and [tenant key management](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/manage_api_key.md).+See [the SDK contract](../../docs/sdk_contract.md)+and [tenant key management](../../docs/manage_api_key.md).## Code map and verificationdiff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dartindex e287ff9..97fee4b 100644--- a/test/regression_manifest_test.dart+++ b/test/regression_manifest_test.dart@@ -213,16 +213,35 @@ void main() {'example/05_framebase_userlogin/lib/data/archive_controller.dart','example/05_framebase_userlogin/test/user_session_controller_test.dart','docs/search_app.md',+ 'docs/diagrams.md','docs/sdk_doc.md','docs/manage_api_key.md','docs/sdk_contract.md',- 'docs/user_session_implementation.md',+ 'docs/README.md',+ 'docs/component_patterns.md',]) {expect(File('${dir.path}/$path').existsSync(), isTrue, reason: path);}final exampleReadme = File('${dir.path}/example/01_full_app/README.md',).readAsStringSync();+ for (final guide in <String>[+ 'docs/README.md',+ 'docs/component_patterns.md',+ ]) {+ final content = File('${dir.path}/$guide').readAsStringSync();+ for (final match in RegExp(r'\]\(([^)]+)\)').allMatches(content)) {+ final target = match.group(1)!;+ if (target.contains('://') || target.startsWith('#')) continue;+ final relative = target.split('#').first;+ final resolved = File('${dir.path}/$guide').uri.resolve(relative);+ expect(+ File.fromUri(resolved).existsSync(),+ isTrue,+ reason: '$guide links to missing export: $target',+ );+ }+ }final searchGuide = File('${dir.path}/docs/search_app.md',).readAsStringSync();