diff --git a/.agents/skills/minos-quality-gate/SKILL.md b/.agents/skills/minos-quality-gate/SKILL.md new file mode 100644 index 00000000..cd1b6f4d --- /dev/null +++ b/.agents/skills/minos-quality-gate/SKILL.md @@ -0,0 +1,95 @@ +--- +name: minos-quality-gate +description: Run and remediate Minos CI-equivalent quality gates for a completed change. Use after any code, test, schema, codegen, dependency, configuration, documentation, comment, rename, or deletion change and before every commit, push, PR update, or handoff; use again when addressing a CI failure. +--- + +# Minos local quality gate + +Use this as the required final phase of a change. CI confirms a locally green +change; it is not a discovery loop. Do not hand off, commit, or push while a +selected gate has failed, been skipped by a missing prerequisite, or has not +been run. + +`docs/ci-gates.md` is the local-gate contract. Read it before selecting +commands. Inspect `.github/workflows/ci.yml` for CI-only setup and exact steps +such as SQLx metadata, the mobile code-generator, or the macOS desktop check. +If the two disagree, resolve the current contract at its owner and update the +documentation in the same change; do not invent a third command list here. + +## 1. Determine the final change surface + +Inspect the complete working tree, including staged and untracked files: + +```bash +git status --short +git diff --name-only +git diff --cached --name-only +git ls-files --others --exclude-standard +``` + +Classify every in-scope changed path, including deletions, generated files, +comments, and renames. Do not validate only the last file edited. Preserve +unrelated user changes; a whole-tree gate can expose their failure, but do not +silently fix or discard them. Report such a failure as not green rather than +claiming the task passed. + +Changes to a comment, a name, or a deleted file retain the gate of their source +language/surface. For example, a Rust doc-comment change can require rustfmt, +clippy, or FRB regeneration; a Desktop rename still requires the file-size +gate. + +## 2. Run every applicable gate + +Use the composite commands below rather than substituting a convenient subset. +They preserve the CI phase order and, for Rust, `clippy --keep-going`. + +| Changed surface | Required local evidence | +| --- | --- | +| Rust workspace: root Cargo files, `crates/**`, `xtask/**`, `schemas/**`, migrations, `.sqlx/**`, `justfile` | `cargo xtask check-rust`. This includes fmt, naming/docs lints, backend platform-contract drift, schema parity, clippy with warnings denied, workspace tests, and daemon `test-support` tests. For `minos-backend`, migrations, SQL queries, or `.sqlx`, also reproduce the workflow's `cargo sqlx prepare --check --workspace -- -p minos-backend --all-targets` step with its SQLite `DATABASE_URL`; install the workflow-pinned `sqlx-cli` first if necessary. Run `just check-backend-pg` for migration/storage-parity changes when its local Postgres prerequisite is available. | +| Desktop TypeScript, Desktop config/dependencies, or `apps/desktop/src-tauri/**` | `cd apps/desktop && pnpm check:all`; on macOS also run `cargo check -p minos-desktop`. `check:all` is mandatory because it includes tests, Biome, file-size, and px-text gates. If the dependency manifest or lockfile changed, first use `pnpm install --frozen-lockfile`. | +| Web TypeScript/config/dependencies under `apps/web/**` | `cd apps/web && pnpm check`. If the dependency manifest or lockfile changed, first use `pnpm install --frozen-lockfile`. | +| Mobile Dart, mobile dependencies, FRB config, `minos-mobile`, or `minos-ffi-frb` | Run `cargo xtask check-all` after confirming that `fvm` and `flutter_rust_bridge_codegen` are available; do not count its toolchain-dependent skip as a pass. Also reproduce the mobile CI sequence from `.github/workflows/ci.yml`: `flutter pub get`; `dart run build_runner build --delete-conflicting-outputs`; `dart format --set-exit-if-changed lib test`; `dart analyze --fatal-warnings`; and `flutter test --exclude-tags ffi`. Use the workflow's temporary plugin-disable step for analysis, not a permanent `analysis_options.yaml` edit. Regenerate FRB with `cargo xtask gen-frb` (or the workflow command) and verify a second generation produces no change. | +| Backend platform contract/OpenAPI/WebSocket schema | `cargo xtask check-rust`; its static phase runs `gen-backend-platform-contract --check`. Do not manually edit generated artifacts to mask drift. | +| Project documentation or agent instructions only | `cargo xtask lint-docs` when documentation paths are affected. For a skill change, run that skill's declared validator as well. | + +For a cross-surface change, run the union of rows. `cargo xtask check-all` is +the preferred aggregate on a prepared macOS/mobile machine, but it does not +replace `pnpm check:all` for Desktop or `pnpm check` for Web. + +Before running FRB drift against Git, distinguish intended generated edits from +new generator output: generate once, include the intended artifacts in the +change, then generate again. The second run must leave the generated roots +unchanged. On a clean final commit, also run the workflow's `git diff +--exit-code` check for `apps/mobile/lib/src/rust` and +`crates/minos-ffi-frb/src/frb_generated.rs`, plus check for untracked output. + +## 3. Fix and re-run to green + +Treat every failure as a defect in the final change until evidence proves it is +an unrelated pre-existing worktree issue. Trace the owning code or contract, +make the smallest correct repair, regenerate committed artifacts when required, +and re-run the failed gate. Then re-run all selected composite gates so an +earlier failure does not hide a later one. Do not waive a lint, loosen an +allowlist, suppress a test, or leave generated drift merely to make a gate +green. + +If a required platform/toolchain is unavailable, install/use the repository's +pinned prerequisite when that is in scope. Otherwise report the gate as +unavailable and request the needed environment; do not call the work complete +or imply that CI will cover it. + +## 4. Hand off with evidence + +State the complete change surfaces and each selected command with its exit +result. Mark non-applicable gates as `not applicable` with the path-based +reason. List any unavailable gate or unrelated worktree failure explicitly. +Only describe the change as complete when every applicable gate exited zero. + +Example: + +```text +Quality gates +- Rust workspace + backend contract: cargo xtask check-rust — passed +- Desktop: apps/desktop pnpm check:all — passed +- Mobile/Web: not applicable (no paths changed) +``` diff --git a/.agents/skills/minos-quality-gate/agents/openai.yaml b/.agents/skills/minos-quality-gate/agents/openai.yaml new file mode 100644 index 00000000..0faeafe8 --- /dev/null +++ b/.agents/skills/minos-quality-gate/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Minos Quality Gate" + short_description: "Run CI-equivalent checks before handoff" + default_prompt: "Use $minos-quality-gate to verify this Minos change before handoff." diff --git a/AGENTS.md b/AGENTS.md index 08eefcea..fb12225c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,7 +90,8 @@ Documentation is a maintained product surface, not a record of agent activity. K ## Verification and completion -- Do not declare work complete without evidence. Compare behavior with the base branch when relevant, run the applicable quality gates, inspect meaningful logs or errors, and report the results. +- Use the project [minos-quality-gate](.agents/skills/minos-quality-gate/SKILL.md) skill as the mandatory final phase of every code, test, schema, codegen, dependency, configuration, documentation, comment, rename, or deletion change. Before any commit, push, PR update, or handoff, classify the complete changed surface, run every selected CI-equivalent local gate, repair failures, and re-run to green. CI confirms this evidence; it must not be the first place an agent discovers formatting, lint, codegen, contract, file-size, or test failures. +- Do not declare work complete without evidence. Compare behavior with the base branch when relevant, run the applicable quality gates, inspect meaningful logs or errors, and report the exact commands and results. Explicitly mark only path-based non-applicable gates; a missing toolchain/platform or an unrun required gate is a blocker, not a passing result. - Review completed work adversarially: trace the broader call chain, state, lifecycle, and failure modes for unexpected behavior. Find the root cause rather than only the reported symptom, then proactively inspect and correct analogous paths to preserve whole-codebase correctness. - Unit tests cover isolated business rules, state changes, parsing, validation, serialization, and error handling. Mock external systems; do not label UI, network, database, filesystem, device, or end-to-end flows as unit tests. - Keep integration and UI coverage separate, and run the relevant test command before handoff. diff --git a/apps/mobile/ARCHITECTURE.md b/apps/mobile/ARCHITECTURE.md index fb22b935..d78d7cf5 100644 --- a/apps/mobile/ARCHITECTURE.md +++ b/apps/mobile/ARCHITECTURE.md @@ -3,6 +3,10 @@ This document describes the layered architecture of the Minos mobile app, following the [Flutter Architecture Best Practices](.agents/skills/flutter-apply-architecture-best-practices/SKILL.md). +Product spine: **conversation-first collaboration IM**. Shell tabs are +Messages / Hosts / Account. Agent session transcript, projects, sessions +inbox, and Agents Hub were removed from the Mobile product surface. + ## Directory Structure ``` @@ -11,11 +15,10 @@ lib/ ├── architecture.dart # Architecture overview (dartdoc) │ ├── domain/ # Domain Layer (pure Dart) -│ ├── models.dart # Barrel export for all domain models +│ ├── models.dart # Barrel export for domain models │ ├── minos_core_protocol.dart # Abstract service contract (DI boundary) -│ ├── active_session.dart # Agent session state machine │ ├── auth_state.dart # Auth lifecycle states -│ ├── agent_profile.dart # Agent configuration model +│ ├── agent_profile.dart # Local bot cache / draft model │ ├── social_message.dart # Chat message model │ ├── group_member.dart # Group membership model │ └── minos_error_display.dart # Error presentation helpers @@ -23,47 +26,48 @@ lib/ ├── infrastructure/ # Data Layer — Services │ ├── minos_core.dart # Rust FFI bridge (implements MinosCoreProtocol) │ ├── secure_pairing_store.dart# Keychain persistence -│ ├── social_cache_store.dart # SQLite message cache +│ ├── social_cache_store.dart # SQLite message cache + outbox SQL +│ ├── im_outbox_store.dart # Outbox policy helpers │ ├── agent_profile_store.dart # JSON file persistence -│ ├── app_paths.dart # Platform path resolution -│ └── workspace_mru_store.dart # MRU workspace persistence +│ └── app_paths.dart # Platform path resolution │ -├── data/ # Data Layer — Repositories (barrel exports) -│ ├── repositories/ -│ │ └── repositories.dart # Re-exports repository providers -│ └── services/ -│ └── services.dart # Re-exports infrastructure services +├── data/ # Data Layer — Repositories / services +│ ├── repositories/ # Concrete repository providers + adapters +│ └── services/ # Concrete service/store providers │ ├── application/ # Application Layer — ViewModels (Riverpod) -│ ├── minos_providers.dart # Core data providers (repository role) +│ ├── minos_providers.dart # Connection / hosts / presence │ ├── auth_provider.dart # Auth state controller -│ ├── active_session_provider.dart # Agent session lifecycle -│ ├── thread_events_provider.dart # Live event stream -│ ├── thread_list_provider.dart # Session list data -│ ├── project_providers.dart # Project CRUD + selection -│ ├── social_providers.dart # Social chat state management -│ ├── agent_profiles_provider.dart # Agent profile CRUD -│ ├── group_agent_provider.dart # Group agent bindings -│ ├── group_agent_dispatcher.dart # Agent mention dispatch +│ ├── social/ # Conversation IM feature modules +│ │ ├── social_conversation_state.dart # freezed timeline state +│ │ ├── social_conversation_notifier.dart +│ │ ├── social_inbox_notifier.dart +│ │ ├── social_chat_view_model.dart # feature ViewModel +│ │ ├── social_chat_actions.dart # intentful actions +│ │ ├── social_ui_state.dart +│ │ ├── social_friends_providers.dart +│ │ └── social_realtime_sync.dart +│ ├── social_providers.dart # Compatibility barrel for social/* +│ ├── im_outbox_worker.dart # Local IM outbox drain +│ ├── agent_profiles_provider.dart # Local bot cache for compose +│ ├── agent_conversation_actions.dart # Create agent conversation +│ ├── group_agent_provider.dart # Participants / mention roster +│ ├── social_actions.dart # DM / group create actions │ ├── preferred_agent_provider.dart # Preferred agent selection +│ ├── ui_state_providers.dart # Shell tab + login form state │ ├── log_records_provider.dart # Debug log mirror │ ├── request_trace_records_provider.dart # Request trace mirror │ └── root_route_decision.dart # Navigation decision logic │ -├── data/ -│ ├── repositories/ # Concrete repository providers + adapters -│ └── services/ # Concrete service/store providers -│ -├── ui/ # UI Layer — Feature-organized implementation +├── ui/ # UI Layer — Feature-organized implementation │ ├── core/ │ │ └── widgets/widgets.dart # Shared widget exports │ └── features/ │ ├── auth/ # Auth screens/widgets + barrel -│ ├── chat/ # Agent session screens/widgets + barrel -│ ├── projects/ # Project screens/widgets + barrel -│ ├── agents/ # Agent management screens/widgets + barrel -│ ├── social/ # Social screens/widgets + barrel -│ ├── pairing/ # Pairing screens/widgets + barrel +│ ├── messages/ # Conversation inbox (primary tab) +│ ├── social/ # Conversation chat / members + chrome +│ ├── hosts/ # Linked hosts list +│ ├── account/ # Profile / logout │ ├── debug/ # Debug screens/widgets + barrel │ └── shell/ # Root app shell, router, navigation │ @@ -82,12 +86,15 @@ lib/ - `data/services/` contains provider-backed service/store access used by repositories. - `infrastructure/` contains raw concrete implementations such as `MinosCore` and persistence stores. - `MinosCore` implements `MinosCoreProtocol`; FRB remains isolated to infrastructure/generated code. +- `RealtimeEventsRepository` exposes Account `uiEvents` only (snapshot/presence/notices). Thread/project/agent-session compose APIs are not part of the Mobile contract. ### Application Layer (`lib/application/`) -- Riverpod providers acting as ViewModels. -- Manages UI state, handles user interactions, orchestrates data flow. +- Riverpod providers acting as ViewModels (codegen `@riverpod` preferred). +- Per-feature aggregation: UI watches feature ViewModels (e.g. `SocialChatViewModel`) and calls Action facades instead of many fine-grained providers. +- Complex timeline state uses freezed immutable models (`SocialConversationState`). - Depends on `domain/` models and `data/repositories/`, never on `ui/` or `infrastructure/` directly. - Root dependency injection happens in `main()` by overriding `minosCoreServiceProvider`. +- Collaboration send path: `SocialChatActions` → `SocialConversation` → outbox → `sendChatMessage`. ### UI Layer (`lib/ui/`) - `ui/` contains the actual widget implementations and feature barrels. @@ -107,6 +114,20 @@ Repositories coordinate service/store access while preserving domain-facing APIs The Infrastructure layer implements domain protocols and low-level persistence. No circular dependencies exist between layers. +## Routes (IM-first) + +| Route | Page | Purpose | +|-------|------|---------| +| `/splash` | splash | bootstrap | +| `/login` | `LoginPage` | auth | +| `/` | `AppShellPage` | Messages / Hosts / Account | +| `/social` | redirect → `/` | legacy inbox deep link | +| `/social/chat/:conversationId` | `SocialChatPage` | conversation timeline | +| `/social/chat/:conversationId/members` | `GroupMembersPage` | members | +| `/log-viewer` | `LogViewerPage` | debug | + +Removed from product: `/thread/*`, `/sessions`, `/agent-start`, `/agent-profile/*`, `/project/*`. + ## Adding a New Feature 1. Define domain models in `lib/domain/` (if new entities are needed). diff --git a/apps/mobile/lib/application/active_session_provider.dart b/apps/mobile/lib/application/active_session_provider.dart deleted file mode 100644 index 3c0d8470..00000000 --- a/apps/mobile/lib/application/active_session_provider.dart +++ /dev/null @@ -1,179 +0,0 @@ -import 'dart:async'; - -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/data/repositories/thread_repository.dart'; -import 'package:minos/domain/active_session.dart'; -import 'package:minos/src/rust/api/minos.dart' - show - AgentName, - MinosError, - UiEventFrame, - UiEventMessage_Error, - UiEventMessage_MessageCompleted, - UiEventMessage_SessionClosed; -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'active_session_provider.g.dart'; - -/// Drives the [ActiveSession] state machine off `core.uiEvents` and -/// the explicit `send/stop` actions. -/// -/// While in [SessionSending] we bind the in-flight conversation to the -/// first UI frame that arrives, because the send path no longer returns a -/// daemon-issued `session_id` synchronously. -@Riverpod(keepAlive: true) -class ActiveSessionController extends _$ActiveSessionController { - StreamSubscription? _eventsSub; - - @override - ActiveSession build() { - _eventsSub = ref - .watch(threadRepositoryProvider) - .uiEvents - .listen(_onUiEvent); - ref.onDispose(() => _eventsSub?.cancel()); - return const SessionIdle(); - } - - void _onUiEvent(UiEventFrame frame) { - final s = state; - if (s is SessionSending) { - state = _nextStateForFrame( - frame, - sessionId: frame.sessionId, - agent: s.agent, - ); - return; - } - if (s is! SessionStreaming || s.sessionId != frame.sessionId) return; - - state = _nextStateForFrame(frame, sessionId: s.sessionId, agent: s.agent); - } - - ActiveSession _nextStateForFrame( - UiEventFrame frame, { - required String sessionId, - required AgentName agent, - }) { - switch (frame.ui) { - case UiEventMessage_MessageCompleted(): - return SessionAwaitingInput(sessionId: sessionId, agent: agent); - case UiEventMessage_SessionClosed(): - return SessionSuspended(sessionId: sessionId, agent: agent); - case UiEventMessage_Error(:final message): - return SessionError( - sessionId: sessionId, - error: MinosError.agentStartFailed(reason: message), - ); - default: - return SessionStreaming(sessionId: sessionId, agent: agent); - } - } - - /// Dispatch a user message. - /// - /// When the current state already carries a `session_id`, a successful send - /// immediately re-enters [SessionStreaming]. Brand-new conversations stay in - /// [SessionSending] until the first matching UI frame binds the session id. - Future send({ - required AgentName agent, - required String text, - required Future Function() dispatch, - }) async { - final previous = state; - logFlutterInfo( - 'active_session', - 'send started agent=$agent textLength=${text.length} previous=${previous.runtimeType}', - ); - state = SessionSending(agent: agent, text: text); - try { - await dispatch(); - final sessionId = switch (previous) { - SessionStreaming(sessionId: final t) => t, - SessionAwaitingInput(sessionId: final t) => t, - SessionSuspended(sessionId: final t) => t, - SessionError(sessionId: final t?) => t, - _ => null, - }; - if (sessionId != null) { - state = SessionStreaming(sessionId: sessionId, agent: agent); - } - logFlutterDebug( - 'active_session', - 'send dispatched agent=$agent sessionId=${sessionId ?? ''}', - ); - return null; - } on MinosError catch (e, stackTrace) { - logFlutterError( - 'active_session', - 'send failed agent=$agent', - error: e, - stackTrace: stackTrace, - ); - state = _restoreAfterSendFailure(previous, e); - return e; - } - } - - ActiveSession _restoreAfterSendFailure( - ActiveSession previous, - MinosError error, - ) { - return switch (previous) { - SessionStreaming(sessionId: final t, agent: final a) => SessionStreaming( - sessionId: t, - agent: a, - ), - SessionAwaitingInput(sessionId: final t, agent: final a) => - SessionAwaitingInput(sessionId: t, agent: a), - SessionSuspended(sessionId: final t, agent: final a) => SessionSuspended( - sessionId: t, - agent: a, - ), - SessionError(sessionId: final t?, :final error) => SessionError( - sessionId: t, - error: error, - ), - _ => SessionError(error: error), - }; - } - - /// Best-effort interrupt. Failures preserve the current `session_id` in a - /// [SessionError] so the UI can still recover. - Future stop() async { - final s = state; - final (String? sessionId, AgentName? agent) = switch (s) { - SessionStreaming(sessionId: final t, agent: final a) => (t, a), - SessionAwaitingInput(sessionId: final t, agent: final a) => (t, a), - _ => (null, null), - }; - if (sessionId == null || agent == null) return; - - try { - await ref - .read(threadRepositoryProvider) - .interruptThread(sessionId: sessionId); - state = SessionSuspended(sessionId: sessionId, agent: agent); - logFlutterInfo( - 'active_session', - 'stop succeeded sessionId=$sessionId agent=$agent', - ); - } on MinosError catch (error, stackTrace) { - logFlutterError( - 'active_session', - 'stop failed sessionId=$sessionId agent=$agent', - error: error, - stackTrace: stackTrace, - ); - state = SessionError(sessionId: sessionId, error: error); - return; - } - } - - /// Clear any thread-bound session state before routing the user into a - /// fresh chat composer. - void reset() { - logFlutterDebug('active_session', 'session reset to idle'); - state = const SessionIdle(); - } -} diff --git a/apps/mobile/lib/application/active_session_provider.g.dart b/apps/mobile/lib/application/active_session_provider.g.dart deleted file mode 100644 index ceb6c096..00000000 --- a/apps/mobile/lib/application/active_session_provider.g.dart +++ /dev/null @@ -1,88 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'active_session_provider.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning -/// Drives the [ActiveSession] state machine off `core.uiEvents` and -/// the explicit `send/stop` actions. -/// -/// While in [SessionSending] we bind the in-flight conversation to the -/// first UI frame that arrives, because the send path no longer returns a -/// daemon-issued `session_id` synchronously. - -@ProviderFor(ActiveSessionController) -final activeSessionControllerProvider = ActiveSessionControllerProvider._(); - -/// Drives the [ActiveSession] state machine off `core.uiEvents` and -/// the explicit `send/stop` actions. -/// -/// While in [SessionSending] we bind the in-flight conversation to the -/// first UI frame that arrives, because the send path no longer returns a -/// daemon-issued `session_id` synchronously. -final class ActiveSessionControllerProvider - extends $NotifierProvider { - /// Drives the [ActiveSession] state machine off `core.uiEvents` and - /// the explicit `send/stop` actions. - /// - /// While in [SessionSending] we bind the in-flight conversation to the - /// first UI frame that arrives, because the send path no longer returns a - /// daemon-issued `session_id` synchronously. - ActiveSessionControllerProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'activeSessionControllerProvider', - isAutoDispose: false, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$activeSessionControllerHash(); - - @$internal - @override - ActiveSessionController create() => ActiveSessionController(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(ActiveSession value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } -} - -String _$activeSessionControllerHash() => - r'a9478de6ba8652ae84cde6bcaf948fe8156f2691'; - -/// Drives the [ActiveSession] state machine off `core.uiEvents` and -/// the explicit `send/stop` actions. -/// -/// While in [SessionSending] we bind the in-flight conversation to the -/// first UI frame that arrives, because the send path no longer returns a -/// daemon-issued `session_id` synchronously. - -abstract class _$ActiveSessionController extends $Notifier { - ActiveSession build(); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - ActiveSession, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} diff --git a/apps/mobile/lib/application/agent_activity_provider.dart b/apps/mobile/lib/application/agent_activity_provider.dart deleted file mode 100644 index f7200e9c..00000000 --- a/apps/mobile/lib/application/agent_activity_provider.dart +++ /dev/null @@ -1,423 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:minos/application/display_payload_preview.dart'; -import 'package:minos/application/group_agent_provider.dart'; -import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/thread_events_provider.dart'; -import 'package:minos/data/repositories/social_repository.dart'; -import 'package:minos/domain/agent_profile.dart'; -import 'package:minos/infrastructure/platform_int64.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -enum AgentActivityKind { running, reasoning, tool, success, error } - -enum AgentActivityTone { info, success, error } - -class AgentActivitySnapshot { - const AgentActivitySnapshot({ - required this.sessionId, - required this.label, - required this.kind, - required this.tone, - }); - - final String sessionId; - final String label; - final AgentActivityKind kind; - final AgentActivityTone tone; -} - -final conversationAgentSessionsProvider = FutureProvider.autoDispose - .family, String>((ref, conversationId) { - return ref - .watch(socialRepositoryProvider) - .listAgentSessions(conversationId: conversationId, limit: 5); - }); - -final conversationAgentActivityProvider = Provider.autoDispose - .family, String>((ref, conversationId) { - final sessionsAsync = ref.watch( - conversationAgentSessionsProvider(conversationId), - ); - final sessions = sessionsAsync.asData?.value; - if (sessions == null) { - if (sessionsAsync.hasError) { - return const AsyncValue.data(null); - } - return const AsyncValue.loading(); - } - - final session = _latestRunnableSession(sessions); - if (session == null) { - return const AsyncValue.data(null); - } - - final agentOnline = _sessionAgentHostOnline( - session: session, - agents: ref.watch(groupAgentsProvider(conversationId)), - hosts: ref.watch(pairedMacsProvider).asData?.value, - activeHostId: ref.watch(activeMacProvider).asData?.value, - connectionState: ref.watch(connectionStateProvider).asData?.value, - ); - if (!agentOnline) { - return const AsyncValue.data(null); - } - - unawaited( - ref - .read(socialRepositoryProvider) - .subscribeAgentSession(sessionId: session.sessionId), - ); - - final eventsAsync = ref.watch(threadEventsProvider(session.sessionId)); - final events = eventsAsync.asData?.value; - if (events == null) { - if (eventsAsync.hasError) { - return const AsyncValue.data(null); - } - return const AsyncValue.loading(); - } - - final snapshot = agentActivitySnapshotFromEvents( - sessionId: session.sessionId, - events: events, - ); - if (snapshot != null) { - return AsyncValue.data(snapshot); - } - - return const AsyncValue.data(null); - }); - -@visibleForTesting -bool debugSessionAgentHostOnline({ - required AgentSessionSummaryDto session, - required List agents, - required List? hosts, - required String? activeHostId, - required ConnectionState? connectionState, -}) { - return _sessionAgentHostOnline( - session: session, - agents: agents, - hosts: hosts, - activeHostId: activeHostId, - connectionState: connectionState, - ); -} - -AgentActivitySnapshot? agentActivitySnapshotFromEvents({ - required String sessionId, - required List events, -}) { - final roleByMessage = {}; - final completedMessages = {}; - final statusByMessage = {}; - final toolMessageById = {}; - final toolNameById = {}; - String? lastAssistantMessageId; - var sessionClosed = false; - - void markAssistantCandidate(String messageId) { - if (roleByMessage[messageId] == MessageRole.user) return; - roleByMessage.putIfAbsent(messageId, () => MessageRole.assistant); - lastAssistantMessageId = messageId; - } - - void setAssistantStatus(String messageId, AgentActivitySnapshot snapshot) { - if (roleByMessage[messageId] == MessageRole.user) return; - markAssistantCandidate(messageId); - statusByMessage[messageId] = snapshot; - } - - for (final event in events) { - switch (event) { - case UiEventMessage_MessageStarted(:final messageId, :final role): - roleByMessage[messageId] = role; - if (role == MessageRole.assistant) { - lastAssistantMessageId = messageId; - } - case UiEventMessage_TextDelta(:final messageId, :final text): - case UiEventMessage_TextReplace(:final messageId, :final text): - final preview = _statusPreview(text.renderPreview()); - setAssistantStatus( - messageId, - AgentActivitySnapshot( - sessionId: sessionId, - label: preview == null ? '生成回复中' : '生成回复中 · $preview', - kind: AgentActivityKind.running, - tone: AgentActivityTone.info, - ), - ); - case UiEventMessage_ReasoningDelta(:final messageId, :final text): - case UiEventMessage_ReasoningReplace(:final messageId, :final text): - final preview = _statusPreview(text.renderPreview()); - setAssistantStatus( - messageId, - AgentActivitySnapshot( - sessionId: sessionId, - label: preview == null ? '思考中' : '思考中 · $preview', - kind: AgentActivityKind.reasoning, - tone: AgentActivityTone.info, - ), - ); - case UiEventMessage_ToolCallPlaced( - :final messageId, - :final toolCallId, - :final name, - ): - markAssistantCandidate(messageId); - toolMessageById[toolCallId] = messageId; - toolNameById[toolCallId] = name; - setAssistantStatus( - messageId, - AgentActivitySnapshot( - sessionId: sessionId, - label: '调用工具 · $name', - kind: AgentActivityKind.tool, - tone: AgentActivityTone.info, - ), - ); - case UiEventMessage_ToolCallCompleted(:final toolCallId, :final isError): - final messageId = toolMessageById[toolCallId] ?? lastAssistantMessageId; - if (messageId == null) break; - markAssistantCandidate(messageId); - final name = toolNameById[toolCallId] ?? '未知工具'; - setAssistantStatus( - messageId, - AgentActivitySnapshot( - sessionId: sessionId, - label: isError ? '工具失败 · $name' : '工具完成 · $name', - kind: isError ? AgentActivityKind.error : AgentActivityKind.success, - tone: isError ? AgentActivityTone.error : AgentActivityTone.success, - ), - ); - case UiEventMessage_MessageCompleted(:final messageId): - completedMessages.add(messageId); - case UiEventMessage_Error(:final message): - return AgentActivitySnapshot( - sessionId: sessionId, - label: '执行出错 · ${_statusPreview(message) ?? message}', - kind: AgentActivityKind.error, - tone: AgentActivityTone.error, - ); - case UiEventMessage_SessionOpened(): - case UiEventMessage_SessionTitleUpdated(): - break; - case UiEventMessage_SubagentSpawned(:final agent, :final title): - final label = title?.trim().isNotEmpty == true - ? '子 agent · ${agent.name} · ${title!.trim()}' - : '子 agent · ${agent.name}'; - if (lastAssistantMessageId != null) { - setAssistantStatus( - lastAssistantMessageId!, - AgentActivitySnapshot( - sessionId: sessionId, - label: label, - kind: AgentActivityKind.running, - tone: AgentActivityTone.info, - ), - ); - } - case UiEventMessage_SubagentStatusUpdated(:final status): - if (lastAssistantMessageId != null) { - final done = status == SubagentStatus.completed; - final failed = - status == SubagentStatus.failed || - status == SubagentStatus.interrupted; - setAssistantStatus( - lastAssistantMessageId!, - AgentActivitySnapshot( - sessionId: sessionId, - label: done - ? '子 agent 完成' - : failed - ? '子 agent 失败' - : '子 agent 运行中', - kind: failed - ? AgentActivityKind.error - : done - ? AgentActivityKind.success - : AgentActivityKind.running, - tone: failed - ? AgentActivityTone.error - : done - ? AgentActivityTone.success - : AgentActivityTone.info, - ), - ); - } - case UiEventMessage_Raw(:final kind): - if (lastAssistantMessageId != null) { - setAssistantStatus( - lastAssistantMessageId!, - AgentActivitySnapshot( - sessionId: sessionId, - label: '处理事件 · $kind', - kind: AgentActivityKind.running, - tone: AgentActivityTone.info, - ), - ); - } - break; - case UiEventMessage_SessionClosed(): - sessionClosed = true; - } - } - - final liveMessageId = lastAssistantMessageId; - if (sessionClosed || - liveMessageId == null || - completedMessages.contains(liveMessageId)) { - return null; - } - return statusByMessage[liveMessageId]; -} - -bool _sessionAgentHostOnline({ - required AgentSessionSummaryDto session, - required List agents, - required List? hosts, - required String? activeHostId, - required ConnectionState? connectionState, -}) { - final agent = _agentForSession(session, agents); - if (agent != null) { - return _agentHostOnline( - agent: agent, - hosts: hosts, - activeHostId: activeHostId, - connectionState: connectionState, - ); - } - - final knownHosts = hosts ?? const []; - if (knownHosts.isNotEmpty) { - if (activeHostId != null) { - for (final host in knownHosts) { - if (host.hostDeviceId == activeHostId) { - return host.online; - } - } - } - return knownHosts.any((host) => host.online); - } - - return connectionState is ConnectionState_Connected; -} - -AgentProfile? _agentForSession( - AgentSessionSummaryDto session, - List agents, -) { - final agentId = session.agentId; - if (agentId != null) { - for (final agent in agents) { - if (agent.agentId == agentId || agent.id == agentId) { - return agent; - } - } - } - if (agents.length == 1) { - return agents.first; - } - return null; -} - -bool _agentHostOnline({ - required AgentProfile agent, - required List? hosts, - required String? activeHostId, - required ConnectionState? connectionState, -}) { - final knownHosts = hosts ?? const []; - final agentHostId = agent.hostDeviceId; - if (agentHostId != null) { - for (final host in knownHosts) { - if (host.hostDeviceId == agentHostId) { - return host.online; - } - } - return false; - } - - if (activeHostId != null) { - for (final host in knownHosts) { - if (host.hostDeviceId == activeHostId) { - return host.online; - } - } - } - - if (knownHosts.length == 1) { - return knownHosts.first.online; - } - if (knownHosts.isNotEmpty) { - return knownHosts.any((host) => host.online); - } - - return connectionState is ConnectionState_Connected; -} - -AgentSessionSummaryDto? _latestRunnableSession( - List sessions, -) { - final runnable = - sessions.where((session) { - return session.endedAtMs == null && _isRunnableStatus(session.status); - }).toList()..sort((a, b) { - return platformInt64ToInt( - b.lastActivityAtMs, - ).compareTo(platformInt64ToInt(a.lastActivityAtMs)); - }); - if (runnable.isEmpty) return null; - return runnable.first; -} - -/// Statuses that mean a live turn is (or may still be) executing. -/// -/// `idle` is **not** runnable: the session may still be @-able for a new turn, -/// but the activity ticker must hide when the agent is waiting for input. -bool _isRunnableStatus(String status) { - final normalized = status.toLowerCase().trim(); - if (normalized.isEmpty) return false; - // Explicit non-running terminal / waiting states. - const notRunnable = { - 'idle', - 'ended', - 'stopped', - 'failed', - 'completed', - 'cancelled', - 'canceled', - 'closed', - 'pending', // formal session registered but host not executing yet - }; - if (notRunnable.contains(normalized)) return false; - // Positive allow-list for known active statuses (avoids treating unknown - // idle-like strings as running forever). - const runnable = { - 'running', - 'streaming', - 'thinking', - 'tool', - 'working', - 'busy', - 'stopping', // still winding down — keep ticker until MessageCompleted - }; - return runnable.contains(normalized); -} - -/// Exposed for unit tests. -@visibleForTesting -bool debugIsRunnableSessionStatus(String status) => _isRunnableStatus(status); - -String? _statusPreview(String raw) { - final collapsed = raw.replaceAll(RegExp(r'\s+'), ' ').trim(); - if (collapsed.isEmpty) return null; - const maxChars = 56; - if (collapsed.length <= maxChars) return collapsed; - return '${collapsed.substring(0, maxChars - 1)}…'; -} diff --git a/apps/mobile/lib/application/agent_conversation_actions.dart b/apps/mobile/lib/application/agent_conversation_actions.dart index 7f1a06b9..6b1167b4 100644 --- a/apps/mobile/lib/application/agent_conversation_actions.dart +++ b/apps/mobile/lib/application/agent_conversation_actions.dart @@ -1,6 +1,5 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:minos/application/active_session_provider.dart'; import 'package:minos/application/agent_profiles_provider.dart'; import 'package:minos/application/group_agent_provider.dart'; import 'package:minos/application/minos_providers.dart'; @@ -32,7 +31,6 @@ Future createAgentConversation( agentId: serverProfile.agentId, ); - ref.read(activeSessionControllerProvider.notifier).reset(); ref.invalidate(conversationsProvider); ref.invalidate(conversationParticipantsProvider(conversation.conversationId)); diff --git a/apps/mobile/lib/application/agent_editor_state.dart b/apps/mobile/lib/application/agent_editor_state.dart deleted file mode 100644 index 698b9e15..00000000 --- a/apps/mobile/lib/application/agent_editor_state.dart +++ /dev/null @@ -1,146 +0,0 @@ -import 'package:minos/domain/agent_profile.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'agent_editor_state.g.dart'; - -@Riverpod(keepAlive: false) -class AgentEditorDraftController extends _$AgentEditorDraftController { - @override - AgentEditorState build(AgentProfileDraft draft) { - return AgentEditorState(draft: draft); - } - - void updateName(String name) { - state = state.copyWith(draft: state.draft.copyWith(name: name)); - } - - void updateDescription(String description) { - state = state.copyWith( - draft: state.draft.copyWith(description: description), - ); - } - - void setHost({ - required String? hostDeviceId, - required String? hostDisplayName, - }) { - final draft = state.draft; - final workspacePath = hostDeviceId == draft.hostDeviceId - ? draft.workspacePath - : null; - state = state.copyWith( - draft: AgentProfileDraft( - name: draft.name, - description: draft.description, - runtimeAgent: draft.runtimeAgent, - model: draft.model, - reasoningEffort: draft.reasoningEffort, - environmentVariables: draft.environmentVariables, - hostDeviceId: hostDeviceId, - hostDisplayName: hostDisplayName, - workspacePath: workspacePath, - ), - ); - } - - void setWorkspacePath(String? workspacePath) { - final draft = state.draft; - state = state.copyWith( - draft: AgentProfileDraft( - name: draft.name, - description: draft.description, - runtimeAgent: draft.runtimeAgent, - model: draft.model, - reasoningEffort: draft.reasoningEffort, - environmentVariables: draft.environmentVariables, - hostDeviceId: draft.hostDeviceId, - hostDisplayName: draft.hostDisplayName, - workspacePath: workspacePath, - ), - ); - } - - void setRuntime(AgentName runtimeAgent, {required String defaultModel}) { - state = state.copyWith( - draft: state.draft.copyWith( - runtimeAgent: runtimeAgent, - model: defaultModel, - ), - ); - } - - void setModel(String model) { - state = state.copyWith(draft: state.draft.copyWith(model: model)); - } - - void setReasoning(AgentReasoningEffort reasoningEffort) { - state = state.copyWith( - draft: state.draft.copyWith(reasoningEffort: reasoningEffort), - ); - } - - void toggleAdvanced() { - state = state.copyWith(showAdvanced: !state.showAdvanced); - } - - void updateEnvironmentKey(int index, String key) { - final variables = List.of( - state.draft.environmentVariables, - ); - if (index < 0 || index >= variables.length) return; - variables[index] = variables[index].copyWith(key: key); - state = state.copyWith( - draft: state.draft.copyWith(environmentVariables: variables), - ); - } - - void updateEnvironmentValue(int index, String value) { - final variables = List.of( - state.draft.environmentVariables, - ); - if (index < 0 || index >= variables.length) return; - variables[index] = variables[index].copyWith(value: value); - state = state.copyWith( - draft: state.draft.copyWith(environmentVariables: variables), - ); - } - - void removeEnvironmentVariable(int index) { - final variables = List.of( - state.draft.environmentVariables, - ); - if (index < 0 || index >= variables.length) return; - variables.removeAt(index); - state = state.copyWith( - draft: state.draft.copyWith(environmentVariables: variables), - ); - } - - void addEnvironmentVariable() { - state = state.copyWith( - draft: state.draft.copyWith( - environmentVariables: [ - ...state.draft.environmentVariables, - const AgentEnvironmentVariable(key: '', value: ''), - ], - ), - ); - } -} - -class AgentEditorState { - const AgentEditorState({required this.draft, this.showAdvanced = false}); - - final AgentProfileDraft draft; - final bool showAdvanced; - - bool get canSave => draft.name.trim().isNotEmpty; - - AgentEditorState copyWith({AgentProfileDraft? draft, bool? showAdvanced}) { - return AgentEditorState( - draft: draft ?? this.draft, - showAdvanced: showAdvanced ?? this.showAdvanced, - ); - } -} diff --git a/apps/mobile/lib/application/agent_editor_state.g.dart b/apps/mobile/lib/application/agent_editor_state.g.dart deleted file mode 100644 index 2d413468..00000000 --- a/apps/mobile/lib/application/agent_editor_state.g.dart +++ /dev/null @@ -1,110 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'agent_editor_state.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning - -@ProviderFor(AgentEditorDraftController) -final agentEditorDraftControllerProvider = AgentEditorDraftControllerFamily._(); - -final class AgentEditorDraftControllerProvider - extends $NotifierProvider { - AgentEditorDraftControllerProvider._({ - required AgentEditorDraftControllerFamily super.from, - required AgentProfileDraft super.argument, - }) : super( - retry: null, - name: r'agentEditorDraftControllerProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$agentEditorDraftControllerHash(); - - @override - String toString() { - return r'agentEditorDraftControllerProvider' - '' - '($argument)'; - } - - @$internal - @override - AgentEditorDraftController create() => AgentEditorDraftController(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(AgentEditorState value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } - - @override - bool operator ==(Object other) { - return other is AgentEditorDraftControllerProvider && - other.argument == argument; - } - - @override - int get hashCode { - return argument.hashCode; - } -} - -String _$agentEditorDraftControllerHash() => - r'ddac0f39fc221ab5996d12c4f98151fce2ca6189'; - -final class AgentEditorDraftControllerFamily extends $Family - with - $ClassFamilyOverride< - AgentEditorDraftController, - AgentEditorState, - AgentEditorState, - AgentEditorState, - AgentProfileDraft - > { - AgentEditorDraftControllerFamily._() - : super( - retry: null, - name: r'agentEditorDraftControllerProvider', - dependencies: null, - $allTransitiveDependencies: null, - isAutoDispose: true, - ); - - AgentEditorDraftControllerProvider call(AgentProfileDraft draft) => - AgentEditorDraftControllerProvider._(argument: draft, from: this); - - @override - String toString() => r'agentEditorDraftControllerProvider'; -} - -abstract class _$AgentEditorDraftController - extends $Notifier { - late final _$args = ref.$arg as AgentProfileDraft; - AgentProfileDraft get draft => _$args; - - AgentEditorState build(AgentProfileDraft draft); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - AgentEditorState, - Object?, - Object? - >; - element.handleCreate(ref, () => build(_$args)); - } -} diff --git a/apps/mobile/lib/application/display_payload_preview.dart b/apps/mobile/lib/application/display_payload_preview.dart deleted file mode 100644 index 97adde5e..00000000 --- a/apps/mobile/lib/application/display_payload_preview.dart +++ /dev/null @@ -1,48 +0,0 @@ -import 'package:minos/src/rust/api/minos.dart'; - -extension DisplayPayloadPreview on DisplayPayload { - String renderPreview() { - return switch (this) { - DisplayPayload_Inline(:final text) => text, - DisplayPayload_StreamingWindow(:final head, :final receivedBytes) => - _appendMarker(head, 'streaming ${_formatBytes(receivedBytes)}'), - DisplayPayload_WindowedFinal( - :final head, - :final tail, - :final omittedBytes, - ) => - omittedBytes == BigInt.zero - ? '$head$tail' - : _joinWindow(head, tail, omittedBytes), - }; - } - - ArtifactRef? get artifactRef { - return switch (this) { - DisplayPayload_Inline() => null, - DisplayPayload_StreamingWindow(:final artifact) => artifact, - DisplayPayload_WindowedFinal(:final artifact) => artifact, - }; - } -} - -String _joinWindow(String head, String tail, BigInt omittedBytes) { - final marker = '[... ${_formatBytes(omittedBytes)} omitted ...]'; - if (head.isEmpty) return '$marker\n$tail'; - if (tail.isEmpty) return '$head\n$marker'; - return '$head\n$marker\n$tail'; -} - -String _appendMarker(String text, String marker) { - if (text.isEmpty) return '[$marker]'; - return '$text\n[$marker]'; -} - -String _formatBytes(BigInt value) { - final bytes = value.toDouble(); - if (bytes < 1024) return '${value.toString()} B'; - final kib = bytes / 1024; - if (kib < 1024) return '${kib.toStringAsFixed(1)} KiB'; - final mib = kib / 1024; - return '${mib.toStringAsFixed(1)} MiB'; -} diff --git a/apps/mobile/lib/application/minos_providers.dart b/apps/mobile/lib/application/minos_providers.dart index 2183d97a..d3bab2da 100644 --- a/apps/mobile/lib/application/minos_providers.dart +++ b/apps/mobile/lib/application/minos_providers.dart @@ -4,8 +4,8 @@ import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart' show AsyncNotifier, AsyncNotifierProvider, FutureProvider, Provider; import 'package:minos/data/repositories/hosts_repository.dart'; +import 'package:minos/data/repositories/realtime_events_repository.dart'; import 'package:minos/data/repositories/runtime_repository.dart'; -import 'package:minos/data/repositories/thread_repository.dart'; import 'package:minos/domain/linked_host.dart'; import 'package:minos/infrastructure/platform_int64.dart'; import 'package:minos/src/rust/api/minos.dart'; @@ -27,7 +27,7 @@ Stream connectionState(Ref ref) { /// Also arms HostLinked / HostUnlinked durable roster events (Realtime R1): /// upsert/remove members — not presence-only. final hostPresenceSyncProvider = Provider((ref) { - final repo = ref.watch(threadRepositoryProvider); + final repo = ref.watch(realtimeEventsRepositoryProvider); final sub = repo.uiEvents.listen((frame) { final ui = frame.ui; if (ui is! UiEventMessage_Raw) return; diff --git a/apps/mobile/lib/application/project_providers.dart b/apps/mobile/lib/application/project_providers.dart deleted file mode 100644 index 827daa4c..00000000 --- a/apps/mobile/lib/application/project_providers.dart +++ /dev/null @@ -1,99 +0,0 @@ -import 'package:minos/data/repositories/project_repository.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'project_providers.g.dart'; - -/// Loads and caches the project list. Refresh via invalidation. -@Riverpod(keepAlive: true) -class ProjectList extends _$ProjectList { - @override - Future> build() async { - return ref.read(projectRepositoryProvider).listProjects(); - } - - Future refresh() async { - final previous = state; - try { - state = AsyncValue.data( - await ref.read(projectRepositoryProvider).listProjects(), - ); - } catch (error, stackTrace) { - if (previous.hasValue) { - state = previous; - Error.throwWithStackTrace(error, stackTrace); - } - state = AsyncValue.error(error, stackTrace); - } - } - - /// Create a new project and refresh the list. - Future createProject({ - required String name, - required String workspaceSlug, - String? workspacePath, - }) async { - final project = await ref - .read(projectRepositoryProvider) - .createProject( - name: name, - workspaceSlug: workspaceSlug, - workspacePath: workspacePath, - ); - await refresh(); - return project; - } - - /// Delete a project and refresh the list. - Future deleteProject(String projectId) async { - await ref.read(projectRepositoryProvider).deleteProject(projectId); - await refresh(); - } - - /// Update a project's name and refresh the list. - Future updateProject({ - required String projectId, - required String name, - }) async { - await ref - .read(projectRepositoryProvider) - .updateProject(projectId: projectId, name: name); - await refresh(); - } -} - -/// Loads sessions for a specific project. -@Riverpod(keepAlive: false) -class ProjectSessions extends _$ProjectSessions { - @override - Future> build(String projectId) async { - return ref.read(projectRepositoryProvider).listProjectThreads(projectId); - } - - Future refresh() async { - final previous = state; - final projectId = this.projectId; - try { - state = AsyncValue.data( - await ref.read(projectRepositoryProvider).listProjectThreads(projectId), - ); - } catch (error, stackTrace) { - if (previous.hasValue) { - state = previous; - Error.throwWithStackTrace(error, stackTrace); - } - state = AsyncValue.error(error, stackTrace); - } - } -} - -/// Currently selected project id. Persisted in memory for navigation. -@Riverpod(keepAlive: true) -class SelectedProject extends _$SelectedProject { - @override - String? build() => null; - - void select(String? projectId) { - state = projectId; - } -} diff --git a/apps/mobile/lib/application/project_providers.g.dart b/apps/mobile/lib/application/project_providers.g.dart deleted file mode 100644 index 1a1654ac..00000000 --- a/apps/mobile/lib/application/project_providers.g.dart +++ /dev/null @@ -1,226 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'project_providers.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning -/// Loads and caches the project list. Refresh via invalidation. - -@ProviderFor(ProjectList) -final projectListProvider = ProjectListProvider._(); - -/// Loads and caches the project list. Refresh via invalidation. -final class ProjectListProvider - extends $AsyncNotifierProvider> { - /// Loads and caches the project list. Refresh via invalidation. - ProjectListProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'projectListProvider', - isAutoDispose: false, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$projectListHash(); - - @$internal - @override - ProjectList create() => ProjectList(); -} - -String _$projectListHash() => r'ee5288d606b69d703648e673e0d8326831aaefbd'; - -/// Loads and caches the project list. Refresh via invalidation. - -abstract class _$ProjectList extends $AsyncNotifier> { - FutureOr> build(); - @$mustCallSuper - @override - void runBuild() { - final ref = - this.ref - as $Ref>, List>; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier< - AsyncValue>, - List - >, - AsyncValue>, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} - -/// Loads sessions for a specific project. - -@ProviderFor(ProjectSessions) -final projectSessionsProvider = ProjectSessionsFamily._(); - -/// Loads sessions for a specific project. -final class ProjectSessionsProvider - extends $AsyncNotifierProvider> { - /// Loads sessions for a specific project. - ProjectSessionsProvider._({ - required ProjectSessionsFamily super.from, - required String super.argument, - }) : super( - retry: null, - name: r'projectSessionsProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$projectSessionsHash(); - - @override - String toString() { - return r'projectSessionsProvider' - '' - '($argument)'; - } - - @$internal - @override - ProjectSessions create() => ProjectSessions(); - - @override - bool operator ==(Object other) { - return other is ProjectSessionsProvider && other.argument == argument; - } - - @override - int get hashCode { - return argument.hashCode; - } -} - -String _$projectSessionsHash() => r'76903f9cca7df6089089b63852bd6cbcfe4ea370'; - -/// Loads sessions for a specific project. - -final class ProjectSessionsFamily extends $Family - with - $ClassFamilyOverride< - ProjectSessions, - AsyncValue>, - List, - FutureOr>, - String - > { - ProjectSessionsFamily._() - : super( - retry: null, - name: r'projectSessionsProvider', - dependencies: null, - $allTransitiveDependencies: null, - isAutoDispose: true, - ); - - /// Loads sessions for a specific project. - - ProjectSessionsProvider call(String projectId) => - ProjectSessionsProvider._(argument: projectId, from: this); - - @override - String toString() => r'projectSessionsProvider'; -} - -/// Loads sessions for a specific project. - -abstract class _$ProjectSessions extends $AsyncNotifier> { - late final _$args = ref.$arg as String; - String get projectId => _$args; - - FutureOr> build(String projectId); - @$mustCallSuper - @override - void runBuild() { - final ref = - this.ref - as $Ref>, List>; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier< - AsyncValue>, - List - >, - AsyncValue>, - Object?, - Object? - >; - element.handleCreate(ref, () => build(_$args)); - } -} - -/// Currently selected project id. Persisted in memory for navigation. - -@ProviderFor(SelectedProject) -final selectedProjectProvider = SelectedProjectProvider._(); - -/// Currently selected project id. Persisted in memory for navigation. -final class SelectedProjectProvider - extends $NotifierProvider { - /// Currently selected project id. Persisted in memory for navigation. - SelectedProjectProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'selectedProjectProvider', - isAutoDispose: false, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$selectedProjectHash(); - - @$internal - @override - SelectedProject create() => SelectedProject(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(String? value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } -} - -String _$selectedProjectHash() => r'e80e496ab33e02f77a7a9b35f05befb2b4ee6b0f'; - -/// Currently selected project id. Persisted in memory for navigation. - -abstract class _$SelectedProject extends $Notifier { - String? build(); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - String?, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} diff --git a/apps/mobile/lib/application/root_route_decision.dart b/apps/mobile/lib/application/root_route_decision.dart index 9c9eb851..a96ab982 100644 --- a/apps/mobile/lib/application/root_route_decision.dart +++ b/apps/mobile/lib/application/root_route_decision.dart @@ -11,19 +11,14 @@ enum RootRoute { /// No auth (or refresh failed). Route to the email/password screen. login, - /// Authenticated + paired + WS up (or transient reconnect). Route to - /// the project list (new home). - projectList, + /// Authenticated and connected (or transient reconnect). IM shell home. + shell, - /// Authenticated + paired but the connection to server is offline / WS - /// torn down. Same surface as [projectList] visually but expected to render - /// an offline banner. - projectListOffline, + /// Authenticated but account WS offline. Same shell surface with offline chrome. + shellOffline, } /// Pure decision matrix gating on auth state first, then connection state. -/// Pairing is now a user-initiated "Add partner" flow from Profile rather -/// than a top-level auth gate. RootRoute decideRootRoute({ required AuthState authState, required core.ConnectionState? connectionState, @@ -35,9 +30,9 @@ RootRoute decideRootRoute({ AuthUnauthenticated() => RootRoute.login, AuthRefreshFailed() => RootRoute.login, AuthAuthenticated() => switch (connectionState) { - core.ConnectionState_Connected() => RootRoute.projectList, - core.ConnectionState_Reconnecting() => RootRoute.projectList, - _ => RootRoute.projectListOffline, + core.ConnectionState_Connected() => RootRoute.shell, + core.ConnectionState_Reconnecting() => RootRoute.shell, + _ => RootRoute.shellOffline, }, }; } diff --git a/apps/mobile/lib/application/social/social_chat_actions.dart b/apps/mobile/lib/application/social/social_chat_actions.dart new file mode 100644 index 00000000..c9e1f703 --- /dev/null +++ b/apps/mobile/lib/application/social/social_chat_actions.dart @@ -0,0 +1,45 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:minos/application/social/social_chat_view_model.dart'; +import 'package:minos/domain/social_message.dart'; + +/// Intentful action facade for [SocialChatPage]. +/// +/// Keeps widgets free of multi-provider orchestration; ViewModel owns state. +final socialChatActionsProvider = Provider.family(( + ref, + conversationId, +) { + return SocialChatActions(ref, conversationId); +}); + +class SocialChatActions { + SocialChatActions(this._ref, this.conversationId); + + final Ref _ref; + final String conversationId; + + SocialChatViewModel get _vm => + _ref.read(socialChatViewModelProvider(conversationId).notifier); + + Future send(String text) => _vm.send(text); + + Future retry(String localId) => _vm.retry(localId); + + Future recall(String localId) => _vm.recall(localId); + + Future toggleReaction({ + required String messageId, + required String emoji, + }) { + return _vm.toggleReaction(messageId: messageId, emoji: emoji); + } + + Future loadOlder() => _vm.loadOlder(); + + Future refresh() => _vm.refresh(); + + void selectReply(SocialChatMessage message) => + _vm.selectReply(message.localId); + + void clearReply() => _vm.clearReply(); +} diff --git a/apps/mobile/lib/application/social/social_chat_view_model.dart b/apps/mobile/lib/application/social/social_chat_view_model.dart new file mode 100644 index 00000000..f7698b0d --- /dev/null +++ b/apps/mobile/lib/application/social/social_chat_view_model.dart @@ -0,0 +1,54 @@ +import 'package:minos/application/social/social_conversation_notifier.dart'; +import 'package:minos/application/social/social_conversation_state.dart'; +import 'package:minos/application/social/social_ui_state.dart'; +import 'package:minos/domain/social_message.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'social_chat_view_model.g.dart'; + +/// Feature-level ViewModel for the open conversation surface. +/// +/// UI should prefer this aggregation over watching multiple fine-grained +/// providers: timeline state, reply draft target, and intentful actions. +@riverpod +class SocialChatViewModel extends _$SocialChatViewModel { + @override + SocialConversationState build(String conversationId) { + return ref.watch(socialConversationProvider(conversationId)); + } + + SocialConversation get _timeline => + ref.read(socialConversationProvider(conversationId).notifier); + + SocialChatMessage? get replyTarget => + ref.read(socialReplyMessageProvider(conversationId)); + + Future send(String text) async { + final reply = replyTarget; + await _timeline.sendMessage(text, replyToMessage: reply); + ref.read(socialReplyDraftProvider(conversationId).notifier).clear(); + } + + Future retry(String localId) => _timeline.retryMessage(localId); + + Future recall(String localId) => _timeline.recallMessage(localId); + + Future toggleReaction({ + required String messageId, + required String emoji, + }) { + return _timeline.toggleReaction(messageId: messageId, emoji: emoji); + } + + Future loadOlder() => _timeline.loadOlder(); + + Future refresh() => _timeline.refresh(); + + void selectReply(String localId) { + ref.read(socialReplyDraftProvider(conversationId).notifier).select(localId); + } + + void clearReply() { + ref.read(socialReplyDraftProvider(conversationId).notifier).clear(); + } +} diff --git a/apps/mobile/lib/application/social/social_chat_view_model.g.dart b/apps/mobile/lib/application/social/social_chat_view_model.g.dart new file mode 100644 index 00000000..92eafb43 --- /dev/null +++ b/apps/mobile/lib/application/social/social_chat_view_model.g.dart @@ -0,0 +1,137 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'social_chat_view_model.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Feature-level ViewModel for the open conversation surface. +/// +/// UI should prefer this aggregation over watching multiple fine-grained +/// providers: timeline state, reply draft target, and intentful actions. + +@ProviderFor(SocialChatViewModel) +final socialChatViewModelProvider = SocialChatViewModelFamily._(); + +/// Feature-level ViewModel for the open conversation surface. +/// +/// UI should prefer this aggregation over watching multiple fine-grained +/// providers: timeline state, reply draft target, and intentful actions. +final class SocialChatViewModelProvider + extends $NotifierProvider { + /// Feature-level ViewModel for the open conversation surface. + /// + /// UI should prefer this aggregation over watching multiple fine-grained + /// providers: timeline state, reply draft target, and intentful actions. + SocialChatViewModelProvider._({ + required SocialChatViewModelFamily super.from, + required String super.argument, + }) : super( + retry: null, + name: r'socialChatViewModelProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$socialChatViewModelHash(); + + @override + String toString() { + return r'socialChatViewModelProvider' + '' + '($argument)'; + } + + @$internal + @override + SocialChatViewModel create() => SocialChatViewModel(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(SocialConversationState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is SocialChatViewModelProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$socialChatViewModelHash() => + r'6c79ec19cc964c4625ee37039dbc6d8eedd5621d'; + +/// Feature-level ViewModel for the open conversation surface. +/// +/// UI should prefer this aggregation over watching multiple fine-grained +/// providers: timeline state, reply draft target, and intentful actions. + +final class SocialChatViewModelFamily extends $Family + with + $ClassFamilyOverride< + SocialChatViewModel, + SocialConversationState, + SocialConversationState, + SocialConversationState, + String + > { + SocialChatViewModelFamily._() + : super( + retry: null, + name: r'socialChatViewModelProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Feature-level ViewModel for the open conversation surface. + /// + /// UI should prefer this aggregation over watching multiple fine-grained + /// providers: timeline state, reply draft target, and intentful actions. + + SocialChatViewModelProvider call(String conversationId) => + SocialChatViewModelProvider._(argument: conversationId, from: this); + + @override + String toString() => r'socialChatViewModelProvider'; +} + +/// Feature-level ViewModel for the open conversation surface. +/// +/// UI should prefer this aggregation over watching multiple fine-grained +/// providers: timeline state, reply draft target, and intentful actions. + +abstract class _$SocialChatViewModel + extends $Notifier { + late final _$args = ref.$arg as String; + String get conversationId => _$args; + + SocialConversationState build(String conversationId); + @$mustCallSuper + @override + void runBuild() { + final ref = + this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + SocialConversationState, + Object?, + Object? + >; + element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/apps/mobile/lib/application/social/social_conversation_notifier.dart b/apps/mobile/lib/application/social/social_conversation_notifier.dart new file mode 100644 index 00000000..2d295163 --- /dev/null +++ b/apps/mobile/lib/application/social/social_conversation_notifier.dart @@ -0,0 +1,637 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:minos/application/flutter_log.dart'; +import 'package:minos/application/group_agent_provider.dart'; +import 'package:minos/application/im_outbox_worker.dart'; +import 'package:minos/application/social/social_conversation_state.dart'; +import 'package:minos/application/social/social_inbox_notifier.dart'; +import 'package:minos/application/social/social_ui_state.dart'; +import 'package:minos/data/repositories/social_repository.dart'; +import 'package:minos/data/services/minos_core_service.dart'; +import 'package:minos/domain/mention_extract.dart'; +import 'package:minos/domain/message_sender_ext.dart'; +import 'package:minos/domain/social_message.dart'; +import 'package:minos/domain/social_message_order.dart'; +import 'package:minos/src/rust/api/minos.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'social_conversation_notifier.g.dart'; + +@riverpod +class SocialConversation extends _$SocialConversation { + static const int _pageSize = 100; + static const Duration _markReadDebounce = Duration(milliseconds: 400); + + StreamSubscription? _eventsSub; + Timer? _markReadTimer; + + late final String _conversationId; + + @override + SocialConversationState build(String conversationId) { + final initialState = SocialConversationState.initial(); + _conversationId = conversationId; + unawaited(_eventsSub?.cancel() ?? Future.value()); + _eventsSub = ref + .read(socialRepositoryProvider) + .socialEvents + .listen( + _onSocialEvent, + // Soft: connection churn must not rebuild + mark-read the open chat. + onError: (Object error, StackTrace stackTrace) {}, + onDone: () {}, + ); + // R3a: open chat subscribes conversation topic for full T1 live frames. + // Account topic digests are inbox-only and must not drive this timeline. + final repository = ref.read(socialRepositoryProvider); + unawaited(repository.subscribeConversation(conversationId: conversationId)); + ref.onDispose(() { + unawaited(_eventsSub?.cancel() ?? Future.value()); + _markReadTimer?.cancel(); + unawaited( + repository.unsubscribeConversation(conversationId: conversationId), + ); + }); + unawaited(_load(seedState: initialState)); + return initialState; + } + + Future refresh() => _load(); + + /// Cache-only reload after outbox ack (no REST, no mark-read, no subscribe). + /// Used when the conversation is already open; never materialize closed chats. + Future reloadFromLocalCache() async { + final repository = ref.read(socialRepositoryProvider); + final messages = await repository.loadMessages(_conversationId); + state = state.withMessages(messages).copyWith(error: null); + } + + /// Older page via Hub `before_seq` (TimelineSync.loadOlder). + Future loadOlder() async { + if (state.loadingOlder || !state.hasOlder) { + return; + } + final minSeq = state.minLoadedSeq; + if (minSeq == null || minSeq <= 1) { + state = state.copyWith(hasOlder: false, loadingOlder: false); + return; + } + + state = state.copyWith(loadingOlder: true); + final repository = ref.read(socialRepositoryProvider); + try { + final response = await repository.listChatMessages( + conversationId: _conversationId, + beforeSeq: minSeq, + limit: _pageSize, + ); + await repository.upsertRemoteMessages( + conversationId: _conversationId, + messages: response.messages, + ); + final messages = await repository.loadMessages(_conversationId); + final hasOlder = + response.nextBeforeSeq != null || + response.messages.length >= _pageSize; + state = state + .withMessages(messages) + .copyWith(hasOlder: hasOlder, loadingOlder: false, error: null); + } catch (error) { + state = state.copyWith(loadingOlder: false, error: error); + } + } + + /// SnapshotRequired range reconcile: keep window, forward fill + latest page. + /// Timeline-only: does **not** mark-read or clear unread (caller must only + /// invoke when this provider already exists / chat is open). + Future onSnapshotRequired() async { + final repository = ref.read(socialRepositoryProvider); + final prev = state.messages; + final maxSeq = state.maxLoadedSeq ?? maxLoadedSeqOf(prev); + try { + if (maxSeq != null) { + final forward = await repository.listChatMessages( + conversationId: _conversationId, + afterSeq: maxSeq, + limit: _pageSize, + ); + await repository.upsertRemoteMessages( + conversationId: _conversationId, + messages: forward.messages, + ); + } + final latest = await repository.listChatMessages( + conversationId: _conversationId, + limit: _pageSize, + ); + await repository.upsertRemoteMessages( + conversationId: _conversationId, + messages: latest.messages, + ); + final messages = await repository.loadMessages(_conversationId); + final hasOlder = + latest.nextBeforeSeq != null || + latest.messages.length >= _pageSize || + state.hasOlder; + state = state + .withMessages(messages) + .copyWith(hasOlder: hasOlder, isLoading: false, error: null); + // No mark-read here: open path / inbound debounce own unread. + } catch (error) { + state = state.copyWith(error: error, isLoading: false); + } + } + + Future sendMessage( + String text, { + SocialChatMessage? replyToMessage, + }) async { + final trimmed = text.trim(); + if (trimmed.isEmpty) { + return; + } + + final repository = ref.read(socialRepositoryProvider); + final replyPreview = _replyPreviewForMessage(replyToMessage); + final sender = await _localSender(); + // Optimistic structured mentions from current roster so local cache/reload + // before Hub ack still carries bot targets (Hub remains SSOT after upsert). + final participants = ref + .read(conversationParticipantsProvider(_conversationId)) + .asData + ?.value; + final optimistic = extractOptimisticMentions( + text: trimmed, + selfAccountId: sender.identityId, + humans: (participants?.humans ?? const []) + .map( + (h) => MentionHumanRef(accountId: h.accountId, minosId: h.minosId), + ) + .toList(growable: false), + agents: (participants?.agents ?? const []) + .where( + (a) => + a.status.trim().isEmpty || a.status.toLowerCase() == 'active', + ) + .map( + (a) => MentionAgentRef( + agentId: a.agentId, + runtimeAgent: a.runtimeAgent, + name: a.name, + ), + ) + .toList(growable: false), + ); + final pending = await repository.insertPendingMessageWithOutbox( + conversationId: _conversationId, + sender: sender, + text: trimmed, + replyTo: replyPreview, + mentionedAccountIds: optimistic.accountIds, + mentionedAgentIds: optimistic.agentIds, + structuredMentions: optimistic.structuredMentions, + ); + await repository.touchConversationPreview( + conversationId: _conversationId, + preview: trimmed, + createdAtMs: pending.createdAtMs, + ); + final messages = await repository.loadMessages(_conversationId); + state = state.withMessages(messages).copyWith(error: null); + // Inbox patch without full REST. + unawaited( + ref + .read(conversationsProvider.notifier) + .patchPreview( + conversationId: _conversationId, + preview: trimmed, + lastMessageAtMs: pending.createdAtMs, + unreadCount: 0, + ), + ); + + // Durable outbox owns transport; kick worker without blocking UI on REST. + unawaited(ref.read(imOutboxWorkerProvider).ensureStarted()); + unawaited(ref.read(imOutboxWorkerProvider).flush()); + } + + Future retryMessage(String localId) async { + SocialChatMessage? target; + for (final message in state.messages) { + if (message.localId == localId) { + target = message; + break; + } + } + if (target == null || + target.deliveryState != SocialMessageDeliveryState.failed) { + return; + } + + final repository = ref.read(socialRepositoryProvider); + final clientMessageId = target.wireClientMessageId; + final replyToMessageId = target.replyTo?.recalledAtMs == null + ? target.replyTo?.messageId + : null; + + await repository.markMessageSending(localId); + // Reuse the same client_message_id — never mint a new key on retry. + // Rebuild structured mentions from body + current roster (Hub validates). + final participants = ref + .read(conversationParticipantsProvider(_conversationId)) + .asData + ?.value; + final selfAccountId = await repository.loadCurrentAccountId(); + final optimistic = extractOptimisticMentions( + text: target.text, + selfAccountId: selfAccountId, + humans: (participants?.humans ?? const []) + .map( + (h) => MentionHumanRef(accountId: h.accountId, minosId: h.minosId), + ) + .toList(growable: false), + agents: (participants?.agents ?? const []) + .where( + (a) => + a.status.trim().isEmpty || a.status.toLowerCase() == 'active', + ) + .map( + (a) => MentionAgentRef( + agentId: a.agentId, + runtimeAgent: a.runtimeAgent, + name: a.name, + ), + ) + .toList(growable: false), + ); + await repository.enqueueUserMessageOutbox( + clientMessageId: clientMessageId, + conversationId: _conversationId, + text: target.text, + replyToMessageId: replyToMessageId, + structuredMentions: optimistic.structuredMentions, + ); + final messages = await repository.loadMessages(_conversationId); + state = state.withMessages(messages); + + unawaited(ref.read(imOutboxWorkerProvider).ensureStarted()); + unawaited(ref.read(imOutboxWorkerProvider).flush()); + } + + Future recallMessage(String localId) async { + SocialChatMessage? target; + for (final message in state.messages) { + if (message.localId == localId) { + target = message; + break; + } + } + if (target == null || !target.canRecall || target.serverMessageId == null) { + return; + } + + final repository = ref.read(socialRepositoryProvider); + final message = await repository.recallChatMessage( + conversationId: _conversationId, + messageId: target.serverMessageId!, + ); + await repository.upsertRemoteMessage(message); + await repository.touchConversationPreview( + conversationId: _conversationId, + preview: message.text, + createdAtMs: repository.platformInt64ToIntValue(message.createdAtMs), + ); + final messages = await repository.loadMessages(_conversationId); + state = state.withMessages(messages); + final replyDraft = ref.read(socialReplyDraftProvider(_conversationId)); + if (replyDraft == localId) { + ref.read(socialReplyDraftProvider(_conversationId).notifier).clear(); + } + unawaited( + ref + .read(conversationsProvider.notifier) + .patchPreview( + conversationId: _conversationId, + preview: message.text, + lastMessageAtMs: repository.platformInt64ToIntValue( + message.createdAtMs, + ), + ), + ); + } + + Future _load({SocialConversationState? seedState}) async { + final repository = ref.read(socialRepositoryProvider); + final previous = seedState ?? state; + final cachedMessages = await repository.loadMessages(_conversationId); + final cachedAccountId = await repository.loadCurrentAccountId(); + state = previous + .withMessages( + cachedMessages.isEmpty ? previous.messages : cachedMessages, + ) + .copyWith( + myAccountId: cachedAccountId ?? previous.myAccountId, + isLoading: true, + error: null, + ); + try { + final profile = await repository.myProfile(); + await repository.saveCurrentAccountId(profile.accountId); + final response = await repository.listChatMessages( + conversationId: _conversationId, + limit: _pageSize, + ); + await repository.upsertRemoteMessages( + conversationId: _conversationId, + messages: response.messages, + ); + await repository.clearUnread(_conversationId); + final messages = await repository.loadMessages(_conversationId); + final hasOlder = + response.nextBeforeSeq != null || + response.messages.length >= _pageSize; + state = SocialConversationState( + myAccountId: profile.accountId, + messages: messages, + minLoadedSeq: minLoadedSeqOf(messages), + maxLoadedSeq: maxLoadedSeqOf(messages), + hasOlder: hasOlder, + loadingOlder: false, + isLoading: false, + error: null, + ); + // Mark-read after state has observed maxLoadedSeq (not before). + unawaited(_markConversationReadNow()); + unawaited( + ref + .read(conversationsProvider.notifier) + .applyMarkReadLocal(_conversationId), + ); + } catch (error) { + final fallback = cachedMessages.isEmpty + ? previous.messages + : cachedMessages; + state = SocialConversationState( + myAccountId: cachedAccountId ?? previous.myAccountId, + messages: fallback, + minLoadedSeq: minLoadedSeqOf(fallback), + maxLoadedSeq: maxLoadedSeqOf(fallback), + hasOlder: previous.hasOlder, + loadingOlder: false, + isLoading: false, + error: error, + ); + } + } + + void _onSocialEvent(SocialEventFrame frame) { + if (frame.conversationId != _conversationId) { + return; + } + // Account T2 digests are for inbox only — never timeline. + if (frame.kind == 'inbox_digest' || frame.kind == 'inbox_recall') { + return; + } + if (frame.kind == 'reaction_updated') { + final mid = frame.message.messageId.trim(); + if (mid.isEmpty) return; + unawaited( + _applyRemoteReactions(mid, frame.message.reactions).then((_) { + return _ackDurable(frame); + }), + ); + return; + } + // Full T1 conversation frames only. + if (frame.kind != 'message') { + return; + } + // Empty shell already filtered in Rust; belt-and-suspenders here. + if (frame.message.messageId.trim().isEmpty) { + return; + } + unawaited( + _applyRemoteMessage(frame.message).then((_) => _ackDurable(frame)), + ); + } + + Future _ackDurable(SocialEventFrame frame) async { + final topic = frame.topic.trim(); + final seq = frame.topicSeq.toInt(); + if (topic.isEmpty || seq <= 0) return; + try { + await ref + .read(minosCoreServiceProvider) + .ackDurableApplied(topic: topic, topicSeq: seq); + } catch (e, st) { + // Hold cursor on failure — do not swallow without log. + logFlutterWarn( + 'social_providers', + 'ackDurableApplied failed', + error: e, + stackTrace: st, + ); + } + } + + Future _applyRemoteReactions( + String messageId, + List reactions, + ) async { + final repository = ref.read(socialRepositoryProvider); + await repository.updateMessageReactions( + conversationId: _conversationId, + messageId: messageId, + reactions: reactions, + ); + final messages = await repository.loadMessages(_conversationId); + state = state.withMessages(messages).copyWith(error: null); + } + + /// Toggle reaction via Intent Outbox; optimistic UI then worker drain. + Future toggleReaction({ + required String messageId, + required String emoji, + }) async { + final mid = messageId.trim(); + final em = emoji.trim(); + if (mid.isEmpty || em.isEmpty) return; + final repository = ref.read(socialRepositoryProvider); + final clientOpId = + 'react-${DateTime.now().microsecondsSinceEpoch}-${mid.hashCode.abs()}'; + // Optimistic: flip reacted_by_me for this emoji in local list. + final nextMessages = state.messages + .map((m) { + if (m.serverMessageId != mid && m.localId != mid) return m; + return m.copyWith(reactions: _optimisticToggle(m.reactions, em)); + }) + .toList(growable: false); + state = state.withMessages(nextMessages); + + await repository.enqueueReactionToggleOutbox( + clientOpId: clientOpId, + conversationId: _conversationId, + messageId: mid, + emoji: em, + ); + final worker = ref.read(imOutboxWorkerProvider); + unawaited(worker.ensureStarted()); + unawaited(worker.flush()); + } + + List _optimisticToggle( + List prev, + String emoji, + ) { + final list = List.from(prev); + final idx = list.indexWhere((g) => g.emoji == emoji); + if (idx < 0) { + list.add( + ReactionGroup( + emoji: emoji, + count: 1, + reactedByMe: true, + actors: const [], + ), + ); + return list; + } + final g = list[idx]; + if (g.reactedByMe) { + final count = g.count - 1; + if (count <= 0) { + list.removeAt(idx); + } else { + list[idx] = ReactionGroup( + emoji: g.emoji, + count: count, + reactedByMe: false, + actors: g.actors, + ); + } + } else { + list[idx] = ReactionGroup( + emoji: g.emoji, + count: g.count + 1, + reactedByMe: true, + actors: g.actors, + ); + } + return list; + } + + Future _applyRemoteMessage(ChatMessageSummary message) async { + final repository = ref.read(socialRepositoryProvider); + await repository.upsertRemoteMessage(message); + await repository.touchConversationPreview( + conversationId: message.conversationId, + preview: message.text, + createdAtMs: repository.platformInt64ToIntValue(message.createdAtMs), + unreadCount: 0, + ); + // Incremental merge: prefer single-row into in-memory list when possible. + final messages = await repository.loadMessages(_conversationId); + state = state.withMessages(messages).copyWith(error: null); + _scheduleMarkRead(); + // Inbox patch: focused → unread 0, no full REST. + unawaited( + ref + .read(conversationsProvider.notifier) + .patchFromInbound( + message: message, + focused: true, + myAccountId: state.myAccountId, + ), + ); + } + + void _scheduleMarkRead() { + _markReadTimer?.cancel(); + _markReadTimer = Timer(_markReadDebounce, () { + unawaited(_markConversationReadNow()); + }); + } + + Future _markConversationReadNow() async { + // Only mark up to the highest Hub message_seq actually loaded/observed. + // Skip HTTP when no observed seq (avoids silently marking unread rows). + final observedSeq = state.maxLoadedSeq ?? maxLoadedSeqOf(state.messages); + if (observedSeq == null || observedSeq <= 0) { + // Still clear local badge; server watermark stays until we observe seq. + try { + await ref.read(socialRepositoryProvider).clearUnread(_conversationId); + unawaited( + ref + .read(conversationsProvider.notifier) + .applyMarkReadLocal(_conversationId), + ); + } catch (_) {} + return; + } + try { + await ref + .read(socialRepositoryProvider) + .markConversationRead( + conversationId: _conversationId, + readUpToMessageSeq: observedSeq, + ); + await ref.read(socialRepositoryProvider).clearUnread(_conversationId); + unawaited( + ref + .read(conversationsProvider.notifier) + .applyMarkReadLocal(_conversationId), + ); + } catch (_) {} + } + + Future _localSender() async { + final accountId = + state.myAccountId ?? + await ref.read(socialRepositoryProvider).loadCurrentAccountId() ?? + 'local-self'; + return MessageSender.account( + accountId: accountId, + minosId: 'me', + displayName: '我', + ); + } + + ChatMessageReplySummary? _replyPreviewForMessage(SocialChatMessage? message) { + if (message == null || + !message.canReply || + message.serverMessageId == null) { + return null; + } + return ChatMessageReplySummary( + messageId: message.serverMessageId!, + sender: message.sender, + text: message.text, + recalledAtMs: message.recalledAtMs == null + ? null + : ref + .read(socialRepositoryProvider) + .platformInt64FromIntValue(message.recalledAtMs!), + ); + } +} + +final socialReplyMessageProvider = Provider.family(( + ref, + conversationId, +) { + final localId = ref.watch(socialReplyDraftProvider(conversationId)); + if (localId == null) { + return null; + } + final messages = ref + .watch(socialConversationProvider(conversationId)) + .messages; + for (final message in messages) { + if (message.localId == localId && message.canReply) { + return message; + } + } + return null; +}); diff --git a/apps/mobile/lib/application/social/social_conversation_notifier.g.dart b/apps/mobile/lib/application/social/social_conversation_notifier.g.dart new file mode 100644 index 00000000..af84ca79 --- /dev/null +++ b/apps/mobile/lib/application/social/social_conversation_notifier.g.dart @@ -0,0 +1,109 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'social_conversation_notifier.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(SocialConversation) +final socialConversationProvider = SocialConversationFamily._(); + +final class SocialConversationProvider + extends $NotifierProvider { + SocialConversationProvider._({ + required SocialConversationFamily super.from, + required String super.argument, + }) : super( + retry: null, + name: r'socialConversationProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$socialConversationHash(); + + @override + String toString() { + return r'socialConversationProvider' + '' + '($argument)'; + } + + @$internal + @override + SocialConversation create() => SocialConversation(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(SocialConversationState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is SocialConversationProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$socialConversationHash() => + r'64771e181d3a87eef524c0f81b032d1b1ea6c608'; + +final class SocialConversationFamily extends $Family + with + $ClassFamilyOverride< + SocialConversation, + SocialConversationState, + SocialConversationState, + SocialConversationState, + String + > { + SocialConversationFamily._() + : super( + retry: null, + name: r'socialConversationProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + SocialConversationProvider call(String conversationId) => + SocialConversationProvider._(argument: conversationId, from: this); + + @override + String toString() => r'socialConversationProvider'; +} + +abstract class _$SocialConversation extends $Notifier { + late final _$args = ref.$arg as String; + String get conversationId => _$args; + + SocialConversationState build(String conversationId); + @$mustCallSuper + @override + void runBuild() { + final ref = + this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + SocialConversationState, + Object?, + Object? + >; + element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/apps/mobile/lib/application/social/social_conversation_state.dart b/apps/mobile/lib/application/social/social_conversation_state.dart new file mode 100644 index 00000000..dfa5a586 --- /dev/null +++ b/apps/mobile/lib/application/social/social_conversation_state.dart @@ -0,0 +1,37 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:minos/domain/social_message.dart'; +import 'package:minos/domain/social_message_order.dart'; + +part 'social_conversation_state.freezed.dart'; + +/// Timeline window + meta for one conversation (TimelineSync). +/// +/// Immutable freezed state so Riverpod equality / copyWith stay correct under +/// complex concurrent updates (load older, snapshot, inbound, outbox). +@freezed +abstract class SocialConversationState with _$SocialConversationState { + const SocialConversationState._(); + + const factory SocialConversationState({ + String? myAccountId, + @Default([]) List messages, + int? minLoadedSeq, + int? maxLoadedSeq, + @Default(false) bool hasOlder, + @Default(false) bool loadingOlder, + @Default(true) bool isLoading, + Object? error, + }) = _SocialConversationState; + + /// Cold-open state before the first hydrate completes. + factory SocialConversationState.initial() => const SocialConversationState(); + + /// Replace messages and recompute seq window from durable rows only. + SocialConversationState withMessages(List next) { + return copyWith( + messages: next, + minLoadedSeq: minLoadedSeqOf(next), + maxLoadedSeq: maxLoadedSeqOf(next), + ); + } +} diff --git a/apps/mobile/lib/application/social/social_conversation_state.freezed.dart b/apps/mobile/lib/application/social/social_conversation_state.freezed.dart new file mode 100644 index 00000000..8157ca7a --- /dev/null +++ b/apps/mobile/lib/application/social/social_conversation_state.freezed.dart @@ -0,0 +1,296 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'social_conversation_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$SocialConversationState { + + String? get myAccountId; List get messages; int? get minLoadedSeq; int? get maxLoadedSeq; bool get hasOlder; bool get loadingOlder; bool get isLoading; Object? get error; +/// Create a copy of SocialConversationState +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$SocialConversationStateCopyWith get copyWith => _$SocialConversationStateCopyWithImpl(this as SocialConversationState, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is SocialConversationState&&(identical(other.myAccountId, myAccountId) || other.myAccountId == myAccountId)&&const DeepCollectionEquality().equals(other.messages, messages)&&(identical(other.minLoadedSeq, minLoadedSeq) || other.minLoadedSeq == minLoadedSeq)&&(identical(other.maxLoadedSeq, maxLoadedSeq) || other.maxLoadedSeq == maxLoadedSeq)&&(identical(other.hasOlder, hasOlder) || other.hasOlder == hasOlder)&&(identical(other.loadingOlder, loadingOlder) || other.loadingOlder == loadingOlder)&&(identical(other.isLoading, isLoading) || other.isLoading == isLoading)&&const DeepCollectionEquality().equals(other.error, error)); +} + + +@override +int get hashCode => Object.hash(runtimeType,myAccountId,const DeepCollectionEquality().hash(messages),minLoadedSeq,maxLoadedSeq,hasOlder,loadingOlder,isLoading,const DeepCollectionEquality().hash(error)); + +@override +String toString() { + return 'SocialConversationState(myAccountId: $myAccountId, messages: $messages, minLoadedSeq: $minLoadedSeq, maxLoadedSeq: $maxLoadedSeq, hasOlder: $hasOlder, loadingOlder: $loadingOlder, isLoading: $isLoading, error: $error)'; +} + + +} + +/// @nodoc +abstract mixin class $SocialConversationStateCopyWith<$Res> { + factory $SocialConversationStateCopyWith(SocialConversationState value, $Res Function(SocialConversationState) _then) = _$SocialConversationStateCopyWithImpl; +@useResult +$Res call({ + String? myAccountId, List messages, int? minLoadedSeq, int? maxLoadedSeq, bool hasOlder, bool loadingOlder, bool isLoading, Object? error +}); + + + + +} +/// @nodoc +class _$SocialConversationStateCopyWithImpl<$Res> + implements $SocialConversationStateCopyWith<$Res> { + _$SocialConversationStateCopyWithImpl(this._self, this._then); + + final SocialConversationState _self; + final $Res Function(SocialConversationState) _then; + +/// Create a copy of SocialConversationState +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? myAccountId = freezed,Object? messages = null,Object? minLoadedSeq = freezed,Object? maxLoadedSeq = freezed,Object? hasOlder = null,Object? loadingOlder = null,Object? isLoading = null,Object? error = freezed,}) { + return _then(_self.copyWith( +myAccountId: freezed == myAccountId ? _self.myAccountId : myAccountId // ignore: cast_nullable_to_non_nullable +as String?,messages: null == messages ? _self.messages : messages // ignore: cast_nullable_to_non_nullable +as List,minLoadedSeq: freezed == minLoadedSeq ? _self.minLoadedSeq : minLoadedSeq // ignore: cast_nullable_to_non_nullable +as int?,maxLoadedSeq: freezed == maxLoadedSeq ? _self.maxLoadedSeq : maxLoadedSeq // ignore: cast_nullable_to_non_nullable +as int?,hasOlder: null == hasOlder ? _self.hasOlder : hasOlder // ignore: cast_nullable_to_non_nullable +as bool,loadingOlder: null == loadingOlder ? _self.loadingOlder : loadingOlder // ignore: cast_nullable_to_non_nullable +as bool,isLoading: null == isLoading ? _self.isLoading : isLoading // ignore: cast_nullable_to_non_nullable +as bool,error: freezed == error ? _self.error : error , + )); +} + +} + + +/// Adds pattern-matching-related methods to [SocialConversationState]. +extension SocialConversationStatePatterns on SocialConversationState { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _SocialConversationState value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _SocialConversationState() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _SocialConversationState value) $default,){ +final _that = this; +switch (_that) { +case _SocialConversationState(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _SocialConversationState value)? $default,){ +final _that = this; +switch (_that) { +case _SocialConversationState() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String? myAccountId, List messages, int? minLoadedSeq, int? maxLoadedSeq, bool hasOlder, bool loadingOlder, bool isLoading, Object? error)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _SocialConversationState() when $default != null: +return $default(_that.myAccountId,_that.messages,_that.minLoadedSeq,_that.maxLoadedSeq,_that.hasOlder,_that.loadingOlder,_that.isLoading,_that.error);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String? myAccountId, List messages, int? minLoadedSeq, int? maxLoadedSeq, bool hasOlder, bool loadingOlder, bool isLoading, Object? error) $default,) {final _that = this; +switch (_that) { +case _SocialConversationState(): +return $default(_that.myAccountId,_that.messages,_that.minLoadedSeq,_that.maxLoadedSeq,_that.hasOlder,_that.loadingOlder,_that.isLoading,_that.error);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String? myAccountId, List messages, int? minLoadedSeq, int? maxLoadedSeq, bool hasOlder, bool loadingOlder, bool isLoading, Object? error)? $default,) {final _that = this; +switch (_that) { +case _SocialConversationState() when $default != null: +return $default(_that.myAccountId,_that.messages,_that.minLoadedSeq,_that.maxLoadedSeq,_that.hasOlder,_that.loadingOlder,_that.isLoading,_that.error);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _SocialConversationState extends SocialConversationState { + const _SocialConversationState({this.myAccountId, final List messages = const [], this.minLoadedSeq, this.maxLoadedSeq, this.hasOlder = false, this.loadingOlder = false, this.isLoading = true, this.error}): _messages = messages,super._(); + + +@override final String? myAccountId; + final List _messages; +@override@JsonKey() List get messages { + if (_messages is EqualUnmodifiableListView) return _messages; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_messages); +} + +@override final int? minLoadedSeq; +@override final int? maxLoadedSeq; +@override@JsonKey() final bool hasOlder; +@override@JsonKey() final bool loadingOlder; +@override@JsonKey() final bool isLoading; +@override final Object? error; + +/// Create a copy of SocialConversationState +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$SocialConversationStateCopyWith<_SocialConversationState> get copyWith => __$SocialConversationStateCopyWithImpl<_SocialConversationState>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _SocialConversationState&&(identical(other.myAccountId, myAccountId) || other.myAccountId == myAccountId)&&const DeepCollectionEquality().equals(other._messages, _messages)&&(identical(other.minLoadedSeq, minLoadedSeq) || other.minLoadedSeq == minLoadedSeq)&&(identical(other.maxLoadedSeq, maxLoadedSeq) || other.maxLoadedSeq == maxLoadedSeq)&&(identical(other.hasOlder, hasOlder) || other.hasOlder == hasOlder)&&(identical(other.loadingOlder, loadingOlder) || other.loadingOlder == loadingOlder)&&(identical(other.isLoading, isLoading) || other.isLoading == isLoading)&&const DeepCollectionEquality().equals(other.error, error)); +} + + +@override +int get hashCode => Object.hash(runtimeType,myAccountId,const DeepCollectionEquality().hash(_messages),minLoadedSeq,maxLoadedSeq,hasOlder,loadingOlder,isLoading,const DeepCollectionEquality().hash(error)); + +@override +String toString() { + return 'SocialConversationState(myAccountId: $myAccountId, messages: $messages, minLoadedSeq: $minLoadedSeq, maxLoadedSeq: $maxLoadedSeq, hasOlder: $hasOlder, loadingOlder: $loadingOlder, isLoading: $isLoading, error: $error)'; +} + + +} + +/// @nodoc +abstract mixin class _$SocialConversationStateCopyWith<$Res> implements $SocialConversationStateCopyWith<$Res> { + factory _$SocialConversationStateCopyWith(_SocialConversationState value, $Res Function(_SocialConversationState) _then) = __$SocialConversationStateCopyWithImpl; +@override @useResult +$Res call({ + String? myAccountId, List messages, int? minLoadedSeq, int? maxLoadedSeq, bool hasOlder, bool loadingOlder, bool isLoading, Object? error +}); + + + + +} +/// @nodoc +class __$SocialConversationStateCopyWithImpl<$Res> + implements _$SocialConversationStateCopyWith<$Res> { + __$SocialConversationStateCopyWithImpl(this._self, this._then); + + final _SocialConversationState _self; + final $Res Function(_SocialConversationState) _then; + +/// Create a copy of SocialConversationState +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? myAccountId = freezed,Object? messages = null,Object? minLoadedSeq = freezed,Object? maxLoadedSeq = freezed,Object? hasOlder = null,Object? loadingOlder = null,Object? isLoading = null,Object? error = freezed,}) { + return _then(_SocialConversationState( +myAccountId: freezed == myAccountId ? _self.myAccountId : myAccountId // ignore: cast_nullable_to_non_nullable +as String?,messages: null == messages ? _self._messages : messages // ignore: cast_nullable_to_non_nullable +as List,minLoadedSeq: freezed == minLoadedSeq ? _self.minLoadedSeq : minLoadedSeq // ignore: cast_nullable_to_non_nullable +as int?,maxLoadedSeq: freezed == maxLoadedSeq ? _self.maxLoadedSeq : maxLoadedSeq // ignore: cast_nullable_to_non_nullable +as int?,hasOlder: null == hasOlder ? _self.hasOlder : hasOlder // ignore: cast_nullable_to_non_nullable +as bool,loadingOlder: null == loadingOlder ? _self.loadingOlder : loadingOlder // ignore: cast_nullable_to_non_nullable +as bool,isLoading: null == isLoading ? _self.isLoading : isLoading // ignore: cast_nullable_to_non_nullable +as bool,error: freezed == error ? _self.error : error , + )); +} + + +} + +// dart format on diff --git a/apps/mobile/lib/application/social/social_friends_providers.dart b/apps/mobile/lib/application/social/social_friends_providers.dart new file mode 100644 index 00000000..b0edc169 --- /dev/null +++ b/apps/mobile/lib/application/social/social_friends_providers.dart @@ -0,0 +1,58 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:minos/application/social/social_ui_state.dart'; +import 'package:minos/data/repositories/realtime_events_repository.dart'; +import 'package:minos/data/repositories/social_repository.dart'; +import 'package:minos/src/rust/api/minos.dart'; + +final friendsProvider = + AsyncNotifierProvider( + FriendsController.new, + ); + +class FriendsController extends AsyncNotifier { + @override + Future build() { + ref.watch(friendRequestRealtimeSyncProvider); + return ref.watch(socialRepositoryProvider).friends(); + } + + Future refresh() async { + state = AsyncValue.data(await ref.read(socialRepositoryProvider).friends()); + } +} + +/// T2 FriendRequestUpdated durable → refresh friend list (HTTP). +/// Also surfaces subscription_limit_exceeded for shell notice (R4). +final friendRequestRealtimeSyncProvider = Provider((ref) { + final repo = ref.watch(realtimeEventsRepositoryProvider); + final sub = repo.uiEvents.listen((frame) { + final ui = frame.ui; + if (ui is! UiEventMessage_Raw) return; + if (ui.kind == 'friend_request_updated') { + unawaited(ref.read(friendsProvider.notifier).refresh()); + return; + } + if (ui.kind == 'subscription_limit_exceeded') { + int limit = 0; + int current = 0; + try { + final payload = jsonDecode(ui.payloadJson) as Map?; + limit = (payload?['limit'] as num?)?.toInt() ?? 0; + current = (payload?['current'] as num?)?.toInt() ?? 0; + } catch (_) {} + ref + .read(subscriptionLimitNoticeControllerProvider.notifier) + .publish( + SubscriptionLimitNotice( + limit: limit, + current: current, + atMs: DateTime.now().millisecondsSinceEpoch, + ), + ); + } + }); + ref.onDispose(sub.cancel); +}); diff --git a/apps/mobile/lib/application/social/social_inbox_notifier.dart b/apps/mobile/lib/application/social/social_inbox_notifier.dart new file mode 100644 index 00000000..31d3dab6 --- /dev/null +++ b/apps/mobile/lib/application/social/social_inbox_notifier.dart @@ -0,0 +1,412 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:minos/application/conversations_sort.dart'; +import 'package:minos/application/flutter_log.dart'; +import 'package:minos/application/group_agent_provider.dart'; +import 'package:minos/application/im_outbox_worker.dart'; +import 'package:minos/application/social/social_conversation_notifier.dart'; +import 'package:minos/application/social/social_realtime_sync.dart'; +import 'package:minos/application/social/social_ui_state.dart'; +import 'package:minos/data/repositories/social_repository.dart'; +import 'package:minos/data/services/minos_core_service.dart'; +import 'package:minos/domain/message_sender_ext.dart'; +import 'package:minos/src/rust/api/minos.dart'; + +final conversationsProvider = + AsyncNotifierProvider( + ConversationsController.new, + ); + +/// InboxSync: incremental patch; full REST only hydrate / refresh / snapshot. +class ConversationsController extends AsyncNotifier { + StreamSubscription? _eventsSub; + + @override + Future build() async { + // Arm SnapshotRequired consumer for app lifetime (Inbox/Timeline). + ref.watch(imSnapshotSyncProvider); + + _eventsSub ??= ref + .read(socialRepositoryProvider) + .socialEvents + .listen( + (frame) { + // Hot path: single-row patch — never invalidateSelf / full REST. + unawaited(_onSocialEvent(frame)); + }, + onError: (Object error, StackTrace stackTrace) { + // Connection errors: soft; next hydrate corrects. + }, + onDone: () {}, + ); + ref.onDispose(() => _eventsSub?.cancel()); + + // Start IM outbox worker once conversations hydrate; wire UI refresh hooks. + final outbox = ref.read(imOutboxWorkerProvider); + // Never materialize autoDispose open-chat for background drain — that + // would subscribe + mark-read a conversation the user is not viewing. + outbox.onConversationDirty = (conversationId) { + final timeline = socialConversationProvider(conversationId); + if (!ref.exists(timeline)) { + return; + } + unawaited(ref.read(timeline.notifier).reloadFromLocalCache()); + }; + outbox.onInboxDirty = () { + // Prefer patch if possible; full refresh only when worker cannot patch. + unawaited(refresh()); + }; + unawaited(outbox.ensureStarted()); + + final repository = ref.read(socialRepositoryProvider); + final cached = await repository.loadConversations(); + if (cached != null && cached.conversations.isNotEmpty) { + unawaited(_refreshFromRemote()); + return conversationsSortedByLastActive(cached); + } + + try { + return await _fetchRemoteConversations(); + } catch (_) { + if (cached != null) { + return conversationsSortedByLastActive(cached); + } + rethrow; + } + } + + Future refresh() async { + state = AsyncValue.data(await _fetchRemoteConversations()); + } + + /// Account SnapshotRequired / pull-to-refresh entry. + Future onAccountSnapshot() => refresh(); + + Future deleteConversation(String conversationId) async { + final previous = state; + final current = previous.asData?.value; + if (current != null) { + state = AsyncValue.data( + conversationsSortedByLastActive( + ConversationsResponse( + conversations: current.conversations + .where( + (conversation) => + conversation.conversationId != conversationId, + ) + .toList(growable: false), + ), + ), + ); + } + try { + await ref + .read(socialRepositoryProvider) + .deleteConversation(conversationId: conversationId); + ref.invalidate(socialConversationProvider(conversationId)); + ref.invalidate(conversationParticipantsProvider(conversationId)); + } catch (error, stackTrace) { + state = previous; + Error.throwWithStackTrace(error, stackTrace); + } + } + + Future applyMarkReadLocal(String conversationId) async { + final current = state.asData?.value; + if (current == null) return; + final next = current.conversations + .map((c) { + if (c.conversationId != conversationId) return c; + return ConversationSummary( + conversationId: c.conversationId, + kind: c.kind, + title: c.title, + counterpart: c.counterpart, + memberCount: c.memberCount, + lastMessagePreview: c.lastMessagePreview, + lastMessageAtMs: c.lastMessageAtMs, + unreadCount: 0, + unreadMentionCount: 0, + ); + }) + .toList(growable: false); + state = AsyncValue.data( + conversationsSortedByLastActive( + ConversationsResponse(conversations: next), + ), + ); + await ref.read(socialRepositoryProvider).clearUnread(conversationId); + } + + Future patchPreview({ + required String conversationId, + required String preview, + required int lastMessageAtMs, + int? unreadCount, + }) async { + final repository = ref.read(socialRepositoryProvider); + await repository.touchConversationPreview( + conversationId: conversationId, + preview: preview, + createdAtMs: lastMessageAtMs, + unreadCount: unreadCount, + ); + final current = state.asData?.value; + if (current == null) return; + final exists = current.conversations.any( + (c) => c.conversationId == conversationId, + ); + List next; + if (exists) { + next = current.conversations + .map((c) { + if (c.conversationId != conversationId) return c; + final prevMs = repository.platformInt64ToIntValue( + c.lastMessageAtMs, + ); + final incoming = lastMessageAtMs > 0 ? lastMessageAtMs : 0; + final nextMs = incoming > 0 + ? (incoming > prevMs ? incoming : prevMs) + : prevMs; + return ConversationSummary( + conversationId: c.conversationId, + kind: c.kind, + title: c.title, + counterpart: c.counterpart, + memberCount: c.memberCount, + lastMessagePreview: preview, + lastMessageAtMs: repository.platformInt64FromIntValue(nextMs), + unreadCount: unreadCount ?? c.unreadCount, + unreadMentionCount: unreadCount == 0 ? 0 : c.unreadMentionCount, + ); + }) + .toList(growable: false); + } else { + next = [ + ConversationSummary( + conversationId: conversationId, + kind: ConversationKind.group, + title: 'Conversation', + memberCount: 0, + lastMessagePreview: preview, + lastMessageAtMs: repository.platformInt64FromIntValue( + lastMessageAtMs > 0 ? lastMessageAtMs : 0, + ), + unreadCount: unreadCount ?? 0, + unreadMentionCount: 0, + ), + ...current.conversations, + ]; + } + state = AsyncValue.data( + conversationsSortedByLastActive( + ConversationsResponse(conversations: next), + ), + ); + } + + Future patchFromInbound({ + required ChatMessageSummary message, + required bool focused, + String? myAccountId, + }) async { + final repository = ref.read(socialRepositoryProvider); + final conversationId = message.conversationId; + if (conversationId.isEmpty || message.messageId.trim().isEmpty) { + return; + } + final createdAtMs = repository.platformInt64ToIntValue(message.createdAtMs); + final isRecall = message.recalledAtMs != null; + final isOwn = + myAccountId != null && + myAccountId.isNotEmpty && + message.sender.accountIdOrNull == myAccountId; + final mention = + myAccountId != null && + message.mentionedAccountIds.contains(myAccountId); + + int unread = 0; + int unreadMention = 0; + final prev = await repository.loadConversation(conversationId); + final prevMs = prev != null + ? repository.platformInt64ToIntValue(prev.lastMessageAtMs) + : 0; + // Monotonic list clock: never regress when a recall/stale frame carries + // an older createdAtMs than the current rail tip. + final nextMs = createdAtMs > 0 + ? (createdAtMs > prevMs ? createdAtMs : prevMs) + : prevMs; + if (focused || isOwn) { + unread = 0; + unreadMention = 0; + await repository.clearUnread(conversationId); + } else if (!isRecall) { + unread = (prev?.unreadCount ?? 0) + 1; + unreadMention = (prev?.unreadMentionCount ?? 0) + (mention ? 1 : 0); + await repository.touchConversationPreview( + conversationId: conversationId, + preview: message.text, + createdAtMs: nextMs, + unreadCount: unread, + unreadMentionCount: unreadMention, + ); + } else { + // Recall: preview only; keep unread as-is (server digest is SSOT). + unread = prev?.unreadCount ?? 0; + unreadMention = prev?.unreadMentionCount ?? 0; + await repository.touchConversationPreview( + conversationId: conversationId, + preview: message.text, + createdAtMs: nextMs, + unreadCount: unread, + unreadMentionCount: unreadMention, + ); + } + if (focused || isOwn) { + await repository.touchConversationPreview( + conversationId: conversationId, + preview: message.text, + createdAtMs: nextMs, + unreadCount: 0, + unreadMentionCount: 0, + ); + } + + final current = state.asData?.value; + if (current == null) return; + + final exists = current.conversations.any( + (c) => c.conversationId == conversationId, + ); + final nextLastAt = repository.platformInt64FromIntValue(nextMs); + List next; + if (exists) { + next = current.conversations + .map((c) { + if (c.conversationId != conversationId) return c; + return ConversationSummary( + conversationId: c.conversationId, + kind: c.kind, + title: c.title, + counterpart: c.counterpart, + memberCount: c.memberCount, + lastMessagePreview: message.text, + lastMessageAtMs: nextLastAt, + unreadCount: focused || isOwn ? 0 : unread, + unreadMentionCount: focused || isOwn ? 0 : unreadMention, + ); + }) + .toList(growable: false); + } else { + next = [ + ConversationSummary( + conversationId: conversationId, + kind: ConversationKind.group, + title: prev?.title ?? 'Conversation', + counterpart: prev?.counterpart, + memberCount: prev?.memberCount ?? 0, + lastMessagePreview: message.text, + lastMessageAtMs: nextLastAt, + unreadCount: focused || isOwn ? 0 : (isRecall ? 0 : 1), + unreadMentionCount: focused || isOwn + ? 0 + : (isRecall ? 0 : (mention ? 1 : 0)), + ), + ...current.conversations, + ]; + } + state = AsyncValue.data( + conversationsSortedByLastActive( + ConversationsResponse(conversations: next), + ), + ); + } + + Future _onSocialEvent(SocialEventFrame frame) async { + // Reactions are conversation-only; do not bump sidebar unread. + // Open conversation controller acks conversation reaction topics. + if (frame.kind == 'reaction_updated') { + return; + } + // Inbox path: account T2 digests + conversation full (when open) both patch + // rail preview/unread. Digests carry preview in message.text stub. + if (frame.kind != 'message' && + frame.kind != 'inbox_digest' && + frame.kind != 'inbox_recall') { + return; + } + if (frame.message.messageId.trim().isEmpty) { + return; + } + final focusedId = ref.read(focusedSocialConversationIdProvider); + final focused = focusedId != null && focusedId == frame.conversationId; + // Open conversation controller also patches; still apply inbox for badge + // when not focused. When focused, SocialConversation drives markRead. + String? myAccountId; + try { + myAccountId = await ref + .read(socialRepositoryProvider) + .loadCurrentAccountId(); + } catch (_) {} + try { + await patchFromInbound( + message: frame.message, + focused: focused, + myAccountId: myAccountId, + ); + // Account digests must ack here (conversation controller ignores them). + // Conversation message frames: open chat acks; when not open, inbox still + // needs cursor advance after digest/rail patch. + final topic = frame.topic.trim(); + final seq = frame.topicSeq.toInt(); + if (topic.isNotEmpty && seq > 0) { + final isAccountTopic = topic.startsWith('account:'); + final isConversationMessage = + frame.kind == 'message' && topic.startsWith('conversation:'); + // Open conversation owns conversation: topic ack for messages. + if (isAccountTopic || + frame.kind == 'inbox_digest' || + frame.kind == 'inbox_recall' || + (isConversationMessage && !focused)) { + await ref + .read(minosCoreServiceProvider) + .ackDurableApplied(topic: topic, topicSeq: seq); + } + } + } catch (e, st) { + // Do not ack on failure — resume will redeliver. + logFlutterWarn( + 'social_providers', + 'inbox social apply failed (cursor held)', + error: e, + stackTrace: st, + ); + } + } + + Future _fetchRemoteConversations() async { + final repository = ref.read(socialRepositoryProvider); + final response = await repository.conversations(); + await repository.saveConversations(response.conversations); + return conversationsSortedByLastActive(response); + } + + Future _refreshFromRemote() async { + try { + state = AsyncValue.data(await _fetchRemoteConversations()); + } catch (_) {} + } +} + +final socialUnreadCountProvider = Provider((ref) { + return ref + .watch(conversationsProvider) + .maybeWhen( + data: (response) => response.conversations.fold( + 0, + (total, conversation) => total + conversation.unreadCount, + ), + orElse: () => 0, + ); +}); diff --git a/apps/mobile/lib/application/social/social_realtime_sync.dart b/apps/mobile/lib/application/social/social_realtime_sync.dart new file mode 100644 index 00000000..b2171646 --- /dev/null +++ b/apps/mobile/lib/application/social/social_realtime_sync.dart @@ -0,0 +1,45 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:minos/application/social/social_conversation_notifier.dart'; +import 'package:minos/application/social/social_inbox_notifier.dart'; +import 'package:minos/data/repositories/realtime_events_repository.dart'; +import 'package:minos/src/rust/api/minos.dart'; + +/// Consume `snapshot_required` UiEvent (Rust realtime) → TimelineSync / InboxSync. +/// +/// Conversation topic: only reconcile when [socialConversationProvider] already +/// exists (chat open). Never cold-start autoDispose for a closed chat (would +/// race mark-read / clear-unread). Background: no-op; next open rebuilds. +/// Account topic: full inbox hydrate is OK. +final imSnapshotSyncProvider = Provider((ref) { + final repo = ref.watch(realtimeEventsRepositoryProvider); + final sub = repo.uiEvents.listen((frame) { + final ui = frame.ui; + if (ui is! UiEventMessage_Raw || ui.kind != 'snapshot_required') return; + try { + final map = jsonDecode(ui.payloadJson); + if (map is! Map) return; + final topic = map['topic']?.toString().trim() ?? ''; + if (topic.isEmpty) return; + if (topic.startsWith('conversation:')) { + final conversationId = topic.substring('conversation:'.length).trim(); + if (conversationId.isEmpty) return; + final timeline = socialConversationProvider(conversationId); + // Prefer exists: do not materialize autoDispose for closed chats. + if (!ref.exists(timeline)) { + return; + } + unawaited(ref.read(timeline.notifier).onSnapshotRequired()); + return; + } + if (topic.startsWith('account:')) { + unawaited(ref.read(conversationsProvider.notifier).onAccountSnapshot()); + } + } catch (_) { + // Malformed snapshot payload — ignore; next hydrate corrects. + } + }); + ref.onDispose(sub.cancel); +}); diff --git a/apps/mobile/lib/application/social/social_ui_state.dart b/apps/mobile/lib/application/social/social_ui_state.dart new file mode 100644 index 00000000..386a2e35 --- /dev/null +++ b/apps/mobile/lib/application/social/social_ui_state.dart @@ -0,0 +1,75 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:minos/application/group_agent_provider.dart'; +import 'package:minos/data/repositories/social_repository.dart'; +import 'package:minos/src/rust/api/minos.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'social_ui_state.g.dart'; + +/// Currently open social chat conversation (focused for unread / markRead). +/// Distinct from "has timeline window" (provider alive with messages). +@Riverpod(keepAlive: true) +class FocusedSocialConversationId extends _$FocusedSocialConversationId { + @override + String? build() => null; + + void set(String? conversationId) => state = conversationId; + + void clear() => state = null; +} + +/// Last realtime subscription limit breach (R4). Shell can toast/banner. +class SubscriptionLimitNotice { + const SubscriptionLimitNotice({ + required this.limit, + required this.current, + required this.atMs, + }); + final int limit; + final int current; + final int atMs; +} + +@Riverpod(keepAlive: true) +class SubscriptionLimitNoticeController + extends _$SubscriptionLimitNoticeController { + @override + SubscriptionLimitNotice? build() => null; + + void publish(SubscriptionLimitNotice notice) => state = notice; + + void clear() => state = null; +} + +/// Compatibility alias for existing listeners. +final subscriptionLimitNoticeProvider = + subscriptionLimitNoticeControllerProvider; + +final socialProfileProvider = FutureProvider((ref) { + return ref.watch(socialRepositoryProvider).myProfile(); +}); + +/// Human members derived from unified participants (ADR 0021). +final conversationMembersProvider = FutureProvider.family + .autoDispose, String>((ref, conversationId) async { + final participants = await ref.watch( + conversationParticipantsProvider(conversationId).future, + ); + return participants.humans; + }); + +@riverpod +class SocialReplyDraft extends _$SocialReplyDraft { + @override + String? build(String conversationId) { + return null; + } + + void select(String localId) { + state = localId; + } + + void clear() { + state = null; + } +} diff --git a/apps/mobile/lib/application/social_providers.g.dart b/apps/mobile/lib/application/social/social_ui_state.g.dart similarity index 55% rename from apps/mobile/lib/application/social_providers.g.dart rename to apps/mobile/lib/application/social/social_ui_state.g.dart index f61fc93a..9085a494 100644 --- a/apps/mobile/lib/application/social_providers.g.dart +++ b/apps/mobile/lib/application/social/social_ui_state.g.dart @@ -1,6 +1,6 @@ // GENERATED CODE - DO NOT MODIFY BY HAND -part of 'social_providers.dart'; +part of 'social_ui_state.dart'; // ************************************************************************** // RiverpodGenerator @@ -8,52 +8,125 @@ part of 'social_providers.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint, type=warning +/// Currently open social chat conversation (focused for unread / markRead). +/// Distinct from "has timeline window" (provider alive with messages). + +@ProviderFor(FocusedSocialConversationId) +final focusedSocialConversationIdProvider = + FocusedSocialConversationIdProvider._(); + +/// Currently open social chat conversation (focused for unread / markRead). +/// Distinct from "has timeline window" (provider alive with messages). +final class FocusedSocialConversationIdProvider + extends $NotifierProvider { + /// Currently open social chat conversation (focused for unread / markRead). + /// Distinct from "has timeline window" (provider alive with messages). + FocusedSocialConversationIdProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'focusedSocialConversationIdProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$focusedSocialConversationIdHash(); + + @$internal + @override + FocusedSocialConversationId create() => FocusedSocialConversationId(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(String? value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$focusedSocialConversationIdHash() => + r'75eef236b7ed3de7c8d8be65f688b8084496bc7e'; + +/// Currently open social chat conversation (focused for unread / markRead). +/// Distinct from "has timeline window" (provider alive with messages). + +abstract class _$FocusedSocialConversationId extends $Notifier { + String? build(); + @$mustCallSuper + @override + void runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + String?, + Object?, + Object? + >; + element.handleCreate(ref, build); + } +} -@ProviderFor(SocialSearchQuery) -final socialSearchQueryProvider = SocialSearchQueryProvider._(); +@ProviderFor(SubscriptionLimitNoticeController) +final subscriptionLimitNoticeControllerProvider = + SubscriptionLimitNoticeControllerProvider._(); -final class SocialSearchQueryProvider - extends $NotifierProvider { - SocialSearchQueryProvider._() +final class SubscriptionLimitNoticeControllerProvider + extends + $NotifierProvider< + SubscriptionLimitNoticeController, + SubscriptionLimitNotice? + > { + SubscriptionLimitNoticeControllerProvider._() : super( from: null, argument: null, retry: null, - name: r'socialSearchQueryProvider', - isAutoDispose: true, + name: r'subscriptionLimitNoticeControllerProvider', + isAutoDispose: false, dependencies: null, $allTransitiveDependencies: null, ); @override - String debugGetCreateSourceHash() => _$socialSearchQueryHash(); + String debugGetCreateSourceHash() => + _$subscriptionLimitNoticeControllerHash(); @$internal @override - SocialSearchQuery create() => SocialSearchQuery(); + SubscriptionLimitNoticeController create() => + SubscriptionLimitNoticeController(); /// {@macro riverpod.override_with_value} - Override overrideWithValue(String value) { + Override overrideWithValue(SubscriptionLimitNotice? value) { return $ProviderOverride( origin: this, - providerOverride: $SyncValueProvider(value), + providerOverride: $SyncValueProvider(value), ); } } -String _$socialSearchQueryHash() => r'8d3b2514681408de97b829d3eb39924c580818ac'; +String _$subscriptionLimitNoticeControllerHash() => + r'8c01829224dd30395a2926e12d8cdc30cd84298c'; -abstract class _$SocialSearchQuery extends $Notifier { - String build(); +abstract class _$SubscriptionLimitNoticeController + extends $Notifier { + SubscriptionLimitNotice? build(); @$mustCallSuper @override void runBuild() { - final ref = this.ref as $Ref; + final ref = + this.ref as $Ref; final element = ref.element as $ClassProviderElement< - AnyNotifier, - String, + AnyNotifier, + SubscriptionLimitNotice?, Object?, Object? >; @@ -157,102 +230,3 @@ abstract class _$SocialReplyDraft extends $Notifier { element.handleCreate(ref, () => build(_$args)); } } - -@ProviderFor(SocialConversation) -final socialConversationProvider = SocialConversationFamily._(); - -final class SocialConversationProvider - extends $NotifierProvider { - SocialConversationProvider._({ - required SocialConversationFamily super.from, - required String super.argument, - }) : super( - retry: null, - name: r'socialConversationProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$socialConversationHash(); - - @override - String toString() { - return r'socialConversationProvider' - '' - '($argument)'; - } - - @$internal - @override - SocialConversation create() => SocialConversation(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(SocialConversationState value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } - - @override - bool operator ==(Object other) { - return other is SocialConversationProvider && other.argument == argument; - } - - @override - int get hashCode { - return argument.hashCode; - } -} - -String _$socialConversationHash() => - r'b8970b659094be55b1a598533b55dc2d7e17c02d'; - -final class SocialConversationFamily extends $Family - with - $ClassFamilyOverride< - SocialConversation, - SocialConversationState, - SocialConversationState, - SocialConversationState, - String - > { - SocialConversationFamily._() - : super( - retry: null, - name: r'socialConversationProvider', - dependencies: null, - $allTransitiveDependencies: null, - isAutoDispose: true, - ); - - SocialConversationProvider call(String conversationId) => - SocialConversationProvider._(argument: conversationId, from: this); - - @override - String toString() => r'socialConversationProvider'; -} - -abstract class _$SocialConversation extends $Notifier { - late final _$args = ref.$arg as String; - String get conversationId => _$args; - - SocialConversationState build(String conversationId); - @$mustCallSuper - @override - void runBuild() { - final ref = - this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - SocialConversationState, - Object?, - Object? - >; - element.handleCreate(ref, () => build(_$args)); - } -} diff --git a/apps/mobile/lib/application/social_actions.dart b/apps/mobile/lib/application/social_actions.dart index 9f0b4cd7..f1c93c1e 100644 --- a/apps/mobile/lib/application/social_actions.dart +++ b/apps/mobile/lib/application/social_actions.dart @@ -22,10 +22,6 @@ class SocialActions { ); } - Future setMinosId({required String minosId}) { - return _repository.setMinosId(minosId: minosId); - } - Future createGroupConversation({ required String title, required List memberAccountIds, @@ -36,18 +32,6 @@ class SocialActions { ); } - Future rejectFriendRequest({required String requestId}) { - return _repository.rejectFriendRequest(requestId: requestId); - } - - Future acceptFriendRequest({required String requestId}) { - return _repository.acceptFriendRequest(requestId: requestId); - } - - Future createFriendRequest({required String targetMinosId}) { - return _repository.createFriendRequest(targetMinosId: targetMinosId); - } - Future addGroupMember({ required String conversationId, required String memberAccountId, diff --git a/apps/mobile/lib/application/social_providers.dart b/apps/mobile/lib/application/social_providers.dart index 7e67cea1..030b0f4f 100644 --- a/apps/mobile/lib/application/social_providers.dart +++ b/apps/mobile/lib/application/social_providers.dart @@ -1,1278 +1,14 @@ -import 'dart:async'; -import 'dart:convert'; - -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_riverpod/legacy.dart' show StateProvider; -import 'package:minos/application/agent_activity_provider.dart'; -import 'package:minos/application/conversations_sort.dart'; -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/application/group_agent_provider.dart'; -import 'package:minos/application/im_outbox_worker.dart'; -import 'package:minos/data/repositories/social_repository.dart'; -import 'package:minos/data/repositories/thread_repository.dart'; -import 'package:minos/data/services/minos_core_service.dart'; -import 'package:minos/domain/mention_extract.dart'; -import 'package:minos/domain/message_sender_ext.dart'; -import 'package:minos/domain/social_message.dart'; -import 'package:minos/domain/social_message_order.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'social_providers.g.dart'; - -/// Currently open social chat conversation (focused for unread / markRead). -/// Distinct from "has timeline window" (provider alive with messages). -final focusedSocialConversationIdProvider = StateProvider((ref) { - return null; -}); - -/// Last realtime subscription limit breach (R4). Shell can toast/banner. -class SubscriptionLimitNotice { - const SubscriptionLimitNotice({ - required this.limit, - required this.current, - required this.atMs, - }); - final int limit; - final int current; - final int atMs; -} - -final subscriptionLimitNoticeProvider = StateProvider( - (ref) => null, -); - -/// Consume `snapshot_required` UiEvent (Rust realtime) → TimelineSync / InboxSync. +/// Compatibility barrel for social application providers. /// -/// Conversation topic: only reconcile when [socialConversationProvider] already -/// exists (chat open). Never cold-start autoDispose for a closed chat (would -/// race mark-read / clear-unread). Background: no-op; next open rebuilds. -/// Account topic: full inbox hydrate is OK. -final imSnapshotSyncProvider = Provider((ref) { - final repo = ref.watch(threadRepositoryProvider); - final sub = repo.uiEvents.listen((frame) { - final ui = frame.ui; - if (ui is! UiEventMessage_Raw || ui.kind != 'snapshot_required') return; - try { - final map = jsonDecode(ui.payloadJson); - if (map is! Map) return; - final topic = map['topic']?.toString().trim() ?? ''; - if (topic.isEmpty) return; - if (topic.startsWith('conversation:')) { - final conversationId = topic.substring('conversation:'.length).trim(); - if (conversationId.isEmpty) return; - final timeline = socialConversationProvider(conversationId); - // Prefer exists: do not materialize autoDispose for closed chats. - if (!ref.exists(timeline)) { - return; - } - unawaited(ref.read(timeline.notifier).onSnapshotRequired()); - return; - } - if (topic.startsWith('account:')) { - unawaited(ref.read(conversationsProvider.notifier).onAccountSnapshot()); - } - } catch (_) { - // Malformed snapshot payload — ignore; next hydrate corrects. - } - }); - ref.onDispose(sub.cancel); -}); - -final socialProfileProvider = FutureProvider((ref) { - return ref.watch(socialRepositoryProvider).myProfile(); -}); - -@riverpod -class SocialSearchQuery extends _$SocialSearchQuery { - @override - String build() { - return ''; - } - - void update(String value) { - state = value.trim(); - } -} - -final socialSearchProvider = FutureProvider.family - .autoDispose, String>((ref, query) async { - final trimmed = query.trim(); - if (trimmed.isEmpty) return const []; - return ref.watch(socialRepositoryProvider).searchUsers(minosId: trimmed); - }); - -/// Human members derived from unified participants (ADR 0021). -final conversationMembersProvider = FutureProvider.family - .autoDispose, String>((ref, conversationId) async { - final participants = await ref.watch( - conversationParticipantsProvider(conversationId).future, - ); - return participants.humans; - }); - -@riverpod -class SocialReplyDraft extends _$SocialReplyDraft { - @override - String? build(String conversationId) { - return null; - } - - void select(String localId) { - state = localId; - } - - void clear() { - state = null; - } -} - -final socialReplyMessageProvider = Provider.family(( - ref, - conversationId, -) { - final localId = ref.watch(socialReplyDraftProvider(conversationId)); - if (localId == null) { - return null; - } - final messages = ref - .watch(socialConversationProvider(conversationId)) - .messages; - for (final message in messages) { - if (message.localId == localId && message.canReply) { - return message; - } - } - return null; -}); - -final socialUnreadCountProvider = Provider((ref) { - return ref - .watch(conversationsProvider) - .maybeWhen( - data: (response) => response.conversations.fold( - 0, - (total, conversation) => total + conversation.unreadCount, - ), - orElse: () => 0, - ); -}); - -const Object _socialConversationUnset = Object(); - -/// Timeline window + meta for one conversation (TimelineSync). -class SocialConversationState { - const SocialConversationState({ - required this.myAccountId, - required this.messages, - required this.isLoading, - required this.error, - this.minLoadedSeq, - this.maxLoadedSeq, - this.hasOlder = false, - this.loadingOlder = false, - }); - - const SocialConversationState.initial() - : myAccountId = null, - messages = const [], - isLoading = true, - error = null, - minLoadedSeq = null, - maxLoadedSeq = null, - hasOlder = false, - loadingOlder = false; - - final String? myAccountId; - final List messages; - final int? minLoadedSeq; - final int? maxLoadedSeq; - final bool hasOlder; - final bool loadingOlder; - final bool isLoading; - final Object? error; - - SocialConversationState copyWith({ - String? myAccountId, - List? messages, - int? minLoadedSeq, - int? maxLoadedSeq, - bool? hasOlder, - bool? loadingOlder, - bool? isLoading, - Object? error = _socialConversationUnset, - }) { - return SocialConversationState( - myAccountId: myAccountId ?? this.myAccountId, - messages: messages ?? this.messages, - minLoadedSeq: minLoadedSeq ?? this.minLoadedSeq, - maxLoadedSeq: maxLoadedSeq ?? this.maxLoadedSeq, - hasOlder: hasOlder ?? this.hasOlder, - loadingOlder: loadingOlder ?? this.loadingOlder, - isLoading: isLoading ?? this.isLoading, - error: identical(error, _socialConversationUnset) ? this.error : error, - ); - } - - SocialConversationState withMessages(List next) { - return copyWith( - messages: next, - minLoadedSeq: minLoadedSeqOf(next), - maxLoadedSeq: maxLoadedSeqOf(next), - ); - } -} - -@riverpod -class SocialConversation extends _$SocialConversation { - static const int _pageSize = 100; - static const Duration _markReadDebounce = Duration(milliseconds: 400); - - StreamSubscription? _eventsSub; - Timer? _markReadTimer; - - late final String _conversationId; - - @override - SocialConversationState build(String conversationId) { - const initialState = SocialConversationState.initial(); - _conversationId = conversationId; - unawaited(_eventsSub?.cancel() ?? Future.value()); - _eventsSub = ref - .read(socialRepositoryProvider) - .socialEvents - .listen( - _onSocialEvent, - // Soft: connection churn must not rebuild + mark-read the open chat. - onError: (Object error, StackTrace stackTrace) {}, - onDone: () {}, - ); - // R3a: open chat subscribes conversation topic for full T1 live frames. - // Account topic digests are inbox-only and must not drive this timeline. - final repository = ref.read(socialRepositoryProvider); - unawaited(repository.subscribeConversation(conversationId: conversationId)); - ref.onDispose(() { - unawaited(_eventsSub?.cancel() ?? Future.value()); - _markReadTimer?.cancel(); - unawaited( - repository.unsubscribeConversation(conversationId: conversationId), - ); - }); - unawaited(_load(seedState: initialState)); - return initialState; - } - - Future refresh() => _load(); - - /// Cache-only reload after outbox ack (no REST, no mark-read, no subscribe). - /// Used when the conversation is already open; never materialize closed chats. - Future reloadFromLocalCache() async { - final repository = ref.read(socialRepositoryProvider); - final messages = await repository.loadMessages(_conversationId); - state = state.withMessages(messages).copyWith(error: null); - } - - /// Older page via Hub `before_seq` (TimelineSync.loadOlder). - Future loadOlder() async { - if (state.loadingOlder || !state.hasOlder) { - return; - } - final minSeq = state.minLoadedSeq; - if (minSeq == null || minSeq <= 1) { - state = state.copyWith(hasOlder: false, loadingOlder: false); - return; - } - - state = state.copyWith(loadingOlder: true); - final repository = ref.read(socialRepositoryProvider); - try { - final response = await repository.listChatMessages( - conversationId: _conversationId, - beforeSeq: minSeq, - limit: _pageSize, - ); - await repository.upsertRemoteMessages( - conversationId: _conversationId, - messages: response.messages, - ); - final messages = await repository.loadMessages(_conversationId); - final hasOlder = - response.nextBeforeSeq != null || - response.messages.length >= _pageSize; - state = state - .withMessages(messages) - .copyWith(hasOlder: hasOlder, loadingOlder: false, error: null); - } catch (error) { - state = state.copyWith(loadingOlder: false, error: error); - } - } - - /// SnapshotRequired range reconcile: keep window, forward fill + latest page. - /// Timeline-only: does **not** mark-read or clear unread (caller must only - /// invoke when this provider already exists / chat is open). - Future onSnapshotRequired() async { - final repository = ref.read(socialRepositoryProvider); - final prev = state.messages; - final maxSeq = state.maxLoadedSeq ?? maxLoadedSeqOf(prev); - try { - if (maxSeq != null) { - final forward = await repository.listChatMessages( - conversationId: _conversationId, - afterSeq: maxSeq, - limit: _pageSize, - ); - await repository.upsertRemoteMessages( - conversationId: _conversationId, - messages: forward.messages, - ); - } - final latest = await repository.listChatMessages( - conversationId: _conversationId, - limit: _pageSize, - ); - await repository.upsertRemoteMessages( - conversationId: _conversationId, - messages: latest.messages, - ); - final messages = await repository.loadMessages(_conversationId); - final hasOlder = - latest.nextBeforeSeq != null || - latest.messages.length >= _pageSize || - state.hasOlder; - state = state - .withMessages(messages) - .copyWith(hasOlder: hasOlder, isLoading: false, error: null); - // No mark-read here: open path / inbound debounce own unread. - } catch (error) { - state = state.copyWith(error: error, isLoading: false); - } - } - - Future sendMessage( - String text, { - SocialChatMessage? replyToMessage, - }) async { - final trimmed = text.trim(); - if (trimmed.isEmpty) { - return; - } - - final repository = ref.read(socialRepositoryProvider); - final replyPreview = _replyPreviewForMessage(replyToMessage); - final sender = await _localSender(); - // Optimistic structured mentions from current roster so local cache/reload - // before Hub ack still carries bot targets (Hub remains SSOT after upsert). - final participants = ref - .read(conversationParticipantsProvider(_conversationId)) - .asData - ?.value; - final optimistic = extractOptimisticMentions( - text: trimmed, - selfAccountId: sender.identityId, - humans: (participants?.humans ?? const []) - .map( - (h) => MentionHumanRef(accountId: h.accountId, minosId: h.minosId), - ) - .toList(growable: false), - agents: (participants?.agents ?? const []) - .where( - (a) => - a.status.trim().isEmpty || a.status.toLowerCase() == 'active', - ) - .map( - (a) => MentionAgentRef( - agentId: a.agentId, - runtimeAgent: a.runtimeAgent, - name: a.name, - ), - ) - .toList(growable: false), - ); - final pending = await repository.insertPendingMessageWithOutbox( - conversationId: _conversationId, - sender: sender, - text: trimmed, - replyTo: replyPreview, - mentionedAccountIds: optimistic.accountIds, - mentionedAgentIds: optimistic.agentIds, - structuredMentions: optimistic.structuredMentions, - ); - await repository.touchConversationPreview( - conversationId: _conversationId, - preview: trimmed, - createdAtMs: pending.createdAtMs, - ); - final messages = await repository.loadMessages(_conversationId); - state = state.withMessages(messages).copyWith(error: null); - // Inbox patch without full REST. - unawaited( - ref - .read(conversationsProvider.notifier) - .patchPreview( - conversationId: _conversationId, - preview: trimmed, - lastMessageAtMs: pending.createdAtMs, - unreadCount: 0, - ), - ); - - // Durable outbox owns transport; kick worker without blocking UI on REST. - unawaited(ref.read(imOutboxWorkerProvider).ensureStarted()); - unawaited(ref.read(imOutboxWorkerProvider).flush()); - } - - Future retryMessage(String localId) async { - SocialChatMessage? target; - for (final message in state.messages) { - if (message.localId == localId) { - target = message; - break; - } - } - if (target == null || - target.deliveryState != SocialMessageDeliveryState.failed) { - return; - } - - final repository = ref.read(socialRepositoryProvider); - final clientMessageId = target.wireClientMessageId; - final replyToMessageId = target.replyTo?.recalledAtMs == null - ? target.replyTo?.messageId - : null; - - await repository.markMessageSending(localId); - // Reuse the same client_message_id — never mint a new key on retry. - // Rebuild structured mentions from body + current roster (Hub validates). - final participants = ref - .read(conversationParticipantsProvider(_conversationId)) - .asData - ?.value; - final selfAccountId = await repository.loadCurrentAccountId(); - final optimistic = extractOptimisticMentions( - text: target.text, - selfAccountId: selfAccountId, - humans: (participants?.humans ?? const []) - .map( - (h) => MentionHumanRef(accountId: h.accountId, minosId: h.minosId), - ) - .toList(growable: false), - agents: (participants?.agents ?? const []) - .where( - (a) => - a.status.trim().isEmpty || a.status.toLowerCase() == 'active', - ) - .map( - (a) => MentionAgentRef( - agentId: a.agentId, - runtimeAgent: a.runtimeAgent, - name: a.name, - ), - ) - .toList(growable: false), - ); - await repository.enqueueUserMessageOutbox( - clientMessageId: clientMessageId, - conversationId: _conversationId, - text: target.text, - replyToMessageId: replyToMessageId, - structuredMentions: optimistic.structuredMentions, - ); - final messages = await repository.loadMessages(_conversationId); - state = state.withMessages(messages); - - unawaited(ref.read(imOutboxWorkerProvider).ensureStarted()); - unawaited(ref.read(imOutboxWorkerProvider).flush()); - } - - Future recallMessage(String localId) async { - SocialChatMessage? target; - for (final message in state.messages) { - if (message.localId == localId) { - target = message; - break; - } - } - if (target == null || !target.canRecall || target.serverMessageId == null) { - return; - } - - final repository = ref.read(socialRepositoryProvider); - final message = await repository.recallChatMessage( - conversationId: _conversationId, - messageId: target.serverMessageId!, - ); - await repository.upsertRemoteMessage(message); - await repository.touchConversationPreview( - conversationId: _conversationId, - preview: message.text, - createdAtMs: repository.platformInt64ToIntValue(message.createdAtMs), - ); - final messages = await repository.loadMessages(_conversationId); - state = state.withMessages(messages); - final replyDraft = ref.read(socialReplyDraftProvider(_conversationId)); - if (replyDraft == localId) { - ref.read(socialReplyDraftProvider(_conversationId).notifier).clear(); - } - unawaited( - ref - .read(conversationsProvider.notifier) - .patchPreview( - conversationId: _conversationId, - preview: message.text, - lastMessageAtMs: repository.platformInt64ToIntValue( - message.createdAtMs, - ), - ), - ); - } - - Future _load({SocialConversationState? seedState}) async { - final repository = ref.read(socialRepositoryProvider); - final previous = seedState ?? state; - final cachedMessages = await repository.loadMessages(_conversationId); - final cachedAccountId = await repository.loadCurrentAccountId(); - state = previous - .withMessages( - cachedMessages.isEmpty ? previous.messages : cachedMessages, - ) - .copyWith( - myAccountId: cachedAccountId ?? previous.myAccountId, - isLoading: true, - error: null, - ); - try { - final profile = await repository.myProfile(); - await repository.saveCurrentAccountId(profile.accountId); - final response = await repository.listChatMessages( - conversationId: _conversationId, - limit: _pageSize, - ); - await repository.upsertRemoteMessages( - conversationId: _conversationId, - messages: response.messages, - ); - await repository.clearUnread(_conversationId); - final messages = await repository.loadMessages(_conversationId); - final hasOlder = - response.nextBeforeSeq != null || - response.messages.length >= _pageSize; - state = SocialConversationState( - myAccountId: profile.accountId, - messages: messages, - minLoadedSeq: minLoadedSeqOf(messages), - maxLoadedSeq: maxLoadedSeqOf(messages), - hasOlder: hasOlder, - loadingOlder: false, - isLoading: false, - error: null, - ); - // Mark-read after state has observed maxLoadedSeq (not before). - unawaited(_markConversationReadNow()); - ref.invalidate(conversationAgentSessionsProvider(_conversationId)); - unawaited( - ref - .read(conversationsProvider.notifier) - .applyMarkReadLocal(_conversationId), - ); - } catch (error) { - final fallback = cachedMessages.isEmpty - ? previous.messages - : cachedMessages; - state = SocialConversationState( - myAccountId: cachedAccountId ?? previous.myAccountId, - messages: fallback, - minLoadedSeq: minLoadedSeqOf(fallback), - maxLoadedSeq: maxLoadedSeqOf(fallback), - hasOlder: previous.hasOlder, - loadingOlder: false, - isLoading: false, - error: error, - ); - } - } - - void _onSocialEvent(SocialEventFrame frame) { - if (frame.conversationId != _conversationId) { - return; - } - // Account T2 digests are for inbox only — never timeline. - if (frame.kind == 'inbox_digest' || frame.kind == 'inbox_recall') { - return; - } - if (frame.kind == 'reaction_updated') { - final mid = frame.message.messageId.trim(); - if (mid.isEmpty) return; - unawaited( - _applyRemoteReactions(mid, frame.message.reactions).then((_) { - return _ackDurable(frame); - }), - ); - return; - } - // Full T1 conversation frames only. - if (frame.kind != 'message') { - return; - } - // Empty shell already filtered in Rust; belt-and-suspenders here. - if (frame.message.messageId.trim().isEmpty) { - return; - } - unawaited( - _applyRemoteMessage(frame.message).then((_) => _ackDurable(frame)), - ); - } - - Future _ackDurable(SocialEventFrame frame) async { - final topic = frame.topic.trim(); - final seq = frame.topicSeq.toInt(); - if (topic.isEmpty || seq <= 0) return; - try { - await ref - .read(minosCoreServiceProvider) - .ackDurableApplied(topic: topic, topicSeq: seq); - } catch (e, st) { - // Hold cursor on failure — do not swallow without log. - logFlutterWarn( - 'social_providers', - 'ackDurableApplied failed', - error: e, - stackTrace: st, - ); - } - } - - Future _applyRemoteReactions( - String messageId, - List reactions, - ) async { - final repository = ref.read(socialRepositoryProvider); - await repository.updateMessageReactions( - conversationId: _conversationId, - messageId: messageId, - reactions: reactions, - ); - final messages = await repository.loadMessages(_conversationId); - state = state.withMessages(messages).copyWith(error: null); - } - - /// Toggle reaction via Intent Outbox; optimistic UI then worker drain. - Future toggleReaction({ - required String messageId, - required String emoji, - }) async { - final mid = messageId.trim(); - final em = emoji.trim(); - if (mid.isEmpty || em.isEmpty) return; - final repository = ref.read(socialRepositoryProvider); - final clientOpId = - 'react-${DateTime.now().microsecondsSinceEpoch}-${mid.hashCode.abs()}'; - // Optimistic: flip reacted_by_me for this emoji in local list. - final nextMessages = state.messages - .map((m) { - if (m.serverMessageId != mid && m.localId != mid) return m; - return m.copyWith(reactions: _optimisticToggle(m.reactions, em)); - }) - .toList(growable: false); - state = state.withMessages(nextMessages); - - await repository.enqueueReactionToggleOutbox( - clientOpId: clientOpId, - conversationId: _conversationId, - messageId: mid, - emoji: em, - ); - final worker = ref.read(imOutboxWorkerProvider); - unawaited(worker.ensureStarted()); - unawaited(worker.flush()); - } - - List _optimisticToggle( - List prev, - String emoji, - ) { - final list = List.from(prev); - final idx = list.indexWhere((g) => g.emoji == emoji); - if (idx < 0) { - list.add( - ReactionGroup( - emoji: emoji, - count: 1, - reactedByMe: true, - actors: const [], - ), - ); - return list; - } - final g = list[idx]; - if (g.reactedByMe) { - final count = g.count - 1; - if (count <= 0) { - list.removeAt(idx); - } else { - list[idx] = ReactionGroup( - emoji: g.emoji, - count: count, - reactedByMe: false, - actors: g.actors, - ); - } - } else { - list[idx] = ReactionGroup( - emoji: g.emoji, - count: g.count + 1, - reactedByMe: true, - actors: g.actors, - ); - } - return list; - } - - Future _applyRemoteMessage(ChatMessageSummary message) async { - final repository = ref.read(socialRepositoryProvider); - await repository.upsertRemoteMessage(message); - await repository.touchConversationPreview( - conversationId: message.conversationId, - preview: message.text, - createdAtMs: repository.platformInt64ToIntValue(message.createdAtMs), - unreadCount: 0, - ); - // Incremental merge: prefer single-row into in-memory list when possible. - final messages = await repository.loadMessages(_conversationId); - state = state.withMessages(messages).copyWith(error: null); - _scheduleMarkRead(); - ref.invalidate(conversationAgentSessionsProvider(_conversationId)); - // Inbox patch: focused → unread 0, no full REST. - unawaited( - ref - .read(conversationsProvider.notifier) - .patchFromInbound( - message: message, - focused: true, - myAccountId: state.myAccountId, - ), - ); - } - - void _scheduleMarkRead() { - _markReadTimer?.cancel(); - _markReadTimer = Timer(_markReadDebounce, () { - unawaited(_markConversationReadNow()); - }); - } - - Future _markConversationReadNow() async { - // Only mark up to the highest Hub message_seq actually loaded/observed. - // Skip HTTP when no observed seq (avoids silently marking unread rows). - final observedSeq = state.maxLoadedSeq ?? maxLoadedSeqOf(state.messages); - if (observedSeq == null || observedSeq <= 0) { - // Still clear local badge; server watermark stays until we observe seq. - try { - await ref.read(socialRepositoryProvider).clearUnread(_conversationId); - unawaited( - ref - .read(conversationsProvider.notifier) - .applyMarkReadLocal(_conversationId), - ); - } catch (_) {} - return; - } - try { - await ref - .read(socialRepositoryProvider) - .markConversationRead( - conversationId: _conversationId, - readUpToMessageSeq: observedSeq, - ); - await ref.read(socialRepositoryProvider).clearUnread(_conversationId); - unawaited( - ref - .read(conversationsProvider.notifier) - .applyMarkReadLocal(_conversationId), - ); - } catch (_) {} - } - - Future _localSender() async { - final accountId = - state.myAccountId ?? - await ref.read(socialRepositoryProvider).loadCurrentAccountId() ?? - 'local-self'; - return MessageSender.account( - accountId: accountId, - minosId: 'me', - displayName: '我', - ); - } - - ChatMessageReplySummary? _replyPreviewForMessage(SocialChatMessage? message) { - if (message == null || - !message.canReply || - message.serverMessageId == null) { - return null; - } - return ChatMessageReplySummary( - messageId: message.serverMessageId!, - sender: message.sender, - text: message.text, - recalledAtMs: message.recalledAtMs == null - ? null - : ref - .read(socialRepositoryProvider) - .platformInt64FromIntValue(message.recalledAtMs!), - ); - } -} - -final friendRequestsProvider = - AsyncNotifierProvider( - FriendRequestsController.new, - ); - -class FriendRequestsController extends AsyncNotifier { - @override - Future build() { - ref.watch(friendRequestRealtimeSyncProvider); - return ref.watch(socialRepositoryProvider).friendRequests(); - } - - Future refresh() async { - state = AsyncValue.data( - await ref.read(socialRepositoryProvider).friendRequests(), - ); - } -} - -final friendsProvider = - AsyncNotifierProvider( - FriendsController.new, - ); - -class FriendsController extends AsyncNotifier { - @override - Future build() { - ref.watch(friendRequestRealtimeSyncProvider); - return ref.watch(socialRepositoryProvider).friends(); - } - - Future refresh() async { - state = AsyncValue.data(await ref.read(socialRepositoryProvider).friends()); - } -} - -/// T2 FriendRequestUpdated durable → refresh friend / request lists (HTTP). -final friendRequestRealtimeSyncProvider = Provider((ref) { - final repo = ref.watch(threadRepositoryProvider); - final sub = repo.uiEvents.listen((frame) { - final ui = frame.ui; - if (ui is! UiEventMessage_Raw) return; - if (ui.kind == 'friend_request_updated') { - unawaited(ref.read(friendRequestsProvider.notifier).refresh()); - unawaited(ref.read(friendsProvider.notifier).refresh()); - return; - } - if (ui.kind == 'subscription_limit_exceeded') { - // Non-silent: publish notice for shell banner/toast (R4). - int limit = 0; - int current = 0; - try { - final payload = jsonDecode(ui.payloadJson) as Map?; - limit = (payload?['limit'] as num?)?.toInt() ?? 0; - current = (payload?['current'] as num?)?.toInt() ?? 0; - } catch (_) {} - ref - .read(subscriptionLimitNoticeProvider.notifier) - .state = SubscriptionLimitNotice( - limit: limit, - current: current, - atMs: DateTime.now().millisecondsSinceEpoch, - ); - } - }); - ref.onDispose(sub.cancel); -}); - -final conversationsProvider = - AsyncNotifierProvider( - ConversationsController.new, - ); - -/// InboxSync: incremental patch; full REST only hydrate / refresh / snapshot. -class ConversationsController extends AsyncNotifier { - StreamSubscription? _eventsSub; - - @override - Future build() async { - // Arm SnapshotRequired consumer for app lifetime (Inbox/Timeline). - ref.watch(imSnapshotSyncProvider); - - _eventsSub ??= ref - .read(socialRepositoryProvider) - .socialEvents - .listen( - (frame) { - // Hot path: single-row patch — never invalidateSelf / full REST. - unawaited(_onSocialEvent(frame)); - }, - onError: (Object error, StackTrace stackTrace) { - // Connection errors: soft; next hydrate corrects. - }, - onDone: () {}, - ); - ref.onDispose(() => _eventsSub?.cancel()); - - // Start IM outbox worker once conversations hydrate; wire UI refresh hooks. - final outbox = ref.read(imOutboxWorkerProvider); - // Never materialize autoDispose open-chat for background drain — that - // would subscribe + mark-read a conversation the user is not viewing. - outbox.onConversationDirty = (conversationId) { - final timeline = socialConversationProvider(conversationId); - if (!ref.exists(timeline)) { - return; - } - unawaited(ref.read(timeline.notifier).reloadFromLocalCache()); - }; - outbox.onInboxDirty = () { - // Prefer patch if possible; full refresh only when worker cannot patch. - unawaited(refresh()); - }; - unawaited(outbox.ensureStarted()); - - final repository = ref.read(socialRepositoryProvider); - final cached = await repository.loadConversations(); - if (cached != null && cached.conversations.isNotEmpty) { - unawaited(_refreshFromRemote()); - return conversationsSortedByLastActive(cached); - } - - try { - return await _fetchRemoteConversations(); - } catch (_) { - if (cached != null) { - return conversationsSortedByLastActive(cached); - } - rethrow; - } - } - - Future refresh() async { - state = AsyncValue.data(await _fetchRemoteConversations()); - } - - /// Account SnapshotRequired / pull-to-refresh entry. - Future onAccountSnapshot() => refresh(); - - Future deleteConversation(String conversationId) async { - final previous = state; - final current = previous.asData?.value; - if (current != null) { - state = AsyncValue.data( - conversationsSortedByLastActive( - ConversationsResponse( - conversations: current.conversations - .where( - (conversation) => - conversation.conversationId != conversationId, - ) - .toList(growable: false), - ), - ), - ); - } - try { - await ref - .read(socialRepositoryProvider) - .deleteConversation(conversationId: conversationId); - ref.invalidate(socialConversationProvider(conversationId)); - ref.invalidate(conversationParticipantsProvider(conversationId)); - } catch (error, stackTrace) { - state = previous; - Error.throwWithStackTrace(error, stackTrace); - } - } - - Future applyMarkReadLocal(String conversationId) async { - final current = state.asData?.value; - if (current == null) return; - final next = current.conversations - .map((c) { - if (c.conversationId != conversationId) return c; - return ConversationSummary( - conversationId: c.conversationId, - kind: c.kind, - title: c.title, - counterpart: c.counterpart, - memberCount: c.memberCount, - lastMessagePreview: c.lastMessagePreview, - lastMessageAtMs: c.lastMessageAtMs, - unreadCount: 0, - unreadMentionCount: 0, - ); - }) - .toList(growable: false); - state = AsyncValue.data( - conversationsSortedByLastActive( - ConversationsResponse(conversations: next), - ), - ); - await ref.read(socialRepositoryProvider).clearUnread(conversationId); - } - - Future patchPreview({ - required String conversationId, - required String preview, - required int lastMessageAtMs, - int? unreadCount, - }) async { - final repository = ref.read(socialRepositoryProvider); - await repository.touchConversationPreview( - conversationId: conversationId, - preview: preview, - createdAtMs: lastMessageAtMs, - unreadCount: unreadCount, - ); - final current = state.asData?.value; - if (current == null) return; - final exists = current.conversations.any( - (c) => c.conversationId == conversationId, - ); - List next; - if (exists) { - next = current.conversations - .map((c) { - if (c.conversationId != conversationId) return c; - final prevMs = repository.platformInt64ToIntValue( - c.lastMessageAtMs, - ); - final incoming = lastMessageAtMs > 0 ? lastMessageAtMs : 0; - final nextMs = incoming > 0 - ? (incoming > prevMs ? incoming : prevMs) - : prevMs; - return ConversationSummary( - conversationId: c.conversationId, - kind: c.kind, - title: c.title, - counterpart: c.counterpart, - memberCount: c.memberCount, - lastMessagePreview: preview, - lastMessageAtMs: repository.platformInt64FromIntValue(nextMs), - unreadCount: unreadCount ?? c.unreadCount, - unreadMentionCount: unreadCount == 0 ? 0 : c.unreadMentionCount, - ); - }) - .toList(growable: false); - } else { - next = [ - ConversationSummary( - conversationId: conversationId, - kind: ConversationKind.group, - title: 'Conversation', - memberCount: 0, - lastMessagePreview: preview, - lastMessageAtMs: repository.platformInt64FromIntValue( - lastMessageAtMs > 0 ? lastMessageAtMs : 0, - ), - unreadCount: unreadCount ?? 0, - unreadMentionCount: 0, - ), - ...current.conversations, - ]; - } - state = AsyncValue.data( - conversationsSortedByLastActive( - ConversationsResponse(conversations: next), - ), - ); - } - - Future patchFromInbound({ - required ChatMessageSummary message, - required bool focused, - String? myAccountId, - }) async { - final repository = ref.read(socialRepositoryProvider); - final conversationId = message.conversationId; - if (conversationId.isEmpty || message.messageId.trim().isEmpty) { - return; - } - final createdAtMs = repository.platformInt64ToIntValue(message.createdAtMs); - final isRecall = message.recalledAtMs != null; - final isOwn = - myAccountId != null && - myAccountId.isNotEmpty && - message.sender.accountIdOrNull == myAccountId; - final mention = - myAccountId != null && - message.mentionedAccountIds.contains(myAccountId); - - int unread = 0; - int unreadMention = 0; - final prev = await repository.loadConversation(conversationId); - final prevMs = prev != null - ? repository.platformInt64ToIntValue(prev.lastMessageAtMs) - : 0; - // Monotonic list clock: never regress when a recall/stale frame carries - // an older createdAtMs than the current rail tip. - final nextMs = createdAtMs > 0 - ? (createdAtMs > prevMs ? createdAtMs : prevMs) - : prevMs; - if (focused || isOwn) { - unread = 0; - unreadMention = 0; - await repository.clearUnread(conversationId); - } else if (!isRecall) { - unread = (prev?.unreadCount ?? 0) + 1; - unreadMention = (prev?.unreadMentionCount ?? 0) + (mention ? 1 : 0); - await repository.touchConversationPreview( - conversationId: conversationId, - preview: message.text, - createdAtMs: nextMs, - unreadCount: unread, - unreadMentionCount: unreadMention, - ); - } else { - // Recall: preview only; keep unread as-is (server digest is SSOT). - unread = prev?.unreadCount ?? 0; - unreadMention = prev?.unreadMentionCount ?? 0; - await repository.touchConversationPreview( - conversationId: conversationId, - preview: message.text, - createdAtMs: nextMs, - unreadCount: unread, - unreadMentionCount: unreadMention, - ); - } - if (focused || isOwn) { - await repository.touchConversationPreview( - conversationId: conversationId, - preview: message.text, - createdAtMs: nextMs, - unreadCount: 0, - unreadMentionCount: 0, - ); - } - - final current = state.asData?.value; - if (current == null) return; - - final exists = current.conversations.any( - (c) => c.conversationId == conversationId, - ); - final nextLastAt = repository.platformInt64FromIntValue(nextMs); - List next; - if (exists) { - next = current.conversations - .map((c) { - if (c.conversationId != conversationId) return c; - return ConversationSummary( - conversationId: c.conversationId, - kind: c.kind, - title: c.title, - counterpart: c.counterpart, - memberCount: c.memberCount, - lastMessagePreview: message.text, - lastMessageAtMs: nextLastAt, - unreadCount: focused || isOwn ? 0 : unread, - unreadMentionCount: focused || isOwn ? 0 : unreadMention, - ); - }) - .toList(growable: false); - } else { - next = [ - ConversationSummary( - conversationId: conversationId, - kind: ConversationKind.group, - title: prev?.title ?? 'Conversation', - counterpart: prev?.counterpart, - memberCount: prev?.memberCount ?? 0, - lastMessagePreview: message.text, - lastMessageAtMs: nextLastAt, - unreadCount: focused || isOwn ? 0 : (isRecall ? 0 : 1), - unreadMentionCount: focused || isOwn - ? 0 - : (isRecall ? 0 : (mention ? 1 : 0)), - ), - ...current.conversations, - ]; - } - state = AsyncValue.data( - conversationsSortedByLastActive( - ConversationsResponse(conversations: next), - ), - ); - } - - Future _onSocialEvent(SocialEventFrame frame) async { - // Reactions are conversation-only; do not bump sidebar unread. - // Open conversation controller acks conversation reaction topics. - if (frame.kind == 'reaction_updated') { - return; - } - // Inbox path: account T2 digests + conversation full (when open) both patch - // rail preview/unread. Digests carry preview in message.text stub. - if (frame.kind != 'message' && - frame.kind != 'inbox_digest' && - frame.kind != 'inbox_recall') { - return; - } - if (frame.message.messageId.trim().isEmpty) { - return; - } - final focusedId = ref.read(focusedSocialConversationIdProvider); - final focused = focusedId != null && focusedId == frame.conversationId; - // Open conversation controller also patches; still apply inbox for badge - // when not focused. When focused, SocialConversation drives markRead. - String? myAccountId; - try { - myAccountId = await ref - .read(socialRepositoryProvider) - .loadCurrentAccountId(); - } catch (_) {} - try { - await patchFromInbound( - message: frame.message, - focused: focused, - myAccountId: myAccountId, - ); - // Account digests must ack here (conversation controller ignores them). - // Conversation message frames: open chat acks; when not open, inbox still - // needs cursor advance after digest/rail patch. - final topic = frame.topic.trim(); - final seq = frame.topicSeq.toInt(); - if (topic.isNotEmpty && seq > 0) { - final isAccountTopic = topic.startsWith('account:'); - final isConversationMessage = - frame.kind == 'message' && topic.startsWith('conversation:'); - // Open conversation owns conversation: topic ack for messages. - if (isAccountTopic || - frame.kind == 'inbox_digest' || - frame.kind == 'inbox_recall' || - (isConversationMessage && !focused)) { - await ref - .read(minosCoreServiceProvider) - .ackDurableApplied(topic: topic, topicSeq: seq); - } - } - } catch (e, st) { - // Do not ack on failure — resume will redeliver. - logFlutterWarn( - 'social_providers', - 'inbox social apply failed (cursor held)', - error: e, - stackTrace: st, - ); - } - } - - Future _fetchRemoteConversations() async { - final repository = ref.read(socialRepositoryProvider); - final response = await repository.conversations(); - await repository.saveConversations(response.conversations); - return conversationsSortedByLastActive(response); - } - - Future _refreshFromRemote() async { - try { - state = AsyncValue.data(await _fetchRemoteConversations()); - } catch (_) {} - } -} +/// Prefer importing the focused modules under `application/social/` from new +/// code. This barrel keeps existing call-sites stable after the split. +library; + +export 'package:minos/application/social/social_chat_actions.dart'; +export 'package:minos/application/social/social_chat_view_model.dart'; +export 'package:minos/application/social/social_conversation_notifier.dart'; +export 'package:minos/application/social/social_conversation_state.dart'; +export 'package:minos/application/social/social_friends_providers.dart'; +export 'package:minos/application/social/social_inbox_notifier.dart'; +export 'package:minos/application/social/social_realtime_sync.dart'; +export 'package:minos/application/social/social_ui_state.dart'; diff --git a/apps/mobile/lib/application/thread_commands.dart b/apps/mobile/lib/application/thread_commands.dart deleted file mode 100644 index 24069bed..00000000 --- a/apps/mobile/lib/application/thread_commands.dart +++ /dev/null @@ -1,133 +0,0 @@ -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/data/repositories/thread_repository.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -final threadCommandsProvider = Provider((ref) { - return ThreadCommands(ref); -}); - -class ThreadCommands { - ThreadCommands(this._ref); - - final Ref _ref; - - ThreadRepository get _repository => _ref.read(threadRepositoryProvider); - - Stream get uiEvents => _repository.uiEvents; - - Future sendUserMessage({ - required String sessionId, - required String text, - }) async { - final effectiveSessionId = sessionId.isEmpty ? '' : sessionId; - logFlutterInfo( - 'thread_commands', - 'sendUserMessage requested sessionId=$effectiveSessionId textLength=${text.length}', - ); - try { - await _repository.sendUserMessage(sessionId: sessionId, text: text); - logFlutterDebug( - 'thread_commands', - 'sendUserMessage accepted sessionId=$effectiveSessionId', - ); - } catch (error, stackTrace) { - logFlutterError( - 'thread_commands', - 'sendUserMessage failed sessionId=$effectiveSessionId textLength=${text.length}', - error: error, - stackTrace: stackTrace, - ); - rethrow; - } - } - - Future sendApprovalDecision({ - required String requestId, - required String sessionId, - required Map decision, - String? clientRequestId, - }) async { - // Stable Hub client_request_id for this user intent. - final opId = clientRequestId?.trim().isNotEmpty == true - ? clientRequestId!.trim() - : 'approval-${DateTime.now().microsecondsSinceEpoch}-$requestId'; - logFlutterInfo( - 'thread_commands', - 'sendApprovalDecision requested sessionId=$sessionId requestId=$requestId', - ); - try { - await _repository.sendApprovalDecision( - requestId: requestId, - sessionId: sessionId, - decision: decision, - clientRequestId: opId, - ); - logFlutterDebug( - 'thread_commands', - 'sendApprovalDecision accepted sessionId=$sessionId requestId=$requestId', - ); - } catch (error, stackTrace) { - logFlutterError( - 'thread_commands', - 'sendApprovalDecision failed sessionId=$sessionId requestId=$requestId', - error: error, - stackTrace: stackTrace, - ); - rethrow; - } - } - - Future respondOpencodeQuestion({ - required String sessionId, - required String questionId, - required List> answers, - }) async { - logFlutterInfo( - 'thread_commands', - 'respondOpencodeQuestion requested sessionId=$sessionId questionId=$questionId', - ); - try { - await _repository.respondOpencodeQuestion( - sessionId: sessionId, - questionId: questionId, - answers: answers, - ); - logFlutterDebug( - 'thread_commands', - 'respondOpencodeQuestion accepted sessionId=$sessionId questionId=$questionId', - ); - } catch (error, stackTrace) { - logFlutterError( - 'thread_commands', - 'respondOpencodeQuestion failed sessionId=$sessionId questionId=$questionId', - error: error, - stackTrace: stackTrace, - ); - rethrow; - } - } - - Future deleteThread({required String sessionId}) async { - logFlutterInfo( - 'thread_commands', - 'deleteThread requested sessionId=$sessionId', - ); - try { - await _repository.deleteThread(sessionId: sessionId); - logFlutterDebug( - 'thread_commands', - 'deleteThread succeeded sessionId=$sessionId', - ); - } catch (error, stackTrace) { - logFlutterError( - 'thread_commands', - 'deleteThread failed sessionId=$sessionId', - error: error, - stackTrace: stackTrace, - ); - rethrow; - } - } -} diff --git a/apps/mobile/lib/application/thread_event_timeline.dart b/apps/mobile/lib/application/thread_event_timeline.dart deleted file mode 100644 index 1ca06a7e..00000000 --- a/apps/mobile/lib/application/thread_event_timeline.dart +++ /dev/null @@ -1,477 +0,0 @@ -import 'package:minos/application/display_payload_preview.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -/// One row in the chat transcript, ordered by first-appearance event index. -/// -/// Gemini/Grok ACP (and other agents) may attach reasoning, tool calls, and -/// assistant text to the same `message_id` for a turn. The transcript must still -/// follow **output order**: each content kind becomes its own item at the event -/// where it first appeared; later contiguous deltas update that item in place. -/// Intervening tool/text/reasoning events close the previous open segment so a -/// later thought or reply opens a **new** item at the end of the timeline -/// instead of rewriting or concatenating into an earlier row. -sealed class ThreadTimelineItem { - const ThreadTimelineItem({required this.eventIndex}); - - /// Index of the first `UiEventMessage` that opened this row. - final int eventIndex; -} - -final class TimelineUserMessage extends ThreadTimelineItem { - const TimelineUserMessage({ - required super.eventIndex, - required this.messageId, - required this.text, - }); - - final String messageId; - final String text; -} - -final class TimelineAssistantText extends ThreadTimelineItem { - const TimelineAssistantText({ - required super.eventIndex, - required this.messageId, - required this.text, - required this.showCursor, - }); - - final String messageId; - final String text; - final bool showCursor; -} - -final class TimelineReasoning extends ThreadTimelineItem { - const TimelineReasoning({ - required super.eventIndex, - required this.messageId, - required this.text, - required this.isLive, - }); - - final String messageId; - final String text; - final bool isLive; -} - -final class TimelineToolCall extends ThreadTimelineItem { - const TimelineToolCall({ - required super.eventIndex, - required this.messageId, - required this.toolCallId, - required this.name, - required this.argsJson, - required this.output, - required this.isError, - }); - - final String messageId; - final String toolCallId; - final String name; - final String argsJson; - final String? output; - final bool isError; -} - -final class TimelineAssistantPlaceholder extends ThreadTimelineItem { - const TimelineAssistantPlaceholder({ - required super.eventIndex, - required this.messageId, - }); - - final String messageId; -} - -final class TimelineError extends ThreadTimelineItem { - const TimelineError({ - required super.eventIndex, - required this.code, - required this.message, - }); - - final String code; - final String message; -} - -final class TimelineClosed extends ThreadTimelineItem { - const TimelineClosed({required super.eventIndex}); -} - -/// Projects a flat ordered `UiEventMessage` list into timeline rows. -List buildThreadEventTimeline( - List events, { - bool showLiveAssistantState = false, -}) { - final roleByMsg = {}; - final completedMsgs = {}; - final userTextByMsg = {}; - final messageStartIndex = {}; - final toolById = {}; - final toolFirstIndex = {}; - final textSegments = <_ContentSegment>[]; - final reasoningSegments = <_ContentSegment>[]; - final markers = []; - - String? openTextMessageId; - String? openReasoningMessageId; - String? lastAssistantMessageId; - - void closeTextSegment() { - openTextMessageId = null; - } - - void closeReasoningSegment() { - openReasoningMessageId = null; - } - - void appendSegment({ - required List<_ContentSegment> segments, - required String? Function() getOpenId, - required void Function(String?) setOpenId, - required String messageId, - required int eventIndex, - required String text, - }) { - if (text.isEmpty) return; - if (getOpenId() == messageId && segments.isNotEmpty) { - segments.last.text.write(text); - return; - } - segments.add( - _ContentSegment( - messageId: messageId, - eventIndex: eventIndex, - text: StringBuffer(text), - ), - ); - setOpenId(messageId); - } - - void replaceSegment({ - required List<_ContentSegment> segments, - required String? Function() getOpenId, - required void Function(String?) setOpenId, - required String messageId, - required int eventIndex, - required String text, - }) { - if (text.isEmpty) { - segments.removeWhere((segment) => segment.messageId == messageId); - if (getOpenId() == messageId) { - setOpenId(null); - } - return; - } - if (getOpenId() == messageId && segments.isNotEmpty) { - segments.last.text - ..clear() - ..write(text); - return; - } - segments.add( - _ContentSegment( - messageId: messageId, - eventIndex: eventIndex, - text: StringBuffer(text), - ), - ); - setOpenId(messageId); - } - - void appendText(String messageId, int eventIndex, String text) { - appendSegment( - segments: textSegments, - getOpenId: () => openTextMessageId, - setOpenId: (id) => openTextMessageId = id, - messageId: messageId, - eventIndex: eventIndex, - text: text, - ); - } - - void replaceText(String messageId, int eventIndex, String text) { - replaceSegment( - segments: textSegments, - getOpenId: () => openTextMessageId, - setOpenId: (id) => openTextMessageId = id, - messageId: messageId, - eventIndex: eventIndex, - text: text, - ); - } - - void appendReasoning(String messageId, int eventIndex, String text) { - appendSegment( - segments: reasoningSegments, - getOpenId: () => openReasoningMessageId, - setOpenId: (id) => openReasoningMessageId = id, - messageId: messageId, - eventIndex: eventIndex, - text: text, - ); - } - - void replaceReasoning(String messageId, int eventIndex, String text) { - replaceSegment( - segments: reasoningSegments, - getOpenId: () => openReasoningMessageId, - setOpenId: (id) => openReasoningMessageId = id, - messageId: messageId, - eventIndex: eventIndex, - text: text, - ); - } - - for (var i = 0; i < events.length; i++) { - final event = events[i]; - switch (event) { - case UiEventMessage_MessageStarted(:final messageId, :final role): - messageStartIndex.putIfAbsent(messageId, () => i); - roleByMsg[messageId] = role; - if (role == MessageRole.user) { - userTextByMsg.putIfAbsent(messageId, StringBuffer.new); - } - if (role == MessageRole.assistant) { - lastAssistantMessageId = messageId; - } - // A new message boundary always ends contiguous content segments. - closeTextSegment(); - closeReasoningSegment(); - case UiEventMessage_TextDelta(:final messageId, :final text): - final preview = text.renderPreview(); - if (preview.isEmpty) break; - final role = roleByMsg[messageId] ?? MessageRole.assistant; - if (role == MessageRole.user) { - userTextByMsg.putIfAbsent(messageId, StringBuffer.new).write(preview); - } else { - // Intervening thought/tool closes any open text segment first via - // those handlers; contiguous assistant deltas stay one bubble. - appendText(messageId, i, preview); - } - closeReasoningSegment(); - case UiEventMessage_TextReplace(:final messageId, :final text): - final preview = text.renderPreview(); - final role = roleByMsg[messageId] ?? MessageRole.assistant; - if (role == MessageRole.user) { - userTextByMsg[messageId] = StringBuffer(preview); - } else { - replaceText(messageId, i, preview); - } - closeReasoningSegment(); - case UiEventMessage_ReasoningDelta(:final messageId, :final text): - // Thought after intermediate reply/tool must open at the timeline tail. - closeTextSegment(); - appendReasoning(messageId, i, text.renderPreview()); - case UiEventMessage_ReasoningReplace(:final messageId, :final text): - closeTextSegment(); - replaceReasoning(messageId, i, text.renderPreview()); - case UiEventMessage_MessageCompleted(:final messageId): - completedMsgs.add(messageId); - closeTextSegment(); - closeReasoningSegment(); - case UiEventMessage_ToolCallPlaced( - :final messageId, - :final toolCallId, - :final name, - :final argsJson, - ): - toolById[toolCallId] = _ToolAccum( - messageId: messageId, - name: name, - argsJson: argsJson.renderPreview(), - ); - toolFirstIndex.putIfAbsent(toolCallId, () => i); - closeTextSegment(); - closeReasoningSegment(); - case UiEventMessage_ToolCallCompleted( - :final toolCallId, - :final output, - :final isError, - ): - final existing = toolById[toolCallId]; - if (existing != null) { - existing.output = output.renderPreview(); - existing.isError = isError; - } else { - final messageId = lastAssistantMessageId ?? ''; - toolById[toolCallId] = _ToolAccum( - messageId: messageId, - name: '(unknown)', - argsJson: '{}', - output: output.renderPreview(), - isError: isError, - ); - toolFirstIndex.putIfAbsent(toolCallId, () => i); - } - case UiEventMessage_Error(:final code, :final message): - markers.add(TimelineError(eventIndex: i, code: code, message: message)); - case UiEventMessage_SessionClosed(): - markers.add(TimelineClosed(eventIndex: i)); - case UiEventMessage_SessionOpened(): - case UiEventMessage_SessionTitleUpdated(): - case UiEventMessage_SubagentSpawned(): - case UiEventMessage_SubagentStatusUpdated(): - case UiEventMessage_Raw(): - // Subagent tree is rendered via agent-session hierarchy, not the - // linear message timeline. - break; - } - } - - final liveAssistantMessageId = showLiveAssistantState - ? lastAssistantMessageId - : null; - - final rows = [...markers]; - - for (final entry in roleByMsg.entries) { - final messageId = entry.key; - final role = entry.value; - if (role != MessageRole.user) continue; - final text = userTextByMsg[messageId]?.toString() ?? ''; - if (text.trim().isEmpty) continue; - rows.add( - TimelineUserMessage( - eventIndex: messageStartIndex[messageId] ?? 0, - messageId: messageId, - text: text, - ), - ); - } - - for (var index = 0; index < reasoningSegments.length; index++) { - final segment = reasoningSegments[index]; - final text = segment.text.toString(); - if (text.isEmpty) continue; - // Only the still-open reasoning segment is "live". Earlier thought blocks - // that were interrupted by tools/text are finished chat rows. - final isOpenTail = - openReasoningMessageId == segment.messageId && - index == reasoningSegments.length - 1; - final isLive = - liveAssistantMessageId == segment.messageId && - isOpenTail && - !completedMsgs.contains(segment.messageId); - rows.add( - TimelineReasoning( - eventIndex: segment.eventIndex, - messageId: segment.messageId, - text: text, - isLive: isLive, - ), - ); - } - - for (final entry in toolFirstIndex.entries) { - final toolCallId = entry.key; - final tool = toolById[toolCallId]; - if (tool == null) continue; - rows.add( - TimelineToolCall( - eventIndex: entry.value, - messageId: tool.messageId, - toolCallId: toolCallId, - name: tool.name, - argsJson: tool.argsJson, - output: tool.output, - isError: tool.isError, - ), - ); - } - - for (var index = 0; index < textSegments.length; index++) { - final segment = textSegments[index]; - final text = segment.text.toString(); - if (text.isEmpty) continue; - // Cursor only on the actively open text segment of the live turn. Closed - // intermediate replies (e.g. early Grok/Gemini agent_message_chunk before - // tools) are plain chat messages with no cursor. - final isOpenTail = - openTextMessageId == segment.messageId && - index == textSegments.length - 1; - final showCursor = - liveAssistantMessageId == segment.messageId && - isOpenTail && - !completedMsgs.contains(segment.messageId); - rows.add( - TimelineAssistantText( - eventIndex: segment.eventIndex, - messageId: segment.messageId, - text: text, - showCursor: showCursor, - ), - ); - } - - // Live assistant with MessageStarted but no content yet → single placeholder - // at the MessageStarted index (under the user message only while waiting). - if (liveAssistantMessageId != null && - !completedMsgs.contains(liveAssistantMessageId)) { - final hasText = textSegments.any( - (segment) => segment.messageId == liveAssistantMessageId, - ); - final hasReasoning = reasoningSegments.any( - (segment) => segment.messageId == liveAssistantMessageId, - ); - final hasTool = toolById.values.any( - (tool) => tool.messageId == liveAssistantMessageId, - ); - if (!hasText && !hasReasoning && !hasTool) { - rows.add( - TimelineAssistantPlaceholder( - eventIndex: - messageStartIndex[liveAssistantMessageId] ?? events.length, - messageId: liveAssistantMessageId, - ), - ); - } - } - - rows.sort((a, b) { - final byIndex = a.eventIndex.compareTo(b.eventIndex); - if (byIndex != 0) return byIndex; - return _timelineKindRank(a).compareTo(_timelineKindRank(b)); - }); - - return rows; -} - -int _timelineKindRank(ThreadTimelineItem item) { - return switch (item) { - TimelineUserMessage() => 0, - TimelineReasoning() => 1, - TimelineToolCall() => 2, - TimelineAssistantText() => 3, - TimelineAssistantPlaceholder() => 4, - TimelineError() => 5, - TimelineClosed() => 6, - }; -} - -class _ContentSegment { - _ContentSegment({ - required this.messageId, - required this.eventIndex, - required this.text, - }); - - final String messageId; - final int eventIndex; - final StringBuffer text; -} - -class _ToolAccum { - _ToolAccum({ - required this.messageId, - required this.name, - required this.argsJson, - this.output, - this.isError = false, - }); - - final String messageId; - final String name; - final String argsJson; - String? output; - bool isError; -} diff --git a/apps/mobile/lib/application/thread_events_provider.dart b/apps/mobile/lib/application/thread_events_provider.dart deleted file mode 100644 index a87086c9..00000000 --- a/apps/mobile/lib/application/thread_events_provider.dart +++ /dev/null @@ -1,104 +0,0 @@ -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/data/repositories/thread_repository.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'thread_events_provider.g.dart'; - -/// Loads the translated history for one session and keeps it live by -/// listening to the backend's fan-out. Per-thread watermark dedup keeps -/// the view consistent with the backend's raw_events seq. -/// -/// `keepAlive: true` so navigating away from the chat page does not drop the -/// in-memory event list and live subscription. Re-entry then renders cached -/// history instantly instead of flashing a center spinner and re-fetching -/// from the daemon. -@Riverpod(keepAlive: true) -class ThreadEvents extends _$ThreadEvents { - BigInt _watermark = BigInt.zero; - - @override - Future> build(String sessionId) async { - final repository = ref.read(threadRepositoryProvider); - logFlutterDebug( - 'thread_events', - 'load session events sessionId=$sessionId', - ); - - final resp = await _readInitialPage(repository, sessionId); - logFlutterDebug( - 'thread_events', - 'loaded initial session events sessionId=$sessionId count=${resp.uiEvents.length}', - ); - if (resp.nextSeq != null) { - _watermark = resp.nextSeq! - BigInt.one; - } else if (resp.uiEvents.isNotEmpty) { - // No next page — seed watermark from the seq the page ended at. We - // don't carry seq inside UiEventMessage itself; the backend's live - // fan-out will include seq on each frame and we'll only accept - // strictly-greater seqs from there. - _watermark = BigInt.zero; - } - - final sub = repository.uiEvents.listen( - (frame) { - if (frame.sessionId != sessionId) return; - if (frame.seq <= _watermark) return; - _watermark = frame.seq; - final prev = state.asData?.value ?? const []; - state = AsyncValue.data([...prev, frame.ui]); - }, - onError: (Object error, StackTrace stackTrace) { - logFlutterWarn( - 'thread_events', - 'live event stream failed sessionId=$sessionId', - error: error, - stackTrace: stackTrace, - ); - ref.invalidateSelf(); - }, - onDone: () { - logFlutterInfo( - 'thread_events', - 'live event stream completed sessionId=$sessionId', - ); - ref.invalidateSelf(); - }, - ); - ref.onDispose(sub.cancel); - - return resp.uiEvents; - } - - Future _readInitialPage( - ThreadRepository repository, - String sessionId, - ) async { - const maxAttempts = 8; - - for (var attempt = 0; attempt < maxAttempts; attempt++) { - try { - return await repository.readThread(sessionId: sessionId); - } on MinosError_SessionNotFound catch (error, stackTrace) { - if (attempt == maxAttempts - 1) { - logFlutterError( - 'thread_events', - 'readThread exhausted retries sessionId=$sessionId attempts=$maxAttempts', - error: error, - stackTrace: stackTrace, - ); - rethrow; - } - logFlutterWarn( - 'thread_events', - 'readThread retry scheduled sessionId=$sessionId attempt=${attempt + 1}', - error: error, - stackTrace: stackTrace, - ); - await Future.delayed(Duration(milliseconds: 150 * (attempt + 1))); - } - } - - throw MinosError.sessionNotFound(sessionId: sessionId); - } -} diff --git a/apps/mobile/lib/application/thread_events_provider.g.dart b/apps/mobile/lib/application/thread_events_provider.g.dart deleted file mode 100644 index 3ac59dd3..00000000 --- a/apps/mobile/lib/application/thread_events_provider.g.dart +++ /dev/null @@ -1,155 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'thread_events_provider.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning -/// Loads the translated history for one session and keeps it live by -/// listening to the backend's fan-out. Per-thread watermark dedup keeps -/// the view consistent with the backend's raw_events seq. -/// -/// `keepAlive: true` so navigating away from the chat page does not drop the -/// in-memory event list and live subscription. Re-entry then renders cached -/// history instantly instead of flashing a center spinner and re-fetching -/// from the daemon. - -@ProviderFor(ThreadEvents) -final threadEventsProvider = ThreadEventsFamily._(); - -/// Loads the translated history for one session and keeps it live by -/// listening to the backend's fan-out. Per-thread watermark dedup keeps -/// the view consistent with the backend's raw_events seq. -/// -/// `keepAlive: true` so navigating away from the chat page does not drop the -/// in-memory event list and live subscription. Re-entry then renders cached -/// history instantly instead of flashing a center spinner and re-fetching -/// from the daemon. -final class ThreadEventsProvider - extends $AsyncNotifierProvider> { - /// Loads the translated history for one session and keeps it live by - /// listening to the backend's fan-out. Per-thread watermark dedup keeps - /// the view consistent with the backend's raw_events seq. - /// - /// `keepAlive: true` so navigating away from the chat page does not drop the - /// in-memory event list and live subscription. Re-entry then renders cached - /// history instantly instead of flashing a center spinner and re-fetching - /// from the daemon. - ThreadEventsProvider._({ - required ThreadEventsFamily super.from, - required String super.argument, - }) : super( - retry: null, - name: r'threadEventsProvider', - isAutoDispose: false, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$threadEventsHash(); - - @override - String toString() { - return r'threadEventsProvider' - '' - '($argument)'; - } - - @$internal - @override - ThreadEvents create() => ThreadEvents(); - - @override - bool operator ==(Object other) { - return other is ThreadEventsProvider && other.argument == argument; - } - - @override - int get hashCode { - return argument.hashCode; - } -} - -String _$threadEventsHash() => r'8ef558d7a8a2260d4a785b50bee39efd47e378da'; - -/// Loads the translated history for one session and keeps it live by -/// listening to the backend's fan-out. Per-thread watermark dedup keeps -/// the view consistent with the backend's raw_events seq. -/// -/// `keepAlive: true` so navigating away from the chat page does not drop the -/// in-memory event list and live subscription. Re-entry then renders cached -/// history instantly instead of flashing a center spinner and re-fetching -/// from the daemon. - -final class ThreadEventsFamily extends $Family - with - $ClassFamilyOverride< - ThreadEvents, - AsyncValue>, - List, - FutureOr>, - String - > { - ThreadEventsFamily._() - : super( - retry: null, - name: r'threadEventsProvider', - dependencies: null, - $allTransitiveDependencies: null, - isAutoDispose: false, - ); - - /// Loads the translated history for one session and keeps it live by - /// listening to the backend's fan-out. Per-thread watermark dedup keeps - /// the view consistent with the backend's raw_events seq. - /// - /// `keepAlive: true` so navigating away from the chat page does not drop the - /// in-memory event list and live subscription. Re-entry then renders cached - /// history instantly instead of flashing a center spinner and re-fetching - /// from the daemon. - - ThreadEventsProvider call(String sessionId) => - ThreadEventsProvider._(argument: sessionId, from: this); - - @override - String toString() => r'threadEventsProvider'; -} - -/// Loads the translated history for one session and keeps it live by -/// listening to the backend's fan-out. Per-thread watermark dedup keeps -/// the view consistent with the backend's raw_events seq. -/// -/// `keepAlive: true` so navigating away from the chat page does not drop the -/// in-memory event list and live subscription. Re-entry then renders cached -/// history instantly instead of flashing a center spinner and re-fetching -/// from the daemon. - -abstract class _$ThreadEvents extends $AsyncNotifier> { - late final _$args = ref.$arg as String; - String get sessionId => _$args; - - FutureOr> build(String sessionId); - @$mustCallSuper - @override - void runBuild() { - final ref = - this.ref - as $Ref>, List>; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier< - AsyncValue>, - List - >, - AsyncValue>, - Object?, - Object? - >; - element.handleCreate(ref, () => build(_$args)); - } -} diff --git a/apps/mobile/lib/application/thread_list_provider.dart b/apps/mobile/lib/application/thread_list_provider.dart deleted file mode 100644 index bb60e70a..00000000 --- a/apps/mobile/lib/application/thread_list_provider.dart +++ /dev/null @@ -1,31 +0,0 @@ -import 'package:minos/data/repositories/thread_repository.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'thread_list_provider.g.dart'; - -/// Loads and caches the paged session list. First build requests the -/// freshest 50 sessions; [refresh] reruns `list_sessions` with the same -/// params. -@Riverpod(keepAlive: false) -class ThreadList extends _$ThreadList { - @override - Future> build() async { - return ref.read(threadRepositoryProvider).listThreads(); - } - - Future refresh() async { - final previous = state; - try { - state = AsyncValue.data( - await ref.read(threadRepositoryProvider).listThreads(), - ); - } catch (error, stackTrace) { - if (previous.hasValue) { - state = previous; - Error.throwWithStackTrace(error, stackTrace); - } - state = AsyncValue.error(error, stackTrace); - } - } -} diff --git a/apps/mobile/lib/application/thread_list_provider.g.dart b/apps/mobile/lib/application/thread_list_provider.g.dart deleted file mode 100644 index 21391e2a..00000000 --- a/apps/mobile/lib/application/thread_list_provider.g.dart +++ /dev/null @@ -1,72 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'thread_list_provider.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning -/// Loads and caches the paged session list. First build requests the -/// freshest 50 sessions; [refresh] reruns `list_sessions` with the same -/// params. - -@ProviderFor(ThreadList) -final threadListProvider = ThreadListProvider._(); - -/// Loads and caches the paged session list. First build requests the -/// freshest 50 sessions; [refresh] reruns `list_sessions` with the same -/// params. -final class ThreadListProvider - extends $AsyncNotifierProvider> { - /// Loads and caches the paged session list. First build requests the - /// freshest 50 sessions; [refresh] reruns `list_sessions` with the same - /// params. - ThreadListProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'threadListProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$threadListHash(); - - @$internal - @override - ThreadList create() => ThreadList(); -} - -String _$threadListHash() => r'a5101bb48da9838337a8659ebf38f551901c0219'; - -/// Loads and caches the paged session list. First build requests the -/// freshest 50 sessions; [refresh] reruns `list_sessions` with the same -/// params. - -abstract class _$ThreadList extends $AsyncNotifier> { - FutureOr> build(); - @$mustCallSuper - @override - void runBuild() { - final ref = - this.ref - as $Ref>, List>; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier< - AsyncValue>, - List - >, - AsyncValue>, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} diff --git a/apps/mobile/lib/application/thread_view_state.dart b/apps/mobile/lib/application/thread_view_state.dart deleted file mode 100644 index 8f2b715d..00000000 --- a/apps/mobile/lib/application/thread_view_state.dart +++ /dev/null @@ -1,238 +0,0 @@ -import 'dart:async'; - -import 'package:riverpod_annotation/riverpod_annotation.dart'; - -part 'thread_view_state.g.dart'; - -@Riverpod(keepAlive: false) -class ThreadViewStateController extends _$ThreadViewStateController { - @override - ThreadViewState build(String viewId) { - ref.onDispose(_disposeTimers); - return const ThreadViewState(); - } - - static const Duration _sendStatusDelay = Duration(milliseconds: 500); - - final Map _optimisticTimers = {}; - int _lastEventCount = 0; - int _nextOptimisticMessageId = 0; - - void updateScrollState({ - required double distanceFromBottom, - required double stickyThreshold, - }) { - final isAtBottom = distanceFromBottom <= stickyThreshold; - if (isAtBottom == state.stickToBottom) return; - state = state.copyWith( - stickToBottom: isAtBottom, - unreadBelow: isAtBottom ? 0 : state.unreadBelow, - ); - } - - void jumpToBottom() { - if (state.stickToBottom && state.unreadBelow == 0) return; - state = state.copyWith(stickToBottom: true, unreadBelow: 0); - } - - void setApprovalSheetVisible(bool visible) { - if (state.approvalSheetVisible == visible) return; - state = state.copyWith(approvalSheetVisible: visible); - } - - String enqueueOptimisticMessage({ - required String text, - required int anchorEventCount, - }) { - final message = ThreadOptimisticUserMessage( - id: 'optimistic-${_nextOptimisticMessageId++}', - text: text, - status: ThreadOptimisticMessageStatus.pending, - anchorEventCount: anchorEventCount, - ); - state = state.copyWith( - optimisticMessages: [ - ...state.optimisticMessages, - message, - ], - ); - _optimisticTimers[message.id] = Timer(_sendStatusDelay, () { - updateOptimisticMessage( - message.id, - (current) => current.status == ThreadOptimisticMessageStatus.pending - ? current.copyWith(status: ThreadOptimisticMessageStatus.sending) - : current, - ); - }); - return message.id; - } - - bool handleThreadMetrics({ - required int eventCount, - required List userMessages, - }) { - _consumeConfirmedUserMessages(userMessages); - - final totalCount = eventCount + state.optimisticMessages.length; - if (totalCount == _lastEventCount) return false; - - final delta = totalCount - _lastEventCount; - _lastEventCount = totalCount; - if (state.stickToBottom) { - return true; - } - if (delta > 0) { - state = state.copyWith(unreadBelow: state.unreadBelow + delta); - } - return false; - } - - void markOptimisticMessageFailed(String id) { - _clearOptimisticTimer(id); - updateOptimisticMessage( - id, - (current) => - current.copyWith(status: ThreadOptimisticMessageStatus.failed), - ); - } - - void markOptimisticMessageConfirmed(String id) { - _clearOptimisticTimer(id); - updateOptimisticMessage( - id, - (current) => - current.copyWith(status: ThreadOptimisticMessageStatus.confirmed), - ); - } - - void updateOptimisticMessage( - String id, - ThreadOptimisticUserMessage Function(ThreadOptimisticUserMessage current) - transform, - ) { - final index = state.optimisticMessages.indexWhere( - (message) => message.id == id, - ); - if (index == -1) return; - - final optimisticMessages = List.of( - state.optimisticMessages, - ); - optimisticMessages[index] = transform(optimisticMessages[index]); - state = state.copyWith(optimisticMessages: optimisticMessages); - } - - void _clearOptimisticTimer(String id) { - _optimisticTimers.remove(id)?.cancel(); - } - - void _consumeConfirmedUserMessages(List userMessages) { - final confirmedIds = state.optimisticMessages - .where( - (message) => - message.status == ThreadOptimisticMessageStatus.confirmed && - threadOptimisticHasEcho(message, userMessages), - ) - .map((message) => message.id) - .toSet(); - if (confirmedIds.isEmpty) return; - - for (final id in confirmedIds) { - _clearOptimisticTimer(id); - } - - state = state.copyWith( - optimisticMessages: state.optimisticMessages - .where((message) => !confirmedIds.contains(message.id)) - .toList(growable: false), - ); - } - - void _disposeTimers() { - for (final timer in _optimisticTimers.values) { - timer.cancel(); - } - _optimisticTimers.clear(); - } -} - -class ThreadViewState { - const ThreadViewState({ - this.stickToBottom = true, - this.unreadBelow = 0, - this.optimisticMessages = const [], - this.approvalSheetVisible = false, - }); - - final bool stickToBottom; - final int unreadBelow; - final List optimisticMessages; - final bool approvalSheetVisible; - - ThreadViewState copyWith({ - bool? stickToBottom, - int? unreadBelow, - List? optimisticMessages, - bool? approvalSheetVisible, - }) { - return ThreadViewState( - stickToBottom: stickToBottom ?? this.stickToBottom, - unreadBelow: unreadBelow ?? this.unreadBelow, - optimisticMessages: optimisticMessages ?? this.optimisticMessages, - approvalSheetVisible: approvalSheetVisible ?? this.approvalSheetVisible, - ); - } -} - -enum ThreadOptimisticMessageStatus { pending, sending, confirmed, failed } - -class ThreadOptimisticUserMessage { - const ThreadOptimisticUserMessage({ - required this.id, - required this.text, - required this.status, - required this.anchorEventCount, - }); - - final String id; - final String text; - final ThreadOptimisticMessageStatus status; - final int anchorEventCount; - - ThreadOptimisticUserMessage copyWith({ - ThreadOptimisticMessageStatus? status, - }) { - return ThreadOptimisticUserMessage( - id: id, - text: text, - status: status ?? this.status, - anchorEventCount: anchorEventCount, - ); - } -} - -class ThreadUserMessageEcho { - const ThreadUserMessageEcho({required this.eventIndex, required this.text}); - - final int eventIndex; - final String text; - - String get normalizedText => normalizeThreadMessageText(text); -} - -bool threadOptimisticHasEcho( - ThreadOptimisticUserMessage message, - List echoes, -) { - final normalized = normalizeThreadMessageText(message.text); - if (normalized.isEmpty) return false; - return echoes.any( - (echo) => - echo.eventIndex >= message.anchorEventCount && - echo.normalizedText == normalized, - ); -} - -String normalizeThreadMessageText(String text) { - return text.trim().split(RegExp(r'\s+')).where((s) => s.isNotEmpty).join(' '); -} diff --git a/apps/mobile/lib/application/thread_view_state.g.dart b/apps/mobile/lib/application/thread_view_state.g.dart deleted file mode 100644 index dada60e7..00000000 --- a/apps/mobile/lib/application/thread_view_state.g.dart +++ /dev/null @@ -1,109 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'thread_view_state.dart'; - -// ************************************************************************** -// RiverpodGenerator -// ************************************************************************** - -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, type=warning - -@ProviderFor(ThreadViewStateController) -final threadViewStateControllerProvider = ThreadViewStateControllerFamily._(); - -final class ThreadViewStateControllerProvider - extends $NotifierProvider { - ThreadViewStateControllerProvider._({ - required ThreadViewStateControllerFamily super.from, - required String super.argument, - }) : super( - retry: null, - name: r'threadViewStateControllerProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$threadViewStateControllerHash(); - - @override - String toString() { - return r'threadViewStateControllerProvider' - '' - '($argument)'; - } - - @$internal - @override - ThreadViewStateController create() => ThreadViewStateController(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(ThreadViewState value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } - - @override - bool operator ==(Object other) { - return other is ThreadViewStateControllerProvider && - other.argument == argument; - } - - @override - int get hashCode { - return argument.hashCode; - } -} - -String _$threadViewStateControllerHash() => - r'36fe0ed17b01122c38f03b5f0dbd490d3b2ea451'; - -final class ThreadViewStateControllerFamily extends $Family - with - $ClassFamilyOverride< - ThreadViewStateController, - ThreadViewState, - ThreadViewState, - ThreadViewState, - String - > { - ThreadViewStateControllerFamily._() - : super( - retry: null, - name: r'threadViewStateControllerProvider', - dependencies: null, - $allTransitiveDependencies: null, - isAutoDispose: true, - ); - - ThreadViewStateControllerProvider call(String viewId) => - ThreadViewStateControllerProvider._(argument: viewId, from: this); - - @override - String toString() => r'threadViewStateControllerProvider'; -} - -abstract class _$ThreadViewStateController extends $Notifier { - late final _$args = ref.$arg as String; - String get viewId => _$args; - - ThreadViewState build(String viewId); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - ThreadViewState, - Object?, - Object? - >; - element.handleCreate(ref, () => build(_$args)); - } -} diff --git a/apps/mobile/lib/application/ui_state_providers.dart b/apps/mobile/lib/application/ui_state_providers.dart index 86888dd0..16abe144 100644 --- a/apps/mobile/lib/application/ui_state_providers.dart +++ b/apps/mobile/lib/application/ui_state_providers.dart @@ -80,65 +80,3 @@ class LoginPageState { ); } } - -@Riverpod(keepAlive: false) -class SelectedProjectThread extends _$SelectedProjectThread { - @override - String? build(String projectId) => null; - - void select(String? sessionId) { - state = sessionId; - } -} - -@Riverpod(keepAlive: false) -class AgentStartPageStateController extends _$AgentStartPageStateController { - @override - AgentStartPageState build() => const AgentStartPageState(); - - void selectProfile(String? profileId) { - state = state.copyWith(selectedProfileId: profileId); - } - - void setSubmitting(bool isSubmitting) { - if (state.isSubmitting == isSubmitting) return; - state = state.copyWith(isSubmitting: isSubmitting); - } -} - -class AgentStartPageState { - const AgentStartPageState({ - this.selectedProfileId, - this.isSubmitting = false, - }); - - final String? selectedProfileId; - final bool isSubmitting; - - AgentStartPageState copyWith({ - String? selectedProfileId, - bool clearSelectedProfileId = false, - bool? isSubmitting, - }) { - return AgentStartPageState( - selectedProfileId: clearSelectedProfileId - ? null - : selectedProfileId ?? this.selectedProfileId, - isSubmitting: isSubmitting ?? this.isSubmitting, - ); - } -} - -@Riverpod(keepAlive: true) -class CollapsedProjectIds extends _$CollapsedProjectIds { - @override - Set build() => {}; - - void toggle(String projectId) { - final next = {...state}; - if (!next.add(projectId)) { - next.remove(projectId); - } - state = next; - } -} diff --git a/apps/mobile/lib/application/ui_state_providers.g.dart b/apps/mobile/lib/application/ui_state_providers.g.dart index c0c4b989..d3881493 100644 --- a/apps/mobile/lib/application/ui_state_providers.g.dart +++ b/apps/mobile/lib/application/ui_state_providers.g.dart @@ -139,210 +139,3 @@ abstract class _$LoginPageStateController extends $Notifier { element.handleCreate(ref, build); } } - -@ProviderFor(SelectedProjectThread) -final selectedProjectThreadProvider = SelectedProjectThreadFamily._(); - -final class SelectedProjectThreadProvider - extends $NotifierProvider { - SelectedProjectThreadProvider._({ - required SelectedProjectThreadFamily super.from, - required String super.argument, - }) : super( - retry: null, - name: r'selectedProjectThreadProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$selectedProjectThreadHash(); - - @override - String toString() { - return r'selectedProjectThreadProvider' - '' - '($argument)'; - } - - @$internal - @override - SelectedProjectThread create() => SelectedProjectThread(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(String? value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } - - @override - bool operator ==(Object other) { - return other is SelectedProjectThreadProvider && other.argument == argument; - } - - @override - int get hashCode { - return argument.hashCode; - } -} - -String _$selectedProjectThreadHash() => - r'2f3c29b6e23760e3d228073d22477e95fecd7138'; - -final class SelectedProjectThreadFamily extends $Family - with - $ClassFamilyOverride< - SelectedProjectThread, - String?, - String?, - String?, - String - > { - SelectedProjectThreadFamily._() - : super( - retry: null, - name: r'selectedProjectThreadProvider', - dependencies: null, - $allTransitiveDependencies: null, - isAutoDispose: true, - ); - - SelectedProjectThreadProvider call(String projectId) => - SelectedProjectThreadProvider._(argument: projectId, from: this); - - @override - String toString() => r'selectedProjectThreadProvider'; -} - -abstract class _$SelectedProjectThread extends $Notifier { - late final _$args = ref.$arg as String; - String get projectId => _$args; - - String? build(String projectId); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - String?, - Object?, - Object? - >; - element.handleCreate(ref, () => build(_$args)); - } -} - -@ProviderFor(AgentStartPageStateController) -final agentStartPageStateControllerProvider = - AgentStartPageStateControllerProvider._(); - -final class AgentStartPageStateControllerProvider - extends - $NotifierProvider { - AgentStartPageStateControllerProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'agentStartPageStateControllerProvider', - isAutoDispose: true, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$agentStartPageStateControllerHash(); - - @$internal - @override - AgentStartPageStateController create() => AgentStartPageStateController(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(AgentStartPageState value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider(value), - ); - } -} - -String _$agentStartPageStateControllerHash() => - r'1b6a694975eb755d9ea2735e1f4b2ab8beeda3c2'; - -abstract class _$AgentStartPageStateController - extends $Notifier { - AgentStartPageState build(); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, - AgentStartPageState, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} - -@ProviderFor(CollapsedProjectIds) -final collapsedProjectIdsProvider = CollapsedProjectIdsProvider._(); - -final class CollapsedProjectIdsProvider - extends $NotifierProvider> { - CollapsedProjectIdsProvider._() - : super( - from: null, - argument: null, - retry: null, - name: r'collapsedProjectIdsProvider', - isAutoDispose: false, - dependencies: null, - $allTransitiveDependencies: null, - ); - - @override - String debugGetCreateSourceHash() => _$collapsedProjectIdsHash(); - - @$internal - @override - CollapsedProjectIds create() => CollapsedProjectIds(); - - /// {@macro riverpod.override_with_value} - Override overrideWithValue(Set value) { - return $ProviderOverride( - origin: this, - providerOverride: $SyncValueProvider>(value), - ); - } -} - -String _$collapsedProjectIdsHash() => - r'2b7767392954799b6eee1397abb9a730465836e4'; - -abstract class _$CollapsedProjectIds extends $Notifier> { - Set build(); - @$mustCallSuper - @override - void runBuild() { - final ref = this.ref as $Ref, Set>; - final element = - ref.element - as $ClassProviderElement< - AnyNotifier, Set>, - Set, - Object?, - Object? - >; - element.handleCreate(ref, build); - } -} diff --git a/apps/mobile/lib/architecture.dart b/apps/mobile/lib/architecture.dart index febbcb8a..1e870a9d 100644 --- a/apps/mobile/lib/architecture.dart +++ b/apps/mobile/lib/architecture.dart @@ -3,6 +3,11 @@ /// This application follows the recommended Flutter layered architecture /// (UI → Application → Data → Domain) with strict separation of concerns. /// +/// Product spine: **conversation-first collaboration IM**. The shell is +/// Messages / Hosts / Account. Agent session transcript and project/session +/// product surfaces were removed from Mobile; bots participate via Hub +/// conversation membership and bubbles. +/// /// ## Layer Diagram /// /// ``` @@ -12,33 +17,32 @@ /// │ └── features/ Feature-grouped views │ /// │ ├── auth/ Login / register │ /// │ ├── messages/ Conversation inbox (primary) │ -/// │ ├── sessions/ Agent session list (secondary) │ -/// │ ├── chat/ Agent session chat │ -/// │ ├── projects/ Project CRUD + sessions │ -/// │ ├── agents/ Agent profile management │ /// │ ├── social/ Conversation chat / members │ +/// │ ├── hosts/ Linked hosts list │ +/// │ ├── account/ Profile / logout │ /// │ ├── debug/ Log viewer & traces │ /// │ └── shell/ Root navigation shell │ /// ├─────────────────────────────────────────────────────────┤ /// │ Application Layer (lib/application/) │ -/// │ Riverpod providers acting as ViewModels: │ +/// │ Riverpod + codegen ViewModels / Actions: │ /// │ ├── auth_provider Auth state machine │ -/// │ ├── active_session_provider Agent session lifecycle │ -/// │ ├── thread_events_provider Live event stream │ -/// │ ├── minos_providers Pairing / runtime state │ -/// │ ├── project_providers Project CRUD + selection │ -/// │ ├── social_providers Chat, friends, conversations │ -/// │ ├── agent_profiles_provider Profile CRUD │ -/// │ ├── *_actions User-triggered mutations │ +/// │ ├── minos_providers Connection / hosts / presence│ +/// │ ├── social/ Conversation IM feature pack │ +/// │ │ freezed timeline state + ViewModel + Actions │ +/// │ ├── social_providers Compatibility barrel │ +/// │ ├── im_outbox_worker Local IM outbox drain │ +/// │ ├── agent_profiles_provider Local bot cache for compose│ +/// │ ├── group_agent_provider Conversation participants │ +/// │ ├── *_actions User-triggered mutations │ /// │ └── root_route_decision Navigation logic │ /// ├─────────────────────────────────────────────────────────┤ /// │ Data Layer (lib/data/ + lib/infrastructure/) │ /// │ ├── repositories/ Single source of truth │ /// │ │ ├── auth_repository Auth / session IO │ /// │ │ ├── runtime_repository Pairing / host state │ -/// │ │ ├── project_repository Project + session list │ -/// │ │ ├── thread_repository Thread event / send IO │ +/// │ │ ├── hosts_repository Linked hosts HTTP │ /// │ │ ├── social_repository Social remote + cache │ +/// │ │ ├── realtime_events_repository Account uiEvents stream │ /// │ │ ├── agent_profile_repository Device cache of bots │ /// │ │ └── group_agent_repository Conversation agents │ /// │ ├── services/ Service providers / wrappers │ @@ -49,18 +53,18 @@ /// │ ├── minos_core Rust FFI bridge (Hub CRUD) │ /// │ ├── secure_pairing_store Keychain persistence │ /// │ ├── social_cache_store SQLite message cache │ +/// │ ├── im_outbox_store Outbox policy helpers │ /// │ └── agent_profile_store Local bot draft cache │ /// ├─────────────────────────────────────────────────────────┤ /// │ Domain Layer (lib/domain/) │ /// │ ├── minos_core_protocol Abstract service contract │ -/// │ ├── active_session Session state machine │ /// │ ├── auth_state Auth lifecycle states │ /// │ ├── agent_profile Bot body draft / cache model │ /// │ ├── social_message Chat message model │ /// │ ├── group_member Group membership model │ /// │ └── minos_error_display Error presentation helpers │ /// │ Note: Hub `agents` is bot identity SSOT; local JSON is │ -/// │ cache/draft only (Hub `agents` is identity SSOT). │ +/// │ cache/draft only. │ /// └─────────────────────────────────────────────────────────┘ /// ``` /// @@ -79,10 +83,15 @@ /// feature widgets and references its view-model providers. Shared /// widgets live in `ui/core/widgets/`. /// -/// 4. **Immutable domain models**: `ActiveSession`, `AuthState`, -/// `SocialChatMessage`, `AgentProfile` are all immutable value types. +/// 4. **Immutable domain models**: `AuthState`, `SocialChatMessage`, +/// `AgentProfile` are immutable value types. /// /// 5. **Single source of truth**: Each piece of data has exactly one -/// authoritative provider. E.g. `projectListProvider` is the single -/// source for the project list; UI reads it, never fetches directly. +/// authoritative provider. E.g. `conversationsProvider` is the single +/// source for the inbox list; UI reads it, never fetches directly. +/// +/// 6. **IM send path**: Collaboration messages go through +/// `SocialConversation.sendMessage` → local outbox → +/// `sendChatMessage` (Account WS AppendMessage). No second product +/// send path on Mobile. library; diff --git a/apps/mobile/lib/data/repositories/project_repository.dart b/apps/mobile/lib/data/repositories/project_repository.dart deleted file mode 100644 index 708bf546..00000000 --- a/apps/mobile/lib/data/repositories/project_repository.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import 'package:minos/data/services/minos_core_service.dart'; -import 'package:minos/domain/minos_core_protocol.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -final projectRepositoryProvider = Provider((ref) { - return ProjectRepository(ref.watch(minosCoreServiceProvider)); -}); - -class ProjectRepository { - const ProjectRepository(this._core); - - final MinosCoreProtocol _core; - - Future> listProjects() async { - final response = await _core.listProjects(); - return response.projects; - } - - Future createProject({ - required String name, - required String workspaceSlug, - String? workspacePath, - }) async { - final response = await _core.createProject( - name: name, - workspaceSlug: workspaceSlug, - workspacePath: workspacePath, - ); - return response.project; - } - - Future deleteProject(String projectId) { - return _core.deleteProject(projectId: projectId); - } - - Future updateProject({ - required String projectId, - required String name, - }) { - return _core.updateProject(projectId: projectId, name: name); - } - - Future> listProjectThreads(String projectId) async { - final response = await _core.listProjectThreads(projectId: projectId); - return response.sessions; - } -} diff --git a/apps/mobile/lib/data/repositories/realtime_events_repository.dart b/apps/mobile/lib/data/repositories/realtime_events_repository.dart new file mode 100644 index 00000000..19261ff5 --- /dev/null +++ b/apps/mobile/lib/data/repositories/realtime_events_repository.dart @@ -0,0 +1,22 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:minos/data/services/minos_core_service.dart'; +import 'package:minos/domain/minos_core_protocol.dart'; +import 'package:minos/src/rust/api/minos.dart'; + +/// Account realtime control-plane events (snapshot / presence / notices). +/// +/// Not a product agent-transcript or session-compose surface. +final realtimeEventsRepositoryProvider = Provider(( + ref, +) { + return RealtimeEventsRepository(ref.watch(minosCoreServiceProvider)); +}); + +class RealtimeEventsRepository { + const RealtimeEventsRepository(this._core); + + final MinosCoreProtocol _core; + + Stream get uiEvents => _core.uiEvents; +} diff --git a/apps/mobile/lib/data/repositories/repositories.dart b/apps/mobile/lib/data/repositories/repositories.dart index 62383f76..722b0fac 100644 --- a/apps/mobile/lib/data/repositories/repositories.dart +++ b/apps/mobile/lib/data/repositories/repositories.dart @@ -13,7 +13,6 @@ export 'package:minos/data/repositories/agent_profile_repository.dart'; export 'package:minos/data/repositories/auth_repository.dart'; export 'package:minos/data/repositories/group_agent_repository.dart'; export 'package:minos/data/repositories/hosts_repository.dart'; -export 'package:minos/data/repositories/project_repository.dart'; +export 'package:minos/data/repositories/realtime_events_repository.dart'; export 'package:minos/data/repositories/runtime_repository.dart'; export 'package:minos/data/repositories/social_repository.dart'; -export 'package:minos/data/repositories/thread_repository.dart'; diff --git a/apps/mobile/lib/data/repositories/runtime_repository.dart b/apps/mobile/lib/data/repositories/runtime_repository.dart index 63c16a09..6732f942 100644 --- a/apps/mobile/lib/data/repositories/runtime_repository.dart +++ b/apps/mobile/lib/data/repositories/runtime_repository.dart @@ -61,10 +61,6 @@ class RuntimeRepository { return _core.setActiveHost(hostDeviceId); } - Future setPeerDisplayName(String? displayName) { - return _core.setPeerDisplayName(displayName); - } - void notifyForegrounded() { _core.notifyForegrounded(); } diff --git a/apps/mobile/lib/data/repositories/social_repository.dart b/apps/mobile/lib/data/repositories/social_repository.dart index 70df275a..c1ce366c 100644 --- a/apps/mobile/lib/data/repositories/social_repository.dart +++ b/apps/mobile/lib/data/repositories/social_repository.dart @@ -31,14 +31,6 @@ class SocialRepository { return _core.myProfile(); } - Future> searchUsers({required String minosId}) { - return _core.searchUsers(minosId: minosId); - } - - Future setMinosId({required String minosId}) { - return _core.setMinosId(minosId: minosId); - } - /// Unified participants (humans ∪ bot agents). Preferred for @ picker and /// membership-first roster reads (ADR 0021). Future listConversationParticipants({ @@ -242,20 +234,6 @@ class SocialRepository { return _cacheStore.reconcileSendingMessagesOnStartup(); } - Future> listAgentSessions({ - required String conversationId, - int limit = 5, - }) { - return _core.listAgentSessions( - conversationId: conversationId, - limit: limit, - ); - } - - Future subscribeAgentSession({required String sessionId}) { - return _core.subscribeAgentSession(sessionId: sessionId); - } - /// R3a: open-chat `conversation:{id}` full T1 frames. Future subscribeConversation({required String conversationId}) { return _core.subscribeConversation(conversationId: conversationId); @@ -329,10 +307,6 @@ class SocialRepository { ); } - Future friendRequests() { - return _core.friendRequests(); - } - Future friends() { return _core.friends(); } @@ -406,18 +380,6 @@ class SocialRepository { return _cacheStore.saveConversations(conversations); } - Future createFriendRequest({required String targetMinosId}) { - return _core.createFriendRequest(targetMinosId: targetMinosId); - } - - Future rejectFriendRequest({required String requestId}) { - return _core.rejectFriendRequest(requestId: requestId); - } - - Future acceptFriendRequest({required String requestId}) { - return _core.acceptFriendRequest(requestId: requestId); - } - Future ensureDirectConversation({ required String friendAccountId, }) { diff --git a/apps/mobile/lib/data/repositories/thread_repository.dart b/apps/mobile/lib/data/repositories/thread_repository.dart deleted file mode 100644 index 3ffc9b12..00000000 --- a/apps/mobile/lib/data/repositories/thread_repository.dart +++ /dev/null @@ -1,72 +0,0 @@ -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import 'package:minos/data/services/minos_core_service.dart'; -import 'package:minos/domain/minos_core_protocol.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -final threadRepositoryProvider = Provider((ref) { - return ThreadRepository(ref.watch(minosCoreServiceProvider)); -}); - -class ThreadRepository { - const ThreadRepository(this._core); - - final MinosCoreProtocol _core; - - Stream get uiEvents => _core.uiEvents; - - Future> listThreads({int limit = 50}) async { - final response = await _core.listThreads(ListSessionsParams(limit: limit)); - return response.sessions; - } - - Future readThread({ - required String sessionId, - int limit = 500, - }) { - return _core.readThread( - ReadSessionParams(sessionId: sessionId, limit: limit), - ); - } - - Future interruptThread({required String sessionId}) { - return _core.interruptThread(sessionId: sessionId); - } - - Future sendUserMessage({ - required String sessionId, - required String text, - }) { - return _core.sendUserMessage(sessionId: sessionId, text: text); - } - - Future sendApprovalDecision({ - required String requestId, - required String sessionId, - required Map decision, - String? clientRequestId, - }) { - return _core.sendApprovalDecision( - requestId: requestId, - sessionId: sessionId, - decision: decision, - clientRequestId: clientRequestId, - ); - } - - Future respondOpencodeQuestion({ - required String sessionId, - required String questionId, - required List> answers, - }) { - return _core.respondOpencodeQuestion( - sessionId: sessionId, - questionId: questionId, - answers: answers, - ); - } - - Future deleteThread({required String sessionId}) { - return _core.deleteThread(sessionId: sessionId); - } -} diff --git a/apps/mobile/lib/data/services/services.dart b/apps/mobile/lib/data/services/services.dart index 9e8ffb5c..a5db21e3 100644 --- a/apps/mobile/lib/data/services/services.dart +++ b/apps/mobile/lib/data/services/services.dart @@ -17,4 +17,3 @@ export 'package:minos/infrastructure/minos_core.dart'; export 'package:minos/infrastructure/platform_int64.dart'; export 'package:minos/infrastructure/secure_pairing_store.dart'; export 'package:minos/infrastructure/social_cache_store.dart'; -export 'package:minos/infrastructure/workspace_mru_store.dart'; diff --git a/apps/mobile/lib/domain/active_session.dart b/apps/mobile/lib/domain/active_session.dart deleted file mode 100644 index 88aca26e..00000000 --- a/apps/mobile/lib/domain/active_session.dart +++ /dev/null @@ -1,120 +0,0 @@ -import 'package:flutter/foundation.dart' show immutable; - -import 'package:minos/src/rust/api/minos.dart' show AgentName, MinosError; - -/// Dart-owned mobile-side state machine for the agent dispatch lifecycle. -/// -/// State transitions (driven by [ActiveSessionController]): -/// ``` -/// Idle ──send()──> Sending ──first UI frame──> Streaming -/// │ │ -/// └────────error──────────────> Error -/// ▼ -/// Streaming ──MessageCompleted──> AwaitingInput -/// │ │ -/// ├──────────send()────────────────┘ -/// │ -/// └────stop()/SessionClosed────> Suspended -/// ``` -/// -/// `sessionId` is the daemon-issued `session_id` (per -/// `crates/minos-protocol/src/messages.rs:50`). -@immutable -sealed class ActiveSession { - const ActiveSession(); -} - -/// No agent session is in flight on this device. -class SessionIdle extends ActiveSession { - const SessionIdle(); - - @override - bool operator ==(Object other) => other is SessionIdle; - - @override - int get hashCode => (SessionIdle).hashCode; -} - -/// A message send has been accepted by the transport layer, but the page does -/// not have a bound `session_id` yet. We stay here until the first live UI -/// frame arrives and lets the controller bind the session. -class SessionSending extends ActiveSession { - final AgentName agent; - final String text; - const SessionSending({required this.agent, required this.text}); - - @override - bool operator ==(Object other) => - other is SessionSending && other.agent == agent && other.text == text; - - @override - int get hashCode => Object.hash(agent, text); -} - -/// Agent is actively producing tokens; UI shows the streaming cursor. -class SessionStreaming extends ActiveSession { - final String sessionId; - final AgentName agent; - const SessionStreaming({required this.sessionId, required this.agent}); - - @override - bool operator ==(Object other) => - other is SessionStreaming && - other.sessionId == sessionId && - other.agent == agent; - - @override - int get hashCode => Object.hash(sessionId, agent); -} - -/// Streaming finished cleanly via `MessageCompleted`; the input bar is -/// re-enabled so the user can send a follow-up. -class SessionAwaitingInput extends ActiveSession { - final String sessionId; - final AgentName agent; - const SessionAwaitingInput({required this.sessionId, required this.agent}); - - @override - bool operator ==(Object other) => - other is SessionAwaitingInput && - other.sessionId == sessionId && - other.agent == agent; - - @override - int get hashCode => Object.hash(sessionId, agent); -} - -/// The thread has been interrupted locally or suspended by the runtime. -/// Sending another message on the same conversation should resume it rather -/// than creating a brand-new session. -class SessionSuspended extends ActiveSession { - final String sessionId; - final AgentName agent; - const SessionSuspended({required this.sessionId, required this.agent}); - - @override - bool operator ==(Object other) => - other is SessionSuspended && - other.sessionId == sessionId && - other.agent == agent; - - @override - int get hashCode => Object.hash(sessionId, agent); -} - -/// Terminal failure on the dispatch path. `sessionId` is null when the -/// failure happened before the runtime surfaced a session id. -class SessionError extends ActiveSession { - final String? sessionId; - final MinosError error; - const SessionError({this.sessionId, required this.error}); - - @override - bool operator ==(Object other) => - other is SessionError && - other.sessionId == sessionId && - other.error == error; - - @override - int get hashCode => Object.hash(sessionId, error); -} diff --git a/apps/mobile/lib/domain/minos_core_protocol.dart b/apps/mobile/lib/domain/minos_core_protocol.dart index 9cc0b7fd..37f174e0 100644 --- a/apps/mobile/lib/domain/minos_core_protocol.dart +++ b/apps/mobile/lib/domain/minos_core_protocol.dart @@ -24,25 +24,8 @@ abstract class MinosCoreProtocol { /// Optional display label for the active host (local preference). Future peerDisplayName(); - /// Persist the active host display name. Pass `null` or empty to clear. - Future setPeerDisplayName(String? name); - Future myProfile(); - Future setMinosId({required String minosId}); - - Future> searchUsers({required String minosId}); - - Future createFriendRequest({ - required String targetMinosId, - }); - - Future friendRequests(); - - Future acceptFriendRequest({required String requestId}); - - Future rejectFriendRequest({required String requestId}); - Future friends(); Future registerAgent({ @@ -144,18 +127,6 @@ abstract class MinosCoreProtocol { required String clientOpId, }); - /// Paged thread summaries for the paired agent-host. - Future listThreads(ListSessionsParams params); - - /// Recent agent sessions, optionally scoped to one social conversation. - Future> listAgentSessions({ - String? conversationId, - int limit = 20, - }); - - /// Subscribe the live WebSocket to one agent session topic. - Future subscribeAgentSession({required String sessionId}); - /// Open-chat live path (R3a): subscribe `conversation:{id}` for full messages. Future subscribeConversation({required String conversationId}); @@ -168,39 +139,12 @@ abstract class MinosCoreProtocol { required int topicSeq, }); - /// Translated UI event history for one session. - Future readThread(ReadSessionParams params); - - // ---- Projects ---- - - /// Create a new project on the daemon. - Future createProject({ - required String name, - required String workspaceSlug, - String? workspacePath, - }); - - /// List all projects on the daemon. - Future listProjects(); - - /// Update a project's name. - Future updateProject({required String projectId, required String name}); - - /// Delete a project. - Future deleteProject({required String projectId}); - - /// List sessions within a project. - Future listProjectThreads({ - required String projectId, - int limit = 50, - int? beforeTsMs, - }); - /// Hot stream of [ConnectionState] transitions, starting with the current /// value. Stream get connectionStates; - /// Hot stream of live [UiEventFrame]s fanned out by the backend. + /// Hot stream of live [UiEventFrame]s (snapshot/presence/control). + /// Not a product agent-transcript surface on Mobile. Stream get uiEvents; /// Hot stream of live [SocialEventFrame]s fanned out by the backend. @@ -225,30 +169,6 @@ abstract class MinosCoreProtocol { /// [authStates]. Future logout(); - // ---- Agent dispatch ---- - - /// Send a follow-up user message to an existing agent session. The - /// `sessionId` is the session/session identifier. - Future sendUserMessage({ - required String sessionId, - required String text, - }); - - /// Pause an in-flight turn while keeping the session resumable. - Future interruptThread({required String sessionId}); - - /// Close an agent session by its `session_id`. The multi-thread - /// `AgentManager` keys lifecycle operations on `session_id` rather than - /// implicitly on the single active session. Idempotent on the daemon side; - /// calling for an already-closed thread is a benign no-op. - Future closeThread({required String sessionId}); - - /// Permanently delete a thread. Used exclusively for the swipe-to-delete - /// gesture in the session list. Semantically identical to [closeThread] on - /// the wire, but named distinctly so call-sites express intent: interrupt - /// pauses a session for later resume, while delete is a permanent close. - Future deleteThread({required String sessionId}); - /// Detect CLI agents available on the paired runtime. Future> listClis(); @@ -287,28 +207,6 @@ abstract class MinosCoreProtocol { /// semantics), then every subsequent change. Stream get authStates; - /// Send an approval decision (accept/decline) for a pending approval - /// request. The [requestId] must match the original request's id, and - /// [sessionId] identifies the session the approval belongs to. The - /// [decision] is a JSON-encodable value matching the expected response - /// shape for the approval variant (command execution, file change, or - /// permissions). - Future sendApprovalDecision({ - required String requestId, - required String sessionId, - required Map decision, - - /// Hub Intent Outbox id. Stable across retries of the same intent. - String? clientRequestId, - }); - - /// Submit answers for a pending opencode question request. - Future respondOpencodeQuestion({ - required String sessionId, - required String questionId, - required List> answers, - }); - /// Re-open the WS using the durable pairing snapshot already loaded /// into the Rust core. Idempotent: a no-op when [currentConnectionState] /// is already `Connected`, and an error when no pairing snapshot exists. diff --git a/apps/mobile/lib/domain/models.dart b/apps/mobile/lib/domain/models.dart index a6cb46b0..cd6bdca6 100644 --- a/apps/mobile/lib/domain/models.dart +++ b/apps/mobile/lib/domain/models.dart @@ -12,7 +12,6 @@ /// - All domain models should be immutable (use `@immutable` or sealed). library; -export 'active_session.dart'; export 'agent_profile.dart'; export 'auth_state.dart'; export 'group_member.dart'; diff --git a/apps/mobile/lib/infrastructure/minos_core.dart b/apps/mobile/lib/infrastructure/minos_core.dart index 9d85eae0..a7f53c49 100644 --- a/apps/mobile/lib/infrastructure/minos_core.dart +++ b/apps/mobile/lib/infrastructure/minos_core.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; - import 'package:flutter/foundation.dart'; import 'package:minos/domain/minos_core_protocol.dart'; import 'package:minos/infrastructure/frb_external_library.dart'; @@ -125,39 +123,9 @@ class MinosCore implements MinosCoreProtocol { @override Future peerDisplayName() => _secure.loadPeerDisplayName(); - @override - Future setPeerDisplayName(String? name) => - _secure.savePeerDisplayName(name); - @override Future myProfile() => _client.myProfile(); - @override - Future setMinosId({required String minosId}) => - _client.setMinosId(minosId: minosId); - - @override - Future> searchUsers({required String minosId}) => - _client.searchUsers(minosId: minosId); - - @override - Future createFriendRequest({ - required String targetMinosId, - }) => _client.createFriendRequest(targetMinosId: targetMinosId); - - @override - Future friendRequests() => _client.friendRequests(); - - @override - Future acceptFriendRequest({ - required String requestId, - }) => _client.acceptFriendRequest(requestId: requestId); - - @override - Future rejectFriendRequest({ - required String requestId, - }) => _client.rejectFriendRequest(requestId: requestId); - @override Future friends() => _client.friends(); @@ -331,20 +299,6 @@ class MinosCore implements MinosCoreProtocol { clientOpId: clientOpId, ); - @override - Future listThreads(ListSessionsParams params) => - _client.listSessions(req: params); - - @override - Future> listAgentSessions({ - String? conversationId, - int limit = 20, - }) => _client.listAgentSessions(conversationId: conversationId, limit: limit); - - @override - Future subscribeAgentSession({required String sessionId}) => - _client.subscribeAgentSession(sessionId: sessionId); - @override Future subscribeConversation({required String conversationId}) => _client.subscribeConversation(conversationId: conversationId); @@ -353,53 +307,6 @@ class MinosCore implements MinosCoreProtocol { Future unsubscribeConversation({required String conversationId}) => _client.unsubscribeConversation(conversationId: conversationId); - @override - Future readThread(ReadSessionParams params) => - _client.readSession(req: params); - - // ---- Project forwarders ---- - - @override - Future createProject({ - required String name, - required String workspaceSlug, - String? workspacePath, - }) => _client.createProject( - req: CreateProjectRequest( - name: name, - workspaceSlug: workspaceSlug, - workspacePath: workspacePath, - ), - ); - - @override - Future listProjects() => _client.listProjects(); - - @override - Future updateProject({ - required String projectId, - required String name, - }) => _client.updateProject( - req: UpdateProjectRequest(projectId: projectId, name: name), - ); - - @override - Future deleteProject({required String projectId}) => - _client.deleteProject(req: DeleteProjectRequest(projectId: projectId)); - - @override - Future listProjectThreads({ - required String projectId, - int limit = 50, - int? beforeTsMs, - }) => _client.listProjectSessions( - req: ListProjectSessionsParams( - projectId: projectId, - limit: limit, - beforeTsMs: beforeTsMs == null ? null : platformInt64FromInt(beforeTsMs), - ), - ); - @override Stream get connectionStates => _client.subscribeState(); @@ -423,8 +330,6 @@ class MinosCore implements MinosCoreProtocol { // ---- Auth forwarders ---- - @override - @override @override Future loginWithSupabase({ required String supabaseAccessToken, @@ -525,24 +430,6 @@ class MinosCore implements MinosCoreProtocol { enabled: enabled, ); - @override - Future sendUserMessage({ - required String sessionId, - required String text, - }) => _client.sendUserMessage(sessionId: sessionId, text: text); - - @override - Future interruptThread({required String sessionId}) => - _client.interruptSession(sessionId: sessionId); - - @override - Future closeThread({required String sessionId}) => - _client.closeSession(sessionId: sessionId); - - @override - Future deleteThread({required String sessionId}) => - _client.closeSession(sessionId: sessionId); - // ---- Lifecycle forwarders ---- @override @@ -574,30 +461,6 @@ class MinosCore implements MinosCoreProtocol { await _saveClientStateBestEffort(_secure, _client); } - @override - Future sendApprovalDecision({ - required String requestId, - required String sessionId, - required Map decision, - String? clientRequestId, - }) => _client.sendApprovalDecision( - requestId: requestId, - sessionId: sessionId, - decisionJson: jsonEncode(decision), - clientRequestId: clientRequestId, - ); - - @override - Future respondOpencodeQuestion({ - required String sessionId, - required String questionId, - required List> answers, - }) => _client.respondOpencodeQuestion( - sessionId: sessionId, - questionId: questionId, - answersJson: jsonEncode(answers), - ); - static bool _shouldDiscardPersistedState(Object error) { return error is MinosError_DeviceNotTrusted || error is MinosError_Unauthorized || diff --git a/apps/mobile/lib/infrastructure/workspace_mru_store.dart b/apps/mobile/lib/infrastructure/workspace_mru_store.dart deleted file mode 100644 index e3c25b51..00000000 --- a/apps/mobile/lib/infrastructure/workspace_mru_store.dart +++ /dev/null @@ -1,77 +0,0 @@ -import 'dart:convert'; -import 'dart:io'; - -import 'package:path_provider/path_provider.dart'; - -/// Per-host workspace MRU (Most Recently Used) store. -/// Persists to a JSON file with a cap of 8 entries per host. -/// Remembers last-used workspaces per host. -class WorkspaceMruStore { - static const int _cap = 8; - static const String _fileName = 'workspace_mru.json'; - - /// Load the MRU list for a given host. Returns up to [_cap] entries. - Future> load(String hostDeviceId) async { - final data = await _readAll(); - final entries = data[hostDeviceId]; - if (entries is! List) return const []; - return entries - .whereType() - .where((s) => s.isNotEmpty) - .take(_cap) - .toList(growable: false); - } - - /// Push a workspace to the front of the MRU for the given host. - /// Deduplicates and caps at [_cap] entries. - Future> push(String hostDeviceId, String workspace) async { - final trimmed = workspace.trim(); - if (trimmed.isEmpty) return load(hostDeviceId); - - final data = await _readAll(); - final current = await load(hostDeviceId); - final next = [ - trimmed, - ...current.where((item) => item != trimmed), - ].take(_cap).toList(growable: false); - - data[hostDeviceId] = next; - await _writeAll(data); - return next; - } - - /// Clear the MRU for a given host. - Future clear(String hostDeviceId) async { - final data = await _readAll(); - data.remove(hostDeviceId); - await _writeAll(data); - } - - Future _file() async { - final dir = await getApplicationDocumentsDirectory(); - return File('${dir.path}/$_fileName'); - } - - Future> _readAll() async { - try { - final file = await _file(); - if (!await file.exists()) return {}; - final raw = await file.readAsString(); - if (raw.trim().isEmpty) return {}; - final decoded = jsonDecode(raw); - if (decoded is! Map) return {}; - return decoded; - } catch (_) { - return {}; - } - } - - Future _writeAll(Map data) async { - final file = await _file(); - await file.parent.create(recursive: true); - await file.writeAsString( - const JsonEncoder.withIndent(' ').convert(data), - flush: true, - ); - } -} diff --git a/apps/mobile/lib/src/rust/api/minos.dart b/apps/mobile/lib/src/rust/api/minos.dart index 273bb1e6..64bec308 100644 --- a/apps/mobile/lib/src/rust/api/minos.dart +++ b/apps/mobile/lib/src/rust/api/minos.dart @@ -9,7 +9,7 @@ import 'package:freezed_annotation/freezed_annotation.dart' hide protected; part 'minos.freezed.dart'; // These functions are ignored because they are not marked as `pub`: `frb_runtime`, `parse_device_id`, `spawn_state_forwarder` -// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `StartAgentResponse` +// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `AgentSessionSummaryDto`, `CreateProjectRequest`, `CreateProjectResponse`, `DeleteProjectRequest`, `FriendRequestStatus`, `FriendRequestSummary`, `FriendRequestsResponse`, `ListProjectSessionsParams`, `ListProjectSessionsResponse`, `ListProjectsResponse`, `ListSessionsParams`, `ListSessionsResponse`, `ProjectSummary`, `ReadSessionParams`, `ReadSessionResponse`, `StartAgentResponse`, `UpdateProjectRequest` // These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`, `fmt`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from` /// Initialize mobile-side Rust logging with the given directory (supplied by @@ -57,8 +57,6 @@ Stream subscribeRequestTraces() => // Rust type: RustOpaqueMoi> abstract class MobileClient implements RustOpaqueInterface { - Future acceptFriendRequest({required String requestId}); - /// Advance durable topic cursor after Dart cache/reducer commit. Future ackDurableApplied({ required String topic, @@ -79,38 +77,23 @@ abstract class MobileClient implements RustOpaqueInterface { required String memberAccountId, }); - /// Permanently close the given thread. Idempotent. - Future closeSession({required String sessionId}); - Future conversationMembers({ required String conversationId, }); Future conversations(); - Future createFriendRequest({ - required String targetMinosId, - }); - Future createGroupConversation({ required String title, required List memberAccountIds, }); - /// Create a new project on the daemon. - Future createProject({ - required CreateProjectRequest req, - }); - /// Current connection state, read from the watch-channel cache. Cheap and /// synchronous. ConnectionState currentState(); Future deleteConversation({required String conversationId}); - /// Delete a project. - Future deleteProject({required DeleteProjectRequest req}); - Future ensureDirectConversation({ required String friendAccountId, }); @@ -119,20 +102,8 @@ abstract class MobileClient implements RustOpaqueInterface { /// when it matches. Idempotent. Future forgetHost({required String hostDeviceId}); - Future friendRequests(); - Future friends(); - /// Pause an in-flight turn on the given thread. Best-effort. The thread - /// transitions to `Suspended { UserInterrupt }` regardless of whether the - /// codex side acknowledges in time. - Future interruptSession({required String sessionId}); - - Future> listAgentSessions({ - String? conversationId, - required int limit, - }); - Future listAgents(); Future listChatMessages({ @@ -168,17 +139,6 @@ abstract class MobileClient implements RustOpaqueInterface { /// List every Mac linked to the caller's account (`GET /v1/hosts`). Future> listPairedHosts(); - /// List sessions within a project. - Future listProjectSessions({ - required ListProjectSessionsParams req, - }); - - /// List all projects on the daemon. - Future listProjects(); - - /// Request a page of thread summaries. - Future listSessions({required ListSessionsParams req}); - /// Exchange a Supabase access token for Minos access/refresh tokens and /// adopt the resulting session. Future loginWithSupabase({required String supabaseAccessToken}); @@ -213,6 +173,21 @@ abstract class MobileClient implements RustOpaqueInterface { /// don't poke the backend while the OS is freezing the process. void notifyBackgrounded(); + /// Send a follow-up user message to an existing agent session. + /// Submit a user approval decision for a pending host request. + /// + /// `client_request_id` is the Hub Intent Outbox id. When omitted, + /// the mobile client generates one so the wire body never hardcodes null. + /// Submit an opencode question answer for a pending host request. + /// Pause an in-flight turn on the given thread. Best-effort. The thread + /// transitions to `Suspended { UserInterrupt }` regardless of whether the + /// codex side acknowledges in time. + /// Permanently close the given thread. Idempotent. + /// Create a new project on the daemon. + /// List all projects on the daemon. + /// Update a project's name. + /// Delete a project. + /// List sessions within a project. /// Mark the app as foregrounded. Resets the reconnect backoff so the /// next connect attempt happens promptly. void notifyForegrounded(); @@ -221,9 +196,6 @@ abstract class MobileClient implements RustOpaqueInterface { /// storage after pairing succeeds. Future persistedPairingState(); - /// Read a window of translated UI events for one session. - Future readSession({required ReadSessionParams req}); - Future recallChatMessage({ required String conversationId, required String messageId, @@ -245,8 +217,6 @@ abstract class MobileClient implements RustOpaqueInterface { String? systemPrompt, }); - Future rejectFriendRequest({required String requestId}); - Future removeAgentFromConversation({ required String conversationId, required String agentId, @@ -257,30 +227,10 @@ abstract class MobileClient implements RustOpaqueInterface { required String memberAccountId, }); - /// Submit an opencode question answer for a pending host request. - Future respondOpencodeQuestion({ - required String sessionId, - required String questionId, - required String answersJson, - }); - /// Reconnect using the durable session snapshot already loaded from the /// Dart-side secure store. Future resumePersistedSession(); - Future> searchUsers({required String minosId}); - - /// Submit a user approval decision for a pending host request. - /// - /// `client_request_id` is the Hub Intent Outbox id. When omitted, - /// the mobile client generates one so the wire body never hardcodes null. - Future sendApprovalDecision({ - required String requestId, - required String sessionId, - required String decisionJson, - String? clientRequestId, - }); - /// `mentions_json` is an optional JSON array of wire `MentionTarget` objects. Future sendChatMessage({ required String conversationId, @@ -290,19 +240,9 @@ abstract class MobileClient implements RustOpaqueInterface { String? mentionsJson, }); - /// Send a follow-up user message to an existing agent session. - Future sendUserMessage({ - required String sessionId, - required String text, - }); - /// Override the active Mac the next forward-RPC routes to. Future setActiveHost({required String hostDeviceId}); - Future setMinosId({required String minosId}); - - Future subscribeAgentSession({required String sessionId}); - /// Subscribe to auth-state transitions. Emits the current cached frame /// immediately, then every subsequent change. The spawned task exits /// once Dart drops the stream (detected via `sink.add(...).is_err()`). @@ -348,9 +288,6 @@ abstract class MobileClient implements RustOpaqueInterface { String? status, }); - /// Update a project's name. - Future updateProject({required UpdateProjectRequest req}); - /// Enable or disable one host-side skill. Future writeHostSkillConfig({ String? hostDeviceId, @@ -454,65 +391,6 @@ class AgentDescriptor { enum AgentName { codex, claude, gemini, opencode, grok } -class AgentSessionSummaryDto { - final String sessionId; - final String conversationId; - final String? agentId; - final AgentName? agent; - final String status; - final PlatformInt64 startedAtMs; - final PlatformInt64? endedAtMs; - final String? title; - final PlatformInt64 lastActivityAtMs; - final int messageCount; - final SessionEndReason? endReason; - - const AgentSessionSummaryDto({ - required this.sessionId, - required this.conversationId, - this.agentId, - this.agent, - required this.status, - required this.startedAtMs, - this.endedAtMs, - this.title, - required this.lastActivityAtMs, - required this.messageCount, - this.endReason, - }); - - @override - int get hashCode => - sessionId.hashCode ^ - conversationId.hashCode ^ - agentId.hashCode ^ - agent.hashCode ^ - status.hashCode ^ - startedAtMs.hashCode ^ - endedAtMs.hashCode ^ - title.hashCode ^ - lastActivityAtMs.hashCode ^ - messageCount.hashCode ^ - endReason.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is AgentSessionSummaryDto && - runtimeType == other.runtimeType && - sessionId == other.sessionId && - conversationId == other.conversationId && - agentId == other.agentId && - agent == other.agent && - status == other.status && - startedAtMs == other.startedAtMs && - endedAtMs == other.endedAtMs && - title == other.title && - lastActivityAtMs == other.lastActivityAtMs && - messageCount == other.messageCount && - endReason == other.endReason; -} - @freezed sealed class AgentStatus with _$AgentStatus { const AgentStatus._(); @@ -963,63 +841,6 @@ class ConversationsResponse { conversations == other.conversations; } -class CreateProjectRequest { - final String name; - final String workspaceSlug; - final String? workspacePath; - - const CreateProjectRequest({ - required this.name, - required this.workspaceSlug, - this.workspacePath, - }); - - @override - int get hashCode => - name.hashCode ^ workspaceSlug.hashCode ^ workspacePath.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is CreateProjectRequest && - runtimeType == other.runtimeType && - name == other.name && - workspaceSlug == other.workspaceSlug && - workspacePath == other.workspacePath; -} - -class CreateProjectResponse { - final ProjectSummary project; - - const CreateProjectResponse({required this.project}); - - @override - int get hashCode => project.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is CreateProjectResponse && - runtimeType == other.runtimeType && - project == other.project; -} - -class DeleteProjectRequest { - final String projectId; - - const DeleteProjectRequest({required this.projectId}); - - @override - int get hashCode => projectId.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is DeleteProjectRequest && - runtimeType == other.runtimeType && - projectId == other.projectId; -} - @freezed sealed class DisplayPayload with _$DisplayPayload { const DisplayPayload._(); @@ -1082,68 +903,6 @@ enum ErrorKind { pairingTokenExpired, } -enum FriendRequestStatus { pending, accepted, rejected, canceled } - -class FriendRequestSummary { - final String requestId; - final UserSummary from; - final UserSummary to; - final FriendRequestStatus status; - final PlatformInt64 createdAtMs; - final PlatformInt64? resolvedAtMs; - - const FriendRequestSummary({ - required this.requestId, - required this.from, - required this.to, - required this.status, - required this.createdAtMs, - this.resolvedAtMs, - }); - - @override - int get hashCode => - requestId.hashCode ^ - from.hashCode ^ - to.hashCode ^ - status.hashCode ^ - createdAtMs.hashCode ^ - resolvedAtMs.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is FriendRequestSummary && - runtimeType == other.runtimeType && - requestId == other.requestId && - from == other.from && - to == other.to && - status == other.status && - createdAtMs == other.createdAtMs && - resolvedAtMs == other.resolvedAtMs; -} - -class FriendRequestsResponse { - final List incoming; - final List outgoing; - - const FriendRequestsResponse({ - required this.incoming, - required this.outgoing, - }); - - @override - int get hashCode => incoming.hashCode ^ outgoing.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is FriendRequestsResponse && - runtimeType == other.runtimeType && - incoming == other.incoming && - outgoing == other.outgoing; -} - class FriendSummary { final String accountId; final String minosId; @@ -1410,100 +1169,6 @@ class ListHostWorkspacesResponse { workspaces == other.workspaces; } -class ListProjectSessionsParams { - final String projectId; - final int limit; - final PlatformInt64? beforeTsMs; - - const ListProjectSessionsParams({ - required this.projectId, - required this.limit, - this.beforeTsMs, - }); - - @override - int get hashCode => projectId.hashCode ^ limit.hashCode ^ beforeTsMs.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ListProjectSessionsParams && - runtimeType == other.runtimeType && - projectId == other.projectId && - limit == other.limit && - beforeTsMs == other.beforeTsMs; -} - -class ListProjectSessionsResponse { - final List sessions; - - const ListProjectSessionsResponse({required this.sessions}); - - @override - int get hashCode => sessions.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ListProjectSessionsResponse && - runtimeType == other.runtimeType && - sessions == other.sessions; -} - -class ListProjectsResponse { - final List projects; - - const ListProjectsResponse({required this.projects}); - - @override - int get hashCode => projects.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ListProjectsResponse && - runtimeType == other.runtimeType && - projects == other.projects; -} - -class ListSessionsParams { - final int limit; - final PlatformInt64? beforeTsMs; - final AgentName? agent; - - const ListSessionsParams({required this.limit, this.beforeTsMs, this.agent}); - - @override - int get hashCode => limit.hashCode ^ beforeTsMs.hashCode ^ agent.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ListSessionsParams && - runtimeType == other.runtimeType && - limit == other.limit && - beforeTsMs == other.beforeTsMs && - agent == other.agent; -} - -class ListSessionsResponse { - final List sessions; - final PlatformInt64? nextBeforeTsMs; - - const ListSessionsResponse({required this.sessions, this.nextBeforeTsMs}); - - @override - int get hashCode => sessions.hashCode ^ nextBeforeTsMs.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ListSessionsResponse && - runtimeType == other.runtimeType && - sessions == other.sessions && - nextBeforeTsMs == other.nextBeforeTsMs; -} - /// Severity tag mirrored from `minos_mobile::log_capture::LogLevel`. enum LogLevel { trace, debug, info, warn, error } @@ -1747,49 +1412,6 @@ class PersistedPairingState { accountEmail == other.accountEmail; } -class ProjectSummary { - final String projectId; - final String name; - final String workspaceSlug; - final String? workspacePath; - final PlatformInt64 createdAtMs; - final PlatformInt64 updatedAtMs; - final int threadCount; - - const ProjectSummary({ - required this.projectId, - required this.name, - required this.workspaceSlug, - this.workspacePath, - required this.createdAtMs, - required this.updatedAtMs, - required this.threadCount, - }); - - @override - int get hashCode => - projectId.hashCode ^ - name.hashCode ^ - workspaceSlug.hashCode ^ - workspacePath.hashCode ^ - createdAtMs.hashCode ^ - updatedAtMs.hashCode ^ - threadCount.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ProjectSummary && - runtimeType == other.runtimeType && - projectId == other.projectId && - name == other.name && - workspaceSlug == other.workspaceSlug && - workspacePath == other.workspacePath && - createdAtMs == other.createdAtMs && - updatedAtMs == other.updatedAtMs && - threadCount == other.threadCount; -} - class ReactionActor { final String actorId; final String actorKind; @@ -1843,55 +1465,6 @@ class ReactionGroup { actors == other.actors; } -class ReadSessionParams { - final String sessionId; - final BigInt? fromSeq; - final int limit; - - const ReadSessionParams({ - required this.sessionId, - this.fromSeq, - required this.limit, - }); - - @override - int get hashCode => sessionId.hashCode ^ fromSeq.hashCode ^ limit.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ReadSessionParams && - runtimeType == other.runtimeType && - sessionId == other.sessionId && - fromSeq == other.fromSeq && - limit == other.limit; -} - -class ReadSessionResponse { - final List uiEvents; - final BigInt? nextSeq; - final SessionEndReason? sessionEndReason; - - const ReadSessionResponse({ - required this.uiEvents, - this.nextSeq, - this.sessionEndReason, - }); - - @override - int get hashCode => - uiEvents.hashCode ^ nextSeq.hashCode ^ sessionEndReason.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ReadSessionResponse && - runtimeType == other.runtimeType && - uiEvents == other.uiEvents && - nextSeq == other.nextSeq && - sessionEndReason == other.sessionEndReason; -} - class RequestTraceRecord { final BigInt id; final RequestTraceTransport transport; @@ -2163,24 +1736,6 @@ sealed class UiEventMessage with _$UiEventMessage { }) = UiEventMessage_Raw; } -class UpdateProjectRequest { - final String projectId; - final String name; - - const UpdateProjectRequest({required this.projectId, required this.name}); - - @override - int get hashCode => projectId.hashCode ^ name.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is UpdateProjectRequest && - runtimeType == other.runtimeType && - projectId == other.projectId && - name == other.name; -} - class UserSummary { final String accountId; final String minosId; diff --git a/apps/mobile/lib/src/rust/frb_generated.dart b/apps/mobile/lib/src/rust/frb_generated.dart index eb703fa9..40c2c1c5 100644 --- a/apps/mobile/lib/src/rust/frb_generated.dart +++ b/apps/mobile/lib/src/rust/frb_generated.dart @@ -64,7 +64,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.12.0'; @override - int get rustContentHash => -520281445; + int get rustContentHash => -801214882; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -76,11 +76,6 @@ class RustLib extends BaseEntrypoint { } abstract class RustLibApi extends BaseApi { - Future crateApiMinosMobileClientAcceptFriendRequest({ - required MobileClient that, - required String requestId, - }); - Future crateApiMinosMobileClientAckDurableApplied({ required MobileClient that, required String topic, @@ -103,11 +98,6 @@ abstract class RustLibApi extends BaseApi { required String memberAccountId, }); - Future crateApiMinosMobileClientCloseSession({ - required MobileClient that, - required String sessionId, - }); - Future crateApiMinosMobileClientConversationMembers({ required MobileClient that, @@ -118,11 +108,6 @@ abstract class RustLibApi extends BaseApi { required MobileClient that, }); - Future crateApiMinosMobileClientCreateFriendRequest({ - required MobileClient that, - required String targetMinosId, - }); - Future crateApiMinosMobileClientCreateGroupConversation({ required MobileClient that, @@ -130,11 +115,6 @@ abstract class RustLibApi extends BaseApi { required List memberAccountIds, }); - Future crateApiMinosMobileClientCreateProject({ - required MobileClient that, - required CreateProjectRequest req, - }); - ConnectionState crateApiMinosMobileClientCurrentState({ required MobileClient that, }); @@ -144,11 +124,6 @@ abstract class RustLibApi extends BaseApi { required String conversationId, }); - Future crateApiMinosMobileClientDeleteProject({ - required MobileClient that, - required DeleteProjectRequest req, - }); - Future crateApiMinosMobileClientEnsureDirectConversation({ required MobileClient that, @@ -160,26 +135,10 @@ abstract class RustLibApi extends BaseApi { required String hostDeviceId, }); - Future crateApiMinosMobileClientFriendRequests({ - required MobileClient that, - }); - Future crateApiMinosMobileClientFriends({ required MobileClient that, }); - Future crateApiMinosMobileClientInterruptSession({ - required MobileClient that, - required String sessionId, - }); - - Future> - crateApiMinosMobileClientListAgentSessions({ - required MobileClient that, - String? conversationId, - required int limit, - }); - Future crateApiMinosMobileClientListAgents({ required MobileClient that, }); @@ -226,21 +185,6 @@ abstract class RustLibApi extends BaseApi { required MobileClient that, }); - Future - crateApiMinosMobileClientListProjectSessions({ - required MobileClient that, - required ListProjectSessionsParams req, - }); - - Future crateApiMinosMobileClientListProjects({ - required MobileClient that, - }); - - Future crateApiMinosMobileClientListSessions({ - required MobileClient that, - required ListSessionsParams req, - }); - Future crateApiMinosMobileClientLoginWithSupabase({ required MobileClient that, required String supabaseAccessToken, @@ -278,11 +222,6 @@ abstract class RustLibApi extends BaseApi { required MobileClient that, }); - Future crateApiMinosMobileClientReadSession({ - required MobileClient that, - required ReadSessionParams req, - }); - Future crateApiMinosMobileClientRecallChatMessage({ required MobileClient that, required String conversationId, @@ -305,11 +244,6 @@ abstract class RustLibApi extends BaseApi { String? systemPrompt, }); - Future crateApiMinosMobileClientRejectFriendRequest({ - required MobileClient that, - required String requestId, - }); - Future crateApiMinosMobileClientRemoveAgentFromConversation({ required MobileClient that, required String conversationId, @@ -322,30 +256,10 @@ abstract class RustLibApi extends BaseApi { required String memberAccountId, }); - Future crateApiMinosMobileClientRespondOpencodeQuestion({ - required MobileClient that, - required String sessionId, - required String questionId, - required String answersJson, - }); - Future crateApiMinosMobileClientResumePersistedSession({ required MobileClient that, }); - Future> crateApiMinosMobileClientSearchUsers({ - required MobileClient that, - required String minosId, - }); - - Future crateApiMinosMobileClientSendApprovalDecision({ - required MobileClient that, - required String requestId, - required String sessionId, - required String decisionJson, - String? clientRequestId, - }); - Future crateApiMinosMobileClientSendChatMessage({ required MobileClient that, required String conversationId, @@ -355,27 +269,11 @@ abstract class RustLibApi extends BaseApi { String? mentionsJson, }); - Future crateApiMinosMobileClientSendUserMessage({ - required MobileClient that, - required String sessionId, - required String text, - }); - Future crateApiMinosMobileClientSetActiveHost({ required MobileClient that, required String hostDeviceId, }); - Future crateApiMinosMobileClientSetMinosId({ - required MobileClient that, - required String minosId, - }); - - Future crateApiMinosMobileClientSubscribeAgentSession({ - required MobileClient that, - required String sessionId, - }); - Stream crateApiMinosMobileClientSubscribeAuthState({ required MobileClient that, }); @@ -424,11 +322,6 @@ abstract class RustLibApi extends BaseApi { String? status, }); - Future crateApiMinosMobileClientUpdateProject({ - required MobileClient that, - required UpdateProjectRequest req, - }); - Future crateApiMinosMobileClientWriteHostSkillConfig({ required MobileClient that, @@ -593,44 +486,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { required super.portManager, }); - @override - Future crateApiMinosMobileClientAcceptFriendRequest({ - required MobileClient that, - required String requestId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(requestId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 1, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_friend_request_summary, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientAcceptFriendRequestConstMeta, - argValues: [that, requestId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientAcceptFriendRequestConstMeta => - const TaskConstMeta( - debugName: "MobileClient_accept_friend_request", - argNames: ["that", "requestId"], - ); - @override Future crateApiMinosMobileClientAckDurableApplied({ required MobileClient that, @@ -650,7 +505,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 2, + funcId: 1, port: port_, ); }, @@ -686,7 +541,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 3, + funcId: 2, port: port_, ); }, @@ -726,7 +581,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 4, + funcId: 3, port: port_, ); }, @@ -766,7 +621,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 5, + funcId: 4, port: port_, ); }, @@ -787,44 +642,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "conversationId", "memberAccountId"], ); - @override - Future crateApiMinosMobileClientCloseSession({ - required MobileClient that, - required String sessionId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(sessionId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 6, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientCloseSessionConstMeta, - argValues: [that, sessionId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientCloseSessionConstMeta => - const TaskConstMeta( - debugName: "MobileClient_close_session", - argNames: ["that", "sessionId"], - ); - @override Future crateApiMinosMobileClientConversationMembers({ @@ -843,7 +660,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 7, + funcId: 5, port: port_, ); }, @@ -879,7 +696,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 8, + funcId: 6, port: port_, ); }, @@ -900,44 +717,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that"], ); - @override - Future crateApiMinosMobileClientCreateFriendRequest({ - required MobileClient that, - required String targetMinosId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(targetMinosId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 9, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_friend_request_summary, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientCreateFriendRequestConstMeta, - argValues: [that, targetMinosId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientCreateFriendRequestConstMeta => - const TaskConstMeta( - debugName: "MobileClient_create_friend_request", - argNames: ["that", "targetMinosId"], - ); - @override Future crateApiMinosMobileClientCreateGroupConversation({ @@ -958,7 +737,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 10, + funcId: 7, port: port_, ); }, @@ -980,44 +759,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "title", "memberAccountIds"], ); - @override - Future crateApiMinosMobileClientCreateProject({ - required MobileClient that, - required CreateProjectRequest req, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_box_autoadd_create_project_request(req, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 11, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_create_project_response, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientCreateProjectConstMeta, - argValues: [that, req], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientCreateProjectConstMeta => - const TaskConstMeta( - debugName: "MobileClient_create_project", - argNames: ["that", "req"], - ); - @override ConnectionState crateApiMinosMobileClientCurrentState({ required MobileClient that, @@ -1030,7 +771,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 12)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 8)!; }, codec: SseCodec( decodeSuccessData: sse_decode_connection_state, @@ -1066,7 +807,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 13, + funcId: 9, port: port_, ); }, @@ -1087,44 +828,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "conversationId"], ); - @override - Future crateApiMinosMobileClientDeleteProject({ - required MobileClient that, - required DeleteProjectRequest req, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_box_autoadd_delete_project_request(req, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 14, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientDeleteProjectConstMeta, - argValues: [that, req], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientDeleteProjectConstMeta => - const TaskConstMeta( - debugName: "MobileClient_delete_project", - argNames: ["that", "req"], - ); - @override Future crateApiMinosMobileClientEnsureDirectConversation({ @@ -1143,7 +846,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 15, + funcId: 10, port: port_, ); }, @@ -1182,7 +885,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 16, + funcId: 11, port: port_, ); }, @@ -1204,7 +907,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); @override - Future crateApiMinosMobileClientFriendRequests({ + Future crateApiMinosMobileClientFriends({ required MobileClient that, }) { return handler.executeNormal( @@ -1218,29 +921,29 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 17, + funcId: 12, port: port_, ); }, codec: SseCodec( - decodeSuccessData: sse_decode_friend_requests_response, + decodeSuccessData: sse_decode_friends_response, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientFriendRequestsConstMeta, + constMeta: kCrateApiMinosMobileClientFriendsConstMeta, argValues: [that], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientFriendRequestsConstMeta => + TaskConstMeta get kCrateApiMinosMobileClientFriendsConstMeta => const TaskConstMeta( - debugName: "MobileClient_friend_requests", + debugName: "MobileClient_friends", argNames: ["that"], ); @override - Future crateApiMinosMobileClientFriends({ + Future crateApiMinosMobileClientListAgents({ required MobileClient that, }) { return handler.executeNormal( @@ -1254,139 +957,24 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 18, + funcId: 13, port: port_, ); }, codec: SseCodec( - decodeSuccessData: sse_decode_friends_response, + decodeSuccessData: sse_decode_list_agents_response, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientFriendsConstMeta, + constMeta: kCrateApiMinosMobileClientListAgentsConstMeta, argValues: [that], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientFriendsConstMeta => + TaskConstMeta get kCrateApiMinosMobileClientListAgentsConstMeta => const TaskConstMeta( - debugName: "MobileClient_friends", - argNames: ["that"], - ); - - @override - Future crateApiMinosMobileClientInterruptSession({ - required MobileClient that, - required String sessionId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(sessionId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 19, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientInterruptSessionConstMeta, - argValues: [that, sessionId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientInterruptSessionConstMeta => - const TaskConstMeta( - debugName: "MobileClient_interrupt_session", - argNames: ["that", "sessionId"], - ); - - @override - Future> - crateApiMinosMobileClientListAgentSessions({ - required MobileClient that, - String? conversationId, - required int limit, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_opt_String(conversationId, serializer); - sse_encode_u_32(limit, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 20, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_list_agent_session_summary_dto, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientListAgentSessionsConstMeta, - argValues: [that, conversationId, limit], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientListAgentSessionsConstMeta => - const TaskConstMeta( - debugName: "MobileClient_list_agent_sessions", - argNames: ["that", "conversationId", "limit"], - ); - - @override - Future crateApiMinosMobileClientListAgents({ - required MobileClient that, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 21, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_list_agents_response, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientListAgentsConstMeta, - argValues: [that], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientListAgentsConstMeta => - const TaskConstMeta( - debugName: "MobileClient_list_agents", + debugName: "MobileClient_list_agents", argNames: ["that"], ); @@ -1413,7 +1001,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 22, + funcId: 14, port: port_, ); }, @@ -1449,7 +1037,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 23, + funcId: 15, port: port_, ); }, @@ -1488,7 +1076,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 24, + funcId: 16, port: port_, ); }, @@ -1527,7 +1115,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 25, + funcId: 17, port: port_, ); }, @@ -1569,7 +1157,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 26, + funcId: 18, port: port_, ); }, @@ -1612,7 +1200,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 27, + funcId: 19, port: port_, ); }, @@ -1648,7 +1236,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 28, + funcId: 20, port: port_, ); }, @@ -1669,119 +1257,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that"], ); - @override - Future - crateApiMinosMobileClientListProjectSessions({ - required MobileClient that, - required ListProjectSessionsParams req, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_box_autoadd_list_project_sessions_params(req, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 29, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_list_project_sessions_response, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientListProjectSessionsConstMeta, - argValues: [that, req], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientListProjectSessionsConstMeta => - const TaskConstMeta( - debugName: "MobileClient_list_project_sessions", - argNames: ["that", "req"], - ); - - @override - Future crateApiMinosMobileClientListProjects({ - required MobileClient that, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 30, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_list_projects_response, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientListProjectsConstMeta, - argValues: [that], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientListProjectsConstMeta => - const TaskConstMeta( - debugName: "MobileClient_list_projects", - argNames: ["that"], - ); - - @override - Future crateApiMinosMobileClientListSessions({ - required MobileClient that, - required ListSessionsParams req, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_box_autoadd_list_sessions_params(req, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 31, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_list_sessions_response, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientListSessionsConstMeta, - argValues: [that, req], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientListSessionsConstMeta => - const TaskConstMeta( - debugName: "MobileClient_list_sessions", - argNames: ["that", "req"], - ); - @override Future crateApiMinosMobileClientLoginWithSupabase({ required MobileClient that, @@ -1799,7 +1274,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 32, + funcId: 21, port: port_, ); }, @@ -1833,7 +1308,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 33, + funcId: 22, port: port_, ); }, @@ -1871,7 +1346,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 34, + funcId: 23, port: port_, ); }, @@ -1907,7 +1382,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 35, + funcId: 24, port: port_, ); }, @@ -1935,7 +1410,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(selfName, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 36)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 25)!; }, codec: SseCodec( decodeSuccessData: @@ -1966,7 +1441,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(selfName, serializer); sse_encode_box_autoadd_persisted_pairing_state(state, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 37)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 26)!; }, codec: SseCodec( decodeSuccessData: @@ -1998,7 +1473,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 38)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 27)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -2029,7 +1504,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 39)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 28)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -2063,7 +1538,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 40, + funcId: 29, port: port_, ); }, @@ -2084,44 +1559,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that"], ); - @override - Future crateApiMinosMobileClientReadSession({ - required MobileClient that, - required ReadSessionParams req, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_box_autoadd_read_session_params(req, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 41, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_read_session_response, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientReadSessionConstMeta, - argValues: [that, req], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientReadSessionConstMeta => - const TaskConstMeta( - debugName: "MobileClient_read_session", - argNames: ["that", "req"], - ); - @override Future crateApiMinosMobileClientRecallChatMessage({ required MobileClient that, @@ -2141,7 +1578,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 42, + funcId: 30, port: port_, ); }, @@ -2177,7 +1614,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 43, + funcId: 31, port: port_, ); }, @@ -2229,7 +1666,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 44, + funcId: 32, port: port_, ); }, @@ -2270,44 +1707,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ], ); - @override - Future crateApiMinosMobileClientRejectFriendRequest({ - required MobileClient that, - required String requestId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(requestId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 45, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_friend_request_summary, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientRejectFriendRequestConstMeta, - argValues: [that, requestId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientRejectFriendRequestConstMeta => - const TaskConstMeta( - debugName: "MobileClient_reject_friend_request", - argNames: ["that", "requestId"], - ); - @override Future crateApiMinosMobileClientRemoveAgentFromConversation({ required MobileClient that, @@ -2322,306 +1721,39 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - sse_encode_String(conversationId, serializer); - sse_encode_String(agentId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 46, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: - kCrateApiMinosMobileClientRemoveAgentFromConversationConstMeta, - argValues: [that, conversationId, agentId], - apiImpl: this, - ), - ); - } - - TaskConstMeta - get kCrateApiMinosMobileClientRemoveAgentFromConversationConstMeta => - const TaskConstMeta( - debugName: "MobileClient_remove_agent_from_conversation", - argNames: ["that", "conversationId", "agentId"], - ); - - @override - Future crateApiMinosMobileClientRemoveGroupMember({ - required MobileClient that, - required String conversationId, - required String memberAccountId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(conversationId, serializer); - sse_encode_String(memberAccountId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 47, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientRemoveGroupMemberConstMeta, - argValues: [that, conversationId, memberAccountId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientRemoveGroupMemberConstMeta => - const TaskConstMeta( - debugName: "MobileClient_remove_group_member", - argNames: ["that", "conversationId", "memberAccountId"], - ); - - @override - Future crateApiMinosMobileClientRespondOpencodeQuestion({ - required MobileClient that, - required String sessionId, - required String questionId, - required String answersJson, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(sessionId, serializer); - sse_encode_String(questionId, serializer); - sse_encode_String(answersJson, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 48, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientRespondOpencodeQuestionConstMeta, - argValues: [that, sessionId, questionId, answersJson], - apiImpl: this, - ), - ); - } - - TaskConstMeta - get kCrateApiMinosMobileClientRespondOpencodeQuestionConstMeta => - const TaskConstMeta( - debugName: "MobileClient_respond_opencode_question", - argNames: ["that", "sessionId", "questionId", "answersJson"], - ); - - @override - Future crateApiMinosMobileClientResumePersistedSession({ - required MobileClient that, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 49, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientResumePersistedSessionConstMeta, - argValues: [that], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientResumePersistedSessionConstMeta => - const TaskConstMeta( - debugName: "MobileClient_resume_persisted_session", - argNames: ["that"], - ); - - @override - Future> crateApiMinosMobileClientSearchUsers({ - required MobileClient that, - required String minosId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(minosId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 50, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_list_user_summary, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientSearchUsersConstMeta, - argValues: [that, minosId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientSearchUsersConstMeta => - const TaskConstMeta( - debugName: "MobileClient_search_users", - argNames: ["that", "minosId"], - ); - - @override - Future crateApiMinosMobileClientSendApprovalDecision({ - required MobileClient that, - required String requestId, - required String sessionId, - required String decisionJson, - String? clientRequestId, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(requestId, serializer); - sse_encode_String(sessionId, serializer); - sse_encode_String(decisionJson, serializer); - sse_encode_opt_String(clientRequestId, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 51, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientSendApprovalDecisionConstMeta, - argValues: [that, requestId, sessionId, decisionJson, clientRequestId], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientSendApprovalDecisionConstMeta => - const TaskConstMeta( - debugName: "MobileClient_send_approval_decision", - argNames: [ - "that", - "requestId", - "sessionId", - "decisionJson", - "clientRequestId", - ], - ); - - @override - Future crateApiMinosMobileClientSendChatMessage({ - required MobileClient that, - required String conversationId, - required String text, - String? replyToMessageId, - String? clientMessageId, - String? mentionsJson, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_String(conversationId, serializer); - sse_encode_String(text, serializer); - sse_encode_opt_String(replyToMessageId, serializer); - sse_encode_opt_String(clientMessageId, serializer); - sse_encode_opt_String(mentionsJson, serializer); + sse_encode_String(conversationId, serializer); + sse_encode_String(agentId, serializer); pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 52, + funcId: 33, port: port_, ); }, codec: SseCodec( - decodeSuccessData: sse_decode_chat_message_summary, + decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientSendChatMessageConstMeta, - argValues: [ - that, - conversationId, - text, - replyToMessageId, - clientMessageId, - mentionsJson, - ], + constMeta: + kCrateApiMinosMobileClientRemoveAgentFromConversationConstMeta, + argValues: [that, conversationId, agentId], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientSendChatMessageConstMeta => + TaskConstMeta + get kCrateApiMinosMobileClientRemoveAgentFromConversationConstMeta => const TaskConstMeta( - debugName: "MobileClient_send_chat_message", - argNames: [ - "that", - "conversationId", - "text", - "replyToMessageId", - "clientMessageId", - "mentionsJson", - ], + debugName: "MobileClient_remove_agent_from_conversation", + argNames: ["that", "conversationId", "agentId"], ); @override - Future crateApiMinosMobileClientSendUserMessage({ + Future crateApiMinosMobileClientRemoveGroupMember({ required MobileClient that, - required String sessionId, - required String text, + required String conversationId, + required String memberAccountId, }) { return handler.executeNormal( NormalTask( @@ -2631,12 +1763,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - sse_encode_String(sessionId, serializer); - sse_encode_String(text, serializer); + sse_encode_String(conversationId, serializer); + sse_encode_String(memberAccountId, serializer); pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 53, + funcId: 34, port: port_, ); }, @@ -2644,23 +1776,22 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientSendUserMessageConstMeta, - argValues: [that, sessionId, text], + constMeta: kCrateApiMinosMobileClientRemoveGroupMemberConstMeta, + argValues: [that, conversationId, memberAccountId], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientSendUserMessageConstMeta => + TaskConstMeta get kCrateApiMinosMobileClientRemoveGroupMemberConstMeta => const TaskConstMeta( - debugName: "MobileClient_send_user_message", - argNames: ["that", "sessionId", "text"], + debugName: "MobileClient_remove_group_member", + argNames: ["that", "conversationId", "memberAccountId"], ); @override - Future crateApiMinosMobileClientSetActiveHost({ + Future crateApiMinosMobileClientResumePersistedSession({ required MobileClient that, - required String hostDeviceId, }) { return handler.executeNormal( NormalTask( @@ -2670,11 +1801,10 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - sse_encode_String(hostDeviceId, serializer); pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 54, + funcId: 35, port: port_, ); }, @@ -2682,23 +1812,27 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientSetActiveHostConstMeta, - argValues: [that, hostDeviceId], + constMeta: kCrateApiMinosMobileClientResumePersistedSessionConstMeta, + argValues: [that], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientSetActiveHostConstMeta => + TaskConstMeta get kCrateApiMinosMobileClientResumePersistedSessionConstMeta => const TaskConstMeta( - debugName: "MobileClient_set_active_host", - argNames: ["that", "hostDeviceId"], + debugName: "MobileClient_resume_persisted_session", + argNames: ["that"], ); @override - Future crateApiMinosMobileClientSetMinosId({ + Future crateApiMinosMobileClientSendChatMessage({ required MobileClient that, - required String minosId, + required String conversationId, + required String text, + String? replyToMessageId, + String? clientMessageId, + String? mentionsJson, }) { return handler.executeNormal( NormalTask( @@ -2708,35 +1842,53 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - sse_encode_String(minosId, serializer); + sse_encode_String(conversationId, serializer); + sse_encode_String(text, serializer); + sse_encode_opt_String(replyToMessageId, serializer); + sse_encode_opt_String(clientMessageId, serializer); + sse_encode_opt_String(mentionsJson, serializer); pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 55, + funcId: 36, port: port_, ); }, codec: SseCodec( - decodeSuccessData: sse_decode_my_profile_response, + decodeSuccessData: sse_decode_chat_message_summary, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientSetMinosIdConstMeta, - argValues: [that, minosId], + constMeta: kCrateApiMinosMobileClientSendChatMessageConstMeta, + argValues: [ + that, + conversationId, + text, + replyToMessageId, + clientMessageId, + mentionsJson, + ], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientSetMinosIdConstMeta => + TaskConstMeta get kCrateApiMinosMobileClientSendChatMessageConstMeta => const TaskConstMeta( - debugName: "MobileClient_set_minos_id", - argNames: ["that", "minosId"], + debugName: "MobileClient_send_chat_message", + argNames: [ + "that", + "conversationId", + "text", + "replyToMessageId", + "clientMessageId", + "mentionsJson", + ], ); @override - Future crateApiMinosMobileClientSubscribeAgentSession({ + Future crateApiMinosMobileClientSetActiveHost({ required MobileClient that, - required String sessionId, + required String hostDeviceId, }) { return handler.executeNormal( NormalTask( @@ -2746,11 +1898,11 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - sse_encode_String(sessionId, serializer); + sse_encode_String(hostDeviceId, serializer); pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 56, + funcId: 37, port: port_, ); }, @@ -2758,17 +1910,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_minos_error, ), - constMeta: kCrateApiMinosMobileClientSubscribeAgentSessionConstMeta, - argValues: [that, sessionId], + constMeta: kCrateApiMinosMobileClientSetActiveHostConstMeta, + argValues: [that, hostDeviceId], apiImpl: this, ), ); } - TaskConstMeta get kCrateApiMinosMobileClientSubscribeAgentSessionConstMeta => + TaskConstMeta get kCrateApiMinosMobileClientSetActiveHostConstMeta => const TaskConstMeta( - debugName: "MobileClient_subscribe_agent_session", - argNames: ["that", "sessionId"], + debugName: "MobileClient_set_active_host", + argNames: ["that", "hostDeviceId"], ); @override @@ -2789,7 +1941,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 57, + funcId: 38, port: port_, ); }, @@ -2829,7 +1981,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 58, + funcId: 39, port: port_, ); }, @@ -2868,7 +2020,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 59, + funcId: 40, port: port_, ); }, @@ -2909,7 +2061,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 60, + funcId: 41, port: port_, ); }, @@ -2950,7 +2102,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 61, + funcId: 42, port: port_, ); }, @@ -2996,7 +2148,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 62, + funcId: 43, port: port_, ); }, @@ -3040,7 +2192,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 63, + funcId: 44, port: port_, ); }, @@ -3097,7 +2249,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 64, + funcId: 45, port: port_, ); }, @@ -3142,44 +2294,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ], ); - @override - Future crateApiMinosMobileClientUpdateProject({ - required MobileClient that, - required UpdateProjectRequest req, - }) { - return handler.executeNormal( - NormalTask( - callFfi: (port_) { - final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMobileClient( - that, - serializer, - ); - sse_encode_box_autoadd_update_project_request(req, serializer); - pdeCallFfi( - generalizedFrbRustBinding, - serializer, - funcId: 65, - port: port_, - ); - }, - codec: SseCodec( - decodeSuccessData: sse_decode_unit, - decodeErrorData: sse_decode_minos_error, - ), - constMeta: kCrateApiMinosMobileClientUpdateProjectConstMeta, - argValues: [that, req], - apiImpl: this, - ), - ); - } - - TaskConstMeta get kCrateApiMinosMobileClientUpdateProjectConstMeta => - const TaskConstMeta( - debugName: "MobileClient_update_project", - argNames: ["that", "req"], - ); - @override Future crateApiMinosMobileClientWriteHostSkillConfig({ @@ -3202,7 +2316,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 66, + funcId: 46, port: port_, ); }, @@ -3235,7 +2349,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 67)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 47)!; }, codec: SseCodec( decodeSuccessData: sse_decode_agent_name, @@ -3266,7 +2380,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 68)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 48)!; }, codec: SseCodec( decodeSuccessData: sse_decode_opt_box_autoadd_session_end_reason, @@ -3299,7 +2413,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 69)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 49)!; }, codec: SseCodec( decodeSuccessData: sse_decode_opt_box_autoadd_i_64, @@ -3332,7 +2446,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 70)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 50)!; }, codec: SseCodec( decodeSuccessData: sse_decode_i_64, @@ -3365,7 +2479,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 71)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 51)!; }, codec: SseCodec( decodeSuccessData: sse_decode_i_64, @@ -3397,7 +2511,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 72)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 52)!; }, codec: SseCodec( decodeSuccessData: sse_decode_u_32, @@ -3430,7 +2544,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 73)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 53)!; }, codec: SseCodec( decodeSuccessData: sse_decode_bool, @@ -3463,7 +2577,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 74)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 54)!; }, codec: SseCodec( decodeSuccessData: sse_decode_opt_String, @@ -3496,7 +2610,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 75)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 55)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -3529,7 +2643,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 76)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 56)!; }, codec: SseCodec( decodeSuccessData: @@ -3561,7 +2675,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 77)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 57)!; }, codec: SseCodec( decodeSuccessData: sse_decode_opt_String, @@ -3594,7 +2708,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_agent_name(agent, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 78)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 58)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3627,7 +2741,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_opt_box_autoadd_session_end_reason(endReason, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 79)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 59)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3662,7 +2776,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_opt_box_autoadd_i_64(endedAtMs, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 80)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 60)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3697,7 +2811,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_i_64(firstTsMs, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 81)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 61)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3732,7 +2846,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_i_64(lastTsMs, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 82)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 62)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3766,7 +2880,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_u_32(messageCount, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 83)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 63)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3801,7 +2915,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_bool(needsContinue, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 84)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 64)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3836,7 +2950,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_opt_String(parentSessionId, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 85)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 65)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3871,7 +2985,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_String(sessionId, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 86)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 66)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3909,7 +3023,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { state, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 87)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 67)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3942,7 +3056,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_opt_String(title, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 88)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 68)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3967,7 +3081,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 89)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 69)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -3996,7 +3110,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_log_level(level, serializer); sse_encode_String(target, serializer); sse_encode_String(message, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 90)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 70)!; }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -4024,7 +3138,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 91, + funcId: 71, port: port_, ); }, @@ -4053,7 +3167,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_error_kind(kind, serializer); sse_encode_lang(lang, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 92)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 72)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -4077,7 +3191,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 93)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 73)!; }, codec: SseCodec( decodeSuccessData: sse_decode_list_log_record, @@ -4099,7 +3213,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 94)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 74)!; }, codec: SseCodec( decodeSuccessData: sse_decode_list_request_trace_record, @@ -4127,7 +3241,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 95, + funcId: 75, port: port_, ); }, @@ -4162,7 +3276,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 96, + funcId: 76, port: port_, ); }, @@ -4370,27 +3484,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return AgentName.values[raw as int]; } - @protected - AgentSessionSummaryDto dco_decode_agent_session_summary_dto(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 11) - throw Exception('unexpected arr length: expect 11 but see ${arr.length}'); - return AgentSessionSummaryDto( - sessionId: dco_decode_String(arr[0]), - conversationId: dco_decode_String(arr[1]), - agentId: dco_decode_opt_String(arr[2]), - agent: dco_decode_opt_box_autoadd_agent_name(arr[3]), - status: dco_decode_String(arr[4]), - startedAtMs: dco_decode_i_64(arr[5]), - endedAtMs: dco_decode_opt_box_autoadd_i_64(arr[6]), - title: dco_decode_opt_String(arr[7]), - lastActivityAtMs: dco_decode_i_64(arr[8]), - messageCount: dco_decode_u_32(arr[9]), - endReason: dco_decode_opt_box_autoadd_session_end_reason(arr[10]), - ); - } - @protected AgentStatus dco_decode_agent_status(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4485,12 +3578,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw as bool; } - @protected - AgentName dco_decode_box_autoadd_agent_name(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_agent_name(raw); - } - @protected ArtifactRef dco_decode_box_autoadd_artifact_ref(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4511,22 +3598,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_chat_message_reply_summary(raw); } - @protected - CreateProjectRequest dco_decode_box_autoadd_create_project_request( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_create_project_request(raw); - } - - @protected - DeleteProjectRequest dco_decode_box_autoadd_delete_project_request( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_delete_project_request(raw); - } - @protected DisplayPayload dco_decode_box_autoadd_display_payload(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4539,20 +3610,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_i_64(raw); } - @protected - ListProjectSessionsParams dco_decode_box_autoadd_list_project_sessions_params( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_list_project_sessions_params(raw); - } - - @protected - ListSessionsParams dco_decode_box_autoadd_list_sessions_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_list_sessions_params(raw); - } - @protected MinosError dco_decode_box_autoadd_minos_error(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4567,12 +3624,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_persisted_pairing_state(raw); } - @protected - ReadSessionParams dco_decode_box_autoadd_read_session_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_read_session_params(raw); - } - @protected SessionEndReason dco_decode_box_autoadd_session_end_reason(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4591,20 +3642,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw as int; } - @protected - BigInt dco_decode_box_autoadd_u_64(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_u_64(raw); - } - - @protected - UpdateProjectRequest dco_decode_box_autoadd_update_project_request( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_update_project_request(raw); - } - @protected UserSummary dco_decode_box_autoadd_user_summary(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4775,37 +3812,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - CreateProjectRequest dco_decode_create_project_request(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return CreateProjectRequest( - name: dco_decode_String(arr[0]), - workspaceSlug: dco_decode_String(arr[1]), - workspacePath: dco_decode_opt_String(arr[2]), - ); - } - - @protected - CreateProjectResponse dco_decode_create_project_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 1) - throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return CreateProjectResponse(project: dco_decode_project_summary(arr[0])); - } - - @protected - DeleteProjectRequest dco_decode_delete_project_request(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 1) - throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return DeleteProjectRequest(projectId: dco_decode_String(arr[0])); - } - @protected DisplayPayload dco_decode_display_payload(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -4814,60 +3820,26 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return DisplayPayload_Inline(text: dco_decode_String(raw[1])); case 1: return DisplayPayload_StreamingWindow( - head: dco_decode_String(raw[1]), - receivedBytes: dco_decode_u_64(raw[2]), - artifact: dco_decode_opt_box_autoadd_artifact_ref(raw[3]), - ); - case 2: - return DisplayPayload_WindowedFinal( - head: dco_decode_String(raw[1]), - tail: dco_decode_String(raw[2]), - omittedBytes: dco_decode_u_64(raw[3]), - artifact: dco_decode_box_autoadd_artifact_ref(raw[4]), - ); - default: - throw Exception("unreachable"); - } - } - - @protected - ErrorKind dco_decode_error_kind(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return ErrorKind.values[raw as int]; - } - - @protected - FriendRequestStatus dco_decode_friend_request_status(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return FriendRequestStatus.values[raw as int]; - } - - @protected - FriendRequestSummary dco_decode_friend_request_summary(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 6) - throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); - return FriendRequestSummary( - requestId: dco_decode_String(arr[0]), - from: dco_decode_user_summary(arr[1]), - to: dco_decode_user_summary(arr[2]), - status: dco_decode_friend_request_status(arr[3]), - createdAtMs: dco_decode_i_64(arr[4]), - resolvedAtMs: dco_decode_opt_box_autoadd_i_64(arr[5]), - ); + head: dco_decode_String(raw[1]), + receivedBytes: dco_decode_u_64(raw[2]), + artifact: dco_decode_opt_box_autoadd_artifact_ref(raw[3]), + ); + case 2: + return DisplayPayload_WindowedFinal( + head: dco_decode_String(raw[1]), + tail: dco_decode_String(raw[2]), + omittedBytes: dco_decode_u_64(raw[3]), + artifact: dco_decode_box_autoadd_artifact_ref(raw[4]), + ); + default: + throw Exception("unreachable"); + } } @protected - FriendRequestsResponse dco_decode_friend_requests_response(dynamic raw) { + ErrorKind dco_decode_error_kind(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) - throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return FriendRequestsResponse( - incoming: dco_decode_list_friend_request_summary(arr[0]), - outgoing: dco_decode_list_friend_request_summary(arr[1]), - ); + return ErrorKind.values[raw as int]; } @protected @@ -4981,19 +3953,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return Lang.values[raw as int]; } - @protected - List - dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List) - .map( - dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary, - ) - .toList(); - } - @protected List dco_decode_list_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5006,16 +3965,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_agent_descriptor).toList(); } - @protected - List dco_decode_list_agent_session_summary_dto( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List) - .map(dco_decode_agent_session_summary_dto) - .toList(); - } - @protected List dco_decode_list_agent_summary(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5065,16 +4014,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_conversation_summary).toList(); } - @protected - List dco_decode_list_friend_request_summary( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List) - .map(dco_decode_friend_request_summary) - .toList(); - } - @protected List dco_decode_list_friend_summary(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5152,54 +4091,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw as Uint8List; } - @protected - ListProjectSessionsParams dco_decode_list_project_sessions_params( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return ListProjectSessionsParams( - projectId: dco_decode_String(arr[0]), - limit: dco_decode_u_32(arr[1]), - beforeTsMs: dco_decode_opt_box_autoadd_i_64(arr[2]), - ); - } - - @protected - ListProjectSessionsResponse dco_decode_list_project_sessions_response( - dynamic raw, - ) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 1) - throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return ListProjectSessionsResponse( - sessions: - dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - arr[0], - ), - ); - } - - @protected - List dco_decode_list_project_summary(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List).map(dco_decode_project_summary).toList(); - } - - @protected - ListProjectsResponse dco_decode_list_projects_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 1) - throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return ListProjectsResponse( - projects: dco_decode_list_project_summary(arr[0]), - ); - } - @protected List dco_decode_list_reaction_actor(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5218,40 +4109,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_request_trace_record).toList(); } - @protected - ListSessionsParams dco_decode_list_sessions_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return ListSessionsParams( - limit: dco_decode_u_32(arr[0]), - beforeTsMs: dco_decode_opt_box_autoadd_i_64(arr[1]), - agent: dco_decode_opt_box_autoadd_agent_name(arr[2]), - ); - } - - @protected - ListSessionsResponse dco_decode_list_sessions_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) - throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return ListSessionsResponse( - sessions: - dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - arr[0], - ), - nextBeforeTsMs: dco_decode_opt_box_autoadd_i_64(arr[1]), - ); - } - - @protected - List dco_decode_list_ui_event_message(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return (raw as List).map(dco_decode_ui_event_message).toList(); - } - @protected List dco_decode_list_user_summary(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5465,12 +4322,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw == null ? null : dco_decode_String(raw); } - @protected - AgentName? dco_decode_opt_box_autoadd_agent_name(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_agent_name(raw); - } - @protected ArtifactRef? dco_decode_opt_box_autoadd_artifact_ref(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5510,12 +4361,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw == null ? null : dco_decode_box_autoadd_u_32(raw); } - @protected - BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return raw == null ? null : dco_decode_box_autoadd_u_64(raw); - } - @protected UserSummary? dco_decode_opt_box_autoadd_user_summary(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5544,23 +4389,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - ProjectSummary dco_decode_project_summary(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 7) - throw Exception('unexpected arr length: expect 7 but see ${arr.length}'); - return ProjectSummary( - projectId: dco_decode_String(arr[0]), - name: dco_decode_String(arr[1]), - workspaceSlug: dco_decode_String(arr[2]), - workspacePath: dco_decode_opt_String(arr[3]), - createdAtMs: dco_decode_i_64(arr[4]), - updatedAtMs: dco_decode_i_64(arr[5]), - threadCount: dco_decode_u_32(arr[6]), - ); - } - @protected ReactionActor dco_decode_reaction_actor(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5588,32 +4416,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - ReadSessionParams dco_decode_read_session_params(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return ReadSessionParams( - sessionId: dco_decode_String(arr[0]), - fromSeq: dco_decode_opt_box_autoadd_u_64(arr[1]), - limit: dco_decode_u_32(arr[2]), - ); - } - - @protected - ReadSessionResponse dco_decode_read_session_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); - return ReadSessionResponse( - uiEvents: dco_decode_list_ui_event_message(arr[0]), - nextSeq: dco_decode_opt_box_autoadd_u_64(arr[1]), - sessionEndReason: dco_decode_opt_box_autoadd_session_end_reason(arr[2]), - ); - } - @protected RequestTraceRecord dco_decode_request_trace_record(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -5850,18 +4652,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return; } - @protected - UpdateProjectRequest dco_decode_update_project_request(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) - throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return UpdateProjectRequest( - projectId: dco_decode_String(arr[0]), - name: dco_decode_String(arr[1]), - ); - } - @protected UserSummary dco_decode_user_summary(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -6091,39 +4881,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return AgentName.values[inner]; } - @protected - AgentSessionSummaryDto sse_decode_agent_session_summary_dto( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_sessionId = sse_decode_String(deserializer); - var var_conversationId = sse_decode_String(deserializer); - var var_agentId = sse_decode_opt_String(deserializer); - var var_agent = sse_decode_opt_box_autoadd_agent_name(deserializer); - var var_status = sse_decode_String(deserializer); - var var_startedAtMs = sse_decode_i_64(deserializer); - var var_endedAtMs = sse_decode_opt_box_autoadd_i_64(deserializer); - var var_title = sse_decode_opt_String(deserializer); - var var_lastActivityAtMs = sse_decode_i_64(deserializer); - var var_messageCount = sse_decode_u_32(deserializer); - var var_endReason = sse_decode_opt_box_autoadd_session_end_reason( - deserializer, - ); - return AgentSessionSummaryDto( - sessionId: var_sessionId, - conversationId: var_conversationId, - agentId: var_agentId, - agent: var_agent, - status: var_status, - startedAtMs: var_startedAtMs, - endedAtMs: var_endedAtMs, - title: var_title, - lastActivityAtMs: var_lastActivityAtMs, - messageCount: var_messageCount, - endReason: var_endReason, - ); - } - @protected AgentStatus sse_decode_agent_status(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -6231,12 +4988,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return deserializer.buffer.getUint8() != 0; } - @protected - AgentName sse_decode_box_autoadd_agent_name(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_agent_name(deserializer)); - } - @protected ArtifactRef sse_decode_box_autoadd_artifact_ref( SseDeserializer deserializer, @@ -6261,22 +5012,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_chat_message_reply_summary(deserializer)); } - @protected - CreateProjectRequest sse_decode_box_autoadd_create_project_request( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_create_project_request(deserializer)); - } - - @protected - DeleteProjectRequest sse_decode_box_autoadd_delete_project_request( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_delete_project_request(deserializer)); - } - @protected DisplayPayload sse_decode_box_autoadd_display_payload( SseDeserializer deserializer, @@ -6291,22 +5026,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_i_64(deserializer)); } - @protected - ListProjectSessionsParams sse_decode_box_autoadd_list_project_sessions_params( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_list_project_sessions_params(deserializer)); - } - - @protected - ListSessionsParams sse_decode_box_autoadd_list_sessions_params( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_list_sessions_params(deserializer)); - } - @protected MinosError sse_decode_box_autoadd_minos_error(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -6321,14 +5040,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_persisted_pairing_state(deserializer)); } - @protected - ReadSessionParams sse_decode_box_autoadd_read_session_params( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_read_session_params(deserializer)); - } - @protected SessionEndReason sse_decode_box_autoadd_session_end_reason( SseDeserializer deserializer, @@ -6349,20 +5060,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_u_32(deserializer)); } - @protected - BigInt sse_decode_box_autoadd_u_64(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_u_64(deserializer)); - } - - @protected - UpdateProjectRequest sse_decode_box_autoadd_update_project_request( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_update_project_request(deserializer)); - } - @protected UserSummary sse_decode_box_autoadd_user_summary( SseDeserializer deserializer, @@ -6558,39 +5255,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ConversationsResponse(conversations: var_conversations); } - @protected - CreateProjectRequest sse_decode_create_project_request( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_name = sse_decode_String(deserializer); - var var_workspaceSlug = sse_decode_String(deserializer); - var var_workspacePath = sse_decode_opt_String(deserializer); - return CreateProjectRequest( - name: var_name, - workspaceSlug: var_workspaceSlug, - workspacePath: var_workspacePath, - ); - } - - @protected - CreateProjectResponse sse_decode_create_project_response( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_project = sse_decode_project_summary(deserializer); - return CreateProjectResponse(project: var_project); - } - - @protected - DeleteProjectRequest sse_decode_delete_project_request( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_projectId = sse_decode_String(deserializer); - return DeleteProjectRequest(projectId: var_projectId); - } - @protected DisplayPayload sse_decode_display_payload(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -6619,62 +5283,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return DisplayPayload_WindowedFinal( head: var_head, tail: var_tail, - omittedBytes: var_omittedBytes, - artifact: var_artifact, - ); - default: - throw UnimplementedError(''); - } - } - - @protected - ErrorKind sse_decode_error_kind(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var inner = sse_decode_i_32(deserializer); - return ErrorKind.values[inner]; - } - - @protected - FriendRequestStatus sse_decode_friend_request_status( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var inner = sse_decode_i_32(deserializer); - return FriendRequestStatus.values[inner]; - } - - @protected - FriendRequestSummary sse_decode_friend_request_summary( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_requestId = sse_decode_String(deserializer); - var var_from = sse_decode_user_summary(deserializer); - var var_to = sse_decode_user_summary(deserializer); - var var_status = sse_decode_friend_request_status(deserializer); - var var_createdAtMs = sse_decode_i_64(deserializer); - var var_resolvedAtMs = sse_decode_opt_box_autoadd_i_64(deserializer); - return FriendRequestSummary( - requestId: var_requestId, - from: var_from, - to: var_to, - status: var_status, - createdAtMs: var_createdAtMs, - resolvedAtMs: var_resolvedAtMs, - ); + omittedBytes: var_omittedBytes, + artifact: var_artifact, + ); + default: + throw UnimplementedError(''); + } } @protected - FriendRequestsResponse sse_decode_friend_requests_response( - SseDeserializer deserializer, - ) { + ErrorKind sse_decode_error_kind(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_incoming = sse_decode_list_friend_request_summary(deserializer); - var var_outgoing = sse_decode_list_friend_request_summary(deserializer); - return FriendRequestsResponse( - incoming: var_incoming, - outgoing: var_outgoing, - ); + var inner = sse_decode_i_32(deserializer); + return ErrorKind.values[inner]; } @protected @@ -6792,25 +5413,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return Lang.values[inner]; } - @protected - List - sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add( - sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - deserializer, - ), - ); - } - return ans_; - } - @protected List sse_decode_list_String(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -6837,20 +5439,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - List sse_decode_list_agent_session_summary_dto( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_agent_session_summary_dto(deserializer)); - } - return ans_; - } - @protected List sse_decode_list_agent_summary( SseDeserializer deserializer, @@ -6929,20 +5517,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - List sse_decode_list_friend_request_summary( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_friend_request_summary(deserializer)); - } - return ans_; - } - @protected List sse_decode_list_friend_summary( SseDeserializer deserializer, @@ -7068,56 +5642,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return deserializer.buffer.getUint8List(len_); } - @protected - ListProjectSessionsParams sse_decode_list_project_sessions_params( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_projectId = sse_decode_String(deserializer); - var var_limit = sse_decode_u_32(deserializer); - var var_beforeTsMs = sse_decode_opt_box_autoadd_i_64(deserializer); - return ListProjectSessionsParams( - projectId: var_projectId, - limit: var_limit, - beforeTsMs: var_beforeTsMs, - ); - } - - @protected - ListProjectSessionsResponse sse_decode_list_project_sessions_response( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_sessions = - sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - deserializer, - ); - return ListProjectSessionsResponse(sessions: var_sessions); - } - - @protected - List sse_decode_list_project_summary( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_project_summary(deserializer)); - } - return ans_; - } - - @protected - ListProjectsResponse sse_decode_list_projects_response( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_projects = sse_decode_list_project_summary(deserializer); - return ListProjectsResponse(projects: var_projects); - } - @protected List sse_decode_list_reaction_actor( SseDeserializer deserializer, @@ -7160,51 +5684,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } - @protected - ListSessionsParams sse_decode_list_sessions_params( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_limit = sse_decode_u_32(deserializer); - var var_beforeTsMs = sse_decode_opt_box_autoadd_i_64(deserializer); - var var_agent = sse_decode_opt_box_autoadd_agent_name(deserializer); - return ListSessionsParams( - limit: var_limit, - beforeTsMs: var_beforeTsMs, - agent: var_agent, - ); - } - - @protected - ListSessionsResponse sse_decode_list_sessions_response( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_sessions = - sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - deserializer, - ); - var var_nextBeforeTsMs = sse_decode_opt_box_autoadd_i_64(deserializer); - return ListSessionsResponse( - sessions: var_sessions, - nextBeforeTsMs: var_nextBeforeTsMs, - ); - } - - @protected - List sse_decode_list_ui_event_message( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - var len_ = sse_decode_i_32(deserializer); - var ans_ = []; - for (var idx_ = 0; idx_ < len_; ++idx_) { - ans_.add(sse_decode_ui_event_message(deserializer)); - } - return ans_; - } - @protected List sse_decode_list_user_summary(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -7464,19 +5943,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - AgentName? sse_decode_opt_box_autoadd_agent_name( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_agent_name(deserializer)); - } else { - return null; - } - } - @protected ArtifactRef? sse_decode_opt_box_autoadd_artifact_ref( SseDeserializer deserializer, @@ -7550,17 +6016,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - if (sse_decode_bool(deserializer)) { - return (sse_decode_box_autoadd_u_64(deserializer)); - } else { - return null; - } - } - @protected UserSummary? sse_decode_opt_box_autoadd_user_summary( SseDeserializer deserializer, @@ -7602,27 +6057,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - ProjectSummary sse_decode_project_summary(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_projectId = sse_decode_String(deserializer); - var var_name = sse_decode_String(deserializer); - var var_workspaceSlug = sse_decode_String(deserializer); - var var_workspacePath = sse_decode_opt_String(deserializer); - var var_createdAtMs = sse_decode_i_64(deserializer); - var var_updatedAtMs = sse_decode_i_64(deserializer); - var var_threadCount = sse_decode_u_32(deserializer); - return ProjectSummary( - projectId: var_projectId, - name: var_name, - workspaceSlug: var_workspaceSlug, - workspacePath: var_workspacePath, - createdAtMs: var_createdAtMs, - updatedAtMs: var_updatedAtMs, - threadCount: var_threadCount, - ); - } - @protected ReactionActor sse_decode_reaction_actor(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -7651,38 +6085,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - ReadSessionParams sse_decode_read_session_params( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_sessionId = sse_decode_String(deserializer); - var var_fromSeq = sse_decode_opt_box_autoadd_u_64(deserializer); - var var_limit = sse_decode_u_32(deserializer); - return ReadSessionParams( - sessionId: var_sessionId, - fromSeq: var_fromSeq, - limit: var_limit, - ); - } - - @protected - ReadSessionResponse sse_decode_read_session_response( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_uiEvents = sse_decode_list_ui_event_message(deserializer); - var var_nextSeq = sse_decode_opt_box_autoadd_u_64(deserializer); - var var_sessionEndReason = sse_decode_opt_box_autoadd_session_end_reason( - deserializer, - ); - return ReadSessionResponse( - uiEvents: var_uiEvents, - nextSeq: var_nextSeq, - sessionEndReason: var_sessionEndReason, - ); - } - @protected RequestTraceRecord sse_decode_request_trace_record( SseDeserializer deserializer, @@ -7991,16 +6393,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { // Codec=Sse (Serialization based), see doc to use other codecs } - @protected - UpdateProjectRequest sse_decode_update_project_request( - SseDeserializer deserializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_projectId = sse_decode_String(deserializer); - var var_name = sse_decode_String(deserializer); - return UpdateProjectRequest(projectId: var_projectId, name: var_name); - } - @protected UserSummary sse_decode_user_summary(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -8284,25 +6676,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_32(self.index, serializer); } - @protected - void sse_encode_agent_session_summary_dto( - AgentSessionSummaryDto self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.sessionId, serializer); - sse_encode_String(self.conversationId, serializer); - sse_encode_opt_String(self.agentId, serializer); - sse_encode_opt_box_autoadd_agent_name(self.agent, serializer); - sse_encode_String(self.status, serializer); - sse_encode_i_64(self.startedAtMs, serializer); - sse_encode_opt_box_autoadd_i_64(self.endedAtMs, serializer); - sse_encode_opt_String(self.title, serializer); - sse_encode_i_64(self.lastActivityAtMs, serializer); - sse_encode_u_32(self.messageCount, serializer); - sse_encode_opt_box_autoadd_session_end_reason(self.endReason, serializer); - } - @protected void sse_encode_agent_status(AgentStatus self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -8380,15 +6753,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer.buffer.putUint8(self ? 1 : 0); } - @protected - void sse_encode_box_autoadd_agent_name( - AgentName self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_agent_name(self, serializer); - } - @protected void sse_encode_box_autoadd_artifact_ref( ArtifactRef self, @@ -8416,24 +6780,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_chat_message_reply_summary(self, serializer); } - @protected - void sse_encode_box_autoadd_create_project_request( - CreateProjectRequest self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_create_project_request(self, serializer); - } - - @protected - void sse_encode_box_autoadd_delete_project_request( - DeleteProjectRequest self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_delete_project_request(self, serializer); - } - @protected void sse_encode_box_autoadd_display_payload( DisplayPayload self, @@ -8452,24 +6798,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_64(self, serializer); } - @protected - void sse_encode_box_autoadd_list_project_sessions_params( - ListProjectSessionsParams self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_project_sessions_params(self, serializer); - } - - @protected - void sse_encode_box_autoadd_list_sessions_params( - ListSessionsParams self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_sessions_params(self, serializer); - } - @protected void sse_encode_box_autoadd_minos_error( MinosError self, @@ -8488,15 +6816,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_persisted_pairing_state(self, serializer); } - @protected - void sse_encode_box_autoadd_read_session_params( - ReadSessionParams self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_read_session_params(self, serializer); - } - @protected void sse_encode_box_autoadd_session_end_reason( SessionEndReason self, @@ -8518,21 +6837,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_u_32(self, serializer); } - @protected - void sse_encode_box_autoadd_u_64(BigInt self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_64(self, serializer); - } - - @protected - void sse_encode_box_autoadd_update_project_request( - UpdateProjectRequest self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_update_project_request(self, serializer); - } - @protected void sse_encode_box_autoadd_user_summary( UserSummary self, @@ -8658,67 +6962,38 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - void sse_encode_conversation_response( - ConversationResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.conversationId, serializer); - } - - @protected - void sse_encode_conversation_summary( - ConversationSummary self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.conversationId, serializer); - sse_encode_conversation_kind(self.kind, serializer); - sse_encode_String(self.title, serializer); - sse_encode_opt_box_autoadd_user_summary(self.counterpart, serializer); - sse_encode_u_32(self.memberCount, serializer); - sse_encode_opt_String(self.lastMessagePreview, serializer); - sse_encode_i_64(self.lastMessageAtMs, serializer); - sse_encode_u_32(self.unreadCount, serializer); - sse_encode_u_32(self.unreadMentionCount, serializer); - } - - @protected - void sse_encode_conversations_response( - ConversationsResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_conversation_summary(self.conversations, serializer); - } - - @protected - void sse_encode_create_project_request( - CreateProjectRequest self, + void sse_encode_conversation_response( + ConversationResponse self, SseSerializer serializer, ) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.name, serializer); - sse_encode_String(self.workspaceSlug, serializer); - sse_encode_opt_String(self.workspacePath, serializer); + sse_encode_String(self.conversationId, serializer); } @protected - void sse_encode_create_project_response( - CreateProjectResponse self, + void sse_encode_conversation_summary( + ConversationSummary self, SseSerializer serializer, ) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_project_summary(self.project, serializer); + sse_encode_String(self.conversationId, serializer); + sse_encode_conversation_kind(self.kind, serializer); + sse_encode_String(self.title, serializer); + sse_encode_opt_box_autoadd_user_summary(self.counterpart, serializer); + sse_encode_u_32(self.memberCount, serializer); + sse_encode_opt_String(self.lastMessagePreview, serializer); + sse_encode_i_64(self.lastMessageAtMs, serializer); + sse_encode_u_32(self.unreadCount, serializer); + sse_encode_u_32(self.unreadMentionCount, serializer); } @protected - void sse_encode_delete_project_request( - DeleteProjectRequest self, + void sse_encode_conversations_response( + ConversationsResponse self, SseSerializer serializer, ) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.projectId, serializer); + sse_encode_list_conversation_summary(self.conversations, serializer); } @protected @@ -8760,39 +7035,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_32(self.index, serializer); } - @protected - void sse_encode_friend_request_status( - FriendRequestStatus self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.index, serializer); - } - - @protected - void sse_encode_friend_request_summary( - FriendRequestSummary self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.requestId, serializer); - sse_encode_user_summary(self.from, serializer); - sse_encode_user_summary(self.to, serializer); - sse_encode_friend_request_status(self.status, serializer); - sse_encode_i_64(self.createdAtMs, serializer); - sse_encode_opt_box_autoadd_i_64(self.resolvedAtMs, serializer); - } - - @protected - void sse_encode_friend_requests_response( - FriendRequestsResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_friend_request_summary(self.incoming, serializer); - sse_encode_list_friend_request_summary(self.outgoing, serializer); - } - @protected void sse_encode_friend_summary(FriendSummary self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -8889,22 +7131,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_32(self.index, serializer); } - @protected - void - sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - List self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - item, - serializer, - ); - } - } - @protected void sse_encode_list_String(List self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -8926,18 +7152,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_list_agent_session_summary_dto( - List self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_agent_session_summary_dto(item, serializer); - } - } - @protected void sse_encode_list_agent_summary( List self, @@ -9005,18 +7219,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_list_friend_request_summary( - List self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_friend_request_summary(item, serializer); - } - } - @protected void sse_encode_list_friend_summary( List self, @@ -9130,50 +7332,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer.buffer.putUint8List(self); } - @protected - void sse_encode_list_project_sessions_params( - ListProjectSessionsParams self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.projectId, serializer); - sse_encode_u_32(self.limit, serializer); - sse_encode_opt_box_autoadd_i_64(self.beforeTsMs, serializer); - } - - @protected - void sse_encode_list_project_sessions_response( - ListProjectSessionsResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - self.sessions, - serializer, - ); - } - - @protected - void sse_encode_list_project_summary( - List self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_project_summary(item, serializer); - } - } - - @protected - void sse_encode_list_projects_response( - ListProjectsResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_project_summary(self.projects, serializer); - } - @protected void sse_encode_list_reaction_actor( List self, @@ -9210,42 +7368,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_list_sessions_params( - ListSessionsParams self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_32(self.limit, serializer); - sse_encode_opt_box_autoadd_i_64(self.beforeTsMs, serializer); - sse_encode_opt_box_autoadd_agent_name(self.agent, serializer); - } - - @protected - void sse_encode_list_sessions_response( - ListSessionsResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - self.sessions, - serializer, - ); - sse_encode_opt_box_autoadd_i_64(self.nextBeforeTsMs, serializer); - } - - @protected - void sse_encode_list_ui_event_message( - List self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_i_32(self.length, serializer); - for (final item in self) { - sse_encode_ui_event_message(item, serializer); - } - } - @protected void sse_encode_list_user_summary( List self, @@ -9483,19 +7605,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_opt_box_autoadd_agent_name( - AgentName? self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_agent_name(self, serializer); - } - } - @protected void sse_encode_opt_box_autoadd_artifact_ref( ArtifactRef? self, @@ -9568,16 +7677,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } - @protected - void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - - sse_encode_bool(self != null, serializer); - if (self != null) { - sse_encode_box_autoadd_u_64(self, serializer); - } - } - @protected void sse_encode_opt_box_autoadd_user_summary( UserSummary? self, @@ -9611,21 +7710,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_opt_String(self.accountEmail, serializer); } - @protected - void sse_encode_project_summary( - ProjectSummary self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.projectId, serializer); - sse_encode_String(self.name, serializer); - sse_encode_String(self.workspaceSlug, serializer); - sse_encode_opt_String(self.workspacePath, serializer); - sse_encode_i_64(self.createdAtMs, serializer); - sse_encode_i_64(self.updatedAtMs, serializer); - sse_encode_u_32(self.threadCount, serializer); - } - @protected void sse_encode_reaction_actor(ReactionActor self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -9643,31 +7727,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_list_reaction_actor(self.actors, serializer); } - @protected - void sse_encode_read_session_params( - ReadSessionParams self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.sessionId, serializer); - sse_encode_opt_box_autoadd_u_64(self.fromSeq, serializer); - sse_encode_u_32(self.limit, serializer); - } - - @protected - void sse_encode_read_session_response( - ReadSessionResponse self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_list_ui_event_message(self.uiEvents, serializer); - sse_encode_opt_box_autoadd_u_64(self.nextSeq, serializer); - sse_encode_opt_box_autoadd_session_end_reason( - self.sessionEndReason, - serializer, - ); - } - @protected void sse_encode_request_trace_record( RequestTraceRecord self, @@ -9944,16 +8003,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { // Codec=Sse (Serialization based), see doc to use other codecs } - @protected - void sse_encode_update_project_request( - UpdateProjectRequest self, - SseSerializer serializer, - ) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.projectId, serializer); - sse_encode_String(self.name, serializer); - } - @protected void sse_encode_user_summary(UserSummary self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -9997,13 +8046,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { RustLib.instance.api.rust_arc_decrement_strong_count_MobileClientPtr, ); - Future acceptFriendRequest({ - required String requestId, - }) => RustLib.instance.api.crateApiMinosMobileClientAcceptFriendRequest( - that: this, - requestId: requestId, - ); - /// Advance durable topic cursor after Dart cache/reducer commit. Future ackDurableApplied({ required String topic, @@ -10037,10 +8079,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { memberAccountId: memberAccountId, ); - /// Permanently close the given thread. Idempotent. - Future closeSession({required String sessionId}) => RustLib.instance.api - .crateApiMinosMobileClientCloseSession(that: this, sessionId: sessionId); - Future conversationMembers({ required String conversationId, }) => RustLib.instance.api.crateApiMinosMobileClientConversationMembers( @@ -10051,13 +8089,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { Future conversations() => RustLib.instance.api.crateApiMinosMobileClientConversations(that: this); - Future createFriendRequest({ - required String targetMinosId, - }) => RustLib.instance.api.crateApiMinosMobileClientCreateFriendRequest( - that: this, - targetMinosId: targetMinosId, - ); - Future createGroupConversation({ required String title, required List memberAccountIds, @@ -10067,14 +8098,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { memberAccountIds: memberAccountIds, ); - /// Create a new project on the daemon. - Future createProject({ - required CreateProjectRequest req, - }) => RustLib.instance.api.crateApiMinosMobileClientCreateProject( - that: this, - req: req, - ); - /// Current connection state, read from the watch-channel cache. Cheap and /// synchronous. ConnectionState currentState() => @@ -10086,12 +8109,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { conversationId: conversationId, ); - /// Delete a project. - Future deleteProject({required DeleteProjectRequest req}) => RustLib - .instance - .api - .crateApiMinosMobileClientDeleteProject(that: this, req: req); - Future ensureDirectConversation({ required String friendAccountId, }) => RustLib.instance.api.crateApiMinosMobileClientEnsureDirectConversation( @@ -10107,30 +8124,9 @@ class MobileClientImpl extends RustOpaque implements MobileClient { hostDeviceId: hostDeviceId, ); - Future friendRequests() => - RustLib.instance.api.crateApiMinosMobileClientFriendRequests(that: this); - Future friends() => RustLib.instance.api.crateApiMinosMobileClientFriends(that: this); - /// Pause an in-flight turn on the given thread. Best-effort. The thread - /// transitions to `Suspended { UserInterrupt }` regardless of whether the - /// codex side acknowledges in time. - Future interruptSession({required String sessionId}) => - RustLib.instance.api.crateApiMinosMobileClientInterruptSession( - that: this, - sessionId: sessionId, - ); - - Future> listAgentSessions({ - String? conversationId, - required int limit, - }) => RustLib.instance.api.crateApiMinosMobileClientListAgentSessions( - that: this, - conversationId: conversationId, - limit: limit, - ); - Future listAgents() => RustLib.instance.api.crateApiMinosMobileClientListAgents(that: this); @@ -10191,26 +8187,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { Future> listPairedHosts() => RustLib.instance.api.crateApiMinosMobileClientListPairedHosts(that: this); - /// List sessions within a project. - Future listProjectSessions({ - required ListProjectSessionsParams req, - }) => RustLib.instance.api.crateApiMinosMobileClientListProjectSessions( - that: this, - req: req, - ); - - /// List all projects on the daemon. - Future listProjects() => - RustLib.instance.api.crateApiMinosMobileClientListProjects(that: this); - - /// Request a page of thread summaries. - Future listSessions({ - required ListSessionsParams req, - }) => RustLib.instance.api.crateApiMinosMobileClientListSessions( - that: this, - req: req, - ); - /// Exchange a Supabase access token for Minos access/refresh tokens and /// adopt the resulting session. Future loginWithSupabase({ @@ -10242,6 +8218,21 @@ class MobileClientImpl extends RustOpaque implements MobileClient { void notifyBackgrounded() => RustLib.instance.api .crateApiMinosMobileClientNotifyBackgrounded(that: this); + /// Send a follow-up user message to an existing agent session. + /// Submit a user approval decision for a pending host request. + /// + /// `client_request_id` is the Hub Intent Outbox id. When omitted, + /// the mobile client generates one so the wire body never hardcodes null. + /// Submit an opencode question answer for a pending host request. + /// Pause an in-flight turn on the given thread. Best-effort. The thread + /// transitions to `Suspended { UserInterrupt }` regardless of whether the + /// codex side acknowledges in time. + /// Permanently close the given thread. Idempotent. + /// Create a new project on the daemon. + /// List all projects on the daemon. + /// Update a project's name. + /// Delete a project. + /// List sessions within a project. /// Mark the app as foregrounded. Resets the reconnect backoff so the /// next connect attempt happens promptly. void notifyForegrounded() => RustLib.instance.api @@ -10252,13 +8243,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { Future persistedPairingState() => RustLib.instance.api .crateApiMinosMobileClientPersistedPairingState(that: this); - /// Read a window of translated UI events for one session. - Future readSession({required ReadSessionParams req}) => - RustLib.instance.api.crateApiMinosMobileClientReadSession( - that: this, - req: req, - ); - Future recallChatMessage({ required String conversationId, required String messageId, @@ -10295,13 +8279,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { systemPrompt: systemPrompt, ); - Future rejectFriendRequest({ - required String requestId, - }) => RustLib.instance.api.crateApiMinosMobileClientRejectFriendRequest( - that: this, - requestId: requestId, - ); - Future removeAgentFromConversation({ required String conversationId, required String agentId, @@ -10321,45 +8298,11 @@ class MobileClientImpl extends RustOpaque implements MobileClient { memberAccountId: memberAccountId, ); - /// Submit an opencode question answer for a pending host request. - Future respondOpencodeQuestion({ - required String sessionId, - required String questionId, - required String answersJson, - }) => RustLib.instance.api.crateApiMinosMobileClientRespondOpencodeQuestion( - that: this, - sessionId: sessionId, - questionId: questionId, - answersJson: answersJson, - ); - /// Reconnect using the durable session snapshot already loaded from the /// Dart-side secure store. Future resumePersistedSession() => RustLib.instance.api .crateApiMinosMobileClientResumePersistedSession(that: this); - Future> searchUsers({required String minosId}) => RustLib - .instance - .api - .crateApiMinosMobileClientSearchUsers(that: this, minosId: minosId); - - /// Submit a user approval decision for a pending host request. - /// - /// `client_request_id` is the Hub Intent Outbox id. When omitted, - /// the mobile client generates one so the wire body never hardcodes null. - Future sendApprovalDecision({ - required String requestId, - required String sessionId, - required String decisionJson, - String? clientRequestId, - }) => RustLib.instance.api.crateApiMinosMobileClientSendApprovalDecision( - that: this, - requestId: requestId, - sessionId: sessionId, - decisionJson: decisionJson, - clientRequestId: clientRequestId, - ); - /// `mentions_json` is an optional JSON array of wire `MentionTarget` objects. Future sendChatMessage({ required String conversationId, @@ -10376,16 +8319,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { mentionsJson: mentionsJson, ); - /// Send a follow-up user message to an existing agent session. - Future sendUserMessage({ - required String sessionId, - required String text, - }) => RustLib.instance.api.crateApiMinosMobileClientSendUserMessage( - that: this, - sessionId: sessionId, - text: text, - ); - /// Override the active Mac the next forward-RPC routes to. Future setActiveHost({required String hostDeviceId}) => RustLib.instance.api.crateApiMinosMobileClientSetActiveHost( @@ -10393,17 +8326,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { hostDeviceId: hostDeviceId, ); - Future setMinosId({required String minosId}) => RustLib - .instance - .api - .crateApiMinosMobileClientSetMinosId(that: this, minosId: minosId); - - Future subscribeAgentSession({required String sessionId}) => - RustLib.instance.api.crateApiMinosMobileClientSubscribeAgentSession( - that: this, - sessionId: sessionId, - ); - /// Subscribe to auth-state transitions. Emits the current cached frame /// immediately, then every subsequent change. The spawned task exits /// once Dart drops the stream (detected via `sink.add(...).is_err()`). @@ -10479,12 +8401,6 @@ class MobileClientImpl extends RustOpaque implements MobileClient { status: status, ); - /// Update a project's name. - Future updateProject({required UpdateProjectRequest req}) => RustLib - .instance - .api - .crateApiMinosMobileClientUpdateProject(that: this, req: req); - /// Enable or disable one host-side skill. Future writeHostSkillConfig({ String? hostDeviceId, diff --git a/apps/mobile/lib/src/rust/frb_generated.io.dart b/apps/mobile/lib/src/rust/frb_generated.io.dart index e0a5aada..98ae60bb 100644 --- a/apps/mobile/lib/src/rust/frb_generated.io.dart +++ b/apps/mobile/lib/src/rust/frb_generated.io.dart @@ -123,9 +123,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected AgentName dco_decode_agent_name(dynamic raw); - @protected - AgentSessionSummaryDto dco_decode_agent_session_summary_dto(dynamic raw); - @protected AgentStatus dco_decode_agent_status(dynamic raw); @@ -144,9 +141,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected bool dco_decode_bool(dynamic raw); - @protected - AgentName dco_decode_box_autoadd_agent_name(dynamic raw); - @protected ArtifactRef dco_decode_box_autoadd_artifact_ref(dynamic raw); @@ -158,30 +152,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dynamic raw, ); - @protected - CreateProjectRequest dco_decode_box_autoadd_create_project_request( - dynamic raw, - ); - - @protected - DeleteProjectRequest dco_decode_box_autoadd_delete_project_request( - dynamic raw, - ); - @protected DisplayPayload dco_decode_box_autoadd_display_payload(dynamic raw); @protected PlatformInt64 dco_decode_box_autoadd_i_64(dynamic raw); - @protected - ListProjectSessionsParams dco_decode_box_autoadd_list_project_sessions_params( - dynamic raw, - ); - - @protected - ListSessionsParams dco_decode_box_autoadd_list_sessions_params(dynamic raw); - @protected MinosError dco_decode_box_autoadd_minos_error(dynamic raw); @@ -190,9 +166,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dynamic raw, ); - @protected - ReadSessionParams dco_decode_box_autoadd_read_session_params(dynamic raw); - @protected SessionEndReason dco_decode_box_autoadd_session_end_reason(dynamic raw); @@ -202,14 +175,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int dco_decode_box_autoadd_u_32(dynamic raw); - @protected - BigInt dco_decode_box_autoadd_u_64(dynamic raw); - - @protected - UpdateProjectRequest dco_decode_box_autoadd_update_project_request( - dynamic raw, - ); - @protected UserSummary dco_decode_box_autoadd_user_summary(dynamic raw); @@ -253,30 +218,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected ConversationsResponse dco_decode_conversations_response(dynamic raw); - @protected - CreateProjectRequest dco_decode_create_project_request(dynamic raw); - - @protected - CreateProjectResponse dco_decode_create_project_response(dynamic raw); - - @protected - DeleteProjectRequest dco_decode_delete_project_request(dynamic raw); - @protected DisplayPayload dco_decode_display_payload(dynamic raw); @protected ErrorKind dco_decode_error_kind(dynamic raw); - @protected - FriendRequestStatus dco_decode_friend_request_status(dynamic raw); - - @protected - FriendRequestSummary dco_decode_friend_request_summary(dynamic raw); - - @protected - FriendRequestsResponse dco_decode_friend_requests_response(dynamic raw); - @protected FriendSummary dco_decode_friend_summary(dynamic raw); @@ -307,23 +254,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Lang dco_decode_lang(dynamic raw); - @protected - List - dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - dynamic raw, - ); - @protected List dco_decode_list_String(dynamic raw); @protected List dco_decode_list_agent_descriptor(dynamic raw); - @protected - List dco_decode_list_agent_session_summary_dto( - dynamic raw, - ); - @protected List dco_decode_list_agent_summary(dynamic raw); @@ -344,11 +280,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_conversation_summary(dynamic raw); - @protected - List dco_decode_list_friend_request_summary( - dynamic raw, - ); - @protected List dco_decode_list_friend_summary(dynamic raw); @@ -383,22 +314,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); - @protected - ListProjectSessionsParams dco_decode_list_project_sessions_params( - dynamic raw, - ); - - @protected - ListProjectSessionsResponse dco_decode_list_project_sessions_response( - dynamic raw, - ); - - @protected - List dco_decode_list_project_summary(dynamic raw); - - @protected - ListProjectsResponse dco_decode_list_projects_response(dynamic raw); - @protected List dco_decode_list_reaction_actor(dynamic raw); @@ -408,15 +323,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_request_trace_record(dynamic raw); - @protected - ListSessionsParams dco_decode_list_sessions_params(dynamic raw); - - @protected - ListSessionsResponse dco_decode_list_sessions_response(dynamic raw); - - @protected - List dco_decode_list_ui_event_message(dynamic raw); - @protected List dco_decode_list_user_summary(dynamic raw); @@ -441,9 +347,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? dco_decode_opt_String(dynamic raw); - @protected - AgentName? dco_decode_opt_box_autoadd_agent_name(dynamic raw); - @protected ArtifactRef? dco_decode_opt_box_autoadd_artifact_ref(dynamic raw); @@ -463,9 +366,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int? dco_decode_opt_box_autoadd_u_32(dynamic raw); - @protected - BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw); - @protected UserSummary? dco_decode_opt_box_autoadd_user_summary(dynamic raw); @@ -475,21 +375,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PersistedPairingState dco_decode_persisted_pairing_state(dynamic raw); - @protected - ProjectSummary dco_decode_project_summary(dynamic raw); - @protected ReactionActor dco_decode_reaction_actor(dynamic raw); @protected ReactionGroup dco_decode_reaction_group(dynamic raw); - @protected - ReadSessionParams dco_decode_read_session_params(dynamic raw); - - @protected - ReadSessionResponse dco_decode_read_session_response(dynamic raw); - @protected RequestTraceRecord dco_decode_request_trace_record(dynamic raw); @@ -535,9 +426,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void dco_decode_unit(dynamic raw); - @protected - UpdateProjectRequest dco_decode_update_project_request(dynamic raw); - @protected UserSummary dco_decode_user_summary(dynamic raw); @@ -644,11 +532,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected AgentName sse_decode_agent_name(SseDeserializer deserializer); - @protected - AgentSessionSummaryDto sse_decode_agent_session_summary_dto( - SseDeserializer deserializer, - ); - @protected AgentStatus sse_decode_agent_status(SseDeserializer deserializer); @@ -667,9 +550,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected bool sse_decode_bool(SseDeserializer deserializer); - @protected - AgentName sse_decode_box_autoadd_agent_name(SseDeserializer deserializer); - @protected ArtifactRef sse_decode_box_autoadd_artifact_ref(SseDeserializer deserializer); @@ -681,16 +561,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - CreateProjectRequest sse_decode_box_autoadd_create_project_request( - SseDeserializer deserializer, - ); - - @protected - DeleteProjectRequest sse_decode_box_autoadd_delete_project_request( - SseDeserializer deserializer, - ); - @protected DisplayPayload sse_decode_box_autoadd_display_payload( SseDeserializer deserializer, @@ -699,16 +569,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PlatformInt64 sse_decode_box_autoadd_i_64(SseDeserializer deserializer); - @protected - ListProjectSessionsParams sse_decode_box_autoadd_list_project_sessions_params( - SseDeserializer deserializer, - ); - - @protected - ListSessionsParams sse_decode_box_autoadd_list_sessions_params( - SseDeserializer deserializer, - ); - @protected MinosError sse_decode_box_autoadd_minos_error(SseDeserializer deserializer); @@ -717,11 +577,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - ReadSessionParams sse_decode_box_autoadd_read_session_params( - SseDeserializer deserializer, - ); - @protected SessionEndReason sse_decode_box_autoadd_session_end_reason( SseDeserializer deserializer, @@ -733,14 +588,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); - @protected - BigInt sse_decode_box_autoadd_u_64(SseDeserializer deserializer); - - @protected - UpdateProjectRequest sse_decode_box_autoadd_update_project_request( - SseDeserializer deserializer, - ); - @protected UserSummary sse_decode_box_autoadd_user_summary(SseDeserializer deserializer); @@ -798,42 +645,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - CreateProjectRequest sse_decode_create_project_request( - SseDeserializer deserializer, - ); - - @protected - CreateProjectResponse sse_decode_create_project_response( - SseDeserializer deserializer, - ); - - @protected - DeleteProjectRequest sse_decode_delete_project_request( - SseDeserializer deserializer, - ); - @protected DisplayPayload sse_decode_display_payload(SseDeserializer deserializer); @protected ErrorKind sse_decode_error_kind(SseDeserializer deserializer); - @protected - FriendRequestStatus sse_decode_friend_request_status( - SseDeserializer deserializer, - ); - - @protected - FriendRequestSummary sse_decode_friend_request_summary( - SseDeserializer deserializer, - ); - - @protected - FriendRequestsResponse sse_decode_friend_requests_response( - SseDeserializer deserializer, - ); - @protected FriendSummary sse_decode_friend_summary(SseDeserializer deserializer); @@ -866,12 +683,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Lang sse_decode_lang(SseDeserializer deserializer); - @protected - List - sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_String(SseDeserializer deserializer); @@ -880,11 +691,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - List sse_decode_list_agent_session_summary_dto( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_agent_summary( SseDeserializer deserializer, @@ -915,11 +721,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - List sse_decode_list_friend_request_summary( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_friend_summary( SseDeserializer deserializer, @@ -966,26 +767,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); - @protected - ListProjectSessionsParams sse_decode_list_project_sessions_params( - SseDeserializer deserializer, - ); - - @protected - ListProjectSessionsResponse sse_decode_list_project_sessions_response( - SseDeserializer deserializer, - ); - - @protected - List sse_decode_list_project_summary( - SseDeserializer deserializer, - ); - - @protected - ListProjectsResponse sse_decode_list_projects_response( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_reaction_actor( SseDeserializer deserializer, @@ -1001,21 +782,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - ListSessionsParams sse_decode_list_sessions_params( - SseDeserializer deserializer, - ); - - @protected - ListSessionsResponse sse_decode_list_sessions_response( - SseDeserializer deserializer, - ); - - @protected - List sse_decode_list_ui_event_message( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_user_summary(SseDeserializer deserializer); @@ -1042,11 +808,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? sse_decode_opt_String(SseDeserializer deserializer); - @protected - AgentName? sse_decode_opt_box_autoadd_agent_name( - SseDeserializer deserializer, - ); - @protected ArtifactRef? sse_decode_opt_box_autoadd_artifact_ref( SseDeserializer deserializer, @@ -1072,9 +833,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); - @protected - BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer); - @protected UserSummary? sse_decode_opt_box_autoadd_user_summary( SseDeserializer deserializer, @@ -1088,25 +846,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - ProjectSummary sse_decode_project_summary(SseDeserializer deserializer); - @protected ReactionActor sse_decode_reaction_actor(SseDeserializer deserializer); @protected ReactionGroup sse_decode_reaction_group(SseDeserializer deserializer); - @protected - ReadSessionParams sse_decode_read_session_params( - SseDeserializer deserializer, - ); - - @protected - ReadSessionResponse sse_decode_read_session_response( - SseDeserializer deserializer, - ); - @protected RequestTraceRecord sse_decode_request_trace_record( SseDeserializer deserializer, @@ -1160,11 +905,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_decode_unit(SseDeserializer deserializer); - @protected - UpdateProjectRequest sse_decode_update_project_request( - SseDeserializer deserializer, - ); - @protected UserSummary sse_decode_user_summary(SseDeserializer deserializer); @@ -1293,12 +1033,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_agent_name(AgentName self, SseSerializer serializer); - @protected - void sse_encode_agent_session_summary_dto( - AgentSessionSummaryDto self, - SseSerializer serializer, - ); - @protected void sse_encode_agent_status(AgentStatus self, SseSerializer serializer); @@ -1320,12 +1054,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_bool(bool self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_agent_name( - AgentName self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_artifact_ref( ArtifactRef self, @@ -1344,18 +1072,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_box_autoadd_create_project_request( - CreateProjectRequest self, - SseSerializer serializer, - ); - - @protected - void sse_encode_box_autoadd_delete_project_request( - DeleteProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_display_payload( DisplayPayload self, @@ -1368,18 +1084,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_box_autoadd_list_project_sessions_params( - ListProjectSessionsParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_box_autoadd_list_sessions_params( - ListSessionsParams self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_minos_error( MinosError self, @@ -1392,12 +1096,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_box_autoadd_read_session_params( - ReadSessionParams self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_session_end_reason( SessionEndReason self, @@ -1410,15 +1108,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_u_64(BigInt self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_update_project_request( - UpdateProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_user_summary( UserSummary self, @@ -1497,24 +1186,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_create_project_request( - CreateProjectRequest self, - SseSerializer serializer, - ); - - @protected - void sse_encode_create_project_response( - CreateProjectResponse self, - SseSerializer serializer, - ); - - @protected - void sse_encode_delete_project_request( - DeleteProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_display_payload( DisplayPayload self, @@ -1524,24 +1195,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_error_kind(ErrorKind self, SseSerializer serializer); - @protected - void sse_encode_friend_request_status( - FriendRequestStatus self, - SseSerializer serializer, - ); - - @protected - void sse_encode_friend_request_summary( - FriendRequestSummary self, - SseSerializer serializer, - ); - - @protected - void sse_encode_friend_requests_response( - FriendRequestsResponse self, - SseSerializer serializer, - ); - @protected void sse_encode_friend_summary(FriendSummary self, SseSerializer serializer); @@ -1590,13 +1243,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_lang(Lang self, SseSerializer serializer); - @protected - void - sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_String(List self, SseSerializer serializer); @@ -1606,12 +1252,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_agent_session_summary_dto( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_agent_summary( List self, @@ -1648,12 +1288,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_friend_request_summary( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_friend_summary( List self, @@ -1714,30 +1348,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_project_sessions_params( - ListProjectSessionsParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_project_sessions_response( - ListProjectSessionsResponse self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_project_summary( - List self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_projects_response( - ListProjectsResponse self, - SseSerializer serializer, - ); - @protected void sse_encode_list_reaction_actor( List self, @@ -1756,24 +1366,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_sessions_params( - ListSessionsParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_sessions_response( - ListSessionsResponse self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_ui_event_message( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_user_summary( List self, @@ -1804,12 +1396,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_String(String? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_agent_name( - AgentName? self, - SseSerializer serializer, - ); - @protected void sse_encode_opt_box_autoadd_artifact_ref( ArtifactRef? self, @@ -1840,9 +1426,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer); - @protected void sse_encode_opt_box_autoadd_user_summary( UserSummary? self, @@ -1858,30 +1441,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_project_summary( - ProjectSummary self, - SseSerializer serializer, - ); - @protected void sse_encode_reaction_actor(ReactionActor self, SseSerializer serializer); @protected void sse_encode_reaction_group(ReactionGroup self, SseSerializer serializer); - @protected - void sse_encode_read_session_params( - ReadSessionParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_read_session_response( - ReadSessionResponse self, - SseSerializer serializer, - ); - @protected void sse_encode_request_trace_record( RequestTraceRecord self, @@ -1951,12 +1516,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_unit(void self, SseSerializer serializer); - @protected - void sse_encode_update_project_request( - UpdateProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_user_summary(UserSummary self, SseSerializer serializer); diff --git a/apps/mobile/lib/src/rust/frb_generated.web.dart b/apps/mobile/lib/src/rust/frb_generated.web.dart index 2aafa854..f7c06904 100644 --- a/apps/mobile/lib/src/rust/frb_generated.web.dart +++ b/apps/mobile/lib/src/rust/frb_generated.web.dart @@ -125,9 +125,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected AgentName dco_decode_agent_name(dynamic raw); - @protected - AgentSessionSummaryDto dco_decode_agent_session_summary_dto(dynamic raw); - @protected AgentStatus dco_decode_agent_status(dynamic raw); @@ -146,9 +143,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected bool dco_decode_bool(dynamic raw); - @protected - AgentName dco_decode_box_autoadd_agent_name(dynamic raw); - @protected ArtifactRef dco_decode_box_autoadd_artifact_ref(dynamic raw); @@ -160,30 +154,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dynamic raw, ); - @protected - CreateProjectRequest dco_decode_box_autoadd_create_project_request( - dynamic raw, - ); - - @protected - DeleteProjectRequest dco_decode_box_autoadd_delete_project_request( - dynamic raw, - ); - @protected DisplayPayload dco_decode_box_autoadd_display_payload(dynamic raw); @protected PlatformInt64 dco_decode_box_autoadd_i_64(dynamic raw); - @protected - ListProjectSessionsParams dco_decode_box_autoadd_list_project_sessions_params( - dynamic raw, - ); - - @protected - ListSessionsParams dco_decode_box_autoadd_list_sessions_params(dynamic raw); - @protected MinosError dco_decode_box_autoadd_minos_error(dynamic raw); @@ -192,9 +168,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { dynamic raw, ); - @protected - ReadSessionParams dco_decode_box_autoadd_read_session_params(dynamic raw); - @protected SessionEndReason dco_decode_box_autoadd_session_end_reason(dynamic raw); @@ -204,14 +177,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int dco_decode_box_autoadd_u_32(dynamic raw); - @protected - BigInt dco_decode_box_autoadd_u_64(dynamic raw); - - @protected - UpdateProjectRequest dco_decode_box_autoadd_update_project_request( - dynamic raw, - ); - @protected UserSummary dco_decode_box_autoadd_user_summary(dynamic raw); @@ -255,30 +220,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected ConversationsResponse dco_decode_conversations_response(dynamic raw); - @protected - CreateProjectRequest dco_decode_create_project_request(dynamic raw); - - @protected - CreateProjectResponse dco_decode_create_project_response(dynamic raw); - - @protected - DeleteProjectRequest dco_decode_delete_project_request(dynamic raw); - @protected DisplayPayload dco_decode_display_payload(dynamic raw); @protected ErrorKind dco_decode_error_kind(dynamic raw); - @protected - FriendRequestStatus dco_decode_friend_request_status(dynamic raw); - - @protected - FriendRequestSummary dco_decode_friend_request_summary(dynamic raw); - - @protected - FriendRequestsResponse dco_decode_friend_requests_response(dynamic raw); - @protected FriendSummary dco_decode_friend_summary(dynamic raw); @@ -309,23 +256,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Lang dco_decode_lang(dynamic raw); - @protected - List - dco_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - dynamic raw, - ); - @protected List dco_decode_list_String(dynamic raw); @protected List dco_decode_list_agent_descriptor(dynamic raw); - @protected - List dco_decode_list_agent_session_summary_dto( - dynamic raw, - ); - @protected List dco_decode_list_agent_summary(dynamic raw); @@ -346,11 +282,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_conversation_summary(dynamic raw); - @protected - List dco_decode_list_friend_request_summary( - dynamic raw, - ); - @protected List dco_decode_list_friend_summary(dynamic raw); @@ -385,22 +316,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); - @protected - ListProjectSessionsParams dco_decode_list_project_sessions_params( - dynamic raw, - ); - - @protected - ListProjectSessionsResponse dco_decode_list_project_sessions_response( - dynamic raw, - ); - - @protected - List dco_decode_list_project_summary(dynamic raw); - - @protected - ListProjectsResponse dco_decode_list_projects_response(dynamic raw); - @protected List dco_decode_list_reaction_actor(dynamic raw); @@ -410,15 +325,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_request_trace_record(dynamic raw); - @protected - ListSessionsParams dco_decode_list_sessions_params(dynamic raw); - - @protected - ListSessionsResponse dco_decode_list_sessions_response(dynamic raw); - - @protected - List dco_decode_list_ui_event_message(dynamic raw); - @protected List dco_decode_list_user_summary(dynamic raw); @@ -443,9 +349,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? dco_decode_opt_String(dynamic raw); - @protected - AgentName? dco_decode_opt_box_autoadd_agent_name(dynamic raw); - @protected ArtifactRef? dco_decode_opt_box_autoadd_artifact_ref(dynamic raw); @@ -465,9 +368,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int? dco_decode_opt_box_autoadd_u_32(dynamic raw); - @protected - BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw); - @protected UserSummary? dco_decode_opt_box_autoadd_user_summary(dynamic raw); @@ -477,21 +377,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PersistedPairingState dco_decode_persisted_pairing_state(dynamic raw); - @protected - ProjectSummary dco_decode_project_summary(dynamic raw); - @protected ReactionActor dco_decode_reaction_actor(dynamic raw); @protected ReactionGroup dco_decode_reaction_group(dynamic raw); - @protected - ReadSessionParams dco_decode_read_session_params(dynamic raw); - - @protected - ReadSessionResponse dco_decode_read_session_response(dynamic raw); - @protected RequestTraceRecord dco_decode_request_trace_record(dynamic raw); @@ -537,9 +428,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void dco_decode_unit(dynamic raw); - @protected - UpdateProjectRequest dco_decode_update_project_request(dynamic raw); - @protected UserSummary dco_decode_user_summary(dynamic raw); @@ -646,11 +534,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected AgentName sse_decode_agent_name(SseDeserializer deserializer); - @protected - AgentSessionSummaryDto sse_decode_agent_session_summary_dto( - SseDeserializer deserializer, - ); - @protected AgentStatus sse_decode_agent_status(SseDeserializer deserializer); @@ -669,9 +552,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected bool sse_decode_bool(SseDeserializer deserializer); - @protected - AgentName sse_decode_box_autoadd_agent_name(SseDeserializer deserializer); - @protected ArtifactRef sse_decode_box_autoadd_artifact_ref(SseDeserializer deserializer); @@ -683,16 +563,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - CreateProjectRequest sse_decode_box_autoadd_create_project_request( - SseDeserializer deserializer, - ); - - @protected - DeleteProjectRequest sse_decode_box_autoadd_delete_project_request( - SseDeserializer deserializer, - ); - @protected DisplayPayload sse_decode_box_autoadd_display_payload( SseDeserializer deserializer, @@ -701,16 +571,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PlatformInt64 sse_decode_box_autoadd_i_64(SseDeserializer deserializer); - @protected - ListProjectSessionsParams sse_decode_box_autoadd_list_project_sessions_params( - SseDeserializer deserializer, - ); - - @protected - ListSessionsParams sse_decode_box_autoadd_list_sessions_params( - SseDeserializer deserializer, - ); - @protected MinosError sse_decode_box_autoadd_minos_error(SseDeserializer deserializer); @@ -719,11 +579,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - ReadSessionParams sse_decode_box_autoadd_read_session_params( - SseDeserializer deserializer, - ); - @protected SessionEndReason sse_decode_box_autoadd_session_end_reason( SseDeserializer deserializer, @@ -735,14 +590,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); - @protected - BigInt sse_decode_box_autoadd_u_64(SseDeserializer deserializer); - - @protected - UpdateProjectRequest sse_decode_box_autoadd_update_project_request( - SseDeserializer deserializer, - ); - @protected UserSummary sse_decode_box_autoadd_user_summary(SseDeserializer deserializer); @@ -800,42 +647,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - CreateProjectRequest sse_decode_create_project_request( - SseDeserializer deserializer, - ); - - @protected - CreateProjectResponse sse_decode_create_project_response( - SseDeserializer deserializer, - ); - - @protected - DeleteProjectRequest sse_decode_delete_project_request( - SseDeserializer deserializer, - ); - @protected DisplayPayload sse_decode_display_payload(SseDeserializer deserializer); @protected ErrorKind sse_decode_error_kind(SseDeserializer deserializer); - @protected - FriendRequestStatus sse_decode_friend_request_status( - SseDeserializer deserializer, - ); - - @protected - FriendRequestSummary sse_decode_friend_request_summary( - SseDeserializer deserializer, - ); - - @protected - FriendRequestsResponse sse_decode_friend_requests_response( - SseDeserializer deserializer, - ); - @protected FriendSummary sse_decode_friend_summary(SseDeserializer deserializer); @@ -868,12 +685,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Lang sse_decode_lang(SseDeserializer deserializer); - @protected - List - sse_decode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_String(SseDeserializer deserializer); @@ -882,11 +693,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - List sse_decode_list_agent_session_summary_dto( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_agent_summary( SseDeserializer deserializer, @@ -917,11 +723,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - List sse_decode_list_friend_request_summary( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_friend_summary( SseDeserializer deserializer, @@ -968,26 +769,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); - @protected - ListProjectSessionsParams sse_decode_list_project_sessions_params( - SseDeserializer deserializer, - ); - - @protected - ListProjectSessionsResponse sse_decode_list_project_sessions_response( - SseDeserializer deserializer, - ); - - @protected - List sse_decode_list_project_summary( - SseDeserializer deserializer, - ); - - @protected - ListProjectsResponse sse_decode_list_projects_response( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_reaction_actor( SseDeserializer deserializer, @@ -1003,21 +784,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - ListSessionsParams sse_decode_list_sessions_params( - SseDeserializer deserializer, - ); - - @protected - ListSessionsResponse sse_decode_list_sessions_response( - SseDeserializer deserializer, - ); - - @protected - List sse_decode_list_ui_event_message( - SseDeserializer deserializer, - ); - @protected List sse_decode_list_user_summary(SseDeserializer deserializer); @@ -1044,11 +810,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected String? sse_decode_opt_String(SseDeserializer deserializer); - @protected - AgentName? sse_decode_opt_box_autoadd_agent_name( - SseDeserializer deserializer, - ); - @protected ArtifactRef? sse_decode_opt_box_autoadd_artifact_ref( SseDeserializer deserializer, @@ -1074,9 +835,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); - @protected - BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer); - @protected UserSummary? sse_decode_opt_box_autoadd_user_summary( SseDeserializer deserializer, @@ -1090,25 +848,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseDeserializer deserializer, ); - @protected - ProjectSummary sse_decode_project_summary(SseDeserializer deserializer); - @protected ReactionActor sse_decode_reaction_actor(SseDeserializer deserializer); @protected ReactionGroup sse_decode_reaction_group(SseDeserializer deserializer); - @protected - ReadSessionParams sse_decode_read_session_params( - SseDeserializer deserializer, - ); - - @protected - ReadSessionResponse sse_decode_read_session_response( - SseDeserializer deserializer, - ); - @protected RequestTraceRecord sse_decode_request_trace_record( SseDeserializer deserializer, @@ -1162,11 +907,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_decode_unit(SseDeserializer deserializer); - @protected - UpdateProjectRequest sse_decode_update_project_request( - SseDeserializer deserializer, - ); - @protected UserSummary sse_decode_user_summary(SseDeserializer deserializer); @@ -1295,12 +1035,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_agent_name(AgentName self, SseSerializer serializer); - @protected - void sse_encode_agent_session_summary_dto( - AgentSessionSummaryDto self, - SseSerializer serializer, - ); - @protected void sse_encode_agent_status(AgentStatus self, SseSerializer serializer); @@ -1322,12 +1056,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_bool(bool self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_agent_name( - AgentName self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_artifact_ref( ArtifactRef self, @@ -1346,18 +1074,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_box_autoadd_create_project_request( - CreateProjectRequest self, - SseSerializer serializer, - ); - - @protected - void sse_encode_box_autoadd_delete_project_request( - DeleteProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_display_payload( DisplayPayload self, @@ -1370,18 +1086,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_box_autoadd_list_project_sessions_params( - ListProjectSessionsParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_box_autoadd_list_sessions_params( - ListSessionsParams self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_minos_error( MinosError self, @@ -1394,12 +1098,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_box_autoadd_read_session_params( - ReadSessionParams self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_session_end_reason( SessionEndReason self, @@ -1412,15 +1110,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_u_64(BigInt self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_update_project_request( - UpdateProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_box_autoadd_user_summary( UserSummary self, @@ -1499,24 +1188,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_create_project_request( - CreateProjectRequest self, - SseSerializer serializer, - ); - - @protected - void sse_encode_create_project_response( - CreateProjectResponse self, - SseSerializer serializer, - ); - - @protected - void sse_encode_delete_project_request( - DeleteProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_display_payload( DisplayPayload self, @@ -1526,24 +1197,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_error_kind(ErrorKind self, SseSerializer serializer); - @protected - void sse_encode_friend_request_status( - FriendRequestStatus self, - SseSerializer serializer, - ); - - @protected - void sse_encode_friend_request_summary( - FriendRequestSummary self, - SseSerializer serializer, - ); - - @protected - void sse_encode_friend_requests_response( - FriendRequestsResponse self, - SseSerializer serializer, - ); - @protected void sse_encode_friend_summary(FriendSummary self, SseSerializer serializer); @@ -1592,13 +1245,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_lang(Lang self, SseSerializer serializer); - @protected - void - sse_encode_list_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSessionSummary( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_String(List self, SseSerializer serializer); @@ -1608,12 +1254,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_agent_session_summary_dto( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_agent_summary( List self, @@ -1650,12 +1290,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_friend_request_summary( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_friend_summary( List self, @@ -1716,30 +1350,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_project_sessions_params( - ListProjectSessionsParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_project_sessions_response( - ListProjectSessionsResponse self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_project_summary( - List self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_projects_response( - ListProjectsResponse self, - SseSerializer serializer, - ); - @protected void sse_encode_list_reaction_actor( List self, @@ -1758,24 +1368,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_list_sessions_params( - ListSessionsParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_sessions_response( - ListSessionsResponse self, - SseSerializer serializer, - ); - - @protected - void sse_encode_list_ui_event_message( - List self, - SseSerializer serializer, - ); - @protected void sse_encode_list_user_summary( List self, @@ -1806,12 +1398,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_String(String? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_agent_name( - AgentName? self, - SseSerializer serializer, - ); - @protected void sse_encode_opt_box_autoadd_artifact_ref( ArtifactRef? self, @@ -1842,9 +1428,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); - @protected - void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer); - @protected void sse_encode_opt_box_autoadd_user_summary( UserSummary? self, @@ -1860,30 +1443,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); - @protected - void sse_encode_project_summary( - ProjectSummary self, - SseSerializer serializer, - ); - @protected void sse_encode_reaction_actor(ReactionActor self, SseSerializer serializer); @protected void sse_encode_reaction_group(ReactionGroup self, SseSerializer serializer); - @protected - void sse_encode_read_session_params( - ReadSessionParams self, - SseSerializer serializer, - ); - - @protected - void sse_encode_read_session_response( - ReadSessionResponse self, - SseSerializer serializer, - ); - @protected void sse_encode_request_trace_record( RequestTraceRecord self, @@ -1953,12 +1518,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_unit(void self, SseSerializer serializer); - @protected - void sse_encode_update_project_request( - UpdateProjectRequest self, - SseSerializer serializer, - ); - @protected void sse_encode_user_summary(UserSummary self, SseSerializer serializer); diff --git a/apps/mobile/lib/ui/README.md b/apps/mobile/lib/ui/README.md index ba9edb77..815b37ba 100644 --- a/apps/mobile/lib/ui/README.md +++ b/apps/mobile/lib/ui/README.md @@ -29,10 +29,9 @@ Bottom tabs (single column): 1. **消息** — conversation inbox (`features/messages/`), sorted by last activity 2. **Hosts** — linked Macs from `GET /v1/hosts` (`features/hosts/`) -3. **账户** — account + logout; secondary entry to Agent sessions +3. **账户** — account + logout + developer log viewer -Agent sessions (`features/sessions/`), social chat detail, projects, and agent -profiles remain on secondary routes. +Conversation detail is `/social/chat/:conversationId` (`features/social/`). ## Feature Map @@ -40,16 +39,15 @@ profiles remain on secondary routes. |-----------|---------------------------------------|-------------------------------------| | auth | `ui/features/auth/auth.dart` | Login / register | | messages | `ui/features/messages/messages.dart` | Golden-path conversation inbox | -| sessions | `ui/features/sessions/sessions.dart` | Agent session list (secondary) | | hosts | `ui/features/hosts/hosts.dart` | Linked hosts | -| chat | `ui/features/chat/chat.dart` | Agent session chat | | account | `ui/features/account/` | Account tab | -| projects | `ui/features/projects/projects.dart` | Project CRUD (secondary) | -| agents | `ui/features/agents/agents.dart` | Agent profile management | | social | `ui/features/social/social.dart` | Collaboration IM (Slack-style rows) | | debug | `ui/features/debug/debug.dart` | Log viewer & traces | | shell | `ui/features/shell/shell.dart` | Root navigation shell | +Removed product surfaces (no longer shipped on Mobile): sessions list, agent +session transcript chat, projects, agents hub. + ## Shared Widgets Cross-feature widgets live in `ui/core/widgets/widgets.dart`: @@ -58,8 +56,8 @@ Cross-feature widgets live in `ui/core/widgets/widgets.dart`: import 'package:minos/ui/core/widgets/widgets.dart'; ``` -Includes toast, buttons, text field, progress, approval sheet, empty state, -page header, surface card, status dot. +Includes toast, buttons, text field, progress, empty state, page header, +surface card, status dot. ## Collaboration IM widgets (`features/social/`) @@ -76,11 +74,13 @@ L/R messenger bubbles): | `widgets/conversation_system_message.dart` | Recall / system centered chrome | | `widgets/conversation_message_actions.dart` | Long-press sheet: reply / copy / retry / recall | -Agent session transcript (`features/chat/`) remains a separate surface. +Application orchestration for the open chat is +`SocialChatViewModel` + `SocialChatActions` under `application/social/`. ## Layer Boundary Rules - Views (this layer) may import from `application/` providers. - Views must NOT import from `infrastructure/` directly. -- Views must NOT contain business logic — delegate to providers. +- Views must NOT contain business logic — delegate to providers / feature + ViewModels and Actions. - Shared widgets in `core/` must be stateless or self-contained. diff --git a/apps/mobile/lib/ui/core/widgets/agent_question_sheet.dart b/apps/mobile/lib/ui/core/widgets/agent_question_sheet.dart deleted file mode 100644 index 53a9afe0..00000000 --- a/apps/mobile/lib/ui/core/widgets/agent_question_sheet.dart +++ /dev/null @@ -1,317 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:minos/ui/core/widgets/minos_button.dart'; -import 'package:minos/ui/theme/theme.dart'; - -class AgentQuestionRequestData { - const AgentQuestionRequestData({ - required this.requestId, - required this.questions, - }); - - final String requestId; - final List questions; - - factory AgentQuestionRequestData.fromJson(Map json) { - final properties = switch (json['properties']) { - final Map value => value.map( - (key, value) => MapEntry('$key', value), - ), - _ => json, - }; - final questions = switch (properties['questions']) { - final List value => - value - .whereType>() - .map( - (item) => AgentQuestionData.fromJson( - item.map((key, value) => MapEntry('$key', value)), - ), - ) - .toList(), - _ => const [], - }; - return AgentQuestionRequestData( - requestId: - properties['id'] as String? ?? - properties['requestID'] as String? ?? - '', - questions: questions, - ); - } -} - -class AgentQuestionData { - const AgentQuestionData({ - required this.header, - required this.question, - required this.options, - required this.multiple, - required this.custom, - }); - - final String header; - final String question; - final List options; - final bool multiple; - final bool custom; - - factory AgentQuestionData.fromJson(Map json) { - final options = switch (json['options']) { - final List value => - value - .whereType>() - .map( - (item) => AgentQuestionOptionData.fromJson( - item.map((key, value) => MapEntry('$key', value)), - ), - ) - .where((option) => option.label.isNotEmpty) - .toList(), - _ => const [], - }; - return AgentQuestionData( - header: json['header'] as String? ?? '', - question: json['question'] as String? ?? 'Question', - options: options, - multiple: json['multiple'] as bool? ?? false, - custom: json['custom'] as bool? ?? false, - ); - } -} - -class AgentQuestionOptionData { - const AgentQuestionOptionData({ - required this.label, - required this.description, - }); - - final String label; - final String description; - - factory AgentQuestionOptionData.fromJson(Map json) { - return AgentQuestionOptionData( - label: json['label'] as String? ?? json['value'] as String? ?? '', - description: json['description'] as String? ?? '', - ); - } -} - -Future>?> showAgentQuestionSheet( - BuildContext context, { - required AgentQuestionRequestData request, -}) { - return showModalBottomSheet>>( - context: context, - isScrollControlled: true, - isDismissible: false, - enableDrag: false, - backgroundColor: Colors.transparent, - builder: (_) => _AgentQuestionSheet(request: request), - ); -} - -class _AgentQuestionSheet extends StatefulWidget { - const _AgentQuestionSheet({required this.request}); - - final AgentQuestionRequestData request; - - @override - State<_AgentQuestionSheet> createState() => _AgentQuestionSheetState(); -} - -class _AgentQuestionSheetState extends State<_AgentQuestionSheet> { - late final List> _selected = List.generate( - widget.request.questions.length, - (_) => {}, - ); - late final List _customControllers = List.generate( - widget.request.questions.length, - (_) => TextEditingController(), - ); - - @override - void dispose() { - for (final controller in _customControllers) { - controller.dispose(); - } - super.dispose(); - } - - bool get _canSubmit { - for (var i = 0; i < widget.request.questions.length; i++) { - if (_answersFor(i).isEmpty) return false; - } - return widget.request.questions.isNotEmpty; - } - - List _answersFor(int index) { - final custom = _customControllers[index].text.trim(); - if (custom.isNotEmpty) return [custom]; - return _selected[index].toList(growable: false); - } - - List> _answers() { - return List.generate(widget.request.questions.length, _answersFor); - } - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final textTheme = Theme.of(context).textTheme; - return SafeArea( - child: Container( - constraints: BoxConstraints( - maxHeight: MediaQuery.sizeOf(context).height * 0.86, - ), - decoration: BoxDecoration( - color: colors.canvas, - borderRadius: const BorderRadius.vertical(top: Radius.circular(16)), - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(20, 16, 20, 12), - child: Row( - children: [ - Icon( - CupertinoIcons.chat_bubble, - size: 22, - color: colors.textPrimary, - ), - const SizedBox(width: 10), - Expanded( - child: Text('Agent 提问', style: textTheme.titleLarge), - ), - ], - ), - ), - Flexible( - child: ListView.separated( - padding: const EdgeInsets.fromLTRB(20, 0, 20, 16), - itemCount: widget.request.questions.length, - separatorBuilder: (_, _) => const SizedBox(height: 16), - itemBuilder: (context, index) { - return _QuestionBlock( - question: widget.request.questions[index], - selected: _selected[index], - customController: _customControllers[index], - onChanged: () => setState(() {}), - ); - }, - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(20, 0, 20, 20), - child: MinosButton( - expanded: true, - onPressed: _canSubmit - ? () => Navigator.of(context).pop(_answers()) - : null, - child: const Text('提交答案'), - ), - ), - ], - ), - ), - ); - } -} - -class _QuestionBlock extends StatelessWidget { - const _QuestionBlock({ - required this.question, - required this.selected, - required this.customController, - required this.onChanged, - }); - - final AgentQuestionData question; - final Set selected; - final TextEditingController customController; - final VoidCallback onChanged; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final textTheme = Theme.of(context).textTheme; - final title = question.header.isEmpty ? question.question : question.header; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(title, style: textTheme.titleMedium), - if (question.header.isNotEmpty) ...[ - const SizedBox(height: 4), - Text( - question.question, - style: textTheme.bodyMedium?.copyWith(color: colors.textSecondary), - ), - ], - const SizedBox(height: 10), - if (question.multiple) - for (final option in question.options) - CheckboxListTile( - contentPadding: EdgeInsets.zero, - value: selected.contains(option.label), - title: Text(option.label), - subtitle: option.description.isEmpty - ? null - : Text(option.description), - onChanged: (checked) { - if (checked == true) { - selected.add(option.label); - } else { - selected.remove(option.label); - } - customController.clear(); - onChanged(); - }, - ) - else - RadioGroup( - groupValue: selected.isEmpty ? null : selected.first, - onChanged: (value) { - selected.clear(); - if (value != null) { - selected.add(value); - } - customController.clear(); - onChanged(); - }, - child: Column( - children: [ - for (final option in question.options) - RadioListTile( - contentPadding: EdgeInsets.zero, - value: option.label, - title: Text(option.label), - subtitle: option.description.isEmpty - ? null - : Text(option.description), - ), - ], - ), - ), - if (question.custom || question.options.isEmpty) ...[ - const SizedBox(height: 8), - TextField( - controller: customController, - minLines: 1, - maxLines: 4, - decoration: const InputDecoration( - labelText: '自定义答案', - border: OutlineInputBorder(), - ), - onChanged: (_) { - if (customController.text.trim().isNotEmpty) { - selected.clear(); - } - onChanged(); - }, - ), - ], - ], - ); - } -} diff --git a/apps/mobile/lib/ui/core/widgets/approval_sheet.dart b/apps/mobile/lib/ui/core/widgets/approval_sheet.dart deleted file mode 100644 index 9b6a9301..00000000 --- a/apps/mobile/lib/ui/core/widgets/approval_sheet.dart +++ /dev/null @@ -1,428 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:minos/ui/theme/theme.dart'; - -final _approvalCountdownProvider = NotifierProvider.autoDispose - .family<_ApprovalCountdownController, int, _ApprovalCountdownConfig>( - _ApprovalCountdownController.new, - ); - -class _ApprovalCountdownConfig { - const _ApprovalCountdownConfig({ - required this.requestId, - required this.timeoutMs, - }); - - final String requestId; - final int timeoutMs; - - @override - bool operator ==(Object other) { - return other is _ApprovalCountdownConfig && - other.requestId == requestId && - other.timeoutMs == timeoutMs; - } - - @override - int get hashCode => Object.hash(requestId, timeoutMs); -} - -class _ApprovalCountdownController extends Notifier { - _ApprovalCountdownController(this.config); - - final _ApprovalCountdownConfig config; - Timer? _timer; - - @override - int build() { - ref.onDispose(() => _timer?.cancel()); - - final remainingSeconds = (config.timeoutMs / 1000).ceil(); - if (remainingSeconds > 0) { - _timer = Timer.periodic(const Duration(seconds: 1), (_) { - final next = state - 1; - if (next <= 0) { - _timer?.cancel(); - if (state != 0) { - state = 0; - } - return; - } - state = next; - }); - } - return remainingSeconds; - } -} - -/// Data class representing an approval request received from the host. -class ApprovalRequestData { - const ApprovalRequestData({ - required this.sessionId, - required this.turnId, - required this.requestId, - required this.method, - required this.params, - required this.timeoutMs, - }); - - final String sessionId; - final String turnId; - final String requestId; - final String method; - final Map params; - final int timeoutMs; - - factory ApprovalRequestData.fromJson(Map json) { - return ApprovalRequestData( - sessionId: json['session_id'] as String? ?? '', - turnId: json['turn_id'] as String? ?? '', - requestId: json['request_id'] as String? ?? '', - method: json['method'] as String? ?? '', - params: switch (json['params']) { - final Map value => value.map( - (key, value) => MapEntry('$key', value), - ), - _ => const {}, - }, - timeoutMs: switch (json['timeout_ms']) { - final int value => value, - final num value => value.toInt(), - _ => 120000, - }, - ); - } -} - -Future showApprovalSheet( - BuildContext context, { - required ApprovalRequestData request, -}) { - return showModalBottomSheet( - context: context, - isScrollControlled: true, - isDismissible: false, - enableDrag: false, - backgroundColor: Colors.transparent, - builder: (_) => _ApprovalSheet(request: request), - ); -} - -enum ApprovalDecision { accept, decline } - -class _ApprovalSheet extends ConsumerStatefulWidget { - const _ApprovalSheet({required this.request}); - - final ApprovalRequestData request; - - @override - ConsumerState<_ApprovalSheet> createState() => _ApprovalSheetState(); -} - -class _ApprovalSheetState extends ConsumerState<_ApprovalSheet> { - late final _ApprovalCountdownConfig _countdownConfig = - _ApprovalCountdownConfig( - requestId: widget.request.requestId, - timeoutMs: widget.request.timeoutMs, - ); - - String get _requestTypeLabel { - final method = widget.request.method; - if (method.contains('command_execution') || - method.contains('exec_command')) { - return '命令执行'; - } else if (method.contains('file_change') || - method.contains('apply_patch')) { - return '文件修改'; - } else if (method.contains('permissions')) { - return '权限请求'; - } - return '操作审批'; - } - - IconData get _requestTypeIcon { - final method = widget.request.method; - if (method.contains('command_execution') || - method.contains('exec_command')) { - return Icons.terminal_rounded; - } else if (method.contains('file_change') || - method.contains('apply_patch')) { - return CupertinoIcons.doc_on_doc; - } else if (method.contains('permissions')) { - return CupertinoIcons.shield; - } - return CupertinoIcons.exclamationmark_triangle; - } - - Widget _buildDetailSection(Map params) { - final widgets = []; - final method = widget.request.method; - final colors = context.minosColors; - - if (method.contains('command_execution') || - method.contains('exec_command')) { - final command = - params['command'] as String? ?? - (params['command_line'] as List?)?.join(' ') ?? - ''; - if (command.isNotEmpty) { - widgets.add(_DetailRow(label: '命令', value: command, isCode: true)); - } - final cwd = params['cwd'] as String? ?? params['working_dir'] as String?; - if (cwd != null && cwd.isNotEmpty) { - widgets.add(_DetailRow(label: '目录', value: cwd)); - } - } - - if (method.contains('file_change') || method.contains('apply_patch')) { - final files = params['files'] as List? ?? params['patches'] as List?; - if (files != null && files.isNotEmpty) { - final fileNames = files - .map((f) => f is Map ? (f['path'] ?? f['file'] ?? '') : '$f') - .where((s) => s.toString().isNotEmpty) - .take(5) - .toList(); - if (fileNames.isNotEmpty) { - widgets.add( - _DetailRow(label: '文件', value: fileNames.join('\n'), isCode: true), - ); - } - if (files.length > 5) { - widgets.add( - Padding( - padding: const EdgeInsets.only(left: 60), - child: Text( - '…及其他 ${files.length - 5} 个文件', - style: TextStyle(fontSize: 12, color: colors.textTertiary), - ), - ), - ); - } - } - } - - if (method.contains('permissions')) { - final permissions = - params['permissions'] as List? ?? params['scopes'] as List?; - if (permissions != null && permissions.isNotEmpty) { - widgets.add( - _DetailRow( - label: '权限', - value: permissions.map((p) => '$p').join(', '), - ), - ); - } - } - - final reason = params['reason'] as String? ?? params['message'] as String?; - if (reason != null && reason.isNotEmpty) { - widgets.add(_DetailRow(label: '原因', value: reason)); - } - - if (widgets.isEmpty && params.isNotEmpty) { - final prettyJson = const JsonEncoder.withIndent(' ').convert(params); - widgets.add(_DetailRow(label: '详情', value: prettyJson, isCode: true)); - } - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: widgets, - ); - } - - @override - Widget build(BuildContext context) { - ref.listen(_approvalCountdownProvider(_countdownConfig), ( - previous, - next, - ) { - if (next != 0 || previous == 0 || !mounted) return; - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) return; - Navigator.of(context).pop(null); - }); - }); - - final colors = context.minosColors; - final theme = Theme.of(context); - - return Container( - decoration: BoxDecoration( - color: colors.surface, - borderRadius: MinosRadii.sheetTop, - ), - padding: EdgeInsets.only( - left: MinosSpacing.xl, - right: MinosSpacing.xl, - top: MinosSpacing.xl, - bottom: MinosSpacing.xl + MediaQuery.of(context).viewPadding.bottom, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Center( - child: Container( - width: 36, - height: 4, - decoration: BoxDecoration( - color: colors.border, - borderRadius: MinosRadii.pillAll, - ), - ), - ), - const SizedBox(height: MinosSpacing.lg), - Row( - children: [ - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: colors.warningSoft, - borderRadius: MinosRadii.smAll, - ), - alignment: Alignment.center, - child: Icon(_requestTypeIcon, size: 20, color: colors.warning), - ), - const SizedBox(width: MinosSpacing.md), - Expanded( - child: Text( - _requestTypeLabel, - style: theme.textTheme.titleLarge, - ), - ), - _ApprovalCountdownBadge(countdownConfig: _countdownConfig), - ], - ), - const SizedBox(height: MinosSpacing.lg), - _buildDetailSection(widget.request.params), - const SizedBox(height: MinosSpacing.xl), - Row( - children: [ - Expanded( - child: OutlinedButton( - onPressed: () => - Navigator.of(context).pop(ApprovalDecision.decline), - child: const Text('拒绝'), - ), - ), - const SizedBox(width: MinosSpacing.md), - Expanded( - child: FilledButton( - onPressed: () => - Navigator.of(context).pop(ApprovalDecision.accept), - child: const Text('允许'), - ), - ), - ], - ), - ], - ), - ); - } -} - -class _ApprovalCountdownBadge extends ConsumerWidget { - const _ApprovalCountdownBadge({required this.countdownConfig}); - - final _ApprovalCountdownConfig countdownConfig; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final colors = context.minosColors; - final remainingSeconds = ref.watch( - _approvalCountdownProvider(countdownConfig), - ); - final timerColor = remainingSeconds <= 30 - ? colors.danger - : colors.textSecondary; - - return Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: timerColor.withValues(alpha: 0.1), - borderRadius: MinosRadii.pillAll, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(CupertinoIcons.timer, size: 14, color: timerColor), - const SizedBox(width: 4), - Text( - '${remainingSeconds}s', - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: timerColor, - ), - ), - ], - ), - ); - } -} - -class _DetailRow extends StatelessWidget { - const _DetailRow({ - required this.label, - required this.value, - this.isCode = false, - }); - - final String label; - final String value; - final bool isCode; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final theme = Theme.of(context); - return Padding( - padding: const EdgeInsets.only(bottom: MinosSpacing.md), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - width: 50, - child: Text( - label, - style: theme.textTheme.labelMedium?.copyWith( - color: colors.textTertiary, - ), - ), - ), - const SizedBox(width: MinosSpacing.md), - Expanded( - child: isCode - ? Container( - padding: const EdgeInsets.all(MinosSpacing.sm), - decoration: BoxDecoration( - color: colors.surfaceMuted, - borderRadius: MinosRadii.xsAll, - ), - child: Text( - value, - style: theme.textTheme.bodySmall?.copyWith( - fontFamily: 'monospace', - color: colors.textPrimary, - ), - maxLines: 8, - overflow: TextOverflow.ellipsis, - ), - ) - : Text( - value, - style: theme.textTheme.bodyMedium?.copyWith( - color: colors.textPrimary, - ), - ), - ), - ], - ), - ); - } -} diff --git a/apps/mobile/lib/ui/core/widgets/widgets.dart b/apps/mobile/lib/ui/core/widgets/widgets.dart index 07ff5f7c..a02f8c77 100644 --- a/apps/mobile/lib/ui/core/widgets/widgets.dart +++ b/apps/mobile/lib/ui/core/widgets/widgets.dart @@ -1,5 +1,3 @@ -export 'agent_question_sheet.dart'; -export 'approval_sheet.dart'; export 'error_feedback.dart'; export 'minos_button.dart'; export 'minos_empty_state.dart'; diff --git a/apps/mobile/lib/ui/features/account/views/account_page.dart b/apps/mobile/lib/ui/features/account/views/account_page.dart index b7001089..8fe0e7d4 100644 --- a/apps/mobile/lib/ui/features/account/views/account_page.dart +++ b/apps/mobile/lib/ui/features/account/views/account_page.dart @@ -90,22 +90,11 @@ class AccountPage extends ConsumerWidget { const SizedBox(height: MinosSpacing.lg), MinosSurface( bordered: true, - child: Column( - children: [ - _SettingsRow( - icon: CupertinoIcons.chat_bubble_2, - title: 'Agent 会话', - subtitle: '按 Agent session 查看历史(次级)', - onTap: () => context.push(AppRoutes.sessions), - ), - Divider(height: 1, color: colors.borderSubtle), - _SettingsRow( - icon: CupertinoIcons.ant, - title: '开发者工具', - subtitle: '日志与请求追踪', - onTap: () => context.push(AppRoutes.logViewer), - ), - ], + child: _SettingsRow( + icon: CupertinoIcons.ant, + title: '开发者工具', + subtitle: '日志与请求追踪', + onTap: () => context.push(AppRoutes.logViewer), ), ), const SizedBox(height: MinosSpacing.lg), diff --git a/apps/mobile/lib/ui/features/agents/agents.dart b/apps/mobile/lib/ui/features/agents/agents.dart deleted file mode 100644 index 4f7f4791..00000000 --- a/apps/mobile/lib/ui/features/agents/agents.dart +++ /dev/null @@ -1,21 +0,0 @@ -/// Feature: Agents Hub -/// -/// Agent profile management — create, edit, delete agent profiles, -/// manage host bindings, and view runtime descriptors. The "Members" -/// tab in the app shell. -/// -/// View Models: -/// - [AgentProfilesController] (application/agent_profiles_provider.dart) -/// - [GroupAgentBindingsController] (application/group_agent_provider.dart) -/// -/// Views: -/// - [AgentsHubTab] -/// - [AgentProfilePage] -/// - [AgentEditorSheet] -library; - -export 'package:minos/application/agent_profiles_provider.dart'; -export 'package:minos/application/group_agent_provider.dart'; -export 'package:minos/application/preferred_agent_provider.dart'; -export 'package:minos/ui/features/agents/views/agent_start_page.dart'; -export 'package:minos/ui/features/agents/views/agents_hub_page.dart'; diff --git a/apps/mobile/lib/ui/features/agents/views/agent_start_page.dart b/apps/mobile/lib/ui/features/agents/views/agent_start_page.dart deleted file mode 100644 index bfb4d681..00000000 --- a/apps/mobile/lib/ui/features/agents/views/agent_start_page.dart +++ /dev/null @@ -1,371 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart' hide ConnectionState; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; -import 'package:minos/application/agent_conversation_actions.dart'; -import 'package:minos/application/agent_profiles_provider.dart'; -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/ui_state_providers.dart'; -import 'package:minos/domain/agent_profile.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:minos/ui/core/widgets/error_feedback.dart'; -import 'package:minos/ui/core/widgets/minos_button.dart'; -import 'package:minos/ui/core/widgets/minos_progress.dart'; -import 'package:minos/ui/features/agents/views/agents_hub_page.dart' - show AgentEditorSheet; -import 'package:minos/ui/features/shell/router.dart'; -import 'package:minos/ui/theme/theme.dart'; - -class AgentStartPage extends ConsumerWidget { - const AgentStartPage({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final profilesAsync = ref.watch(agentProfilesControllerProvider); - final hosts = - ref.watch(pairedMacsProvider).asData?.value ?? const []; - final descriptors = - ref.watch(runtimeAgentDescriptorsProvider).asData?.value ?? - const []; - final pageState = ref.watch(agentStartPageStateControllerProvider); - final colors = context.minosColors; - - return Scaffold( - backgroundColor: colors.canvas, - appBar: AppBar( - title: const Text('开始 Agent 对话'), - surfaceTintColor: Colors.transparent, - ), - body: profilesAsync.when( - loading: () => const Center(child: MinosProgress()), - error: (error, _) => _AgentStartError( - error: error, - onRetry: () => ref.invalidate(agentProfilesControllerProvider), - ), - data: (workspaceState) { - final orderedProfiles = _orderedProfiles( - workspaceState.profiles, - workspaceState.preferredProfileId, - ); - final selectedProfile = _resolveSelectedProfile( - orderedProfiles, - pageState.selectedProfileId, - workspaceState.preferredProfileId, - ); - - return SafeArea( - bottom: false, - child: ListView( - padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), - children: [ - Text( - '先选择一个现有 Agent,然后创建一条新的对话。', - style: Theme.of( - context, - ).textTheme.bodyMedium?.copyWith(color: colors.textSecondary), - ), - const SizedBox(height: 16), - _PickerSection( - title: 'Agent', - trailing: MinosButton.ghost( - onPressed: () => _openEditor( - context, - hosts: hosts, - descriptors: descriptors, - ), - child: const Text('创建 Agent'), - ), - child: orderedProfiles.isEmpty - ? _EmptySelectionState( - title: '还没有 Agent', - description: '先创建一个 Agent profile,之后这里就可以直接开始新对话。', - actionLabel: '创建 Agent', - onAction: () => _openEditor( - context, - hosts: hosts, - descriptors: descriptors, - ), - ) - : RadioGroup( - groupValue: selectedProfile?.id, - onChanged: (value) { - if (value == null) return; - ref - .read( - agentStartPageStateControllerProvider - .notifier, - ) - .selectProfile(value); - }, - child: Column( - children: [ - for (final profile in orderedProfiles) - RadioListTile( - value: profile.id, - title: Text(profile.name), - subtitle: Text( - _profileSubtitle(profile, hosts), - maxLines: 2, - overflow: .ellipsis, - ), - contentPadding: const .symmetric( - horizontal: 12, - ), - ), - ], - ), - ), - ), - const SizedBox(height: 20), - MinosButton( - onPressed: selectedProfile == null || pageState.isSubmitting - ? null - : () => - _createConversation(context, ref, selectedProfile), - child: Text(pageState.isSubmitting ? '创建中…' : '开始对话'), - ), - ], - ), - ); - }, - ), - ); - } - - AgentProfile? _resolveSelectedProfile( - List orderedProfiles, - String? selectedProfileId, - String? preferredProfileId, - ) { - if (orderedProfiles.isEmpty) { - return null; - } - for (final profile in orderedProfiles) { - if (profile.id == selectedProfileId) { - return profile; - } - } - if (preferredProfileId != null) { - for (final profile in orderedProfiles) { - if (profile.id == preferredProfileId) { - return profile; - } - } - } - return orderedProfiles.first; - } - - Future _openEditor( - BuildContext context, { - required List hosts, - required List descriptors, - }) { - return showModalBottomSheet( - context: context, - isScrollControlled: true, - useSafeArea: true, - backgroundColor: Theme.of(context).colorScheme.surface, - builder: (_) => AgentEditorSheet(hosts: hosts, descriptors: descriptors), - ); - } - - Future _createConversation( - BuildContext context, - WidgetRef ref, - AgentProfile profile, - ) async { - ref - .read(agentStartPageStateControllerProvider.notifier) - .setSubmitting(true); - logFlutterInfo( - 'agent_start', - 'create conversation requested profileId=${profile.id} hostDeviceId=${profile.hostDeviceId ?? ''}', - ); - try { - final conversation = await createAgentConversation(ref, profile: profile); - logFlutterInfo( - 'agent_start', - 'create conversation succeeded profileId=${profile.id} conversationId=${conversation.conversationId}', - ); - if (!context.mounted) return; - unawaited( - context.push( - '/social/chat/${conversation.conversationId}', - extra: SocialChatRouteExtra( - title: profile.name, - kind: ConversationKind.group, - ), - ), - ); - } catch (error) { - if (!context.mounted) return; - showLoggedErrorToast( - context, - target: 'agent_start', - title: '创建对话失败', - error: error, - ); - } finally { - ref - .read(agentStartPageStateControllerProvider.notifier) - .setSubmitting(false); - } - } -} - -class _AgentStartError extends StatelessWidget { - const _AgentStartError({required this.error, required this.onRetry}); - - final Object error; - final VoidCallback onRetry; - - @override - Widget build(BuildContext context) { - return Center( - child: Padding( - padding: const .all(24), - child: Column( - mainAxisSize: .min, - children: [ - Text('加载 Agent 失败: $error', textAlign: .center), - const SizedBox(height: 12), - MinosButton(onPressed: onRetry, child: const Text('重试')), - ], - ), - ), - ); - } -} - -class _PickerSection extends StatelessWidget { - const _PickerSection({ - required this.title, - required this.child, - this.trailing, - }); - - final String title; - final Widget child; - final Widget? trailing; - - @override - Widget build(BuildContext context) { - return Column( - crossAxisAlignment: .start, - children: [ - Row( - children: [ - Expanded( - child: Text( - title, - style: Theme.of( - context, - ).textTheme.titleSmall?.copyWith(fontWeight: .w700), - ), - ), - ?trailing, - ], - ), - const SizedBox(height: 8), - DecoratedBox( - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surfaceContainerLow, - borderRadius: .circular(16), - ), - child: child, - ), - ], - ); - } -} - -class _EmptySelectionState extends StatelessWidget { - const _EmptySelectionState({ - required this.title, - required this.description, - required this.actionLabel, - required this.onAction, - }); - - final String title; - final String description; - final String actionLabel; - final VoidCallback onAction; - - @override - Widget build(BuildContext context) { - return Padding( - padding: const .all(16), - child: Column( - crossAxisAlignment: .start, - children: [ - Text( - title, - style: Theme.of( - context, - ).textTheme.titleMedium?.copyWith(fontWeight: .w700), - ), - const SizedBox(height: 6), - Text( - description, - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 12), - MinosButton(onPressed: onAction, child: Text(actionLabel)), - ], - ), - ); - } -} - -List _orderedProfiles( - List profiles, - String? preferredProfileId, -) { - final ordered = [...profiles] - ..sort((left, right) { - if (left.id == preferredProfileId) return -1; - if (right.id == preferredProfileId) return 1; - return right.updatedAtMs.compareTo(left.updatedAtMs); - }); - return ordered; -} - -String _profileSubtitle(AgentProfile profile, List hosts) { - final hostLabel = - _hostLabelForId(hosts, profile.hostDeviceId) ?? - profile.hostDisplayName ?? - '跟随当前 runtime'; - final detail = profile.description.trim().isEmpty - ? '${_runtimeLabel(profile.runtimeAgent)} · ${profile.model}' - : profile.description.trim(); - return '$hostLabel · $detail'; -} - -String? _hostLabelForId(List hosts, String? hostDeviceId) { - if (hostDeviceId == null) { - return null; - } - for (final host in hosts) { - if (host.hostDeviceId != hostDeviceId) { - continue; - } - final displayName = host.hostDisplayName.trim(); - return displayName.isEmpty ? host.hostDeviceId : displayName; - } - return null; -} - -String _runtimeLabel(AgentName agent) { - return switch (agent) { - AgentName.codex => 'Codex', - AgentName.claude => 'Claude', - AgentName.gemini => 'Gemini', - AgentName.opencode => 'OpenCode', - AgentName.grok => 'Grok', - }; -} diff --git a/apps/mobile/lib/ui/features/agents/views/agents_hub_page.dart b/apps/mobile/lib/ui/features/agents/views/agents_hub_page.dart deleted file mode 100644 index 67882da3..00000000 --- a/apps/mobile/lib/ui/features/agents/views/agents_hub_page.dart +++ /dev/null @@ -1,2762 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/cupertino.dart' hide ConnectionState; -import 'package:flutter/material.dart' hide ConnectionState; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; -import 'package:minos/application/agent_conversation_actions.dart'; -import 'package:minos/application/agent_editor_state.dart'; -import 'package:minos/application/agent_profiles_provider.dart'; -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/runtime_actions.dart'; -import 'package:minos/application/social_actions.dart'; -import 'package:minos/application/social_providers.dart'; -import 'package:minos/domain/agent_profile.dart'; -import 'package:minos/src/rust/api/minos.dart' - as minos_api - show ConnectionState; -import 'package:minos/src/rust/api/minos.dart' hide ConnectionState; -import 'package:minos/ui/core/widgets/error_feedback.dart'; -import 'package:minos/ui/core/widgets/minos_button.dart'; -import 'package:minos/ui/core/widgets/minos_text_field.dart'; -import 'package:minos/ui/core/widgets/shimmer_box.dart'; -import 'package:minos/ui/features/shell/router.dart'; -import 'package:minos/ui/theme/theme.dart'; - -class AgentsHubTab extends ConsumerWidget { - const AgentsHubTab({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final profilesAsync = ref.watch(agentProfilesControllerProvider); - final preferredProfile = ref.watch(preferredAgentProfileProvider); - final runtimeDescriptors = ref.watch(runtimeAgentDescriptorsProvider); - final pairedHosts = ref.watch(pairedMacsProvider); - final hosts = pairedHosts.asData?.value ?? const []; - final activeHostId = ref.watch(activeMacProvider).asData?.value; - final connection = ref.watch(connectionStateProvider).asData?.value; - - return SafeArea( - bottom: false, - child: RefreshIndicator( - onRefresh: () async { - try { - await ref.read(pairedMacsProvider.notifier).refresh(); - await ref.read(friendsProvider.notifier).refresh(); - ref.invalidate(runtimeAgentDescriptorsProvider); - await ref.read(runtimeAgentDescriptorsProvider.future); - } catch (error) { - if (context.mounted) { - _showRefreshError(context, '成员刷新失败', error); - } - } - }, - child: ListView( - padding: const EdgeInsets.only(top: 12, bottom: 28), - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 4), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '伙伴', - style: Theme.of(context).textTheme.headlineLarge?.copyWith( - fontWeight: FontWeight.w800, - letterSpacing: 0, - ), - ), - const SizedBox(height: 4), - Text( - preferredProfile == null - ? '管理设备、Agent 和好友。' - : '默认 Agent:${preferredProfile.name}', - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - const SizedBox(height: 16), - _HostRuntimeCard( - pairedHosts: pairedHosts, - activeHostId: activeHostId, - connection: connection, - ), - const SizedBox(height: 16), - profilesAsync.when( - loading: () => _SectionCard( - title: 'AGENTS 0', - trailing: _SectionActionButton( - tooltip: '新建 Agent', - onPressed: () => _openEditor( - context, - ref, - hosts: hosts, - descriptors: - runtimeDescriptors.asData?.value ?? - const [], - ), - ), - child: const _AgentListSkeleton(), - ), - error: (error, _) => _SectionCard( - title: 'AGENTS 0', - trailing: _SectionActionButton( - tooltip: '新建 Agent', - onPressed: () => _openEditor( - context, - ref, - hosts: hosts, - descriptors: - runtimeDescriptors.asData?.value ?? - const [], - ), - ), - child: Padding( - padding: const EdgeInsets.all(18), - child: Text('加载 Agent 失败: $error'), - ), - ), - data: (state) => _ProfilesSection( - state: state, - preferredProfileId: preferredProfile?.id, - hosts: hosts, - onAdd: () => _openEditor( - context, - ref, - hosts: hosts, - descriptors: - runtimeDescriptors.asData?.value ?? - const [], - ), - ), - ), - const SizedBox(height: 16), - const _HumansSection(), - ], - ), - ), - ); - } - - Future _openEditor( - BuildContext context, - WidgetRef ref, { - required List hosts, - required List descriptors, - AgentProfile? profile, - }) { - return showModalBottomSheet( - context: context, - isScrollControlled: true, - useSafeArea: true, - backgroundColor: Theme.of(context).colorScheme.surface, - builder: (_) => AgentEditorSheet( - profile: profile, - hosts: hosts, - descriptors: descriptors, - ), - ); - } -} - -class _SectionActionButton extends StatelessWidget { - const _SectionActionButton({required this.tooltip, required this.onPressed}); - - final String tooltip; - final VoidCallback onPressed; - - @override - Widget build(BuildContext context) { - return IconButton( - tooltip: tooltip, - icon: const Icon(CupertinoIcons.plus, size: 18), - onPressed: onPressed, - constraints: const BoxConstraints.tightFor(width: 38, height: 38), - padding: EdgeInsets.zero, - visualDensity: VisualDensity.compact, - ); - } -} - -class _AgentListSkeleton extends StatelessWidget { - const _AgentListSkeleton(); - - @override - Widget build(BuildContext context) { - return Column( - children: List.generate( - 2, - (index) => const Padding( - padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ShimmerBox(width: 42, height: 42, circular: true), - SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ShimmerBox(width: 80, height: 12), - SizedBox(height: 8), - ShimmerBox(width: 120, height: 16), - SizedBox(height: 8), - ShimmerBox(width: double.infinity, height: 14), - SizedBox(height: 4), - ShimmerBox(width: 200, height: 14), - ], - ), - ), - ], - ), - ), - ), - ); - } -} - -class _DeviceListSkeleton extends StatelessWidget { - const _DeviceListSkeleton(); - - @override - Widget build(BuildContext context) { - return Column( - children: List.generate( - 1, - (index) => const Padding( - padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - children: [ - ShimmerBox(width: 42, height: 42, circular: true), - SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ShimmerBox(width: 100, height: 16), - SizedBox(height: 8), - ShimmerBox(width: 140, height: 14), - ], - ), - ), - ], - ), - ), - ), - ); - } -} - -class _HumanListSkeleton extends StatelessWidget { - const _HumanListSkeleton(); - - @override - Widget build(BuildContext context) { - return const Padding( - padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - children: [ - ShimmerBox(width: 42, height: 42, circular: true), - SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ShimmerBox(width: 120, height: 16), - SizedBox(height: 8), - ShimmerBox(width: 180, height: 14), - ], - ), - ), - ], - ), - ); - } -} - -class _CompactErrorPanel extends StatelessWidget { - const _CompactErrorPanel({ - required this.title, - required this.description, - required this.actionLabel, - required this.onAction, - }); - - final String title; - final String description; - final String actionLabel; - final VoidCallback onAction; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final textTheme = Theme.of(context).textTheme; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Icon( - CupertinoIcons.exclamationmark_triangle, - size: 18, - color: colors.textSecondary, - ), - const SizedBox(width: 8), - Expanded( - child: Text( - title, - style: textTheme.bodySmall?.copyWith(color: colors.textPrimary), - ), - ), - ], - ), - const SizedBox(height: 6), - Text( - description, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: textTheme.bodyMedium?.copyWith(color: colors.textSecondary), - ), - const SizedBox(height: 10), - MinosButton.outline(onPressed: onAction, child: Text(actionLabel)), - ], - ); - } -} - -class _MemberStatusDot extends StatelessWidget { - const _MemberStatusDot({required this.color}); - - final Color color; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Container( - width: 10, - height: 10, - decoration: BoxDecoration( - color: color, - shape: BoxShape.circle, - border: Border.all(color: theme.colorScheme.surface, width: 1.5), - boxShadow: [ - BoxShadow(color: color.withValues(alpha: 0.4), blurRadius: 4), - ], - ), - ); - } -} - -class _DeviceAvatar extends StatelessWidget { - const _DeviceAvatar(); - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final isDark = theme.brightness == Brightness.dark; - return Container( - width: 42, - height: 42, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(14), - color: isDark ? const Color(0xFF1E3A8A) : const Color(0xFFDBEAFE), - ), - alignment: Alignment.center, - child: Icon( - CupertinoIcons.desktopcomputer, - color: isDark ? const Color(0xFF60A5FA) : const Color(0xFF2563EB), - size: 20, - ), - ); - } -} - -class _HumanAvatar extends StatelessWidget { - const _HumanAvatar({required this.label}); - - final String label; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final isDark = theme.brightness == Brightness.dark; - return Container( - width: 42, - height: 42, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(14), - color: isDark ? const Color(0xFF4C1D95) : const Color(0xFFEDE9FE), - ), - alignment: Alignment.center, - child: Text( - label, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w800, - color: isDark ? const Color(0xFFA78BFA) : const Color(0xFF7C3AED), - ), - ), - ); - } -} - -String _resolvedProfileHostLabel( - AgentProfile profile, - List hosts, -) { - final resolved = _hostLabelForId(hosts, profile.hostDeviceId); - if (resolved != null && resolved.trim().isNotEmpty) return resolved; - final fallback = profile.hostDisplayName?.trim(); - if (fallback != null && fallback.isNotEmpty) return fallback; - return '未绑定 runtime'; -} - -Color _connectionColor( - minos_api.ConnectionState? state, - bool isActive, - bool isDark, -) { - if (!isActive) { - return isDark ? const Color(0xFF3F3F46) : const Color(0xFFD4D4D8); - } - return switch (state) { - ConnectionState_Connected() => - isDark ? const Color(0xFF22C55E) : const Color(0xFF16A34A), - ConnectionState_Reconnecting() || ConnectionState_Pairing() => - isDark ? const Color(0xFFEAB308) : const Color(0xFFCA8A04), - _ => isDark ? const Color(0xFF52525B) : const Color(0xFFA1A1AA), - }; -} - -String _connectionLabel(minos_api.ConnectionState? state) { - return switch (state) { - ConnectionState_Connected() => '在线', - ConnectionState_Reconnecting() => '重连中', - ConnectionState_Pairing() => '配对中', - _ => '离线', - }; -} - -void _showRefreshError(BuildContext context, String title, Object error) { - showLoggedErrorToast( - context, - target: 'agents_hub', - title: title, - error: error, - ); -} - -class AgentProfilePage extends ConsumerWidget { - const AgentProfilePage({super.key, required this.profileId}); - - final String profileId; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final workspace = ref.watch(agentProfilesControllerProvider).asData?.value; - final profile = workspace?.profileById(profileId); - final preferredId = workspace?.preferredProfileId; - final hosts = - ref.watch(pairedMacsProvider).asData?.value ?? const []; - final activeHostId = ref.watch(activeMacProvider).asData?.value; - final effectiveHostId = profile?.hostDeviceId ?? activeHostId; - final effectiveHostLabel = - profile?.hostDisplayName ?? - _hostLabelForId(hosts, effectiveHostId) ?? - '未选择 runtime'; - final descriptors = - ref.watch(runtimeAgentDescriptorsProvider).asData?.value ?? - const []; - if (profile == null) { - return Scaffold( - appBar: AppBar(title: const Text('Agent')), - body: const Center(child: Text('Agent 不存在或已被删除。')), - ); - } - - return Scaffold( - appBar: AppBar( - title: Text(profile.name), - actions: [ - IconButton( - tooltip: '编辑', - onPressed: () => showModalBottomSheet( - context: context, - isScrollControlled: true, - useSafeArea: true, - backgroundColor: Theme.of(context).colorScheme.surface, - builder: (_) => AgentEditorSheet( - profile: profile, - hosts: hosts, - descriptors: descriptors, - ), - ), - icon: const Icon(CupertinoIcons.pencil), - ), - ], - ), - body: ListView( - padding: const EdgeInsets.only(top: 12, bottom: 28), - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: _ProfileHero( - profile: profile, - isPreferred: preferredId == profile.id, - ), - ), - const SizedBox(height: 16), - _SectionCard( - title: 'Profile', - child: Column( - children: [ - _DetailRow(label: 'Display Name', value: profile.name), - const Divider(height: 1), - _DetailRow( - label: 'Description', - value: profile.description.isEmpty - ? 'No description' - : profile.description, - ), - const Divider(height: 1), - _DetailRow( - label: 'Computer', - value: profile.hostDisplayName ?? '跟随当前 runtime', - ), - const Divider(height: 1), - _DetailRow( - label: 'Workspace', - value: profile.workspacePath?.trim().isEmpty ?? true - ? '默认工作区' - : profile.workspacePath!, - ), - ], - ), - ), - const SizedBox(height: 16), - _SectionCard( - title: 'Runtime Configuration', - child: Padding( - padding: const EdgeInsets.all(16), - child: Wrap( - spacing: 10, - runSpacing: 10, - children: [ - _BadgeChip(label: _runtimeLabel(profile.runtimeAgent)), - _BadgeChip(label: profile.model), - _BadgeChip(label: _reasoningLabel(profile.reasoningEffort)), - if (profile.workspacePath?.trim().isNotEmpty ?? false) - _BadgeChip(label: profile.workspacePath!.trim()), - ], - ), - ), - ), - const SizedBox(height: 16), - _SectionCard( - title: 'Environment Variables', - child: profile.environmentVariables.isEmpty - ? const Padding( - padding: EdgeInsets.all(16), - child: Text('No environment variables configured.'), - ) - : Column( - children: [ - for ( - var i = 0; - i < profile.environmentVariables.length; - i++ - ) ...[ - if (i > 0) const Divider(height: 1), - _DetailRow( - label: profile.environmentVariables[i].key, - value: profile.environmentVariables[i].value, - ), - ], - ], - ), - ), - const SizedBox(height: 16), - _HostSkillsSection( - hostDeviceId: effectiveHostId, - hostLabel: effectiveHostLabel, - skillsAsync: effectiveHostId == null - ? null - : ref.watch(hostSkillsProvider(effectiveHostId)), - ), - const SizedBox(height: 18), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: FilledButton.icon( - onPressed: () async { - try { - final conversation = await createAgentConversation( - ref, - profile: profile, - ); - if (!context.mounted) return; - unawaited( - context.push( - '/social/chat/${conversation.conversationId}', - extra: SocialChatRouteExtra( - title: profile.name, - kind: ConversationKind.group, - ), - ), - ); - } catch (error) { - if (!context.mounted) return; - showLoggedErrorToast( - context, - target: 'agents_hub', - title: '创建对话失败', - error: error, - ); - } - }, - icon: const Icon(CupertinoIcons.bubble_left_bubble_right_fill), - label: const Text('从这个 Agent 发起对话'), - ), - ), - if (preferredId != profile.id) ...[ - const SizedBox(height: 10), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: OutlinedButton.icon( - onPressed: () => ref - .read(agentProfilesControllerProvider.notifier) - .setPreferredProfile(profile.id), - icon: const Icon(CupertinoIcons.star), - label: const Text('设为默认 Agent'), - ), - ), - ], - ], - ), - ); - } -} - -class AgentEditorSheet extends ConsumerStatefulWidget { - const AgentEditorSheet({ - super.key, - required this.hosts, - required this.descriptors, - this.profile, - }); - - final AgentProfile? profile; - final List hosts; - final List descriptors; - - @override - ConsumerState createState() => _AgentEditorSheetState(); -} - -class _AgentEditorSheetState extends ConsumerState { - late final AgentProfileDraft _initialDraft; - late final TextEditingController _nameController; - late final TextEditingController _descriptionController; - late final TextEditingController _workspacePathController; - - @override - void initState() { - super.initState(); - _initialDraft = widget.profile == null - ? _seedDraft(widget.hosts) - : AgentProfileDraft.fromProfile(widget.profile!); - _nameController = TextEditingController(text: _initialDraft.name); - _nameController.addListener(_handleNameChanged); - _descriptionController = TextEditingController( - text: _initialDraft.description, - ); - _descriptionController.addListener(_handleDescriptionChanged); - _workspacePathController = TextEditingController( - text: _initialDraft.workspacePath ?? '', - ); - _workspacePathController.addListener(_handleWorkspacePathChanged); - } - - void _handleNameChanged() { - ref - .read(agentEditorDraftControllerProvider(_initialDraft).notifier) - .updateName(_nameController.text); - } - - void _handleDescriptionChanged() { - ref - .read(agentEditorDraftControllerProvider(_initialDraft).notifier) - .updateDescription(_descriptionController.text); - } - - void _handleWorkspacePathChanged() { - final path = _workspacePathController.text.trim(); - ref - .read(agentEditorDraftControllerProvider(_initialDraft).notifier) - .setWorkspacePath(path.isEmpty ? null : path); - } - - @override - void dispose() { - _nameController.removeListener(_handleNameChanged); - _descriptionController.removeListener(_handleDescriptionChanged); - _workspacePathController.removeListener(_handleWorkspacePathChanged); - _nameController.dispose(); - _descriptionController.dispose(); - _workspacePathController.dispose(); - super.dispose(); - } - - AgentProfileDraft _seedDraft(List hosts) { - final activeId = ref.read(activeMacProvider).asData?.value; - HostSummaryDto? host; - for (final candidate in hosts) { - if (candidate.hostDeviceId == activeId) { - host = candidate; - break; - } - } - host ??= hosts.isEmpty ? null : hosts.first; - return AgentProfileDraft( - name: 'new-agent', - description: '', - runtimeAgent: _preferredRuntime(widget.descriptors), - model: _defaultModel(_preferredRuntime(widget.descriptors)), - reasoningEffort: AgentReasoningEffort.medium, - environmentVariables: const [], - hostDeviceId: host?.hostDeviceId, - hostDisplayName: host?.hostDisplayName, - workspacePath: null, - ); - } - - String _hostSelectionLabel(AgentProfileDraft draft) { - final explicit = draft.hostDisplayName?.trim(); - if (explicit != null && explicit.isNotEmpty) return explicit; - final fromList = _hostLabelForId(widget.hosts, draft.hostDeviceId); - if (fromList != null && fromList.trim().isNotEmpty) return fromList; - return '跟随当前 runtime'; - } - - Future _showPickerSheet({ - required String title, - required List<_PickerOption> options, - required T? currentValue, - }) { - return showModalBottomSheet( - context: context, - useSafeArea: true, - showDragHandle: true, - backgroundColor: Theme.of(context).colorScheme.surface, - builder: (sheetContext) { - return SafeArea( - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - title, - style: Theme.of(sheetContext).textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w800, - ), - ), - const SizedBox(height: 12), - Flexible( - child: ListView.separated( - shrinkWrap: true, - itemCount: options.length, - separatorBuilder: (_, _) => const Divider(height: 1), - itemBuilder: (_, index) { - final option = options[index]; - final selected = option.value == currentValue; - return ListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 4, - vertical: 2, - ), - title: Text(option.title), - subtitle: option.subtitle == null - ? null - : Text(option.subtitle!), - trailing: selected - ? const Icon(CupertinoIcons.check_mark) - : null, - onTap: () => - Navigator.of(sheetContext).pop(option.value), - ); - }, - ), - ), - ], - ), - ), - ); - }, - ); - } - - Future _pickHost() async { - final draft = ref - .read(agentEditorDraftControllerProvider(_initialDraft)) - .draft; - final hostOptions = <_PickerOption>[ - const _PickerOption( - value: null, - title: '跟随当前 runtime', - subtitle: '始终使用当前激活设备', - ), - for (final host in widget.hosts) - _PickerOption( - value: host.hostDeviceId, - title: - _hostLabelForId(widget.hosts, host.hostDeviceId) ?? - host.hostDeviceId, - subtitle: '${host.hostDeviceId} · ${host.online ? '设备在线' : '设备离线'}', - ), - ]; - final selected = await _showPickerSheet( - title: '选择运行设备', - options: hostOptions, - currentValue: draft.hostDeviceId, - ); - if (!mounted) return; - HostSummaryDto? selectedHost; - for (final host in widget.hosts) { - if (host.hostDeviceId == selected) { - selectedHost = host; - break; - } - } - ref - .read(agentEditorDraftControllerProvider(_initialDraft).notifier) - .setHost( - hostDeviceId: selected, - hostDisplayName: selectedHost?.hostDisplayName, - ); - final nextDraft = ref - .read(agentEditorDraftControllerProvider(_initialDraft)) - .draft; - if (_workspacePathController.text != (nextDraft.workspacePath ?? '')) { - _workspacePathController.text = nextDraft.workspacePath ?? ''; - } - } - - void _pickWorkspace(HostWorkspaceSummary workspace) { - _workspacePathController.text = workspace.path; - } - - Future _pickRuntime(List runtimeOptions) async { - final draft = ref - .read(agentEditorDraftControllerProvider(_initialDraft)) - .draft; - final selected = await _showPickerSheet( - title: '选择 Runtime', - options: <_PickerOption>[ - for (final agent in runtimeOptions) - _PickerOption( - value: agent, - title: _runtimeLabel(agent), - subtitle: _defaultModel(agent), - ), - ], - currentValue: draft.runtimeAgent, - ); - if (selected == null || !mounted) return; - ref - .read(agentEditorDraftControllerProvider(_initialDraft).notifier) - .setRuntime(selected, defaultModel: _defaultModel(selected)); - } - - Future _pickModel(List models) async { - final draft = ref - .read(agentEditorDraftControllerProvider(_initialDraft)) - .draft; - final selected = await _showPickerSheet( - title: '选择模型', - options: <_PickerOption>[ - for (final model in models) - _PickerOption(value: model, title: model), - ], - currentValue: draft.model, - ); - if (selected == null || !mounted) return; - ref - .read(agentEditorDraftControllerProvider(_initialDraft).notifier) - .setModel(selected); - } - - Future _saveProfile() async { - final draft = ref - .read(agentEditorDraftControllerProvider(_initialDraft)) - .draft; - final controller = ref.read(agentProfilesControllerProvider.notifier); - logFlutterInfo( - 'agent_editor', - 'save profile requested isEditing=${widget.profile != null} runtime=${draft.runtimeAgent} model=${draft.model} hostDeviceId=${draft.hostDeviceId ?? ''}', - ); - try { - if (widget.profile == null) { - final created = await controller.createProfile(draft); - await controller.setPreferredProfile(created.id); - logFlutterInfo( - 'agent_editor', - 'profile created profileId=${created.id} runtime=${draft.runtimeAgent}', - ); - } else { - await controller.updateProfile(widget.profile!, draft); - logFlutterInfo( - 'agent_editor', - 'profile updated profileId=${widget.profile!.id} runtime=${draft.runtimeAgent}', - ); - } - if (mounted) Navigator.of(context).pop(); - } catch (error, stackTrace) { - logFlutterError( - 'agent_editor', - 'save profile failed isEditing=${widget.profile != null}', - error: error, - stackTrace: stackTrace, - ); - if (!mounted) return; - showLoggedErrorToast( - context, - target: 'agent_editor', - title: widget.profile == null ? '创建 Agent 失败' : '保存 Agent 失败', - error: error, - ); - } - } - - @override - Widget build(BuildContext context) { - final editorState = ref.watch( - agentEditorDraftControllerProvider(_initialDraft), - ); - var draft = editorState.draft; - final isEditing = widget.profile != null; - final hosts = widget.hosts; - final activeHostId = ref.watch(activeMacProvider).asData?.value; - final effectiveHostId = draft.hostDeviceId ?? activeHostId; - final effectiveHostLabel = - _hostLabelForId(hosts, effectiveHostId) ?? _hostSelectionLabel(draft); - final workspacesAsync = effectiveHostId == null - ? null - : ref.watch(hostWorkspacesProvider(effectiveHostId)); - final runtimeOptions = _runtimeOptions(widget.descriptors); - final models = _modelOptions(draft.runtimeAgent); - if (!models.contains(draft.model)) { - draft = draft.copyWith(model: models.first); - } - final canSave = draft.name.trim().isNotEmpty; - final media = MediaQuery.of(context); - final navigator = Navigator.of(context); - - return AnimatedPadding( - duration: const Duration(milliseconds: 160), - curve: Curves.easeOut, - padding: EdgeInsets.only(bottom: media.viewInsets.bottom), - child: ConstrainedBox( - constraints: BoxConstraints(maxHeight: media.size.height * 0.9), - child: Padding( - padding: const EdgeInsets.fromLTRB(20, 10, 20, 20), - child: Column( - children: [ - Container( - width: 42, - height: 5, - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.outlineVariant, - borderRadius: BorderRadius.circular(999), - ), - ), - const SizedBox(height: 16), - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - isEditing ? '编辑 Agent' : '创建 Agent', - style: Theme.of(context).textTheme.headlineSmall - ?.copyWith( - fontWeight: FontWeight.w800, - letterSpacing: -0.4, - ), - ), - const SizedBox(height: 4), - Text( - '用移动端常见的表单交互配置名称、运行设备和模型。', - style: Theme.of(context).textTheme.bodyMedium - ?.copyWith( - color: Theme.of( - context, - ).colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - IconButton( - onPressed: navigator.pop, - icon: const Icon(CupertinoIcons.xmark), - ), - ], - ), - const SizedBox(height: 16), - Expanded( - child: ListView( - children: [ - _EditorSection( - title: '基本信息', - child: Padding( - padding: const EdgeInsets.all(14), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '名称', - style: Theme.of(context).textTheme.labelLarge, - ), - const SizedBox(height: 8), - MinosTextField( - controller: _nameController, - placeholder: '例如:codex', - ), - const SizedBox(height: 14), - Text( - '描述', - style: Theme.of(context).textTheme.labelLarge, - ), - const SizedBox(height: 8), - MinosTextField( - controller: _descriptionController, - minLines: 3, - maxLines: 5, - placeholder: '简短描述这个 Agent 擅长什么。', - ), - ], - ), - ), - ), - const SizedBox(height: 14), - _EditorSection( - title: '运行配置', - child: Column( - children: [ - _EditorPickerTile( - label: '运行设备', - value: _hostSelectionLabel(draft), - onTap: _pickHost, - ), - const Divider(height: 1), - _EditorPickerTile( - label: 'Runtime', - value: _runtimeLabel(draft.runtimeAgent), - onTap: () => _pickRuntime(runtimeOptions), - ), - const Divider(height: 1), - _EditorPickerTile( - label: 'Model', - value: draft.model, - onTap: () => _pickModel(models), - ), - const Divider(height: 1), - _EditorWorkspacePathPicker( - controller: _workspacePathController, - workspacesAsync: workspacesAsync, - selectedPath: draft.workspacePath, - onPick: _pickWorkspace, - onRefresh: effectiveHostId == null - ? null - : () => ref.invalidate( - hostWorkspacesProvider(effectiveHostId), - ), - ), - ], - ), - ), - if (hosts.isEmpty) ...[ - const SizedBox(height: 12), - const _EditorHintCard( - message: - '还没有 Linked Host。请在 Desktop 用同一账号 Link this Mac,然后下拉刷新。', - ), - ], - const SizedBox(height: 14), - _EditorSection( - title: 'Skill 预览', - child: _EditorHostSkillsPreview( - hostDeviceId: effectiveHostId, - hostLabel: effectiveHostLabel, - skillsAsync: effectiveHostId == null - ? null - : ref.watch(hostSkillsProvider(effectiveHostId)), - ), - ), - const SizedBox(height: 14), - _EditorSection( - title: '推理强度', - child: Padding( - padding: const EdgeInsets.all(14), - child: - CupertinoSlidingSegmentedControl< - AgentReasoningEffort - >( - groupValue: draft.reasoningEffort, - children: const { - AgentReasoningEffort.low: Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text('低'), - ), - AgentReasoningEffort.medium: Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text('中'), - ), - AgentReasoningEffort.high: Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text('高'), - ), - }, - onValueChanged: (value) { - if (value == null) return; - ref - .read( - agentEditorDraftControllerProvider( - _initialDraft, - ).notifier, - ) - .setReasoning(value); - }, - ), - ), - ), - const SizedBox(height: 14), - _EditorSection( - title: '高级设置', - child: Column( - children: [ - InkWell( - onTap: () => ref - .read( - agentEditorDraftControllerProvider( - _initialDraft, - ).notifier, - ) - .toggleAdvanced(), - child: Padding( - padding: const EdgeInsets.fromLTRB( - 14, - 14, - 14, - 14, - ), - child: Row( - children: [ - Expanded( - child: Text( - '环境变量', - style: Theme.of(context) - .textTheme - .titleSmall - ?.copyWith( - fontWeight: FontWeight.w700, - ), - ), - ), - Icon( - editorState.showAdvanced - ? CupertinoIcons.chevron_down - : CupertinoIcons.chevron_right, - size: 18, - ), - ], - ), - ), - ), - if (editorState.showAdvanced) ...[ - const Divider(height: 1), - Padding( - padding: const EdgeInsets.fromLTRB(14, 12, 14, 0), - child: Text( - '这些变量只保存在当前手机上的 Agent profile 中。', - style: Theme.of(context).textTheme.bodySmall - ?.copyWith( - color: Theme.of( - context, - ).colorScheme.onSurfaceVariant, - ), - ), - ), - for ( - var i = 0; - i < draft.environmentVariables.length; - i++ - ) - Padding( - padding: const EdgeInsets.fromLTRB( - 14, - 12, - 14, - 0, - ), - child: Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: Theme.of( - context, - ).colorScheme.surfaceContainerLowest, - borderRadius: BorderRadius.circular(16), - border: Border.all( - color: Theme.of( - context, - ).colorScheme.outlineVariant, - ), - ), - child: Row( - children: [ - Expanded( - child: TextFormField( - initialValue: - draft.environmentVariables[i].key, - decoration: const InputDecoration( - hintText: 'KEY', - border: InputBorder.none, - isDense: true, - ), - onChanged: (value) { - ref - .read( - agentEditorDraftControllerProvider( - _initialDraft, - ).notifier, - ) - .updateEnvironmentKey(i, value); - }, - ), - ), - const SizedBox(width: 8), - Expanded( - child: TextFormField( - initialValue: draft - .environmentVariables[i] - .value, - decoration: const InputDecoration( - hintText: 'VALUE', - border: InputBorder.none, - isDense: true, - ), - onChanged: (value) { - ref - .read( - agentEditorDraftControllerProvider( - _initialDraft, - ).notifier, - ) - .updateEnvironmentValue( - i, - value, - ); - }, - ), - ), - IconButton( - onPressed: () => ref - .read( - agentEditorDraftControllerProvider( - _initialDraft, - ).notifier, - ) - .removeEnvironmentVariable(i), - icon: const Icon( - CupertinoIcons.minus_circle_fill, - ), - ), - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(14, 8, 14, 14), - child: Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: () => ref - .read( - agentEditorDraftControllerProvider( - _initialDraft, - ).notifier, - ) - .addEnvironmentVariable(), - icon: const Icon(CupertinoIcons.add), - label: const Text('添加变量'), - ), - ), - ), - ], - ], - ), - ), - ], - ), - ), - const SizedBox(height: 14), - Row( - children: [ - Expanded( - child: MinosButton.outline( - onPressed: navigator.pop, - child: const Text('取消'), - ), - ), - const SizedBox(width: 12), - Expanded( - child: MinosButton( - onPressed: canSave ? _saveProfile : null, - child: Text(isEditing ? '保存' : '创建'), - ), - ), - ], - ), - ], - ), - ), - ), - ); - } -} - -class _PickerOption { - const _PickerOption({ - required this.value, - required this.title, - this.subtitle, - }); - - final T value; - final String title; - final String? subtitle; -} - -class _EditorWorkspacePathPicker extends StatelessWidget { - const _EditorWorkspacePathPicker({ - required this.controller, - required this.workspacesAsync, - required this.selectedPath, - required this.onPick, - required this.onRefresh, - }); - - final TextEditingController controller; - final AsyncValue? workspacesAsync; - final String? selectedPath; - final ValueChanged onPick; - final VoidCallback? onRefresh; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final asyncValue = workspacesAsync; - return Padding( - padding: const EdgeInsets.fromLTRB(14, 12, 14, 14), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded(child: Text('工作路径', style: theme.textTheme.labelLarge)), - if (onRefresh != null) - IconButton( - tooltip: '刷新文件夹', - onPressed: onRefresh, - icon: const Icon(CupertinoIcons.arrow_clockwise, size: 18), - ), - ], - ), - const SizedBox(height: 8), - MinosTextField( - controller: controller, - placeholder: '/Users/you/develop/project 或 ~/develop/project', - ), - const SizedBox(height: 12), - if (asyncValue == null) - Text( - '先选择运行设备。', - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ) - else - asyncValue.when( - loading: () => const LinearProgressIndicator(minHeight: 2), - error: (error, _) => Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: onRefresh, - icon: const Icon(CupertinoIcons.arrow_clockwise, size: 16), - label: const Text('重新加载 Host 文件夹'), - ), - ), - data: (response) { - if (response.workspaces.isEmpty) { - return Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: onRefresh, - icon: const Icon(CupertinoIcons.folder_open, size: 16), - label: const Text('Host 文件夹为空'), - ), - ); - } - return ConstrainedBox( - constraints: const BoxConstraints(maxHeight: 220), - child: ListView.separated( - shrinkWrap: true, - itemCount: response.workspaces.length, - separatorBuilder: (_, _) => const Divider(height: 1), - itemBuilder: (context, index) { - final workspace = response.workspaces[index]; - final selected = workspace.path == selectedPath; - return ListTile( - dense: true, - contentPadding: EdgeInsets.zero, - leading: Icon( - workspace.isGitRepo - ? CupertinoIcons.arrow_branch - : CupertinoIcons.folder, - size: 18, - ), - title: Text( - workspace.displayName, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - subtitle: Text( - workspace.path, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - trailing: selected - ? const Icon(CupertinoIcons.check_mark, size: 18) - : null, - onTap: () => onPick(workspace), - ); - }, - ), - ); - }, - ), - ], - ), - ); - } -} - -class _EditorHostSkillsPreview extends ConsumerWidget { - const _EditorHostSkillsPreview({ - required this.hostDeviceId, - required this.hostLabel, - required this.skillsAsync, - }); - - final String? hostDeviceId; - final String hostLabel; - final AsyncValue>? skillsAsync; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - final resolvedHostDeviceId = hostDeviceId; - final resolvedSkillsAsync = skillsAsync; - if (resolvedHostDeviceId == null || resolvedSkillsAsync == null) { - return Padding( - padding: const .all(14), - child: Text( - '选择运行设备后可预览该设备上的 Skills。', - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ); - } - - return Column( - crossAxisAlignment: .start, - children: [ - Padding( - padding: const .fromLTRB(14, 10, 8, 0), - child: Row( - children: [ - Expanded( - child: Text( - hostLabel, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.labelLarge?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - fontWeight: .w700, - ), - ), - ), - IconButton( - tooltip: '重新扫描', - onPressed: () => - ref.invalidate(hostSkillsProvider(resolvedHostDeviceId)), - icon: const Icon(CupertinoIcons.refresh, size: 18), - ), - ], - ), - ), - resolvedSkillsAsync.when( - loading: () => const Padding( - padding: .all(18), - child: Center(child: CupertinoActivityIndicator()), - ), - error: (error, _) => Padding( - padding: const .fromLTRB(14, 8, 14, 14), - child: Column( - crossAxisAlignment: .start, - children: [ - Text('读取 Skills 失败: $error'), - const SizedBox(height: 10), - OutlinedButton.icon( - onPressed: () => - ref.invalidate(hostSkillsProvider(resolvedHostDeviceId)), - icon: const Icon(CupertinoIcons.refresh), - label: const Text('重试'), - ), - ], - ), - ), - data: (entries) { - final hasSkills = entries.any((entry) => entry.skills.isNotEmpty); - final hasErrors = entries.any((entry) => entry.errors.isNotEmpty); - if (!hasSkills && !hasErrors) { - return const Padding( - padding: .all(14), - child: Text('当前设备没有扫描到可用 Skills。'), - ); - } - return Column( - children: [ - for (var i = 0; i < entries.length; i++) ...[ - const Divider(height: 1), - Padding( - padding: const .fromLTRB(14, 10, 14, 4), - child: Align( - alignment: .centerLeft, - child: Text( - entries[i].cwd, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.labelMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - fontWeight: .w700, - ), - ), - ), - ), - for (final error in entries[i].errors) - _HostSkillErrorTile(error: error), - for ( - var skillIndex = 0; - skillIndex < entries[i].skills.length; - skillIndex++ - ) ...[ - if (skillIndex > 0) const Divider(height: 1), - _HostSkillTile( - hostDeviceId: resolvedHostDeviceId, - skill: entries[i].skills[skillIndex], - ), - ], - ], - ], - ); - }, - ), - ], - ); - } -} - -class _EditorSection extends StatelessWidget { - const _EditorSection({required this.title, required this.child}); - - final String title; - final Widget child; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Container( - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration( - color: theme.colorScheme.surface, - borderRadius: BorderRadius.circular(16), - border: Border.all( - color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(14, 14, 14, 0), - child: Text( - title, - style: theme.textTheme.labelMedium?.copyWith( - fontWeight: FontWeight.w700, - color: theme.colorScheme.onSurfaceVariant, - letterSpacing: 0.6, - ), - ), - ), - child, - ], - ), - ); - } -} - -class _EditorPickerTile extends StatelessWidget { - const _EditorPickerTile({ - required this.label, - required this.value, - required this.onTap, - }); - - final String label; - final String value; - final VoidCallback onTap; - - @override - Widget build(BuildContext context) { - return ListTile( - contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 2), - title: Text(label), - subtitle: Text(value, maxLines: 1, overflow: TextOverflow.ellipsis), - trailing: const Icon(CupertinoIcons.chevron_right, size: 18), - onTap: onTap, - ); - } -} - -class _EditorHintCard extends StatelessWidget { - const _EditorHintCard({required this.message}); - - final String message; - - @override - Widget build(BuildContext context) { - return Container( - padding: const EdgeInsets.all(14), - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, - borderRadius: BorderRadius.circular(20), - ), - child: Text(message), - ); - } -} - -class _ProfilesSection extends ConsumerWidget { - const _ProfilesSection({ - required this.state, - required this.preferredProfileId, - required this.hosts, - required this.onAdd, - }); - - final AgentWorkspaceState state; - final String? preferredProfileId; - final List hosts; - final VoidCallback onAdd; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final ordered = [...state.profiles] - ..sort((left, right) { - if (left.id == preferredProfileId) return -1; - if (right.id == preferredProfileId) return 1; - return right.updatedAtMs.compareTo(left.updatedAtMs); - }); - return _SectionCard( - title: 'AGENTS ${ordered.length}', - trailing: _SectionActionButton(tooltip: '新建 Agent', onPressed: onAdd), - child: ordered.isEmpty - ? Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 18), - child: Text( - '还没有 Agent。点右上角添加一个,并把它绑定到对应的 runtime。', - style: Theme.of(context).textTheme.bodyMedium, - ), - ) - : Column( - children: [ - for ( - var index = 0; - index < ordered.length; - index++ - ) ...[ - if (index > 0) const Divider(height: 1), - _AgentProfileTile( - profile: ordered[index], - hostLabel: _resolvedProfileHostLabel(ordered[index], hosts), - isPreferred: ordered[index].id == preferredProfileId, - onTap: () => unawaited( - context.push('/agent-profile/${ordered[index].id}'), - ), - onMakeDefault: () => ref - .read(agentProfilesControllerProvider.notifier) - .setPreferredProfile(ordered[index].id), - onDelete: () { - unawaited( - showCupertinoDialog( - context: context, - builder: (dialogContext) => CupertinoAlertDialog( - title: const Text('删除 Agent'), - content: const Text('确定要删除这个 Agent 吗?此操作无法撤销。'), - actions: [ - CupertinoDialogAction( - onPressed: () => - Navigator.of(dialogContext).pop(), - child: const Text('取消'), - ), - CupertinoDialogAction( - isDestructiveAction: true, - onPressed: () async { - await ref - .read( - agentProfilesControllerProvider - .notifier, - ) - .deleteProfile(ordered[index].id); - if (dialogContext.mounted) { - Navigator.of(dialogContext).pop(); - } - }, - child: const Text('删除'), - ), - ], - ), - ), - ); - }, - ), - ], - ], - ), - ); - } -} - -class _HostRuntimeCard extends ConsumerWidget { - const _HostRuntimeCard({ - required this.pairedHosts, - required this.activeHostId, - required this.connection, - }); - - final AsyncValue> pairedHosts; - final String? activeHostId; - final minos_api.ConnectionState? connection; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - return _SectionCard( - title: 'HOSTS ${pairedHosts.asData?.value.length ?? 0}', - trailing: IconButton( - tooltip: '刷新', - icon: const Icon(CupertinoIcons.arrow_clockwise, size: 18), - onPressed: () async { - try { - await ref.read(pairedMacsProvider.notifier).refresh(); - } catch (error) { - if (context.mounted) { - _showRefreshError(context, 'Hosts 刷新失败', error); - } - } - }, - ), - child: pairedHosts.when( - loading: () => const _DeviceListSkeleton(), - error: (error, _) => Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 18), - child: _CompactErrorPanel( - title: 'Hosts 暂时不可用', - description: error.toString(), - actionLabel: '重试', - onAction: () async { - try { - await ref.read(pairedMacsProvider.notifier).refresh(); - } catch (error) { - if (context.mounted) { - _showRefreshError(context, 'Hosts 刷新失败', error); - } - } - }, - ), - ), - data: (hosts) { - if (hosts.isEmpty) { - return Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 18), - child: Text( - '还没有 Linked Host。\n' - '在 Desktop 登录同一 Minos 账号并 Link this Mac 后,下拉或点刷新即可看到。', - style: theme.textTheme.bodyMedium, - ), - ); - } - - return Column( - children: [ - for (var index = 0; index < hosts.length; index++) ...[ - if (index > 0) const Divider(height: 1), - _DeviceRosterTile( - host: hosts[index], - isActive: hosts[index].hostDeviceId == activeHostId, - connection: connection, - onTap: () => ref - .read(activeMacProvider.notifier) - .setActive(hosts[index].hostDeviceId), - onDelete: () { - unawaited( - showCupertinoDialog( - context: context, - builder: (dialogContext) => CupertinoAlertDialog( - title: const Text('移除设备'), - content: const Text('确定要移除此设备吗?此操作无法撤销。'), - actions: [ - CupertinoDialogAction( - onPressed: () => - Navigator.of(dialogContext).pop(), - child: const Text('取消'), - ), - CupertinoDialogAction( - isDestructiveAction: true, - onPressed: () async { - await ref - .read(runtimeActionsProvider) - .forgetHost(hosts[index].hostDeviceId); - try { - await ref - .read(pairedMacsProvider.notifier) - .refresh(); - } catch (_) {} - await ref - .read(activeMacProvider.notifier) - .refresh(); - if (dialogContext.mounted) { - Navigator.of(dialogContext).pop(); - } - }, - child: const Text('移除'), - ), - ], - ), - ), - ); - }, - ), - ], - ], - ); - }, - ), - ); - } -} - -class _AgentProfileTile extends StatelessWidget { - const _AgentProfileTile({ - required this.profile, - required this.hostLabel, - required this.isPreferred, - required this.onTap, - required this.onMakeDefault, - this.onDelete, - }); - - final AgentProfile profile; - final String hostLabel; - final bool isPreferred; - final VoidCallback onTap; - final VoidCallback onMakeDefault; - final VoidCallback? onDelete; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final detail = profile.description.trim().isEmpty - ? '${_runtimeLabel(profile.runtimeAgent)} · ${profile.model}' - : profile.description.trim(); - final isDark = theme.brightness == Brightness.dark; - - final highlight = isPreferred - ? theme.colorScheme.primaryContainer.withValues( - alpha: isDark ? 0.2 : 0.4, - ) - : Colors.transparent; - - return InkWell( - onTap: onTap, - onLongPress: isPreferred ? null : onMakeDefault, - child: Container( - color: highlight, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _AgentAvatar(agent: profile.runtimeAgent, size: 42), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - hostLabel, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 4), - Text( - profile.name, - style: theme.textTheme.titleLarge?.copyWith( - fontWeight: FontWeight.w800, - letterSpacing: 0, - ), - ), - const SizedBox(height: 4), - Text( - detail, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - const SizedBox(width: 12), - Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Padding( - padding: const EdgeInsets.only(top: 8), - child: _MemberStatusDot( - color: isPreferred - ? (isDark - ? const Color(0xFF22C55E) - : const Color(0xFF16A34A)) - : theme.colorScheme.outline, - ), - ), - if (onDelete != null) ...[ - const SizedBox(height: 8), - IconButton( - onPressed: onDelete, - icon: const Icon(CupertinoIcons.trash, size: 16), - constraints: const BoxConstraints.tightFor( - width: 32, - height: 32, - ), - padding: EdgeInsets.zero, - visualDensity: VisualDensity.compact, - ), - ], - ], - ), - ], - ), - ), - ); - } -} - -class _DeviceRosterTile extends StatelessWidget { - const _DeviceRosterTile({ - required this.host, - required this.isActive, - required this.connection, - required this.onTap, - this.onDelete, - }); - - final HostSummaryDto host; - final bool isActive; - final minos_api.ConnectionState? connection; - final VoidCallback onTap; - final VoidCallback? onDelete; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final title = host.hostDisplayName.trim().isEmpty - ? host.hostDeviceId - : host.hostDisplayName.trim(); - final runtimeLabel = host.online ? '设备在线' : '设备离线'; - final stateLabel = isActive - ? '当前路由 · $runtimeLabel · App ${_connectionLabel(connection)}' - : '已配对 · $runtimeLabel'; - final subtitle = title == host.hostDeviceId - ? stateLabel - : '${host.hostDeviceId} · $stateLabel'; - final isDark = theme.brightness == Brightness.dark; - final highlight = isActive - ? theme.colorScheme.secondaryContainer.withValues( - alpha: isDark ? 0.2 : 0.4, - ) - : Colors.transparent; - - return InkWell( - onTap: onTap, - child: Container( - color: highlight, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - children: [ - const _DeviceAvatar(), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w700, - ), - ), - const SizedBox(height: 4), - Text( - subtitle, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - const SizedBox(width: 12), - Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _MemberStatusDot( - color: _connectionColor(connection, isActive, isDark), - ), - if (onDelete != null) ...[ - const SizedBox(height: 8), - IconButton( - onPressed: onDelete, - icon: const Icon(CupertinoIcons.trash, size: 16), - constraints: const BoxConstraints.tightFor( - width: 32, - height: 32, - ), - padding: EdgeInsets.zero, - visualDensity: VisualDensity.compact, - ), - ], - ], - ), - ], - ), - ), - ); - } -} - -class _HumansSection extends ConsumerWidget { - const _HumansSection(); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final friendsAsync = ref.watch(friendsProvider); - return friendsAsync.when( - loading: () => - const _SectionCard(title: 'HUMANS 0', child: _HumanListSkeleton()), - error: (error, _) => _SectionCard( - title: 'HUMANS 0', - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 18), - child: _CompactErrorPanel( - title: '好友暂时不可用', - description: error.toString(), - actionLabel: '重试', - onAction: () async { - try { - await ref.read(friendsProvider.notifier).refresh(); - } catch (error) { - if (context.mounted) { - _showRefreshError(context, '好友刷新失败', error); - } - } - }, - ), - ), - ), - data: (friends) => _SectionCard( - title: 'HUMANS ${friends.friends.length}', - child: friends.friends.isEmpty - ? const Padding( - padding: EdgeInsets.fromLTRB(16, 8, 16, 18), - child: Text('还没有好友。'), - ) - : Column( - children: [ - for ( - var index = 0; - index < friends.friends.length; - index++ - ) ...[ - if (index > 0) const Divider(height: 1), - _HumanFriendTile(friend: friends.friends[index]), - ], - ], - ), - ), - ); - } -} - -class _HumanFriendTile extends ConsumerWidget { - const _HumanFriendTile({required this.friend}); - - final FriendSummary friend; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - final title = friend.displayName.trim().isEmpty - ? friend.minosId - : friend.displayName.trim(); - final initial = title.isEmpty ? '?' : title.substring(0, 1).toUpperCase(); - return InkWell( - onTap: () async { - try { - final response = await ref - .read(socialActionsProvider) - .ensureDirectConversation(friendAccountId: friend.accountId); - if (!context.mounted) return; - ref.invalidate(conversationsProvider); - await context.push( - '/social/chat/${response.conversationId}', - extra: SocialChatRouteExtra( - title: title, - kind: ConversationKind.direct, - ), - ); - } catch (error) { - if (!context.mounted) return; - showLoggedErrorToast( - context, - target: 'agents_hub', - title: '打开聊天失败', - error: error, - ); - } - }, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - children: [ - _HumanAvatar(label: initial), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w700, - ), - ), - const SizedBox(height: 4), - Text( - '@${friend.minosId}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - const SizedBox(width: 12), - Icon( - CupertinoIcons.chat_bubble, - size: 18, - color: theme.colorScheme.onSurfaceVariant, - ), - ], - ), - ), - ); - } -} - -class _ProfileHero extends StatelessWidget { - const _ProfileHero({required this.profile, required this.isPreferred}); - - final AgentProfile profile; - final bool isPreferred; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final isDark = theme.brightness == Brightness.dark; - return Container( - padding: const EdgeInsets.all(18), - decoration: BoxDecoration( - color: theme.colorScheme.surfaceContainerLow, - borderRadius: BorderRadius.circular(16), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: isDark ? 0.08 : 0.03), - blurRadius: 10, - offset: const Offset(0, 2), - ), - ], - ), - child: Row( - children: [ - _AgentAvatar(agent: profile.runtimeAgent, size: 64), - const SizedBox(width: 16), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded( - child: Text( - profile.name, - style: theme.textTheme.headlineSmall?.copyWith( - fontWeight: FontWeight.w800, - ), - ), - ), - if (isPreferred) - _BadgeChip( - label: 'Default', - background: theme.colorScheme.primaryContainer, - ), - ], - ), - const SizedBox(height: 6), - Text( - profile.description.isEmpty - ? 'General-purpose agent profile' - : profile.description, - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 10), - Wrap( - spacing: 8, - runSpacing: 8, - children: [ - _BadgeChip(label: _runtimeLabel(profile.runtimeAgent)), - _BadgeChip(label: profile.model), - if (profile.hostDisplayName != null) - _BadgeChip(label: profile.hostDisplayName!), - if (profile.workspacePath?.trim().isNotEmpty ?? false) - _BadgeChip(label: profile.workspacePath!.trim()), - ], - ), - ], - ), - ), - ], - ), - ); - } -} - -class _DetailRow extends StatelessWidget { - const _DetailRow({required this.label, required this.value}); - - final String label; - final String value; - - @override - Widget build(BuildContext context) { - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox( - width: 120, - child: Text( - label, - style: Theme.of(context).textTheme.labelLarge?.copyWith( - color: Theme.of(context).colorScheme.onSurfaceVariant, - fontWeight: FontWeight.w700, - ), - ), - ), - Expanded( - child: Text(value, style: Theme.of(context).textTheme.bodyLarge), - ), - ], - ), - ); - } -} - -class _HostSkillsSection extends ConsumerWidget { - const _HostSkillsSection({ - required this.hostDeviceId, - required this.hostLabel, - required this.skillsAsync, - }); - - final String? hostDeviceId; - final String hostLabel; - final AsyncValue>? skillsAsync; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - final resolvedHostDeviceId = hostDeviceId; - final resolvedSkillsAsync = skillsAsync; - if (resolvedHostDeviceId == null || resolvedSkillsAsync == null) { - return const _SectionCard( - title: 'Skills', - child: Padding( - padding: EdgeInsets.all(16), - child: Text('先为这个 Agent 绑定一个 runtime host,才能扫描和编辑 host skills。'), - ), - ); - } - - return _SectionCard( - title: 'Skills', - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 10, 8, 0), - child: Row( - children: [ - Expanded( - child: Text( - 'Runtime · $hostLabel', - style: theme.textTheme.labelLarge?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - fontWeight: FontWeight.w700, - ), - ), - ), - IconButton( - tooltip: '重新扫描', - onPressed: () => - ref.invalidate(hostSkillsProvider(resolvedHostDeviceId)), - icon: const Icon(CupertinoIcons.refresh), - ), - ], - ), - ), - resolvedSkillsAsync.when( - loading: () => const Padding( - padding: EdgeInsets.all(18), - child: Center(child: CupertinoActivityIndicator()), - ), - error: (error, _) => Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '读取 host skills 失败: $error', - style: theme.textTheme.bodyMedium, - ), - const SizedBox(height: 10), - OutlinedButton.icon( - onPressed: () => ref.invalidate( - hostSkillsProvider(resolvedHostDeviceId), - ), - icon: const Icon(CupertinoIcons.refresh), - label: const Text('重试'), - ), - ], - ), - ), - data: (entries) { - final hasSkills = entries.any((entry) => entry.skills.isNotEmpty); - final hasErrors = entries.any((entry) => entry.errors.isNotEmpty); - if (!hasSkills && !hasErrors) { - return const Padding( - padding: EdgeInsets.all(16), - child: Text('当前 host 上没有扫描到可用 skills。'), - ); - } - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (var i = 0; i < entries.length; i++) ...[ - const Divider(height: 1), - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 6), - child: Text( - entries[i].cwd, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.labelMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - fontWeight: FontWeight.w700, - ), - ), - ), - for (final error in entries[i].errors) - _HostSkillErrorTile(error: error), - if (entries[i].errors.isNotEmpty && - entries[i].skills.isNotEmpty) - const Divider(height: 1), - for ( - var skillIndex = 0; - skillIndex < entries[i].skills.length; - skillIndex++ - ) ...[ - if (skillIndex > 0) const Divider(height: 1), - _HostSkillTile( - hostDeviceId: resolvedHostDeviceId, - skill: entries[i].skills[skillIndex], - ), - ], - ], - ], - ); - }, - ), - ], - ), - ); - } -} - -class _HostSkillTile extends ConsumerWidget { - const _HostSkillTile({required this.hostDeviceId, required this.skill}); - - final String hostDeviceId; - final HostSkillSummary skill; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - final displayName = - skill.displayName != null && skill.displayName!.trim().isNotEmpty - ? skill.displayName! - : skill.name; - final secondary = - skill.shortDescription != null && - skill.shortDescription!.trim().isNotEmpty - ? skill.shortDescription! - : skill.description; - - return SwitchListTile.adaptive( - value: skill.enabled, - contentPadding: const EdgeInsets.fromLTRB(16, 4, 12, 8), - title: Text(displayName), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 4), - Text(secondary, maxLines: 2, overflow: TextOverflow.ellipsis), - const SizedBox(height: 8), - Wrap( - spacing: 8, - runSpacing: 8, - children: [ - _BadgeChip(label: skill.scope.toUpperCase()), - if (displayName != skill.name) _BadgeChip(label: skill.name), - ], - ), - const SizedBox(height: 8), - Text( - skill.path, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - onChanged: (enabled) => _setSkillEnabled(context, ref, enabled), - ); - } - - Future _setSkillEnabled( - BuildContext context, - WidgetRef ref, - bool enabled, - ) async { - try { - await ref - .read(runtimeActionsProvider) - .writeHostSkillConfig( - hostDeviceId: hostDeviceId, - path: skill.path, - enabled: enabled, - ); - ref.invalidate(hostSkillsProvider(hostDeviceId)); - } catch (error) { - if (!context.mounted) return; - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text('更新 skill 失败: $error'))); - } - } -} - -class _HostSkillErrorTile extends StatelessWidget { - const _HostSkillErrorTile({required this.error}); - - final HostSkillError error; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return ListTile( - leading: const Icon(CupertinoIcons.exclamationmark_triangle_fill), - title: Text(error.message), - subtitle: Text( - error.path, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ); - } -} - -class _SectionCard extends StatelessWidget { - const _SectionCard({required this.title, required this.child, this.trailing}); - - final String title; - final Widget child; - final Widget? trailing; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(4, 20, 4, 8), - child: Row( - children: [ - Expanded( - child: Text( - title, - style: theme.textTheme.labelMedium?.copyWith( - fontWeight: FontWeight.w700, - color: theme.colorScheme.onSurfaceVariant, - letterSpacing: 0.8, - ), - ), - ), - ?trailing, - ], - ), - ), - Container( - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration( - color: theme.colorScheme.surfaceContainerLow, - borderRadius: BorderRadius.circular(16), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.015), - blurRadius: 10, - offset: const Offset(0, 1), - ), - ], - ), - child: child, - ), - ], - ), - ); - } -} - -class _BadgeChip extends StatelessWidget { - const _BadgeChip({this.background, required this.label}); - - final Color? background; - final String label; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final isDark = theme.brightness == Brightness.dark; - final bg = - background ?? - (isDark - ? theme.colorScheme.surfaceContainerHighest - : theme.colorScheme.surfaceContainerHigh); - return ConstrainedBox( - constraints: BoxConstraints( - maxWidth: MediaQuery.sizeOf(context).width - 64, - ), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: bg, - borderRadius: BorderRadius.circular(6), - ), - child: Text( - label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.labelSmall?.copyWith( - fontWeight: FontWeight.w600, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ), - ); - } -} - -class _AgentAvatar extends StatelessWidget { - const _AgentAvatar({required this.agent, this.size = 32}); - - final AgentName agent; - final double size; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final isDark = theme.brightness == Brightness.dark; - final (label, bgColor, fgColor) = switch (agent) { - AgentName.codex => ( - 'C', - isDark ? const Color(0xFF14532D) : const Color(0xFFDCFCE7), - isDark ? const Color(0xFF4ADE80) : const Color(0xFF16A34A), - ), - AgentName.claude => ( - 'A', - isDark ? const Color(0xFF7C2D12) : const Color(0xFFFFEDD5), - isDark ? const Color(0xFFFB923C) : const Color(0xFFEA580C), - ), - AgentName.gemini => ( - 'G', - isDark ? const Color(0xFF164E63) : const Color(0xFFCFFAFE), - isDark ? const Color(0xFF22D3EE) : const Color(0xFF0891B2), - ), - AgentName.opencode => ( - 'O', - isDark ? const Color(0xFF1E293B) : const Color(0xFFF1F5F9), - isDark ? const Color(0xFF94A3B8) : const Color(0xFF475569), - ), - AgentName.grok => ( - 'X', - isDark ? const Color(0xFF78350F) : const Color(0xFFFEF3C7), - isDark ? const Color(0xFFFBBF24) : const Color(0xFFB45309), - ), - }; - return Container( - width: size, - height: size, - decoration: BoxDecoration(shape: BoxShape.circle, color: bgColor), - alignment: Alignment.center, - child: Text( - label, - style: TextStyle( - color: fgColor, - fontWeight: FontWeight.w800, - fontSize: size * 0.42, - ), - ), - ); - } -} - -String? _hostLabelForId(List hosts, String? hostId) { - if (hostId == null) return null; - for (final host in hosts) { - if (host.hostDeviceId == hostId) { - final trimmed = host.hostDisplayName.trim(); - return trimmed.isEmpty ? host.hostDeviceId : trimmed; - } - } - return hostId; -} - -String _runtimeLabel(AgentName agent) { - return switch (agent) { - AgentName.codex => 'Codex CLI', - AgentName.claude => 'Claude CLI', - AgentName.gemini => 'Gemini CLI', - AgentName.opencode => 'OpenCode CLI', - AgentName.grok => 'Grok CLI', - }; -} - -String _reasoningLabel(AgentReasoningEffort value) { - return switch (value) { - AgentReasoningEffort.low => 'Low', - AgentReasoningEffort.medium => 'Medium', - AgentReasoningEffort.high => 'High', - }; -} - -List _runtimeOptions(List descriptors) { - final usable = descriptors - .where((descriptor) => descriptor.status is AgentStatus_Ok) - .map((descriptor) => descriptor.name) - .toSet() - .toList(); - if (usable.isNotEmpty) return usable; - return AgentName.values; -} - -AgentName _preferredRuntime(List descriptors) { - return _runtimeOptions(descriptors).first; -} - -List _modelOptions(AgentName runtimeAgent) { - return switch (runtimeAgent) { - AgentName.codex => const ['GPT-5.5', 'GPT-5.1', 'o4-mini'], - AgentName.claude => const ['Claude Opus 4.1', 'Claude Sonnet 4'], - AgentName.gemini => const ['Gemini 2.5 Pro', 'Gemini 2.5 Flash'], - AgentName.opencode => const [ - 'openai/gpt-5.2', - 'openai/gpt-5.2-codex', - ], - AgentName.grok => const ['grok-4.5'], - }; -} - -String _defaultModel(AgentName runtimeAgent) { - return _modelOptions(runtimeAgent).first; -} diff --git a/apps/mobile/lib/ui/features/chat/chat.dart b/apps/mobile/lib/ui/features/chat/chat.dart deleted file mode 100644 index 97d6f2c2..00000000 --- a/apps/mobile/lib/ui/features/chat/chat.dart +++ /dev/null @@ -1,25 +0,0 @@ -/// Feature: Chat (Agent Thread View) -/// -/// Real-time chat surface for agent sessions. Renders translated -/// UiEventMessage streams as message bubbles, tool-call cards, and -/// reasoning sections with a sticky composer. -/// -/// View Models: -/// - [ActiveSessionController] (application/active_session_provider.dart) -/// - [ThreadEvents] (application/thread_events_provider.dart) -/// -/// Views: -/// - [ThreadViewPage] -/// - [InputBar], [MessageBubble], [StreamingText], [ToolCallCard], -/// [ReasoningSection] -library; - -export 'package:minos/application/active_session_provider.dart'; -export 'package:minos/application/thread_events_provider.dart'; -export 'package:minos/ui/features/chat/views/thread_view_page.dart'; -export 'package:minos/ui/features/chat/widgets/input_bar.dart'; -export 'package:minos/ui/features/chat/widgets/message_bubble.dart'; -export 'package:minos/ui/features/chat/widgets/message_meta_row.dart'; -export 'package:minos/ui/features/chat/widgets/reasoning_section.dart'; -export 'package:minos/ui/features/chat/widgets/streaming_text.dart'; -export 'package:minos/ui/features/chat/widgets/tool_call_card.dart'; diff --git a/apps/mobile/lib/ui/features/chat/views/thread_view_page.dart b/apps/mobile/lib/ui/features/chat/views/thread_view_page.dart deleted file mode 100644 index fef8ed65..00000000 --- a/apps/mobile/lib/ui/features/chat/views/thread_view_page.dart +++ /dev/null @@ -1,1084 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; - -import 'package:flutter/material.dart' hide ConnectionState; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:minos/application/active_session_provider.dart'; -import 'package:minos/application/agent_profiles_provider.dart'; -import 'package:minos/application/display_payload_preview.dart'; -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/preferred_agent_provider.dart'; -import 'package:minos/application/thread_commands.dart'; -import 'package:minos/application/thread_event_timeline.dart'; -import 'package:minos/application/thread_events_provider.dart'; -import 'package:minos/application/thread_view_state.dart'; -import 'package:minos/domain/active_session.dart'; -import 'package:minos/domain/agent_profile.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:minos/ui/core/widgets/agent_question_sheet.dart'; -import 'package:minos/ui/core/widgets/approval_sheet.dart'; -import 'package:minos/ui/core/widgets/error_feedback.dart'; -import 'package:minos/ui/core/widgets/minos_toast.dart'; -import 'package:minos/ui/features/chat/widgets/input_bar.dart'; -import 'package:minos/ui/features/chat/widgets/message_bubble.dart'; -import 'package:minos/ui/features/chat/widgets/reasoning_section.dart'; -import 'package:minos/ui/features/chat/widgets/streaming_text.dart'; -import 'package:minos/ui/features/chat/widgets/tool_call_card.dart'; -import 'package:minos/ui/theme/theme.dart'; - -/// Chat surface for a single thread. Renders the translated -/// `UiEventMessage` stream as a sequence of bubbles + tool-call cards + -/// reasoning sections, with a sticky composer at the bottom. -/// -/// The page is the integration seam where: -/// -/// - `threadEventsProvider(sessionId)` supplies the historical + -/// live event stream; -/// - `activeSessionControllerProvider` says whether the user can -/// compose, must wait, or should see a Stop button instead. -/// -/// `sessionId == null` means the user just landed on a "new chat" — the -/// list renders empty and the first `onSend` dispatches via -/// `sendChatMessage`. Once the controller transitions to -/// `SessionStreaming` we follow that session id for events. -class ThreadViewPage extends ConsumerStatefulWidget { - const ThreadViewPage({ - super.key, - this.sessionId, - this.agent, - this.agentProfileId, - }); - - /// Pre-existing thread to load. Null = new chat. - final String? sessionId; - - /// Agent the session was started with. Set when navigating from the thread - /// list (we already have it on the [SessionSummary]); the title falls back - /// to it whenever the global active session is bound to a *different* - /// thread, so we never label a historical thread with the live session's - /// agent. - final AgentName? agent; - final String? agentProfileId; - - @override - ConsumerState createState() => _ThreadViewPageState(); -} - -class _ThreadViewPageState extends ConsumerState { - static const double _stickyThreshold = 120; - static const Duration _keyboardRevealDelay = Duration(milliseconds: 120); - static const Duration _keyboardRevealSettleDelay = Duration( - milliseconds: 260, - ); - - final ScrollController _scroll = ScrollController(); - StreamSubscription? _approvalSub; - late final String _viewStateId; - double _lastKeyboardInsetBottom = 0; - - @override - void initState() { - super.initState(); - _viewStateId = widget.sessionId ?? 'draft-${identityHashCode(this)}'; - _scroll.addListener(_onScroll); - _listenForApprovalEvents(); - } - - @override - void dispose() { - unawaited(_approvalSub?.cancel()); - _scroll - ..removeListener(_onScroll) - ..dispose(); - super.dispose(); - } - - /// Subscribe to the live UI event stream and intercept approval-related - /// events for the current thread. Approval requests trigger the bottom - /// sheet; approval timeouts dismiss it and show a toast. - void _listenForApprovalEvents() { - final threadCommands = ref.read(threadCommandsProvider); - _approvalSub = threadCommands.uiEvents.listen((frame) { - if (!mounted) return; - final session = ref.read(activeSessionControllerProvider); - final sessionId = _resolvedThreadId(session); - if (sessionId == null || frame.sessionId != sessionId) return; - - final event = frame.ui; - if (event is UiEventMessage_Raw) { - _handleRawApprovalEvent(event, sessionId); - } - }); - } - - void _handleRawApprovalEvent(UiEventMessage_Raw event, String sessionId) { - if (event.kind == 'approval/request' || event.kind == 'approval_request') { - unawaited(_onApprovalRequest(event.payloadJson, sessionId)); - } else if (event.kind == 'approval/timeout' || - event.kind == 'approval_timeout') { - _onApprovalTimeout(event.payloadJson); - } else if (event.kind == 'opencode/question.asked') { - unawaited(_onAgentQuestionRequest(event.payloadJson, sessionId)); - } else if (event.kind == 'opencode/question.replied' || - event.kind == 'opencode/question.rejected') { - _onAgentQuestionResolved(); - } - } - - Future _onApprovalRequest(String payloadJson, String sessionId) async { - final threadViewState = ref.read( - threadViewStateControllerProvider(_viewStateId), - ); - if (threadViewState.approvalSheetVisible) return; - - final Map json; - try { - json = jsonDecode(payloadJson) as Map; - } catch (error, stackTrace) { - logFlutterWarn( - 'thread_view', - 'approval request decode failed sessionId=$sessionId', - error: error, - stackTrace: stackTrace, - ); - return; - } - - final request = ApprovalRequestData.fromJson(json); - logFlutterInfo( - 'thread_view', - 'approval request received sessionId=$sessionId requestId=${request.requestId} method=${request.method}', - ); - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .setApprovalSheetVisible(true); - - final decision = await showApprovalSheet(context, request: request); - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .setApprovalSheetVisible(false); - - if (decision == null) { - logFlutterInfo( - 'thread_view', - 'approval request dismissed sessionId=$sessionId requestId=${request.requestId}', - ); - // Timeout or dismissed without decision — host auto-declines - return; - } - - final decisionPayload = _buildDecisionPayload(request.method, decision); - - try { - await ref - .read(threadCommandsProvider) - .sendApprovalDecision( - requestId: request.requestId, - sessionId: request.sessionId, - decision: decisionPayload, - ); - } catch (error) { - if (mounted) { - showLoggedErrorToast( - context, - target: 'thread_view', - title: '发送审批决定失败', - error: error, - ); - } - } - } - - void _onApprovalTimeout(String payloadJson) { - // Dismiss the approval sheet if it's currently showing - final controller = ref.read( - threadViewStateControllerProvider(_viewStateId).notifier, - ); - if (ref - .read(threadViewStateControllerProvider(_viewStateId)) - .approvalSheetVisible && - mounted) { - Navigator.of(context).pop(null); - controller.setApprovalSheetVisible(false); - } - - // Show a toast indicating the approval timed out - if (mounted) { - final Map json; - try { - json = jsonDecode(payloadJson) as Map; - } catch (_) { - logFlutterWarn('thread_view', 'approval timeout payload decode failed'); - _showThreadInfo(context, '审批已超时,自动拒绝'); - return; - } - final reason = json['reason'] as String? ?? 'timeout'; - logFlutterInfo('thread_view', 'approval timed out reason=$reason'); - final message = reason == 'disconnected' ? '连接断开,审批已自动拒绝' : '审批已超时,自动拒绝'; - _showThreadInfo(context, message); - } - } - - Future _onAgentQuestionRequest( - String payloadJson, - String sessionId, - ) async { - final threadViewState = ref.read( - threadViewStateControllerProvider(_viewStateId), - ); - if (threadViewState.approvalSheetVisible) return; - - final Map json; - try { - json = jsonDecode(payloadJson) as Map; - } catch (error, stackTrace) { - logFlutterWarn( - 'thread_view', - 'agent question decode failed sessionId=$sessionId', - error: error, - stackTrace: stackTrace, - ); - return; - } - - final request = AgentQuestionRequestData.fromJson(json); - if (request.requestId.isEmpty || request.questions.isEmpty) { - logFlutterWarn( - 'thread_view', - 'agent question payload missing request id or questions sessionId=$sessionId', - ); - return; - } - - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .setApprovalSheetVisible(true); - final answers = await showAgentQuestionSheet(context, request: request); - if (!mounted) return; - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .setApprovalSheetVisible(false); - - if (answers == null) return; - - try { - await ref - .read(threadCommandsProvider) - .respondOpencodeQuestion( - sessionId: sessionId, - questionId: request.requestId, - answers: answers, - ); - } catch (error) { - if (mounted) { - showLoggedErrorToast( - context, - target: 'thread_view', - title: '发送问题答案失败', - error: error, - ); - } - } - } - - void _onAgentQuestionResolved() { - final controller = ref.read( - threadViewStateControllerProvider(_viewStateId).notifier, - ); - if (ref - .read(threadViewStateControllerProvider(_viewStateId)) - .approvalSheetVisible && - mounted) { - Navigator.of(context).pop(null); - controller.setApprovalSheetVisible(false); - } - } - - Map _buildDecisionPayload( - String method, - ApprovalDecision decision, - ) { - final accept = decision == ApprovalDecision.accept; - if (method.contains('command_execution') || - method.contains('exec_command')) { - return {'decision': accept ? 'accept' : 'decline'}; - } else if (method.contains('file_change') || - method.contains('apply_patch')) { - return {'decision': accept ? 'accept' : 'decline'}; - } else if (method.contains('permissions')) { - if (accept) { - return { - 'granted': { - 'profile': 'default', - 'scope': 'session', - }, - }; - } else { - return {'denied': {}}; - } - } - return {'decision': accept ? 'accept' : 'decline'}; - } - - void _onScroll() { - if (!_scroll.hasClients) return; - final pos = _scroll.position; - final distanceFromBottom = pos.maxScrollExtent - pos.pixels; - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .updateScrollState( - distanceFromBottom: distanceFromBottom, - stickyThreshold: _stickyThreshold, - ); - } - - String? _resolvedThreadId(ActiveSession session) { - // When the user navigated into a specific thread, that always wins — - // otherwise tapping an older thread would show the most-recently-started - // session's events because the active-session controller is global. - // The session-derived branch is only meant for the "new chat" path, - // where widget.sessionId is null and we need sendChatMessage to mint one. - if (widget.sessionId != null) return widget.sessionId; - return _sessionThreadId(session); - } - - static String? _sessionThreadId(ActiveSession session) { - return switch (session) { - SessionStreaming(sessionId: final t) => t, - SessionAwaitingInput(sessionId: final t) => t, - SessionSuspended(sessionId: final t) => t, - SessionError(sessionId: final t?) => t, - _ => null, - }; - } - - /// Returns the global session if it is currently bound to the session the - /// page is rendering, otherwise [SessionIdle]. The whole page (title, - /// subtitle, input bar, send/start decision) reads off this view-scoped - /// value so historical sessions never inherit the live session's "回复中" - /// badge or "停止" button while the agent is busy on a different thread. - ActiveSession _viewSession(ActiveSession session) { - if (widget.sessionId == null) return session; - return _sessionThreadId(session) == widget.sessionId - ? session - : const SessionIdle(); - } - - String _enqueueOptimisticMessage(String text) { - // Snapshot the event count at enqueue time so the bubble can be slotted - // back into the timeline at the right chronological position even if a - // codex reply lands before our own MessageStarted{user} echo. - final anchor = - ref - .read( - threadEventsProvider( - _resolvedThreadId(ref.read(activeSessionControllerProvider)) ?? - '', - ), - ) - .asData - ?.value - .length ?? - 0; - return ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .enqueueOptimisticMessage(text: text, anchorEventCount: anchor); - } - - void _markOptimisticMessageFailed(String id) { - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .markOptimisticMessageFailed(id); - } - - /// Daemon RPC ack means the message is durable; clear the spinner now - /// instead of waiting for a `MessageStarted{role:user}` echo (which the - /// upstream pipeline does not always deliver in a timely fashion). The - /// optimistic entry stays in the list as a `confirmed` row until either - /// the real `MessageStarted{user}` event consumes it, or the user - /// navigates away. - void _markOptimisticMessageConfirmed(String id) { - ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .markOptimisticMessageConfirmed(id); - } - - void _handleThreadMetrics( - String sessionId, - int eventCount, - List userMessages, - ) { - final shouldAutoScroll = ref - .read(threadViewStateControllerProvider(_viewStateId).notifier) - .handleThreadMetrics( - eventCount: eventCount, - userMessages: userMessages, - ); - if (!shouldAutoScroll) return; - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted || !_scroll.hasClients) return; - _scroll.jumpTo(_scroll.position.maxScrollExtent); - }); - } - - void _syncKeyboardInset(double keyboardInsetBottom, {required bool stick}) { - if ((_lastKeyboardInsetBottom - keyboardInsetBottom).abs() < 0.5) return; - _lastKeyboardInsetBottom = keyboardInsetBottom; - _revealBottomMessages(stick: stick); - } - - void _revealBottomMessages({required bool stick}) { - if (!stick) return; - - void jumpToBottom() { - if (!mounted || !_scroll.hasClients) return; - _scroll.jumpTo(_scroll.position.maxScrollExtent); - } - - WidgetsBinding.instance.addPostFrameCallback((_) => jumpToBottom()); - unawaited(Future.delayed(_keyboardRevealDelay, jumpToBottom)); - unawaited(Future.delayed(_keyboardRevealSettleDelay, jumpToBottom)); - } - - Future _dispatchMessage(String text, ActiveSession viewSession) async { - final controller = ref.read(activeSessionControllerProvider.notifier); - final targetThreadId = widget.sessionId ?? _sessionThreadId(viewSession); - final selectedProfile = _dispatchProfile(targetThreadId); - // AgentProfile selection: for new chats (no thread yet), use the - // preferred agent from the profile or global preference. For existing - // sessions, fall back through profile → widget.agent → session agent → - // global preference. - final dispatchAgent = - selectedProfile?.runtimeAgent ?? - widget.agent ?? - _sessionAgent(viewSession) ?? - ref.read(preferredAgentProvider); - if (dispatchAgent == null) { - _showThreadInfo(context, '请先选择一个 Agent'); - return; - } - - final optimisticId = _enqueueOptimisticMessage(text); - if (selectedProfile?.hostDeviceId case final hostId?) { - await ref.read(activeMacProvider.notifier).setActive(hostId); - } - - // Unified send path: all messages go through sendChatMessage (via - // sendUserMessage on the wire). The server handles session creation - // when sessionId is empty and state-based dispatch (turn/start vs - // turn/steer) when a session already exists. - final sessionId = targetThreadId ?? ''; - final error = await controller.send( - agent: dispatchAgent, - text: text, - dispatch: () => ref - .read(threadCommandsProvider) - .sendUserMessage(sessionId: sessionId, text: text), - ); - - if (!mounted) return; - if (error != null) { - _markOptimisticMessageFailed(optimisticId); - } else { - _markOptimisticMessageConfirmed(optimisticId); - final startedThreadId = _sessionThreadId( - ref.read(activeSessionControllerProvider), - ); - if (selectedProfile != null && startedThreadId != null) { - await ref - .read(agentProfilesControllerProvider.notifier) - .bindThreadToProfile( - sessionId: startedThreadId, - profileId: selectedProfile.id, - ); - } - } - } - - AgentProfile? _dispatchProfile(String? sessionId) { - final profiles = ref.read(agentProfilesControllerProvider).asData?.value; - if (profiles == null) return null; - if (widget.agentProfileId != null) { - return profiles.profileById(widget.agentProfileId!); - } - if (sessionId != null) { - return profiles.profileForThread(sessionId); - } - return profiles.preferredProfile; - } - - void _onSend(String text, ActiveSession viewSession) { - unawaited(_dispatchMessage(text, viewSession)); - } - - @override - Widget build(BuildContext context) { - final session = ref.watch(activeSessionControllerProvider); - final threadViewState = ref.watch( - threadViewStateControllerProvider(_viewStateId), - ); - final viewSession = _viewSession(session); - final sessionId = _resolvedThreadId(session); - final selectedProfile = widget.agentProfileId != null - ? ref - .watch(agentProfilesControllerProvider) - .asData - ?.value - .profileById(widget.agentProfileId!) - : (sessionId == null - ? ref.watch(preferredAgentProfileProvider) - : ref.watch(threadBoundAgentProfileProvider(sessionId))); - - final body = sessionId == null && threadViewState.optimisticMessages.isEmpty - ? _NewChatEmptyState() - : sessionId == null - ? _LoadingThreadState( - optimisticUserMessages: threadViewState.optimisticMessages, - ) - : _ThreadEventStream( - sessionId: sessionId, - optimisticUserMessages: threadViewState.optimisticMessages, - scroll: _scroll, - stickToBottom: threadViewState.stickToBottom, - showLiveAssistantState: - viewSession is SessionStreaming || - viewSession is SessionSending, - onMetricsChanged: (eventCount, userMessages) => - _handleThreadMetrics(sessionId, eventCount, userMessages), - unreadBelow: threadViewState.unreadBelow, - onJumpToBottom: () { - if (!_scroll.hasClients) return; - unawaited( - _scroll.animateTo( - _scroll.position.maxScrollExtent, - duration: const Duration(milliseconds: 200), - curve: Curves.easeOut, - ), - ); - ref - .read( - threadViewStateControllerProvider(_viewStateId).notifier, - ) - .jumpToBottom(); - }, - ); - - final theme = Theme.of(context); - final colors = context.minosColors; - final scaffoldBg = colors.canvas; - final liveAgent = _sessionAgent(viewSession); - final titleAgent = liveAgent ?? widget.agent; - final subtitle = _sessionSubtitle( - viewSession, - selectedProfile: selectedProfile, - ); - final keyboardInsetBottom = MediaQuery.of(context).viewInsets.bottom; - _syncKeyboardInset( - keyboardInsetBottom, - stick: threadViewState.stickToBottom, - ); - - return Scaffold( - resizeToAvoidBottomInset: false, - backgroundColor: scaffoldBg, - appBar: AppBar( - backgroundColor: colors.surface, - surfaceTintColor: Colors.transparent, - scrolledUnderElevation: 0, - elevation: 0, - shape: Border( - bottom: BorderSide(color: colors.borderSubtle, width: 0.5), - ), - centerTitle: true, - titleSpacing: 0, - title: SizedBox( - width: double.infinity, - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - sessionId == null - ? (selectedProfile?.name ?? '新对话') - : (selectedProfile?.name ?? - (titleAgent == null - ? '会话' - : _agentLabel(titleAgent))), - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w600, - color: colors.textPrimary, - ), - ), - if (subtitle != null) - Text( - subtitle, - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - style: theme.textTheme.bodySmall?.copyWith( - color: colors.textSecondary, - ), - ), - ], - ), - ), - ), - body: SafeArea( - bottom: false, - child: Column( - children: [ - Expanded(child: body), - AnimatedPadding( - duration: const Duration(milliseconds: 220), - curve: Curves.easeOutCubic, - padding: EdgeInsets.only(bottom: keyboardInsetBottom), - child: InputBar( - session: viewSession, - onSend: (t) => _onSend(t, viewSession), - onStop: () => - ref.read(activeSessionControllerProvider.notifier).stop(), - ), - ), - ], - ), - ), - ); - } -} - -AgentName? _sessionAgent(ActiveSession session) { - return switch (session) { - SessionSending(:final agent) => agent, - SessionStreaming(:final agent) => agent, - SessionAwaitingInput(:final agent) => agent, - SessionSuspended(:final agent) => agent, - _ => null, - }; -} - -String? _sessionSubtitle( - ActiveSession session, { - AgentProfile? selectedProfile, -}) { - final profileLabel = selectedProfile == null - ? null - : '${selectedProfile.model} · ${_reasoningLabel(selectedProfile.reasoningEffort)}'; - return switch (session) { - SessionIdle() => profileLabel, - SessionSending(:final agent) => - '${profileLabel ?? _agentLabel(agent)} 发送中…', - SessionStreaming(:final agent) => - '${profileLabel ?? _agentLabel(agent)} 回复中', - SessionAwaitingInput(:final agent) => - '${profileLabel ?? _agentLabel(agent)} 等待输入', - SessionSuspended() => '已暂停', - SessionError() => '出错', - }; -} - -String _reasoningLabel(AgentReasoningEffort effort) { - return switch (effort) { - AgentReasoningEffort.low => 'Low', - AgentReasoningEffort.medium => 'Medium', - AgentReasoningEffort.high => 'High', - }; -} - -String _agentLabel(AgentName agent) { - return switch (agent) { - AgentName.codex => 'Codex', - AgentName.claude => 'Claude', - AgentName.gemini => 'Gemini', - AgentName.opencode => 'OpenCode', - AgentName.grok => 'Grok', - }; -} - -class _NewChatEmptyState extends StatelessWidget { - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final colors = context.minosColors; - return Center( - child: Padding( - padding: const EdgeInsets.all(MinosSpacing.xxl), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.chat_bubble_outline_rounded, - size: 44, - color: colors.textTertiary, - ), - const SizedBox(height: MinosSpacing.md), - Text( - '开始新对话', - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w600, - color: colors.textPrimary, - ), - ), - const SizedBox(height: MinosSpacing.xs), - Text( - '在下方输入消息,Agent 会立刻接管。', - style: theme.textTheme.bodyMedium?.copyWith( - color: colors.textSecondary, - ), - textAlign: TextAlign.center, - ), - ], - ), - ), - ); - } -} - -void _showThreadInfo(BuildContext context, String title) { - showMinosToast(context, title: title); -} - -class _ThreadEventStream extends ConsumerWidget { - const _ThreadEventStream({ - required this.sessionId, - required this.optimisticUserMessages, - required this.scroll, - required this.stickToBottom, - required this.showLiveAssistantState, - required this.onMetricsChanged, - required this.unreadBelow, - required this.onJumpToBottom, - }); - - final String sessionId; - final List optimisticUserMessages; - final ScrollController scroll; - final bool stickToBottom; - final bool showLiveAssistantState; - final void Function(int eventCount, List userMessages) - onMetricsChanged; - final int unreadBelow; - final VoidCallback onJumpToBottom; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final eventsAsync = ref.watch(threadEventsProvider(sessionId)); - return eventsAsync.when( - loading: () => - _LoadingThreadState(optimisticUserMessages: optimisticUserMessages), - error: (e, _) => Center(child: Text('加载失败: $e')), - data: (events) { - WidgetsBinding.instance.addPostFrameCallback((_) { - onMetricsChanged(events.length, _extractUserMessages(events)); - }); - if (events.isEmpty && optimisticUserMessages.isEmpty) { - return const Center(child: Text('暂无消息')); - } - final groups = _GroupedEvents.from( - events, - optimistic: optimisticUserMessages, - showLiveAssistantState: showLiveAssistantState, - ); - final items = groups.items; - return Stack( - children: [ - ListView.builder( - controller: scroll, - padding: const .symmetric(vertical: 8), - itemCount: items.length, - itemBuilder: (_, i) => items[i], - ), - if (unreadBelow > 0) - Positioned( - right: 16, - bottom: 16, - child: FloatingActionButton.small( - onPressed: onJumpToBottom, - child: Badge.count( - count: unreadBelow, - child: const Icon(Icons.arrow_downward), - ), - ), - ), - ], - ); - }, - ); - } - - List _extractUserMessages( - List events, - ) => _extractUserMessageEchoes(events); -} - -/// Quiet placeholder shown while the initial `readThread` future resolves -/// or while a brand-new chat is waiting for `sendChatMessage` to mint a thread -/// id. Optimistic bubbles render in their natural top-to-bottom order; we -/// deliberately drop the centered `CircularProgressIndicator` because the -/// thread provider is now `keepAlive: true` and re-entry usually returns a -/// cached event list within a frame, so a big spinner looked jarring. -class _LoadingThreadState extends StatelessWidget { - const _LoadingThreadState({required this.optimisticUserMessages}); - - final List optimisticUserMessages; - - @override - Widget build(BuildContext context) { - return ListView( - padding: const EdgeInsets.symmetric(vertical: 8), - children: [ - for (final message in optimisticUserMessages) - MessageBubble( - isUser: true, - markdownContent: message.text, - deliveryState: switch (message.status) { - ThreadOptimisticMessageStatus.sending => - MessageDeliveryState.sending, - ThreadOptimisticMessageStatus.failed => - MessageDeliveryState.failed, - _ => MessageDeliveryState.none, - }, - ), - ], - ); - } -} - -/// Translates a flat ordered list of `UiEventMessage`s into chat widgets. -/// -/// Projection rules (timeline-first, matching TUI `ChatState`): -/// -/// - Each content kind is its own row at the **first event** that produced it -/// - Contiguous streaming deltas update that row in place -/// - Text/reasoning interrupted by tools (or each other) opens a **new** row -/// at the timeline tail — intermediate ACP `agent_message_chunk`s are not -/// merged into the later final reply -/// - Only the still-open text segment of a live turn shows a streaming cursor -/// - Tool cards stay visible while the turn is live -/// -/// Optimistic user messages are interleaved by their `anchorEventCount` -/// (events.length at enqueue): each optimistic renders just before the -/// first timeline row whose eventIndex >= its anchor. Anything anchored -/// past the end of the events list trails. -class _GroupedEvents { - _GroupedEvents._(this.items); - final List items; - - factory _GroupedEvents.from( - List events, { - List optimistic = - const [], - bool showLiveAssistantState = false, - }) { - final timeline = buildThreadEventTimeline( - events, - showLiveAssistantState: showLiveAssistantState, - ); - final userEchoes = _extractUserMessageEchoes(events); - - final pendingOptimistic = - optimistic - .where((message) => !threadOptimisticHasEcho(message, userEchoes)) - .toList() - ..sort((a, b) => a.anchorEventCount.compareTo(b.anchorEventCount)); - - Widget optimisticWidget(ThreadOptimisticUserMessage m) => MessageBubble( - isUser: true, - markdownContent: m.text, - deliveryState: switch (m.status) { - ThreadOptimisticMessageStatus.sending => MessageDeliveryState.sending, - ThreadOptimisticMessageStatus.failed => MessageDeliveryState.failed, - _ => MessageDeliveryState.none, - }, - ); - - final ordered = []; - var optimisticIdx = 0; - - void flushOptimisticThrough(int eventIndex) { - while (optimisticIdx < pendingOptimistic.length && - pendingOptimistic[optimisticIdx].anchorEventCount <= eventIndex) { - ordered.add(optimisticWidget(pendingOptimistic[optimisticIdx])); - optimisticIdx++; - } - } - - for (final row in timeline) { - flushOptimisticThrough(row.eventIndex); - ordered.add(_widgetForTimelineItem(row)); - } - - while (optimisticIdx < pendingOptimistic.length) { - ordered.add(optimisticWidget(pendingOptimistic[optimisticIdx])); - optimisticIdx++; - } - - return _GroupedEvents._(ordered); - } -} - -Widget _widgetForTimelineItem(ThreadTimelineItem item) { - return switch (item) { - TimelineUserMessage(:final text) => MessageBubble( - isUser: true, - markdownContent: text, - isStreaming: false, - ), - TimelineAssistantText(:final messageId, :final text, :final showCursor) => - StreamingText( - messageId: messageId, - accumulatedText: text, - showCursor: showCursor, - ), - TimelineAssistantPlaceholder(:final messageId) => StreamingText( - messageId: messageId, - accumulatedText: '', - showCursor: true, - ), - TimelineReasoning(:final messageId, :final text, :final isLive) => - ReasoningSection( - messageId: messageId, - reasoningText: text, - initiallyExpanded: isLive, - ), - TimelineToolCall( - :final toolCallId, - :final name, - :final argsJson, - :final output, - :final isError, - ) => - ToolCallCard( - toolCallId: toolCallId, - toolName: name, - argsJson: argsJson, - output: output, - isError: isError, - ), - TimelineError(:final code, :final message) => _ErrorBubble( - code: code, - message: message, - ), - TimelineClosed() => const _ClosedDivider(), - }; -} - -List _extractUserMessageEchoes( - List events, { - Map? roleByMsg, - Map? textByMsg, - Map? messageStartIndex, -}) { - final roles = roleByMsg ?? {}; - final texts = textByMsg ?? {}; - final starts = messageStartIndex ?? {}; - - if (roleByMsg == null || textByMsg == null || messageStartIndex == null) { - for (var i = 0; i < events.length; i++) { - switch (events[i]) { - case UiEventMessage_MessageStarted(:final messageId, :final role): - starts.putIfAbsent(messageId, () => i); - roles[messageId] = role; - texts.putIfAbsent(messageId, StringBuffer.new); - case UiEventMessage_TextDelta(:final messageId, :final text): - texts - .putIfAbsent(messageId, StringBuffer.new) - .write(text.renderPreview()); - case UiEventMessage_TextReplace(:final messageId, :final text): - texts[messageId] = StringBuffer(text.renderPreview()); - default: - break; - } - } - } - - final echoes = []; - for (final entry in roles.entries) { - if (entry.value != MessageRole.user) continue; - final text = texts[entry.key]?.toString() ?? ''; - if (text.trim().isEmpty) continue; - echoes.add( - ThreadUserMessageEcho(eventIndex: starts[entry.key] ?? 0, text: text), - ); - } - echoes.sort((a, b) => a.eventIndex.compareTo(b.eventIndex)); - return echoes; -} - -class _ClosedDivider extends StatelessWidget { - const _ClosedDivider(); - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Padding( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 32), - child: Row( - children: [ - Expanded(child: Divider(color: theme.colorScheme.outlineVariant)), - const SizedBox(width: 8), - Text( - 'session ended', - style: theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - const SizedBox(width: 8), - Expanded(child: Divider(color: theme.colorScheme.outlineVariant)), - ], - ), - ); - } -} - -class _ErrorBubble extends StatelessWidget { - const _ErrorBubble({required this.code, required this.message}); - final String code; - final String message; - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - child: Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: theme.colorScheme.errorContainer, - borderRadius: BorderRadius.circular(10), - ), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Icon( - Icons.error_outline, - color: theme.colorScheme.onErrorContainer, - ), - const SizedBox(width: 8), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - code, - style: theme.textTheme.labelMedium?.copyWith( - color: theme.colorScheme.onErrorContainer, - fontWeight: FontWeight.bold, - ), - ), - Text( - message, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onErrorContainer, - ), - ), - ], - ), - ), - ], - ), - ), - ); - } -} diff --git a/apps/mobile/lib/ui/features/chat/widgets/input_bar.dart b/apps/mobile/lib/ui/features/chat/widgets/input_bar.dart deleted file mode 100644 index d59cdaec..00000000 --- a/apps/mobile/lib/ui/features/chat/widgets/input_bar.dart +++ /dev/null @@ -1,253 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:minos/domain/active_session.dart'; -import 'package:minos/ui/theme/theme.dart'; - -final _inputBarDraftProvider = NotifierProvider.autoDispose - .family<_InputBarDraftController, String, String>( - _InputBarDraftController.new, - ); - -class _InputBarDraftController extends Notifier { - _InputBarDraftController(String _); - - @override - String build() => ''; - - void setText(String text) { - if (state == text) return; - state = text; - } -} - -/// Sticky bottom composer for the chat surface. -class InputBar extends ConsumerStatefulWidget { - const InputBar({ - super.key, - required this.session, - required this.onSend, - required this.onStop, - }); - - final ActiveSession session; - final ValueChanged onSend; - final VoidCallback onStop; - - @override - ConsumerState createState() => _InputBarState(); -} - -class _InputBarState extends ConsumerState { - static const int _maxChars = 8000; - - final TextEditingController _ctl = TextEditingController(); - final FocusNode _focus = FocusNode(); - late final String _composerId = 'input-bar-${identityHashCode(this)}'; - - @override - void initState() { - super.initState(); - _ctl.addListener(_syncDraftText); - } - - @override - void dispose() { - _ctl.removeListener(_syncDraftText); - _ctl.dispose(); - _focus.dispose(); - super.dispose(); - } - - void _syncDraftText() { - ref.read(_inputBarDraftProvider(_composerId).notifier).setText(_ctl.text); - } - - bool get _isStreaming => - widget.session is SessionStreaming || widget.session is SessionSending; - - bool _canSend(String draft) { - final s = widget.session; - final composable = - s is SessionIdle || - s is SessionAwaitingInput || - s is SessionSuspended || - s is SessionError; - if (!composable) return false; - final trimmed = draft.trim(); - if (trimmed.isEmpty) return false; - if (draft.length > _maxChars) return false; - return true; - } - - void _submit() { - final text = _ctl.text; - if (!_canSend(text)) return; - widget.onSend(text); - _ctl.clear(); - } - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final theme = Theme.of(context); - final helperText = _isStreaming ? 'Agent 正在回复,可随时停止。' : '准备好后发送,可连续追问。'; - - return SafeArea( - top: false, - child: DecoratedBox( - decoration: BoxDecoration( - color: colors.surface, - border: Border(top: BorderSide(color: colors.borderSubtle)), - ), - child: Padding( - padding: const EdgeInsets.fromLTRB( - MinosSpacing.md, - MinosSpacing.md, - MinosSpacing.md, - MinosSpacing.md, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - decoration: BoxDecoration( - color: colors.surfaceMuted, - borderRadius: MinosRadii.mdAll, - border: Border.all(color: colors.borderSubtle), - ), - padding: const EdgeInsets.fromLTRB(12, 4, 4, 4), - child: Row( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Expanded( - child: TextField( - controller: _ctl, - focusNode: _focus, - minLines: 1, - maxLines: 6, - enabled: !_isStreaming, - textCapitalization: TextCapitalization.sentences, - keyboardType: TextInputType.multiline, - textInputAction: TextInputAction.newline, - style: theme.textTheme.bodyMedium?.copyWith( - height: 1.35, - ), - decoration: InputDecoration( - hintText: '继续追问,或让它帮你完成下一步…', - hintStyle: theme.textTheme.bodyMedium?.copyWith( - color: colors.textTertiary, - ), - border: InputBorder.none, - enabledBorder: InputBorder.none, - focusedBorder: InputBorder.none, - filled: false, - contentPadding: const EdgeInsets.symmetric( - vertical: 10, - ), - ), - ), - ), - Consumer( - builder: (context, ref, _) { - final draft = ref.watch( - _inputBarDraftProvider(_composerId), - ); - final canSend = _canSend(draft); - return _ComposerActionButton( - icon: _isStreaming - ? CupertinoIcons.stop_circle_fill - : CupertinoIcons.arrow_up_circle_fill, - onTap: _isStreaming - ? widget.onStop - : (canSend ? _submit : null), - destructive: _isStreaming, - enabled: _isStreaming || canSend, - ); - }, - ), - ], - ), - ), - const SizedBox(height: MinosSpacing.sm), - _ComposerStatusRow( - composerId: _composerId, - isStreaming: _isStreaming, - helperText: helperText, - maxChars: _maxChars, - ), - ], - ), - ), - ), - ); - } -} - -class _ComposerStatusRow extends ConsumerWidget { - const _ComposerStatusRow({ - required this.composerId, - required this.isStreaming, - required this.helperText, - required this.maxChars, - }); - - final String composerId; - final bool isStreaming; - final String helperText; - final int maxChars; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final colors = context.minosColors; - final draftLength = ref.watch( - _inputBarDraftProvider(composerId).select((draft) => draft.length), - ); - final overLimit = draftLength > maxChars; - - return Row( - children: [ - Expanded( - child: Text( - overLimit ? '$draftLength / $maxChars 字符' : helperText, - style: Theme.of(context).textTheme.bodySmall?.copyWith( - color: overLimit ? colors.danger : colors.textTertiary, - ), - ), - ), - if (!overLimit && !isStreaming) - Icon(CupertinoIcons.sparkles, size: 14, color: colors.textTertiary), - ], - ); - } -} - -class _ComposerActionButton extends StatelessWidget { - const _ComposerActionButton({ - required this.icon, - required this.onTap, - required this.destructive, - required this.enabled, - }); - - final IconData icon; - final VoidCallback? onTap; - final bool destructive; - final bool enabled; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final color = !enabled - ? colors.textTertiary.withValues(alpha: 0.45) - : (destructive ? colors.danger : colors.accent); - - return IconButton( - onPressed: enabled ? onTap : null, - icon: Icon(icon, color: color, size: 30), - visualDensity: VisualDensity.compact, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 40, minHeight: 40), - ); - } -} diff --git a/apps/mobile/lib/ui/features/chat/widgets/message_bubble.dart b/apps/mobile/lib/ui/features/chat/widgets/message_bubble.dart deleted file mode 100644 index 4f6b4834..00000000 --- a/apps/mobile/lib/ui/features/chat/widgets/message_bubble.dart +++ /dev/null @@ -1,290 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; -import 'package:minos/ui/theme/theme.dart'; - -enum MessageDeliveryState { none, sending, failed } - -enum MessageBubbleStatusTone { neutral, info, success, error } - -class MessageBubbleStatusLine { - const MessageBubbleStatusLine({ - required this.icon, - required this.label, - this.tone = MessageBubbleStatusTone.neutral, - }); - - final IconData icon; - final String label; - final MessageBubbleStatusTone tone; -} - -/// Chat bubble for the golden-path transcript. -/// -/// User messages sit on the right as accent bubbles; assistant messages use a -/// soft full-width transcript rail with a compact bot glyph. -class MessageBubble extends StatelessWidget { - const MessageBubble({ - super.key, - required this.isUser, - required this.markdownContent, - this.isStreaming = false, - this.deliveryState = MessageDeliveryState.none, - this.statusLines = const [], - }); - - final bool isUser; - final String markdownContent; - final bool isStreaming; - final MessageDeliveryState deliveryState; - final List statusLines; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final colors = context.minosColors; - - final bg = isUser ? colors.userBubble : colors.assistantBubble; - final fg = isUser ? colors.userBubbleForeground : colors.textPrimary; - - final radius = BorderRadius.only( - topLeft: const Radius.circular(MinosRadii.md), - topRight: const Radius.circular(MinosRadii.md), - bottomLeft: Radius.circular(isUser ? MinosRadii.md : MinosRadii.xs), - bottomRight: Radius.circular(isUser ? MinosRadii.xs : MinosRadii.md), - ); - - final content = Column( - crossAxisAlignment: isUser - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - MarkdownBody( - data: markdownContent, - selectable: true, - styleSheet: MarkdownStyleSheet.fromTheme(theme).copyWith( - p: theme.textTheme.bodyMedium?.copyWith(color: fg, height: 1.48), - code: theme.textTheme.bodySmall?.copyWith( - fontFamily: 'monospace', - color: fg, - backgroundColor: isUser - ? Colors.white.withValues(alpha: 0.18) - : colors.surfaceMuted, - ), - a: TextStyle( - color: isUser ? Colors.white : colors.accent, - decoration: TextDecoration.underline, - ), - ), - ), - if (statusLines.isNotEmpty) - Padding( - padding: const EdgeInsets.only(top: MinosSpacing.sm), - child: _MessageStatusLines(lines: statusLines), - ), - if (isStreaming) - Padding( - padding: EdgeInsets.only( - top: statusLines.isEmpty ? MinosSpacing.sm : MinosSpacing.sm, - ), - child: _StreamingCursor(color: fg), - ), - ], - ); - - final bubble = isUser - ? ConstrainedBox( - constraints: BoxConstraints( - maxWidth: MediaQuery.of(context).size.width * 0.84, - ), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), - decoration: BoxDecoration(color: bg, borderRadius: radius), - child: content, - ), - ) - : Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), - decoration: BoxDecoration( - color: bg, - borderRadius: radius, - border: Border.all(color: colors.borderSubtle), - ), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - width: 26, - height: 26, - decoration: BoxDecoration( - color: colors.accentSoft, - borderRadius: MinosRadii.xsAll, - ), - alignment: Alignment.center, - child: Icon( - CupertinoIcons.sparkles, - size: 14, - color: colors.accent, - ), - ), - const SizedBox(width: 10), - Expanded( - child: Padding( - padding: const EdgeInsets.only(top: 1), - child: content, - ), - ), - ], - ), - ); - - final showIndicator = isUser && deliveryState != MessageDeliveryState.none; - - final child = isUser - ? Row( - mainAxisAlignment: MainAxisAlignment.end, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - if (showIndicator) - Padding( - padding: const EdgeInsets.only(right: 6), - child: _DeliveryStateIndicator( - state: deliveryState, - color: colors.textSecondary, - ), - ), - Flexible(child: bubble), - ], - ) - : bubble; - - return Padding( - padding: EdgeInsets.fromLTRB(isUser ? 48 : 12, 4, isUser ? 12 : 12, 4), - child: child, - ); - } -} - -class _DeliveryStateIndicator extends StatelessWidget { - const _DeliveryStateIndicator({required this.state, required this.color}); - - final MessageDeliveryState state; - final Color color; - - @override - Widget build(BuildContext context) { - return switch (state) { - MessageDeliveryState.sending => SizedBox( - width: 14, - height: 14, - child: CircularProgressIndicator( - strokeWidth: 1.8, - valueColor: AlwaysStoppedAnimation(color), - ), - ), - MessageDeliveryState.failed => Icon( - Icons.error_outline, - size: 14, - color: color, - ), - MessageDeliveryState.none => const SizedBox.shrink(), - }; - } -} - -class _StreamingCursor extends StatefulWidget { - const _StreamingCursor({required this.color}); - final Color color; - - @override - State<_StreamingCursor> createState() => _StreamingCursorState(); -} - -class _StreamingCursorState extends State<_StreamingCursor> - with SingleTickerProviderStateMixin { - late final AnimationController _ctl = AnimationController( - vsync: this, - duration: const Duration(milliseconds: 700), - )..repeat(reverse: true); - - @override - void dispose() { - _ctl.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return FadeTransition( - opacity: _ctl, - child: Container( - key: const ValueKey('streaming-cursor'), - width: 6, - height: 12, - decoration: BoxDecoration( - color: widget.color, - borderRadius: BorderRadius.circular(2), - ), - ), - ); - } -} - -class _MessageStatusLines extends StatelessWidget { - const _MessageStatusLines({required this.lines}); - - final List lines; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final colors = context.minosColors; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (var index = 0; index < lines.length; index++) ...[ - if (index > 0) const SizedBox(height: 4), - Row( - children: [ - Icon( - lines[index].icon, - size: 14, - color: _statusColor(colors, lines[index].tone), - ), - const SizedBox(width: 6), - Expanded( - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 180), - switchInCurve: Curves.easeOut, - switchOutCurve: Curves.easeIn, - child: Text( - lines[index].label, - key: ValueKey(lines[index].label), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.labelSmall?.copyWith( - color: _statusColor(colors, lines[index].tone), - fontWeight: FontWeight.w500, - height: 1.2, - ), - ), - ), - ), - ], - ), - ], - ], - ); - } - - static Color _statusColor(MinosColors colors, MessageBubbleStatusTone tone) { - return switch (tone) { - MessageBubbleStatusTone.info => colors.accent, - MessageBubbleStatusTone.success => colors.success, - MessageBubbleStatusTone.error => colors.danger, - MessageBubbleStatusTone.neutral => colors.textSecondary, - }; - } -} diff --git a/apps/mobile/lib/ui/features/chat/widgets/message_meta_row.dart b/apps/mobile/lib/ui/features/chat/widgets/message_meta_row.dart deleted file mode 100644 index a67ac990..00000000 --- a/apps/mobile/lib/ui/features/chat/widgets/message_meta_row.dart +++ /dev/null @@ -1,59 +0,0 @@ -import 'package:flutter/material.dart'; - -import 'package:minos/src/rust/api/minos.dart' show AgentName; - -/// Caption row that anchors a message to the wall clock (timestamp) and -/// the model that produced it. Rendered above an assistant bubble or -/// below a user bubble depending on caller layout — the row itself is -/// alignment-neutral. -class MessageMetaRow extends StatelessWidget { - const MessageMetaRow({super.key, required this.timestamp, this.agent}); - - /// Wall-clock time (UTC) the message originated. Rendered as - /// HH:MM in the local zone for readability. - final DateTime timestamp; - - /// The agent the message came from. Null for user messages — only - /// the timestamp is shown then. - final AgentName? agent; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final style = theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ); - final time = _formatHHMM(timestamp.toLocal()); - return Padding( - padding: const .symmetric(horizontal: 16, vertical: 2), - child: Row( - mainAxisSize: .min, - children: [ - Text(time, style: style), - if (agent != null) ...[ - const SizedBox(width: 6), - Text('•', style: style), - const SizedBox(width: 6), - Text(_agentLabel(agent!), style: style), - ], - ], - ), - ); - } - - static String _formatHHMM(DateTime dt) { - final hh = dt.hour.toString().padLeft(2, '0'); - final mm = dt.minute.toString().padLeft(2, '0'); - return '$hh:$mm'; - } - - static String _agentLabel(AgentName a) { - return switch (a) { - AgentName.codex => 'Codex', - AgentName.claude => 'Claude', - AgentName.gemini => 'Gemini', - AgentName.opencode => 'OpenCode', - AgentName.grok => 'Grok', - }; - } -} diff --git a/apps/mobile/lib/ui/features/chat/widgets/reasoning_section.dart b/apps/mobile/lib/ui/features/chat/widgets/reasoning_section.dart deleted file mode 100644 index 4e1aec5c..00000000 --- a/apps/mobile/lib/ui/features/chat/widgets/reasoning_section.dart +++ /dev/null @@ -1,64 +0,0 @@ -import 'package:flutter/material.dart'; - -/// Collapsible card that hosts the assistant's chain-of-thought -/// (`UiEventMessage_ReasoningDelta` accumulation). Collapsed by default -/// — reasoning is auxiliary; the user opts in to see it. The body -/// renders monospace italic to differentiate from regular markdown. -class ReasoningSection extends StatelessWidget { - const ReasoningSection({ - super.key, - required this.messageId, - required this.reasoningText, - this.initiallyExpanded = false, - }); - - /// The assistant `message_id` whose reasoning deltas accumulate here. - final String messageId; - - /// Concatenation of every `UiEventMessage_ReasoningDelta.text` in - /// arrival order. - final String reasoningText; - - /// Default expansion state. ThreadViewPage keeps reasoning collapsed - /// so the chat surface isn't dominated by it. - final bool initiallyExpanded; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Padding( - padding: const .symmetric(horizontal: 12, vertical: 4), - child: Theme( - // Strip the default ExpansionTile divider — it clashes with the - // surrounding bubble layout. - data: theme.copyWith(dividerColor: Colors.transparent), - child: ExpansionTile( - tilePadding: const .symmetric(horizontal: 8), - childrenPadding: const .fromLTRB(12, 0, 12, 12), - initiallyExpanded: initiallyExpanded, - leading: const Icon(Icons.psychology_outlined, size: 18), - title: Text( - 'Reasoning', - style: theme.textTheme.labelMedium?.copyWith( - fontStyle: .italic, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - children: [ - Align( - alignment: .centerLeft, - child: SelectableText( - reasoningText.isEmpty ? '(empty)' : reasoningText, - style: theme.textTheme.bodySmall?.copyWith( - fontFamily: 'monospace', - fontStyle: .italic, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ), - ], - ), - ), - ); - } -} diff --git a/apps/mobile/lib/ui/features/chat/widgets/streaming_text.dart b/apps/mobile/lib/ui/features/chat/widgets/streaming_text.dart deleted file mode 100644 index c2d6fdcf..00000000 --- a/apps/mobile/lib/ui/features/chat/widgets/streaming_text.dart +++ /dev/null @@ -1,53 +0,0 @@ -import 'package:flutter/material.dart'; - -import 'message_bubble.dart'; - -/// Renders an in-flight assistant message as a [MessageBubble] whose -/// markdown content grows in place as `accumulatedText` accumulates. -/// -/// The widget itself is dumb — it owns no event-listening logic. The -/// parent (e.g. `ThreadViewPage`) is responsible for grouping -/// `UiEventMessage_TextDelta`s by `messageId` and concatenating them -/// before passing them in, and for flipping `isComplete=true` when the -/// matching `UiEventMessage_MessageCompleted` arrives. -/// -/// When [accumulatedText] is empty, a "thinking…" placeholder is shown -/// so the bubble has visible content while the first delta is in -/// flight; the [isComplete] flag still controls whether the streaming -/// cursor renders. -class StreamingText extends StatelessWidget { - const StreamingText({ - super.key, - required this.messageId, - required this.accumulatedText, - required this.showCursor, - this.statusLines = const [], - }); - - /// The `message_id` from the bridging `UiEventMessage`s. Carried for - /// debugging / future per-message actions; the widget itself doesn't - /// rely on it for rendering. - final String messageId; - - /// Concatenated text from every `UiEventMessage_TextDelta` for this - /// message, in arrival order. - final String accumulatedText; - - /// True while this message owns the live cursor. - final bool showCursor; - - /// Compact activity rows rendered below the message body while the turn is - /// still active. - final List statusLines; - - @override - Widget build(BuildContext context) { - final hasText = accumulatedText.isNotEmpty; - return MessageBubble( - isUser: false, - markdownContent: hasText ? accumulatedText : '_处理中…_', - isStreaming: showCursor, - statusLines: statusLines, - ); - } -} diff --git a/apps/mobile/lib/ui/features/chat/widgets/tool_call_card.dart b/apps/mobile/lib/ui/features/chat/widgets/tool_call_card.dart deleted file mode 100644 index 5358b548..00000000 --- a/apps/mobile/lib/ui/features/chat/widgets/tool_call_card.dart +++ /dev/null @@ -1,224 +0,0 @@ -import 'dart:convert'; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_highlight/flutter_highlight.dart'; -import 'package:flutter_highlight/themes/atom-one-dark.dart'; -import 'package:flutter_highlight/themes/atom-one-light.dart'; -import 'package:minos/ui/theme/theme.dart'; - -/// Collapsed-by-default tool call card for the transcript stream. -class ToolCallCard extends StatefulWidget { - const ToolCallCard({ - super.key, - required this.toolCallId, - required this.toolName, - required this.argsJson, - this.output, - this.isError = false, - }); - - final String toolCallId; - final String toolName; - final String argsJson; - final String? output; - final bool isError; - - @override - State createState() => _ToolCallCardState(); -} - -class _ToolCallCardState extends State { - bool _expanded = false; - - bool get _inFlight => widget.output == null; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final colors = context.minosColors; - final statusLabel = _inFlight - ? 'running…' - : (widget.isError ? 'failed' : 'done'); - final statusColor = _inFlight - ? colors.accent - : (widget.isError ? colors.danger : colors.success); - - return Padding( - padding: const EdgeInsets.symmetric( - horizontal: MinosSpacing.md, - vertical: MinosSpacing.xs, - ), - child: DecoratedBox( - decoration: BoxDecoration( - color: colors.surface, - borderRadius: MinosRadii.smAll, - border: Border.all(color: colors.borderSubtle), - ), - child: Column( - children: [ - Material( - color: Colors.transparent, - child: InkWell( - borderRadius: MinosRadii.smAll, - onTap: () => setState(() => _expanded = !_expanded), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: MinosSpacing.md, - vertical: MinosSpacing.md, - ), - child: Row( - children: [ - _StatusIcon(inFlight: _inFlight, isError: widget.isError), - const SizedBox(width: MinosSpacing.sm), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - widget.toolName, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleSmall, - ), - const SizedBox(height: 2), - Text( - statusLabel, - style: theme.textTheme.labelSmall?.copyWith( - color: statusColor, - ), - ), - ], - ), - ), - Icon( - _expanded - ? CupertinoIcons.chevron_up - : CupertinoIcons.chevron_down, - size: 14, - color: colors.textTertiary, - ), - ], - ), - ), - ), - ), - if (_expanded) - Padding( - padding: const EdgeInsets.fromLTRB( - MinosSpacing.md, - 0, - MinosSpacing.md, - MinosSpacing.md, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _LabeledBlock( - label: 'args', - child: HighlightView( - _prettyJson(widget.argsJson), - language: 'json', - theme: colors.isDark - ? atomOneDarkTheme - : atomOneLightTheme, - padding: const EdgeInsets.all(MinosSpacing.sm), - textStyle: const TextStyle( - fontFamily: 'monospace', - fontSize: 12, - ), - ), - ), - if (widget.output != null) ...[ - const SizedBox(height: MinosSpacing.sm), - _LabeledBlock( - label: widget.isError ? 'error' : 'output', - child: SelectableText( - widget.output!, - style: theme.textTheme.bodySmall?.copyWith( - fontFamily: 'monospace', - color: widget.isError ? colors.danger : null, - ), - ), - ), - ], - ], - ), - ), - ], - ), - ), - ); - } - - static String _prettyJson(String raw) { - try { - final decoded = jsonDecode(raw); - return const JsonEncoder.withIndent(' ').convert(decoded); - } catch (_) { - return raw; - } - } -} - -class _StatusIcon extends StatelessWidget { - const _StatusIcon({required this.inFlight, required this.isError}); - final bool inFlight; - final bool isError; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - if (inFlight) { - return SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator(strokeWidth: 2, color: colors.accent), - ); - } - if (isError) { - return Icon( - CupertinoIcons.xmark_circle_fill, - size: 18, - color: colors.danger, - ); - } - return Icon( - CupertinoIcons.checkmark_circle_fill, - size: 18, - color: colors.success, - ); - } -} - -class _LabeledBlock extends StatelessWidget { - const _LabeledBlock({required this.label, required this.child}); - final String label; - final Widget child; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final colors = context.minosColors; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text( - label, - style: theme.textTheme.labelSmall?.copyWith( - color: colors.textTertiary, - ), - ), - const SizedBox(height: MinosSpacing.xs), - Container( - decoration: BoxDecoration( - color: colors.surfaceMuted, - borderRadius: MinosRadii.xsAll, - ), - padding: const EdgeInsets.all(MinosSpacing.xs), - child: child, - ), - ], - ); - } -} diff --git a/apps/mobile/lib/ui/features/projects/projects.dart b/apps/mobile/lib/ui/features/projects/projects.dart deleted file mode 100644 index b70d8ce0..00000000 --- a/apps/mobile/lib/ui/features/projects/projects.dart +++ /dev/null @@ -1,18 +0,0 @@ -/// Feature: Projects -/// -/// Project management — list, create, rename, delete projects and their -/// associated sessions. Discord-style project → thread hierarchy. -/// -/// View Models: -/// - [ProjectList] (application/project_providers.dart) -/// - [ProjectSessions] (application/project_providers.dart) -/// - [SelectedProject] (application/project_providers.dart) -/// -/// Views: -/// - [ProjectListPage] -/// - [ProjectDetailPage] -library; - -export 'package:minos/application/project_providers.dart'; -export 'package:minos/ui/features/projects/views/project_detail_page.dart'; -export 'package:minos/ui/features/projects/views/project_list_page.dart'; diff --git a/apps/mobile/lib/ui/features/projects/views/project_detail_page.dart b/apps/mobile/lib/ui/features/projects/views/project_detail_page.dart deleted file mode 100644 index 85af9861..00000000 --- a/apps/mobile/lib/ui/features/projects/views/project_detail_page.dart +++ /dev/null @@ -1,536 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; -import 'package:minos/application/agent_profiles_provider.dart'; -import 'package:minos/application/flutter_log.dart'; -import 'package:minos/application/project_providers.dart'; -import 'package:minos/application/thread_commands.dart'; -import 'package:minos/application/ui_state_providers.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:minos/ui/core/widgets/error_feedback.dart'; -import 'package:minos/ui/core/widgets/minos_toast.dart'; -import 'package:minos/ui/features/chat/views/thread_view_page.dart'; -import 'package:minos/ui/features/shell/router.dart'; - -/// Discord-style project detail page. -/// Shows a sidebar-like thread/channel list on the left with the project name -/// at the top. Tapping a session opens the chat view. -/// Swipe-back (iOS gesture) returns to the project list. -class ProjectDetailPage extends ConsumerWidget { - const ProjectDetailPage({ - super.key, - required this.projectId, - required this.projectName, - }); - - final String projectId; - final String projectName; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final threadsAsync = ref.watch(projectSessionsProvider(projectId)); - final selectedThreadId = ref.watch( - selectedProjectThreadProvider(projectId), - ); - final isWide = MediaQuery.of(context).size.width > 600; - - if (isWide) { - // Tablet/landscape: side-by-side layout - return Scaffold( - backgroundColor: _scaffoldBg(context), - body: Row( - children: [ - SizedBox( - width: 280, - child: _ChannelSidebar( - projectId: projectId, - projectName: projectName, - threadsAsync: threadsAsync, - selectedThreadId: selectedThreadId, - onThreadSelected: (id) => ref - .read(selectedProjectThreadProvider(projectId).notifier) - .select(id), - onNewThread: () => _startNewThread(context, ref), - onDeleteThread: (id) => _deleteThread(context, ref, id), - ), - ), - const VerticalDivider(width: 1), - Expanded( - child: selectedThreadId != null - ? ThreadViewPage(sessionId: selectedThreadId) - : const _NoThreadSelected(), - ), - ], - ), - ); - } - - // Phone: full-screen channel list, push to thread view - return Scaffold( - backgroundColor: _scaffoldBg(context), - body: _ChannelSidebar( - projectId: projectId, - projectName: projectName, - threadsAsync: threadsAsync, - selectedThreadId: selectedThreadId, - onThreadSelected: (id) { - ref - .read(selectedProjectThreadProvider(projectId).notifier) - .select(id); - unawaited(context.push('/thread/$id')); - }, - onNewThread: () => _startNewThread(context, ref), - onDeleteThread: (id) => _deleteThread(context, ref, id), - ), - ); - } - - Future _startNewThread(BuildContext context, WidgetRef ref) async { - final preferredProfile = ref.read(preferredAgentProfileProvider); - - // Show a simple prompt dialog - final promptController = TextEditingController(); - final displayName = preferredProfile?.name ?? 'Codex'; - - final result = await showDialog( - context: context, - builder: (ctx) => AlertDialog( - title: Text('新建会话 ($displayName)'), - content: TextField( - controller: promptController, - autofocus: true, - maxLines: 3, - decoration: const InputDecoration( - hintText: '输入你的问题或任务...', - border: OutlineInputBorder(), - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(ctx), - child: const Text('取消'), - ), - FilledButton( - onPressed: () => Navigator.pop(ctx, promptController.text.trim()), - child: const Text('开始'), - ), - ], - ), - ); - - if (result == null || result.isEmpty) return; - if (!context.mounted) return; - logFlutterInfo( - 'project_detail', - 'start project thread requested projectId=$projectId promptLength=${result.length}', - ); - - // Start agent in project — in the refactored architecture, mobile - // sends messages directly via sendUserMessage. The host auto-creates - // a session when session_id is empty. - try { - await ref - .read(threadCommandsProvider) - .sendUserMessage(sessionId: '', text: result); - - // Refresh the session list - ref.invalidate(projectSessionsProvider(projectId)); - - logFlutterInfo( - 'project_detail', - 'project thread dispatch accepted projectId=$projectId', - ); - - if (!context.mounted) return; - - // Navigate to the new thread view (session ID will arrive via events) - unawaited(context.push(AppRoutes.newThread)); - } catch (error) { - if (!context.mounted) return; - showLoggedErrorToast( - context, - target: 'project_detail', - title: '启动会话失败', - error: error, - ); - } - } - - Future _deleteThread( - BuildContext context, - WidgetRef ref, - String sessionId, - ) async { - try { - await ref.read(threadCommandsProvider).deleteThread(sessionId: sessionId); - ref.invalidate(projectSessionsProvider(projectId)); - if (ref.read(selectedProjectThreadProvider(projectId)) == sessionId) { - ref - .read(selectedProjectThreadProvider(projectId).notifier) - .select(null); - } - logFlutterInfo( - 'project_detail', - 'project thread deleted projectId=$projectId sessionId=$sessionId', - ); - if (!context.mounted) return; - showMinosToast(context, title: '会话已删除'); - } catch (error) { - if (!context.mounted) return; - showLoggedErrorToast( - context, - target: 'project_detail', - title: '删除会话失败', - error: error, - ); - } - } -} - -// ─────────────────────────── Channel Sidebar ─────────────────────────── - -class _ChannelSidebar extends ConsumerWidget { - const _ChannelSidebar({ - required this.projectId, - required this.projectName, - required this.threadsAsync, - required this.selectedThreadId, - required this.onThreadSelected, - required this.onNewThread, - required this.onDeleteThread, - }); - - final String projectId; - final String projectName; - final AsyncValue> threadsAsync; - final String? selectedThreadId; - final ValueChanged onThreadSelected; - final VoidCallback onNewThread; - final Future Function(String sessionId) onDeleteThread; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final colorScheme = Theme.of(context).colorScheme; - - return SafeArea( - bottom: false, - child: Column( - crossAxisAlignment: .start, - children: [ - // Project header (Discord-style server name bar) - Container( - padding: const .fromLTRB(16, 12, 8, 12), - decoration: BoxDecoration( - border: Border( - bottom: BorderSide( - color: colorScheme.outlineVariant.withValues(alpha: 0.3), - ), - ), - ), - child: Row( - children: [ - GestureDetector( - onTap: () => Navigator.of(context).maybePop(), - child: Icon( - CupertinoIcons.chevron_back, - size: 20, - color: colorScheme.onSurface, - ), - ), - const SizedBox(width: 8), - Expanded( - child: Text( - projectName, - style: Theme.of( - context, - ).textTheme.titleMedium?.copyWith(fontWeight: .bold), - maxLines: 1, - overflow: .ellipsis, - ), - ), - IconButton( - icon: const Icon(CupertinoIcons.plus, size: 20), - onPressed: onNewThread, - tooltip: '新建会话', - ), - ], - ), - ), - - // Channel category header - Padding( - padding: const .fromLTRB(16, 16, 16, 8), - child: Row( - children: [ - Icon( - CupertinoIcons.number, - size: 14, - color: colorScheme.outline, - ), - const SizedBox(width: 6), - Text( - '会话', - style: Theme.of(context).textTheme.labelSmall?.copyWith( - color: colorScheme.outline, - fontWeight: .w600, - letterSpacing: 0.5, - ), - ), - ], - ), - ), - - // Session list - Expanded( - child: threadsAsync.when( - data: (sessions) => sessions.isEmpty - ? _EmptyThreads(onNewThread: onNewThread) - : RefreshIndicator( - onRefresh: () => ref - .read(projectSessionsProvider(projectId).notifier) - .refresh(), - child: ListView.builder( - padding: const .symmetric(horizontal: 8), - itemCount: sessions.length, - itemBuilder: (context, index) { - final thread = sessions[index]; - final isSelected = - thread.sessionId == selectedThreadId; - return Dismissible( - key: ValueKey(thread.sessionId), - direction: DismissDirection.endToStart, - confirmDismiss: (_) async { - return showDialog( - context: context, - builder: (dialogContext) => AlertDialog( - title: const Text('删除会话'), - content: Text( - '确定要删除「${_threadTitle(thread)}」吗?', - ), - actions: [ - TextButton( - onPressed: () => Navigator.of( - dialogContext, - ).pop(false), - child: const Text('取消'), - ), - TextButton( - onPressed: () => - Navigator.of(dialogContext).pop(true), - child: const Text('删除'), - ), - ], - ), - ); - }, - onDismissed: (_) => - onDeleteThread(thread.sessionId), - background: Container( - margin: const .symmetric(vertical: 1), - padding: const .only(right: 16), - alignment: .centerRight, - decoration: BoxDecoration( - color: Theme.of( - context, - ).colorScheme.errorContainer, - borderRadius: .circular(6), - ), - child: Icon( - CupertinoIcons.trash, - size: 16, - color: Theme.of(context).colorScheme.error, - ), - ), - child: _ThreadChannelTile( - thread: thread, - isSelected: isSelected, - onTap: () => onThreadSelected(thread.sessionId), - ), - ); - }, - ), - ), - loading: () => const Center(child: CircularProgressIndicator()), - error: (e, _) => Center( - child: Padding( - padding: const .all(16), - child: Text( - '加载失败: $e', - style: TextStyle(color: colorScheme.error), - ), - ), - ), - ), - ), - ], - ), - ); - } -} - -// ─────────────────────────── Thread Channel Tile ─────────────────────────── - -class _ThreadChannelTile extends StatelessWidget { - const _ThreadChannelTile({ - required this.thread, - required this.isSelected, - required this.onTap, - }); - - final SessionSummary thread; - final bool isSelected; - final VoidCallback onTap; - - @override - Widget build(BuildContext context) { - final colorScheme = Theme.of(context).colorScheme; - final isEnded = thread.endedAtMs != null; - - return Padding( - padding: const .symmetric(vertical: 1), - child: Material( - color: isSelected - ? colorScheme.primaryContainer.withValues(alpha: 0.4) - : Colors.transparent, - borderRadius: .circular(6), - child: InkWell( - borderRadius: .circular(6), - onTap: onTap, - child: Padding( - padding: const .symmetric(horizontal: 10, vertical: 8), - child: Row( - children: [ - Icon( - isEnded ? CupertinoIcons.chat_bubble : CupertinoIcons.number, - size: 16, - color: isSelected ? colorScheme.primary : colorScheme.outline, - ), - const SizedBox(width: 8), - Expanded( - child: Text( - _threadTitle(thread), - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - fontWeight: isSelected ? .w600 : .normal, - color: isEnded - ? colorScheme.outline - : colorScheme.onSurface, - ), - maxLines: 1, - overflow: .ellipsis, - ), - ), - if (!isEnded) - Container( - width: 8, - height: 8, - decoration: BoxDecoration( - color: _agentColor(thread.agent), - shape: BoxShape.circle, - ), - ), - ], - ), - ), - ), - ), - ); - } - - Color _agentColor(AgentName agent) { - return switch (agent) { - AgentName.codex => Colors.green, - AgentName.claude => Colors.orange, - AgentName.gemini => Colors.blue, - AgentName.opencode => Colors.blueGrey, - AgentName.grok => Colors.amber, - }; - } -} - -String _threadTitle(SessionSummary thread) { - if (thread.title != null && thread.title!.isNotEmpty) { - return thread.title!; - } - final agent = switch (thread.agent) { - AgentName.codex => 'Codex', - AgentName.claude => 'Claude', - AgentName.gemini => 'Gemini', - AgentName.opencode => 'OpenCode', - AgentName.grok => 'Grok', - }; - final time = DateTime.fromMillisecondsSinceEpoch(thread.lastTsMs); - return '$agent · ${time.month}/${time.day} ${time.hour}:${time.minute.toString().padLeft(2, '0')}'; -} - -// ─────────────────────────── Empty States ─────────────────────────── - -class _EmptyThreads extends StatelessWidget { - const _EmptyThreads({required this.onNewThread}); - final VoidCallback onNewThread; - - @override - Widget build(BuildContext context) { - return Center( - child: Column( - mainAxisSize: .min, - children: [ - Icon( - CupertinoIcons.square_pencil, - size: 48, - color: Theme.of(context).colorScheme.outline, - ), - const SizedBox(height: 12), - Text( - '还没有会话', - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - color: Theme.of(context).colorScheme.outline, - ), - ), - const SizedBox(height: 16), - TextButton.icon( - onPressed: onNewThread, - icon: const Icon(CupertinoIcons.plus, size: 16), - label: const Text('新建会话'), - ), - ], - ), - ); - } -} - -class _NoThreadSelected extends StatelessWidget { - const _NoThreadSelected(); - - @override - Widget build(BuildContext context) { - return Center( - child: Column( - mainAxisSize: .min, - children: [ - Icon( - CupertinoIcons.chat_bubble, - size: 48, - color: Theme.of(context).colorScheme.outline, - ), - const SizedBox(height: 12), - Text( - '选择一个会话开始', - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - color: Theme.of(context).colorScheme.outline, - ), - ), - ], - ), - ); - } -} - -Color _scaffoldBg(BuildContext context) { - final brightness = Theme.of(context).brightness; - return brightness == Brightness.dark - ? const Color(0xFF1A1A1D) - : const Color(0xFFF2F3F5); -} diff --git a/apps/mobile/lib/ui/features/projects/views/project_list_page.dart b/apps/mobile/lib/ui/features/projects/views/project_list_page.dart deleted file mode 100644 index 2d9b8eea..00000000 --- a/apps/mobile/lib/ui/features/projects/views/project_list_page.dart +++ /dev/null @@ -1,609 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; -import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/project_providers.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:minos/ui/features/shell/router.dart'; - -/// Full-screen project list — the app's home after login. -/// Tapping a project navigates to [ProjectDetailPage] (Discord-style). -/// Swipe-back from the detail page returns here. -class ProjectListPage extends ConsumerWidget { - const ProjectListPage({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final projectsAsync = ref.watch(projectListProvider); - - return Scaffold( - backgroundColor: _scaffoldBg(context), - body: SafeArea( - bottom: false, - child: Column( - children: [ - _Header(onAdd: () => _showCreateDialog(context, ref)), - Expanded( - child: projectsAsync.when( - data: (projects) => projects.isEmpty - ? _EmptyState(onAdd: () => _showCreateDialog(context, ref)) - : _ProjectGrid(projects: projects), - loading: () => const Center(child: CircularProgressIndicator()), - error: (e, _) => Center( - child: Text( - '加载失败: $e', - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), - ), - ), - ), - ), - ], - ), - ), - ); - } - - void _showCreateDialog(BuildContext context, WidgetRef ref) { - unawaited( - showDialog( - context: context, - builder: (_) => const _CreateProjectDialog(), - ), - ); - } - - static String _slugify(String input) { - return input - .toLowerCase() - .replaceAll(RegExp(r'[^a-z0-9\u4e00-\u9fff]+'), '-') - .replaceAll(RegExp(r'^-+|-+$'), ''); - } -} - -class _CreateProjectDialog extends ConsumerStatefulWidget { - const _CreateProjectDialog(); - - @override - ConsumerState<_CreateProjectDialog> createState() => - _CreateProjectDialogState(); -} - -class _CreateProjectDialogState extends ConsumerState<_CreateProjectDialog> { - final TextEditingController _nameController = TextEditingController(); - final TextEditingController _slugController = TextEditingController(); - final TextEditingController _workspacePathController = - TextEditingController(); - - bool _slugEdited = false; - bool _creating = false; - - @override - void initState() { - super.initState(); - _nameController.addListener(_refresh); - _slugController.addListener(_refresh); - } - - @override - void dispose() { - _nameController.dispose(); - _slugController.dispose(); - _workspacePathController.dispose(); - super.dispose(); - } - - void _refresh() { - if (mounted) { - setState(() {}); - } - } - - @override - Widget build(BuildContext context) { - final activeHostId = ref.watch(activeMacProvider).asData?.value; - final workspacesAsync = ref.watch(hostWorkspacesProvider(activeHostId)); - final canCreate = - _nameController.text.trim().isNotEmpty && - _slugController.text.trim().isNotEmpty && - !_creating; - - return AlertDialog( - title: const Text('新建项目'), - content: SizedBox( - width: 420, - child: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: _nameController, - decoration: const InputDecoration( - labelText: '项目名称', - hintText: '例如: My App', - ), - autofocus: true, - onChanged: _onNameChanged, - ), - const SizedBox(height: 12), - TextField( - controller: _slugController, - decoration: const InputDecoration( - labelText: 'Workspace 标识', - hintText: '例如: my-app', - ), - onChanged: (_) => _slugEdited = true, - ), - const SizedBox(height: 12), - TextField( - controller: _workspacePathController, - decoration: const InputDecoration( - labelText: 'Host 工作区路径', - hintText: '/Users/you/develop/my-app', - ), - ), - const SizedBox(height: 12), - _WorkspacePickerList( - workspacesAsync: workspacesAsync, - onPick: _pickWorkspace, - onRefresh: () => - ref.invalidate(hostWorkspacesProvider(activeHostId)), - ), - ], - ), - ), - ), - actions: [ - TextButton( - onPressed: _creating ? null : () => Navigator.pop(context), - child: const Text('取消'), - ), - FilledButton( - onPressed: canCreate ? _create : null, - child: _creating - ? const SizedBox.square( - dimension: 18, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : const Text('创建'), - ), - ], - ); - } - - void _onNameChanged(String value) { - if (!_slugEdited) { - _slugController.text = ProjectListPage._slugify(value); - } - } - - void _pickWorkspace(HostWorkspaceSummary workspace) { - _workspacePathController.text = workspace.path; - if (_nameController.text.trim().isEmpty) { - _nameController.text = workspace.displayName; - } - if (!_slugEdited || _slugController.text.trim().isEmpty) { - _slugController.text = ProjectListPage._slugify(workspace.displayName); - _slugEdited = false; - } - } - - Future _create() async { - final name = _nameController.text.trim(); - final slug = _slugController.text.trim(); - final workspacePath = _workspacePathController.text.trim(); - if (name.isEmpty || slug.isEmpty) { - return; - } - setState(() => _creating = true); - try { - await ref - .read(projectListProvider.notifier) - .createProject( - name: name, - workspaceSlug: slug, - workspacePath: workspacePath.isEmpty ? null : workspacePath, - ); - if (mounted) { - Navigator.pop(context); - } - } catch (error) { - if (mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text('创建失败: $error'))); - setState(() => _creating = false); - } - } - } -} - -class _WorkspacePickerList extends StatelessWidget { - const _WorkspacePickerList({ - required this.workspacesAsync, - required this.onPick, - required this.onRefresh, - }); - - final AsyncValue workspacesAsync; - final ValueChanged onPick; - final VoidCallback onRefresh; - - @override - Widget build(BuildContext context) { - return workspacesAsync.when( - loading: () => const LinearProgressIndicator(minHeight: 2), - error: (error, _) => Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: onRefresh, - icon: const Icon(CupertinoIcons.arrow_clockwise, size: 16), - label: const Text('重新加载 Host 文件夹'), - ), - ), - data: (response) { - if (response.workspaces.isEmpty) { - return Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: onRefresh, - icon: const Icon(CupertinoIcons.folder_open, size: 16), - label: const Text('Host 文件夹为空'), - ), - ); - } - return ConstrainedBox( - constraints: const BoxConstraints(maxHeight: 220), - child: ListView.separated( - shrinkWrap: true, - itemCount: response.workspaces.length, - separatorBuilder: (_, _) => const Divider(height: 1), - itemBuilder: (context, index) { - final workspace = response.workspaces[index]; - return ListTile( - dense: true, - contentPadding: EdgeInsets.zero, - leading: Icon( - workspace.isGitRepo - ? CupertinoIcons.arrow_branch - : CupertinoIcons.folder, - size: 18, - ), - title: Text( - workspace.displayName, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - subtitle: Text( - workspace.path, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - onTap: () => onPick(workspace), - ); - }, - ), - ); - }, - ); - } -} - -// ─────────────────────────── Header ─────────────────────────── - -class _Header extends StatelessWidget { - const _Header({required this.onAdd}); - final VoidCallback onAdd; - - @override - Widget build(BuildContext context) { - return Padding( - padding: const .symmetric(horizontal: 20, vertical: 12), - child: Row( - children: [ - Text( - '项目', - style: Theme.of( - context, - ).textTheme.headlineMedium?.copyWith(fontWeight: .bold), - ), - const Spacer(), - IconButton( - icon: const Icon(CupertinoIcons.plus, size: 22), - onPressed: onAdd, - ), - ], - ), - ); - } -} - -// ─────────────────────────── Empty State ─────────────────────────── - -class _EmptyState extends StatelessWidget { - const _EmptyState({required this.onAdd}); - final VoidCallback onAdd; - - @override - Widget build(BuildContext context) { - return Center( - child: Column( - mainAxisSize: .min, - children: [ - Icon( - CupertinoIcons.folder_open, - size: 64, - color: Theme.of(context).colorScheme.outline, - ), - const SizedBox(height: 16), - Text( - '还没有项目', - style: Theme.of(context).textTheme.titleMedium?.copyWith( - color: Theme.of(context).colorScheme.outline, - ), - ), - const SizedBox(height: 8), - Text( - '创建一个项目来开始使用 AI 助手', - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - color: Theme.of(context).colorScheme.outline, - ), - ), - const SizedBox(height: 24), - FilledButton.icon( - onPressed: onAdd, - icon: const Icon(CupertinoIcons.plus, size: 16), - label: const Text('新建项目'), - ), - ], - ), - ); - } -} - -// ─────────────────────────── Project Grid ─────────────────────────── - -class _ProjectGrid extends ConsumerWidget { - const _ProjectGrid({required this.projects}); - final List projects; - - @override - Widget build(BuildContext context, WidgetRef ref) { - return RefreshIndicator( - onRefresh: () => ref.read(projectListProvider.notifier).refresh(), - child: ListView.separated( - padding: const .symmetric(horizontal: 16, vertical: 8), - itemCount: projects.length, - separatorBuilder: (_, _) => const SizedBox(height: 8), - itemBuilder: (context, index) { - final project = projects[index]; - return _ProjectCard(project: project); - }, - ), - ); - } -} - -class _ProjectCard extends ConsumerWidget { - const _ProjectCard({required this.project}); - final ProjectSummary project; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final colorScheme = Theme.of(context).colorScheme; - final workspaceLabel = _projectWorkspaceLabel(project); - - return Card( - elevation: 0, - shape: RoundedRectangleBorder( - borderRadius: .circular(12), - side: BorderSide( - color: colorScheme.outlineVariant.withValues(alpha: 0.3), - ), - ), - child: InkWell( - borderRadius: .circular(12), - onTap: () { - ref.read(selectedProjectProvider.notifier).select(project.projectId); - unawaited( - context.push( - '/project/${project.projectId}', - extra: ProjectDetailRouteExtra(projectName: project.name), - ), - ); - }, - onLongPress: () => _showProjectMenu(context, ref), - child: Padding( - padding: const .all(16), - child: Row( - children: [ - Container( - width: 48, - height: 48, - decoration: BoxDecoration( - color: _projectColor( - project.projectId, - ).withValues(alpha: 0.15), - borderRadius: .circular(12), - ), - child: Center( - child: Text( - project.name.isNotEmpty - ? project.name[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - fontWeight: .bold, - color: _projectColor(project.projectId), - ), - ), - ), - ), - const SizedBox(width: 14), - Expanded( - child: Column( - crossAxisAlignment: .start, - children: [ - Text( - project.name, - style: Theme.of( - context, - ).textTheme.titleSmall?.copyWith(fontWeight: .w600), - maxLines: 1, - overflow: .ellipsis, - ), - const SizedBox(height: 4), - Text( - '${project.threadCount} 个会话 · $workspaceLabel', - style: Theme.of(context).textTheme.bodySmall?.copyWith( - color: colorScheme.outline, - ), - maxLines: 1, - overflow: .ellipsis, - ), - ], - ), - ), - Icon( - CupertinoIcons.chevron_right, - size: 18, - color: colorScheme.outline, - ), - ], - ), - ), - ), - ); - } - - void _showProjectMenu(BuildContext context, WidgetRef ref) { - unawaited( - showModalBottomSheet( - context: context, - builder: (ctx) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - leading: const Icon(CupertinoIcons.pencil), - title: const Text('重命名'), - onTap: () { - Navigator.pop(ctx); - _showRenameDialog(context, ref); - }, - ), - ListTile( - leading: Icon( - CupertinoIcons.trash, - color: Theme.of(context).colorScheme.error, - ), - title: Text( - '删除', - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - onTap: () { - Navigator.pop(ctx); - _confirmDelete(context, ref); - }, - ), - ], - ), - ), - ), - ); - } - - void _showRenameDialog(BuildContext context, WidgetRef ref) { - final controller = TextEditingController(text: project.name); - unawaited( - showDialog( - context: context, - builder: (ctx) => AlertDialog( - title: const Text('重命名项目'), - content: TextField( - controller: controller, - autofocus: true, - decoration: const InputDecoration(labelText: '项目名称'), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(ctx), - child: const Text('取消'), - ), - FilledButton( - onPressed: () async { - final name = controller.text.trim(); - if (name.isEmpty) return; - Navigator.pop(ctx); - await ref - .read(projectListProvider.notifier) - .updateProject(projectId: project.projectId, name: name); - }, - child: const Text('确定'), - ), - ], - ), - ), - ); - } - - void _confirmDelete(BuildContext context, WidgetRef ref) { - unawaited( - showDialog( - context: context, - builder: (ctx) => AlertDialog( - title: const Text('删除项目'), - content: Text('确定要删除「${project.name}」吗?项目内的会话不会被删除。'), - actions: [ - TextButton( - onPressed: () => Navigator.pop(ctx), - child: const Text('取消'), - ), - FilledButton( - style: FilledButton.styleFrom( - backgroundColor: Theme.of(context).colorScheme.error, - ), - onPressed: () async { - Navigator.pop(ctx); - await ref - .read(projectListProvider.notifier) - .deleteProject(project.projectId); - }, - child: const Text('删除'), - ), - ], - ), - ), - ); - } - - Color _projectColor(String id) { - final colors = [ - Colors.blue, - Colors.purple, - Colors.teal, - Colors.orange, - Colors.pink, - Colors.indigo, - Colors.green, - Colors.amber, - ]; - return colors[id.hashCode.abs() % colors.length]; - } -} - -String _projectWorkspaceLabel(ProjectSummary project) { - final path = project.workspacePath?.trim(); - return path == null || path.isEmpty ? project.workspaceSlug : path; -} - -Color _scaffoldBg(BuildContext context) { - final brightness = Theme.of(context).brightness; - return brightness == Brightness.dark - ? const Color(0xFF0F0F0F) - : const Color(0xFFF8F8F8); -} diff --git a/apps/mobile/lib/ui/features/sessions/sessions.dart b/apps/mobile/lib/ui/features/sessions/sessions.dart deleted file mode 100644 index 2ebbd329..00000000 --- a/apps/mobile/lib/ui/features/sessions/sessions.dart +++ /dev/null @@ -1,2 +0,0 @@ -export 'views/sessions_page.dart'; -export 'widgets/session_tile.dart'; diff --git a/apps/mobile/lib/ui/features/sessions/views/sessions_page.dart b/apps/mobile/lib/ui/features/sessions/views/sessions_page.dart deleted file mode 100644 index 1f098e96..00000000 --- a/apps/mobile/lib/ui/features/sessions/views/sessions_page.dart +++ /dev/null @@ -1,216 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; -import 'package:minos/application/active_session_provider.dart'; -import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/thread_list_provider.dart'; -import 'package:minos/ui/core/widgets/error_feedback.dart'; -import 'package:minos/ui/core/widgets/minos_empty_state.dart'; -import 'package:minos/ui/core/widgets/minos_page_header.dart'; -import 'package:minos/ui/core/widgets/minos_surface.dart'; -import 'package:minos/ui/core/widgets/shimmer_box.dart'; -import 'package:minos/ui/features/sessions/widgets/session_tile.dart'; -import 'package:minos/ui/features/shell/router.dart'; -import 'package:minos/ui/theme/theme.dart'; - -/// Secondary Agent Sessions inbox (demoted from primary tab). -class SessionsPage extends ConsumerWidget { - const SessionsPage({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final sessionsAsync = ref.watch(threadListProvider); - final hosts = ref.watch(pairedMacsProvider).asData?.value ?? const []; - final hasHosts = hosts.isNotEmpty; - final colors = context.minosColors; - final canPop = context.canPop(); - - return Scaffold( - backgroundColor: colors.canvas, - body: SafeArea( - bottom: false, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - MinosPageHeader( - title: 'Agent 会话', - subtitle: hasHosts - ? '从 Linked Host 同步的 Agent session' - : '先在 Hosts 查看 Linked Mac', - trailing: Row( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - tooltip: '新建对话', - onPressed: () { - ref - .read(activeSessionControllerProvider.notifier) - .reset(); - unawaited(context.push(AppRoutes.agentStart)); - }, - icon: Icon( - CupertinoIcons.square_pencil, - color: colors.accent, - ), - ), - if (canPop) - IconButton( - tooltip: '关闭', - onPressed: () => context.pop(), - icon: Icon( - CupertinoIcons.xmark_circle_fill, - color: colors.textTertiary, - ), - ), - ], - ), - ), - Expanded( - child: RefreshIndicator( - onRefresh: () => _refresh(context, ref), - child: sessionsAsync.when( - loading: () => const _SessionsSkeleton(), - error: (error, _) => ListView( - physics: const AlwaysScrollableScrollPhysics( - parent: BouncingScrollPhysics(), - ), - children: [ - MinosEmptyState( - icon: CupertinoIcons.exclamationmark_triangle, - title: '会话列表不可用', - subtitle: error.toString(), - actionLabel: '重试', - onAction: () => _refresh(context, ref), - ), - ], - ), - data: (sessions) { - if (sessions.isEmpty) { - return ListView( - physics: const AlwaysScrollableScrollPhysics( - parent: BouncingScrollPhysics(), - ), - children: [ - MinosEmptyState( - icon: CupertinoIcons.chat_bubble_2, - title: hasHosts ? '还没有会话' : '还没有 Linked Host', - subtitle: hasHosts - ? '点右上角新建对话,或在 Desktop 开始一个 Agent 会话。' - : '在 Desktop 用同一账号 Link this Mac,然后下拉刷新。', - actionLabel: hasHosts ? '新建对话' : null, - onAction: hasHosts - ? () { - ref - .read( - activeSessionControllerProvider - .notifier, - ) - .reset(); - unawaited( - context.push(AppRoutes.agentStart), - ); - } - : null, - ), - ], - ); - } - - return ListView.separated( - physics: const AlwaysScrollableScrollPhysics( - parent: BouncingScrollPhysics(), - ), - padding: const EdgeInsets.fromLTRB( - MinosSpacing.pageX, - MinosSpacing.sm, - MinosSpacing.pageX, - MinosSpacing.pageBottom, - ), - itemCount: sessions.length, - separatorBuilder: (_, _) => - const SizedBox(height: MinosSpacing.sm), - itemBuilder: (context, index) { - final session = sessions[index]; - return SessionTile( - session: session, - onTap: () { - unawaited( - context.push( - '/thread/${session.sessionId}', - extra: ThreadRouteExtra(agent: session.agent), - ), - ); - }, - ); - }, - ); - }, - ), - ), - ), - ], - ), - ), - ); - } - - Future _refresh(BuildContext context, WidgetRef ref) async { - try { - await ref.read(threadListProvider.notifier).refresh(); - await ref.read(pairedMacsProvider.notifier).refresh(); - } catch (error) { - if (context.mounted) { - showLoggedErrorToast( - context, - target: 'sessions_page', - title: '会话刷新失败', - error: error, - ); - } - } - } -} - -class _SessionsSkeleton extends StatelessWidget { - const _SessionsSkeleton(); - - @override - Widget build(BuildContext context) { - return ListView( - padding: const EdgeInsets.fromLTRB( - MinosSpacing.pageX, - MinosSpacing.sm, - MinosSpacing.pageX, - MinosSpacing.pageBottom, - ), - children: List.generate(6, (index) { - return const Padding( - padding: EdgeInsets.only(bottom: MinosSpacing.sm), - child: MinosSurface( - bordered: true, - padding: EdgeInsets.all(MinosSpacing.lg), - child: Row( - children: [ - ShimmerBox(width: 42, height: 42, borderRadius: MinosRadii.sm), - SizedBox(width: MinosSpacing.md), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ShimmerBox(width: 160, height: 13), - SizedBox(height: MinosSpacing.sm), - ShimmerBox(width: 110, height: 11), - ], - ), - ), - ], - ), - ), - ); - }), - ); - } -} diff --git a/apps/mobile/lib/ui/features/sessions/widgets/session_tile.dart b/apps/mobile/lib/ui/features/sessions/widgets/session_tile.dart deleted file mode 100644 index 4c82286f..00000000 --- a/apps/mobile/lib/ui/features/sessions/widgets/session_tile.dart +++ /dev/null @@ -1,135 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:minos/ui/core/widgets/minos_surface.dart'; -import 'package:minos/ui/theme/theme.dart'; - -/// One row in the Sessions inbox. -class SessionTile extends StatelessWidget { - const SessionTile({super.key, required this.session, required this.onTap}); - - final SessionSummary session; - final VoidCallback onTap; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final theme = Theme.of(context); - final ended = session.endedAtMs != null; - final title = _sessionTitle(session); - final agent = _agentLabel(session.agent); - - return MinosSurface( - bordered: true, - onTap: onTap, - padding: const EdgeInsets.symmetric( - horizontal: MinosSpacing.lg, - vertical: MinosSpacing.md, - ), - child: Row( - children: [ - Container( - width: 42, - height: 42, - decoration: BoxDecoration( - color: ended ? colors.surfaceMuted : colors.accentSoft, - borderRadius: MinosRadii.smAll, - ), - alignment: Alignment.center, - child: Icon( - CupertinoIcons.bubble_left_bubble_right_fill, - size: 18, - color: ended ? colors.textTertiary : colors.accent, - ), - ), - const SizedBox(width: MinosSpacing.md), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded( - child: Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleSmall?.copyWith( - color: ended - ? colors.textSecondary - : colors.textPrimary, - ), - ), - ), - const SizedBox(width: MinosSpacing.sm), - Text( - _formatRelativeTimestamp(session.lastTsMs.toInt()), - style: theme.textTheme.labelSmall?.copyWith( - color: colors.textTertiary, - ), - ), - ], - ), - const SizedBox(height: MinosSpacing.xs), - Text( - '$agent · ${session.messageCount} 条消息' - '${ended ? ' · 已结束' : ''}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall?.copyWith( - color: colors.textSecondary, - ), - ), - ], - ), - ), - const SizedBox(width: MinosSpacing.sm), - Icon( - ended ? CupertinoIcons.lock : CupertinoIcons.chevron_right, - size: 16, - color: colors.textTertiary, - ), - ], - ), - ); - } -} - -String _sessionTitle(SessionSummary session) { - final title = session.title?.trim(); - if (title != null && title.isNotEmpty) return title; - final ts = DateTime.fromMillisecondsSinceEpoch(session.lastTsMs.toInt()); - return '${_agentLabel(session.agent)} · ${ts.month}/${ts.day} ' - '${_two(ts.hour)}:${_two(ts.minute)}'; -} - -String _agentLabel(AgentName agent) { - return switch (agent) { - AgentName.codex => 'Codex', - AgentName.claude => 'Claude', - AgentName.gemini => 'Gemini', - AgentName.opencode => 'OpenCode', - AgentName.grok => 'Grok', - }; -} - -String _formatRelativeTimestamp(int ms) { - final now = DateTime.now(); - final ts = DateTime.fromMillisecondsSinceEpoch(ms).toLocal(); - final diff = now.difference(ts); - - if (diff.inSeconds < 60) return '刚刚'; - if (diff.inMinutes < 60) return '${diff.inMinutes} 分钟前'; - - final today = DateTime(now.year, now.month, now.day); - final tsDay = DateTime(ts.year, ts.month, ts.day); - if (tsDay == today) return '${_two(ts.hour)}:${_two(ts.minute)}'; - - final yesterday = today.subtract(const Duration(days: 1)); - if (tsDay == yesterday) return '昨天'; - - if (ts.year == now.year) return '${_two(ts.month)}-${_two(ts.day)}'; - return '${ts.year}-${_two(ts.month)}-${_two(ts.day)}'; -} - -String _two(int n) => n.toString().padLeft(2, '0'); diff --git a/apps/mobile/lib/ui/features/shell/router.dart b/apps/mobile/lib/ui/features/shell/router.dart index 63c80cfc..15e47a46 100644 --- a/apps/mobile/lib/ui/features/shell/router.dart +++ b/apps/mobile/lib/ui/features/shell/router.dart @@ -3,28 +3,18 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:minos/application/auth_provider.dart'; import 'package:minos/application/root_route_decision.dart'; -import 'package:minos/src/rust/api/minos.dart' show AgentName, ConversationKind; -import 'package:minos/ui/features/agents/views/agent_start_page.dart'; -import 'package:minos/ui/features/agents/views/agents_hub_page.dart'; +import 'package:minos/src/rust/api/minos.dart' show ConversationKind; import 'package:minos/ui/features/auth/views/login_page.dart'; -import 'package:minos/ui/features/chat/views/thread_view_page.dart'; import 'package:minos/ui/features/debug/views/log_viewer_page.dart'; -import 'package:minos/ui/features/projects/views/project_detail_page.dart'; -import 'package:minos/ui/features/sessions/views/sessions_page.dart'; import 'package:minos/ui/features/shell/views/app_shell_page.dart'; import 'package:minos/ui/features/social/views/group_members_page.dart'; import 'package:minos/ui/features/social/views/social_chat_page.dart'; -/// Route path constants for the app. +/// Route path constants for the IM-first app shell. abstract final class AppRoutes { static const String splash = '/splash'; static const String login = '/login'; static const String shell = '/'; - static const String sessions = '/sessions'; - static const String thread = '/thread/:sessionId'; - static const String newThread = '/thread/new'; - static const String agentStart = '/agent-start'; - static const String agentProfile = '/agent-profile/:profileId'; static const String logViewer = '/log-viewer'; static const String socialHub = '/social'; static const String socialChat = '/social/chat/:conversationId'; @@ -34,9 +24,9 @@ abstract final class AppRoutes { /// Creates the [GoRouter] instance wired to Riverpod for auth-based redirects. /// /// Redirect reads only the synchronous [authControllerProvider]. Both -/// [RootRoute.projectList] and [RootRoute.projectListOffline] map to the -/// same shell path, so async connection/pairing providers are not needed -/// here (offline chrome lives inside the shell). +/// [RootRoute.shell] and [RootRoute.shellOffline] map to the same shell path, +/// so async connection/pairing providers are not needed here (offline chrome +/// lives inside the shell). GoRouter createAppRouter(Ref ref) { final routerNotifier = _RouterRefreshNotifier(ref); @@ -57,8 +47,8 @@ GoRouter createAppRouter(Ref ref) { if (currentPath != AppRoutes.splash) return AppRoutes.splash; case RootRoute.login: if (currentPath != AppRoutes.login) return AppRoutes.login; - case RootRoute.projectList: - case RootRoute.projectListOffline: + case RootRoute.shell: + case RootRoute.shellOffline: if (currentPath == AppRoutes.splash || currentPath == AppRoutes.login) { return AppRoutes.shell; @@ -79,55 +69,10 @@ GoRouter createAppRouter(Ref ref) { path: AppRoutes.shell, builder: (context, state) => const AppShellPage(), ), - GoRoute( - path: AppRoutes.thread, - builder: (context, state) { - final sessionId = state.pathParameters['sessionId']!; - final extra = state.extra as ThreadRouteExtra?; - return ThreadViewPage( - sessionId: sessionId, - agent: extra?.agent, - agentProfileId: extra?.agentProfileId, - ); - }, - ), - GoRoute( - path: AppRoutes.newThread, - builder: (context, state) { - final extra = state.extra as ThreadRouteExtra?; - return ThreadViewPage(agentProfileId: extra?.agentProfileId); - }, - ), - GoRoute( - path: AppRoutes.agentStart, - builder: (context, state) => const AgentStartPage(), - ), - GoRoute( - path: AppRoutes.agentProfile, - builder: (context, state) { - final profileId = state.pathParameters['profileId']!; - return AgentProfilePage(profileId: profileId); - }, - ), GoRoute( path: AppRoutes.logViewer, builder: (context, state) => const LogViewerPage(), ), - GoRoute( - path: '/project/:projectId', - builder: (context, state) { - final projectId = state.pathParameters['projectId']!; - final extra = state.extra as ProjectDetailRouteExtra?; - return ProjectDetailPage( - projectId: projectId, - projectName: extra?.projectName ?? '', - ); - }, - ), - GoRoute( - path: AppRoutes.sessions, - builder: (context, state) => const SessionsPage(), - ), // Legacy deep link: conversation inbox is now the shell Messages tab. GoRoute( path: AppRoutes.socialHub, @@ -160,13 +105,6 @@ GoRouter createAppRouter(Ref ref) { ); } -class ThreadRouteExtra { - const ThreadRouteExtra({this.agent, this.agentProfileId}); - - final AgentName? agent; - final String? agentProfileId; -} - class SocialChatRouteExtra { const SocialChatRouteExtra({required this.title, required this.kind}); @@ -180,12 +118,6 @@ class GroupMembersRouteExtra { final String title; } -class ProjectDetailRouteExtra { - const ProjectDetailRouteExtra({required this.projectName}); - - final String projectName; -} - class _RouterRefreshNotifier extends ChangeNotifier { _RouterRefreshNotifier(this._ref) { // Auth alone drives root redirects (splash ↔ login ↔ shell). diff --git a/apps/mobile/lib/ui/features/shell/views/app.dart b/apps/mobile/lib/ui/features/shell/views/app.dart index 7548b91a..2011cc7d 100644 --- a/apps/mobile/lib/ui/features/shell/views/app.dart +++ b/apps/mobile/lib/ui/features/shell/views/app.dart @@ -3,11 +3,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:minos/application/agent_profiles_provider.dart'; import 'package:minos/application/im_outbox_worker.dart'; import 'package:minos/application/minos_providers.dart'; -import 'package:minos/application/project_providers.dart'; import 'package:minos/application/runtime_actions.dart'; import 'package:minos/application/social_providers.dart'; -import 'package:minos/application/thread_events_provider.dart'; -import 'package:minos/application/thread_list_provider.dart'; import 'package:minos/src/rust/api/minos.dart' as core; import 'package:minos/ui/features/shell/router_provider.dart'; import 'package:minos/ui/theme/theme.dart'; @@ -58,12 +55,8 @@ class _MinosAppState extends ConsumerState } ref - ..invalidate(projectListProvider) - ..invalidate(threadListProvider) - ..invalidate(threadEventsProvider) ..invalidate(conversationsProvider) ..invalidate(friendsProvider) - ..invalidate(friendRequestsProvider) ..invalidate(socialProfileProvider) ..invalidate(pairedMacsProvider) ..invalidate(activeMacProvider) diff --git a/apps/mobile/lib/ui/features/shell/views/app_shell_page.dart b/apps/mobile/lib/ui/features/shell/views/app_shell_page.dart index fc7902fd..62f1fdd0 100644 --- a/apps/mobile/lib/ui/features/shell/views/app_shell_page.dart +++ b/apps/mobile/lib/ui/features/shell/views/app_shell_page.dart @@ -10,8 +10,7 @@ import 'package:minos/ui/theme/theme.dart'; /// Golden-path mobile shell: Messages / Hosts / Account. /// -/// Single-column bottom navigation. Agent sessions, projects, and agent-profile -/// management stay reachable via secondary routes. +/// Single-column bottom navigation for IM-first Mobile. class AppShellPage extends ConsumerWidget { const AppShellPage({super.key}); diff --git a/apps/mobile/lib/ui/features/social/social.dart b/apps/mobile/lib/ui/features/social/social.dart index 7e80d6c1..a7626f26 100644 --- a/apps/mobile/lib/ui/features/social/social.dart +++ b/apps/mobile/lib/ui/features/social/social.dart @@ -1,16 +1,14 @@ -/// Feature: Social (People & Conversations) +/// Feature: Social (Conversation IM) /// -/// Friend management, direct messaging, and group conversations. -/// Collaboration IM uses Slack/Buzz full-width rows (aligned with Desktop). +/// Collaboration IM: inbox lives in Messages tab; this feature owns the +/// conversation timeline, members, and message chrome (Slack/Buzz full-width). /// /// View Models: /// - [SocialConversation] (application/social_providers.dart) /// - [ConversationsController] (application/social_providers.dart) -/// - [FriendRequestsController] (application/social_providers.dart) /// - [FriendsController] (application/social_providers.dart) /// /// Views: -/// - [SocialHubPage] /// - [SocialChatPage] /// - [GroupMembersPage] library; @@ -18,5 +16,3 @@ library; export 'package:minos/application/social_providers.dart'; export 'package:minos/ui/features/social/views/group_members_page.dart'; export 'package:minos/ui/features/social/views/social_chat_page.dart'; -export 'package:minos/ui/features/social/views/social_hub_page.dart'; -export 'package:minos/ui/features/social/widgets/social_management_sections.dart'; diff --git a/apps/mobile/lib/ui/features/social/views/social_chat_page.dart b/apps/mobile/lib/ui/features/social/views/social_chat_page.dart index af54700d..36255c58 100644 --- a/apps/mobile/lib/ui/features/social/views/social_chat_page.dart +++ b/apps/mobile/lib/ui/features/social/views/social_chat_page.dart @@ -5,16 +5,13 @@ import 'package:flutter/material.dart' hide ConnectionState; import 'package:flutter_list_view/flutter_list_view.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:minos/application/agent_activity_provider.dart'; import 'package:minos/application/group_agent_provider.dart'; import 'package:minos/application/minos_providers.dart'; import 'package:minos/application/social_providers.dart'; -import 'package:minos/data/repositories/social_repository.dart'; import 'package:minos/domain/agent_profile.dart'; import 'package:minos/domain/group_member.dart'; import 'package:minos/domain/message_sender_ext.dart'; import 'package:minos/domain/social_message.dart'; -import 'package:minos/infrastructure/platform_int64.dart'; import 'package:minos/src/rust/api/minos.dart'; import 'package:minos/ui/core/widgets/error_feedback.dart'; import 'package:minos/ui/core/widgets/minos_button.dart'; @@ -71,8 +68,9 @@ class _SocialChatPageState extends ConsumerState { // Focused for unread / markRead (distinct from timeline window open). WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; - ref.read(focusedSocialConversationIdProvider.notifier).state = - widget.conversationId; + ref + .read(focusedSocialConversationIdProvider.notifier) + .set(widget.conversationId); }); } @@ -82,7 +80,7 @@ class _SocialChatPageState extends ConsumerState { // Clear focus if we still own it. final focused = ref.read(focusedSocialConversationIdProvider); if (focused == widget.conversationId) { - ref.read(focusedSocialConversationIdProvider.notifier).state = null; + ref.read(focusedSocialConversationIdProvider.notifier).clear(); } _controller.dispose(); _composerFocusNode.dispose(); @@ -97,12 +95,13 @@ class _SocialChatPageState extends ConsumerState { } // Near top of ASC list → load older page (before_seq). if (_isNearTop()) { - final notifier = ref.read( - socialConversationProvider(widget.conversationId).notifier, - ); - final st = ref.read(socialConversationProvider(widget.conversationId)); + final st = ref.read(socialChatViewModelProvider(widget.conversationId)); if (st.hasOlder && !st.loadingOlder) { - unawaited(notifier.loadOlder()); + unawaited( + ref + .read(socialChatActionsProvider(widget.conversationId)) + .loadOlder(), + ); } } } @@ -117,16 +116,12 @@ class _SocialChatPageState extends ConsumerState { if (text.isEmpty) { return; } - final replyTarget = ref.read( - socialReplyMessageProvider(widget.conversationId), - ); _controller.clear(); - ref.read(socialReplyDraftProvider(widget.conversationId).notifier).clear(); _jumpToBottom(); try { await ref - .read(socialConversationProvider(widget.conversationId).notifier) - .sendMessage(text, replyToMessage: replyTarget); + .read(socialChatActionsProvider(widget.conversationId)) + .send(text); if (!mounted) { return; } @@ -155,7 +150,7 @@ class _SocialChatPageState extends ConsumerState { /// Membership-first @ picker: only current conversation participants. Future _showMentionPicker() async { final myAccountId = ref - .read(socialConversationProvider(widget.conversationId)) + .read(socialChatViewModelProvider(widget.conversationId)) .myAccountId; final participants = ref .read(groupMentionableMembersProvider(widget.conversationId)) @@ -301,7 +296,7 @@ class _SocialChatPageState extends ConsumerState { _syncKeyboardInset(keyboardInsetBottom); ref.listen( - socialConversationProvider(widget.conversationId), + socialChatViewModelProvider(widget.conversationId), (previous, next) { final previousCount = previous?.messages.length ?? 0; if (next.messages.length > previousCount && @@ -315,7 +310,7 @@ class _SocialChatPageState extends ConsumerState { ); final messageCount = ref.watch( - socialConversationProvider( + socialChatViewModelProvider( widget.conversationId, ).select((SocialConversationState s) => s.messages.length), ); @@ -448,7 +443,7 @@ class _ConversationTitle extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final colors = context.minosColors; - final conversation = ref.watch(socialConversationProvider(conversationId)); + final conversation = ref.watch(socialChatViewModelProvider(conversationId)); final conversationSummary = _findConversationSummary( ref.watch(conversationsProvider).asData?.value, conversationId, @@ -613,62 +608,6 @@ class _ConversationMessagePane extends ConsumerWidget { final String conversationId; final FlutterListViewController scrollController; - Future _openAgentSession( - BuildContext context, - WidgetRef ref, { - required String conversationId, - required SocialChatMessage message, - }) async { - final fromId = message.agentSessionIdFromMessageId; - String? sessionId = fromId; - if (sessionId == null || sessionId.isEmpty) { - try { - final sessions = await ref - .read(socialRepositoryProvider) - .listAgentSessions(conversationId: conversationId, limit: 20); - final agentKey = message.sender.identityId.trim(); - final matched = sessions.where((s) { - final id = s.agentId?.trim(); - return id != null && - id.isNotEmpty && - (id == agentKey || id.toLowerCase() == agentKey.toLowerCase()); - }).toList(); - final pool = matched.isNotEmpty ? matched : sessions; - if (pool.isNotEmpty) { - pool.sort((a, b) { - return platformInt64ToInt( - b.lastActivityAtMs, - ).compareTo(platformInt64ToInt(a.lastActivityAtMs)); - }); - sessionId = pool.first.sessionId; - } - } catch (error) { - if (!context.mounted) return; - showMinosToast( - context, - title: '无法打开 session', - description: error.toString(), - destructive: true, - ); - return; - } - } - if (!context.mounted) return; - if (sessionId == null || sessionId.isEmpty) { - showMinosToast(context, title: '暂无该 Agent 的执行 session'); - return; - } - // Subscribe so ThreadView has a live topic when opened from chat. - unawaited( - ref - .read(socialRepositoryProvider) - .subscribeAgentSession(sessionId: sessionId), - ); - unawaited( - context.push(AppRoutes.thread.replaceFirst(':sessionId', sessionId)), - ); - } - Future _showMessageActions( BuildContext context, WidgetRef ref, { @@ -687,8 +626,8 @@ class _ConversationMessagePane extends ConsumerWidget { switch (action) { case ConversationMessageAction.reply: ref - .read(socialReplyDraftProvider(conversationId).notifier) - .select(message.localId); + .read(socialChatActionsProvider(conversationId)) + .selectReply(message); return; case ConversationMessageAction.copy: await copyMessageText(message.text); @@ -698,8 +637,8 @@ class _ConversationMessagePane extends ConsumerWidget { case ConversationMessageAction.retry: try { await ref - .read(socialConversationProvider(conversationId).notifier) - .retryMessage(message.localId); + .read(socialChatActionsProvider(conversationId)) + .retry(message.localId); } catch (error) { if (!context.mounted) return; _showError(context, '重试失败', error); @@ -712,8 +651,8 @@ class _ConversationMessagePane extends ConsumerWidget { } try { await ref - .read(socialConversationProvider(conversationId).notifier) - .recallMessage(message.localId); + .read(socialChatActionsProvider(conversationId)) + .recall(message.localId); } catch (error) { if (!context.mounted) { return; @@ -726,11 +665,10 @@ class _ConversationMessagePane extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final state = ref.watch(socialConversationProvider(conversationId)); + final state = ref.watch(socialChatViewModelProvider(conversationId)); return RefreshIndicator( - onRefresh: () => ref - .read(socialConversationProvider(conversationId).notifier) - .refresh(), + onRefresh: () => + ref.read(socialChatActionsProvider(conversationId)).refresh(), child: state.isLoading && state.messages.isEmpty ? ListView( controller: scrollController, @@ -770,7 +708,6 @@ class _ConversationMessagePane extends ConsumerWidget { ); final isMine = message.sender.accountIdOrNull == state.myAccountId; - final isAgent = message.senderType == SenderType.agent; final mentionsMe = !isMine && state.myAccountId != null && @@ -782,12 +719,8 @@ class _ConversationMessagePane extends ConsumerWidget { final retryAction = message.deliveryState == SocialMessageDeliveryState.failed ? () => ref - .read( - socialConversationProvider( - conversationId, - ).notifier, - ) - .retryMessage(message.localId) + .read(socialChatActionsProvider(conversationId)) + .retry(message.localId) : null; final canShowActions = !message.isRecalled && @@ -826,14 +759,6 @@ class _ConversationMessagePane extends ConsumerWidget { mentionsMe: mentionsMe, onRetry: retryAction, onLongPress: actionHandler, - onOpenAgentSession: !isAgent - ? null - : () => _openAgentSession( - context, - ref, - conversationId: conversationId, - message: message, - ), onToggleReaction: message.serverMessageId == null || message.isRecalled @@ -842,9 +767,9 @@ class _ConversationMessagePane extends ConsumerWidget { unawaited( ref .read( - socialConversationProvider( + socialChatActionsProvider( conversationId, - ).notifier, + ), ) .toggleReaction( messageId: message.serverMessageId!, @@ -891,7 +816,7 @@ class _ConversationComposer extends ConsumerWidget { final colors = context.minosColors; final replyTarget = ref.watch(socialReplyMessageProvider(conversationId)); final myAccountId = ref.watch( - socialConversationProvider( + socialChatViewModelProvider( conversationId, ).select((SocialConversationState state) => state.myAccountId), ); @@ -902,10 +827,6 @@ class _ConversationComposer extends ConsumerWidget { .toList(growable: false) : const []; final hasMentionable = mentionable.isNotEmpty; - final activity = ref - .watch(conversationAgentActivityProvider(conversationId)) - .asData - ?.value; return Container( decoration: BoxDecoration( @@ -922,15 +843,11 @@ class _ConversationComposer extends ConsumerWidget { text: replyTarget.text, isRecalled: replyTarget.recalledAtMs != null, onClear: () => ref - .read(socialReplyDraftProvider(conversationId).notifier) - .clear(), + .read(socialChatActionsProvider(conversationId)) + .clearReply(), ), const SizedBox(height: 10), ], - if (activity != null) ...[ - _AgentActivityTicker(activity: activity), - const SizedBox(height: 8), - ], Row( children: [ if (kind == ConversationKind.group) ...[ @@ -960,194 +877,6 @@ class _ConversationComposer extends ConsumerWidget { } } -class _AgentActivityTicker extends StatelessWidget { - const _AgentActivityTicker({required this.activity}); - - final AgentActivitySnapshot activity; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final toneColor = _activityToneColor(context, activity.tone); - final textStyle = Theme.of(context).textTheme.labelMedium?.copyWith( - color: colors.textPrimary, - fontWeight: FontWeight.w600, - height: 1.1, - ); - return AnimatedSwitcher( - duration: const Duration(milliseconds: 180), - switchInCurve: Curves.easeOutCubic, - switchOutCurve: Curves.easeInCubic, - // Key by session only — label changes every stream token and must not - // recreate the ticker (or collide when labels match across frames). - child: SizedBox( - key: ValueKey(activity.sessionId), - height: 34, - width: double.infinity, - child: DecoratedBox( - decoration: BoxDecoration( - color: colors.surfaceMuted.withValues(alpha: 0.72), - borderRadius: BorderRadius.circular(8), - border: Border.all(color: toneColor.withValues(alpha: 0.28)), - ), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 10), - child: Row( - children: [ - Icon(_activityIcon(activity.kind), size: 15, color: toneColor), - const SizedBox(width: 8), - Expanded( - child: DefaultTextStyle.merge( - style: textStyle, - maxLines: 1, - softWrap: false, - overflow: TextOverflow.clip, - child: _MarqueeText(text: activity.label), - ), - ), - ], - ), - ), - ), - ), - ); - } -} - -IconData _activityIcon(AgentActivityKind kind) { - return switch (kind) { - AgentActivityKind.reasoning => CupertinoIcons.sparkles, - AgentActivityKind.tool => CupertinoIcons.chevron_left_slash_chevron_right, - AgentActivityKind.success => CupertinoIcons.gear_alt_fill, - AgentActivityKind.error => CupertinoIcons.exclamationmark_triangle, - AgentActivityKind.running => CupertinoIcons.gear_alt_fill, - }; -} - -Color _activityToneColor(BuildContext context, AgentActivityTone tone) { - final colors = context.minosColors; - return switch (tone) { - AgentActivityTone.info => colors.accent, - AgentActivityTone.success => colors.accent, - AgentActivityTone.error => colors.danger, - }; -} - -class _MarqueeText extends StatefulWidget { - const _MarqueeText({required this.text}); - - final String text; - - @override - State<_MarqueeText> createState() => _MarqueeTextState(); -} - -class _MarqueeTextState extends State<_MarqueeText> - with SingleTickerProviderStateMixin { - late final AnimationController _controller = AnimationController( - vsync: this, - duration: const Duration(milliseconds: 6200), - ); - - @override - void initState() { - super.initState(); - unawaited(_controller.repeat()); - } - - @override - void didUpdateWidget(_MarqueeText oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.text != widget.text) { - _controller.reset(); - unawaited(_controller.repeat()); - } - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final style = DefaultTextStyle.of(context).style; - // Cap display length so stream previews cannot explode layout. - final display = _marqueeDisplayText(widget.text); - return LayoutBuilder( - builder: (context, constraints) { - final maxW = constraints.maxWidth; - if (!maxW.isFinite || maxW <= 0) { - return Text( - display, - maxLines: 1, - overflow: TextOverflow.ellipsis, - softWrap: false, - ); - } - - final painter = TextPainter( - text: TextSpan(text: display, style: style), - maxLines: 1, - textDirection: Directionality.of(context), - )..layout(maxWidth: double.infinity); - final textWidth = painter.width; - if (textWidth <= maxW) { - return Text( - display, - maxLines: 1, - overflow: TextOverflow.ellipsis, - softWrap: false, - ); - } - - const gap = 42.0; - final distance = textWidth + gap; - // OverflowBox lets the scrolling Row size itself beyond the viewport; - // ClipRect hides the excess. Without this, Flutter asserts Row overflow - // even though the marquee is intentionally wider than the slot. - return ClipRect( - child: OverflowBox( - alignment: Alignment.centerLeft, - minWidth: 0, - maxWidth: double.infinity, - minHeight: 0, - maxHeight: constraints.maxHeight.isFinite - ? constraints.maxHeight - : null, - child: AnimatedBuilder( - animation: _controller, - builder: (context, child) { - return Transform.translate( - offset: Offset(-distance * _controller.value, 0), - child: child, - ); - }, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(display, maxLines: 1, softWrap: false), - const SizedBox(width: gap), - Text(display, maxLines: 1, softWrap: false), - ], - ), - ), - ), - ); - }, - ); - } -} - -String _marqueeDisplayText(String raw) { - final collapsed = raw.replaceAll(RegExp(r'\s+'), ' ').trim(); - if (collapsed.isEmpty) return '…'; - const maxChars = 80; - if (collapsed.length <= maxChars) return collapsed; - return '${collapsed.substring(0, maxChars - 1)}…'; -} - class _ComposerReplyBanner extends StatelessWidget { const _ComposerReplyBanner({ required this.senderName, diff --git a/apps/mobile/lib/ui/features/social/views/social_hub_page.dart b/apps/mobile/lib/ui/features/social/views/social_hub_page.dart deleted file mode 100644 index 230d30b7..00000000 --- a/apps/mobile/lib/ui/features/social/views/social_hub_page.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:minos/ui/features/messages/views/messages_page.dart'; - -/// Legacy route entry for `/social`. Redirects to the Messages golden path. -class SocialHubPage extends StatelessWidget { - const SocialHubPage({super.key, this.showAppBar = true}); - - /// Kept for call-site compatibility; [MessagesPage] owns its own chrome. - final bool showAppBar; - - @override - Widget build(BuildContext context) => const MessagesPage(); -} diff --git a/apps/mobile/lib/ui/features/social/widgets/social_management_sections.dart b/apps/mobile/lib/ui/features/social/widgets/social_management_sections.dart deleted file mode 100644 index 73aa8cb1..00000000 --- a/apps/mobile/lib/ui/features/social/widgets/social_management_sections.dart +++ /dev/null @@ -1,462 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:minos/application/social_actions.dart'; -import 'package:minos/application/social_providers.dart'; -import 'package:minos/src/rust/api/minos.dart'; -import 'package:minos/ui/core/widgets/error_feedback.dart'; -import 'package:minos/ui/core/widgets/minos_button.dart'; -import 'package:minos/ui/core/widgets/minos_progress.dart'; -import 'package:minos/ui/core/widgets/minos_text_field.dart'; -import 'package:minos/ui/core/widgets/minos_toast.dart'; -import 'package:minos/ui/theme/theme.dart'; - -class SocialProfileSection extends ConsumerWidget { - const SocialProfileSection({super.key}); - - Future _editMinosId( - BuildContext context, - WidgetRef ref, - MyProfileResponse profile, - ) async { - final controller = TextEditingController(text: profile.minosId); - final rootContext = context; - await showCupertinoDialog( - context: rootContext, - builder: (dialogContext) { - final colors = dialogContext.minosColors; - return CupertinoAlertDialog( - title: const Text('设置 Minos ID'), - content: Column( - children: [ - const SizedBox(height: 8), - const Text('仅允许数字和英文字母,区分大小写。'), - const SizedBox(height: 12), - Material( - color: Colors.transparent, - child: MinosTextField(controller: controller), - ), - ], - ), - actions: [ - CupertinoDialogAction( - onPressed: () => Navigator.of(dialogContext).pop(), - child: Text('取消', style: TextStyle(color: colors.textSecondary)), - ), - CupertinoDialogAction( - isDefaultAction: true, - onPressed: () async { - try { - await ref - .read(socialActionsProvider) - .setMinosId(minosId: controller.text.trim()); - ref.invalidate(socialProfileProvider); - if (dialogContext.mounted) { - Navigator.of(dialogContext).pop(); - } - } catch (error) { - if (!rootContext.mounted) return; - showSocialFeedbackError(rootContext, '设置失败', error); - } - }, - child: Text('保存', style: TextStyle(color: colors.accent)), - ), - ], - ); - }, - ); - controller.dispose(); - } - - Future _copyText( - BuildContext context, - String text, - String title, - ) async { - await Clipboard.setData(ClipboardData(text: text)); - if (context.mounted) { - showSocialInfoToast(context, title); - } - } - - @override - Widget build(BuildContext context, WidgetRef ref) { - final profileAsync = ref.watch(socialProfileProvider); - final colors = context.minosColors; - final theme = Theme.of(context); - return profileAsync.when( - loading: () => const SocialSectionCard( - title: '账户 ID', - child: Padding( - padding: EdgeInsets.all(16), - child: Center(child: MinosProgress()), - ), - ), - error: (error, _) => SocialSectionCard( - title: '账户 ID', - child: SocialSectionMessage(text: error.toString()), - ), - data: (profile) { - final minosId = profile.minosId.trim().isEmpty - ? '未设置' - : profile.minosId.trim(); - return SocialSectionCard( - title: '账户 ID', - trailing: Row( - mainAxisSize: MainAxisSize.min, - children: [ - MinosButton.ghost( - onPressed: profile.minosId.trim().isEmpty - ? null - : () => _copyText( - context, - 'minos://add-friend/${profile.minosId}', - '邀请链接已复制', - ), - child: const Text('邀请'), - ), - MinosButton.ghost( - onPressed: () => _editMinosId(context, ref, profile), - child: const Text('编辑'), - ), - ], - ), - child: InkWell( - onTap: profile.minosId.trim().isEmpty - ? null - : () => _copyText(context, profile.minosId, 'Minos ID 已复制'), - child: Padding( - padding: const EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - profile.email, - style: theme.textTheme.bodySmall?.copyWith( - color: colors.textSecondary, - ), - ), - const SizedBox(height: 10), - _ProfileValueRow(label: 'Minos ID', value: minosId), - const SizedBox(height: 10), - _ProfileValueRow(label: '账户 ID', value: profile.accountId), - ], - ), - ), - ), - ); - }, - ); - } -} - -class FriendSearchSection extends ConsumerStatefulWidget { - const FriendSearchSection({super.key}); - - @override - ConsumerState createState() => - _FriendSearchSectionState(); -} - -class _FriendSearchSectionState extends ConsumerState { - final TextEditingController _controller = TextEditingController(); - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final query = ref.watch(socialSearchQueryProvider); - final searchAsync = ref.watch(socialSearchProvider(query)); - return SocialSectionCard( - title: '添加好友', - child: Padding( - padding: const EdgeInsets.all(16), - child: Column( - children: [ - MinosTextField( - controller: _controller, - placeholder: '输入 Minos ID 或邀请链接', - onChanged: (value) { - ref - .read(socialSearchQueryProvider.notifier) - .update(normalizeFriendSearchInput(value)); - }, - ), - if (query.isNotEmpty) ...[ - const SizedBox(height: 12), - searchAsync.when( - loading: () => const Center(child: MinosProgress()), - error: (error, _) => - SocialSectionMessage(text: error.toString()), - data: (users) => users.isEmpty - ? const SocialSectionMessage(text: '没有找到这个用户') - : Column( - children: [ - for (final user in users) - ListTile( - contentPadding: EdgeInsets.zero, - title: Text(user.displayName), - subtitle: Text('@${user.minosId}'), - trailing: MinosButton.outline( - onPressed: () async { - try { - await ref - .read(socialActionsProvider) - .createFriendRequest( - targetMinosId: user.minosId, - ); - await ref - .read(friendRequestsProvider.notifier) - .refresh(); - if (context.mounted) { - showSocialInfoToast(context, '请求已发送'); - } - } catch (error) { - if (!context.mounted) return; - showSocialFeedbackError( - context, - '发送请求失败', - error, - ); - } - }, - child: const Text('添加'), - ), - ), - ], - ), - ), - ], - ], - ), - ), - ); - } -} - -class FriendRequestsSection extends ConsumerWidget { - const FriendRequestsSection({super.key}); - - Future _refreshSocialLists(WidgetRef ref) async { - await Future.wait(>[ - ref.read(friendRequestsProvider.notifier).refresh(), - ref.read(friendsProvider.notifier).refresh(), - ]); - } - - @override - Widget build(BuildContext context, WidgetRef ref) { - final requestsAsync = ref.watch(friendRequestsProvider); - return requestsAsync.when( - loading: () => const SocialSectionCard( - title: '好友请求', - child: Padding( - padding: EdgeInsets.all(16), - child: Center(child: MinosProgress()), - ), - ), - error: (error, _) => SocialSectionCard( - title: '好友请求', - child: SocialSectionMessage(text: error.toString()), - ), - data: (requests) { - final count = requests.incoming.length + requests.outgoing.length; - return SocialSectionCard( - title: count == 0 ? '好友请求' : '好友请求 $count', - child: requests.incoming.isEmpty && requests.outgoing.isEmpty - ? const SocialSectionMessage(text: '暂无好友请求') - : Column( - children: [ - for (var i = 0; i < requests.incoming.length; i++) ...[ - if (i > 0) const Divider(height: 1), - ListTile( - title: Text(requests.incoming[i].from.displayName), - subtitle: Text('@${requests.incoming[i].from.minosId}'), - trailing: Row( - mainAxisSize: MainAxisSize.min, - children: [ - MinosButton.outline( - onPressed: () async { - try { - await ref - .read(socialActionsProvider) - .rejectFriendRequest( - requestId: - requests.incoming[i].requestId, - ); - await _refreshSocialLists(ref); - } catch (error) { - if (!context.mounted) return; - showSocialFeedbackError( - context, - '拒绝失败', - error, - ); - } - }, - child: const Text('拒绝'), - ), - const SizedBox(width: 8), - MinosButton( - onPressed: () async { - try { - await ref - .read(socialActionsProvider) - .acceptFriendRequest( - requestId: - requests.incoming[i].requestId, - ); - await _refreshSocialLists(ref); - } catch (error) { - if (!context.mounted) return; - showSocialFeedbackError( - context, - '接受失败', - error, - ); - } - }, - child: const Text('接受'), - ), - ], - ), - ), - ], - for (var i = 0; i < requests.outgoing.length; i++) ...[ - if (requests.incoming.isNotEmpty || i > 0) - const Divider(height: 1), - ListTile( - title: Text(requests.outgoing[i].to.displayName), - subtitle: Text( - '@${requests.outgoing[i].to.minosId} · 已发送', - ), - ), - ], - ], - ), - ); - }, - ); - } -} - -class SocialSectionCard extends StatelessWidget { - const SocialSectionCard({ - super.key, - required this.title, - required this.child, - this.trailing, - }); - - final String title; - final Widget child; - final Widget? trailing; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final theme = Theme.of(context); - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(4, 0, 4, 8), - child: Row( - children: [ - Expanded( - child: Text( - title, - style: theme.textTheme.bodySmall?.copyWith( - color: colors.textSecondary, - ), - ), - ), - ?trailing, - ], - ), - ), - DecoratedBox( - decoration: BoxDecoration( - color: colors.surfaceMuted, - borderRadius: BorderRadius.circular(16), - ), - child: child, - ), - ], - ); - } -} - -class SocialSectionMessage extends StatelessWidget { - const SocialSectionMessage({super.key, required this.text}); - - final String text; - - @override - Widget build(BuildContext context) { - return Padding(padding: const EdgeInsets.all(16), child: Text(text)); - } -} - -class _ProfileValueRow extends StatelessWidget { - const _ProfileValueRow({required this.label, required this.value}); - - final String label; - final String value; - - @override - Widget build(BuildContext context) { - final colors = context.minosColors; - final theme = Theme.of(context); - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - label, - style: theme.textTheme.bodyMedium?.copyWith( - color: colors.textSecondary, - ), - ), - const SizedBox(height: 4), - Text( - value, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleLarge, - ), - ], - ); - } -} - -String normalizeFriendSearchInput(String value) { - final trimmed = value.trim(); - if (trimmed.startsWith('minos://add-friend/')) { - return trimmed.substring('minos://add-friend/'.length); - } - final uri = Uri.tryParse(trimmed); - if (uri != null && - uri.pathSegments.length >= 2 && - uri.pathSegments[uri.pathSegments.length - 2] == 'add-friend') { - return uri.pathSegments.last; - } - return trimmed; -} - -void showSocialFeedbackError(BuildContext context, String title, Object error) { - showLoggedErrorToast( - context, - target: 'social_hub', - title: title, - error: error, - ); -} - -void showSocialInfoToast(BuildContext context, String title) { - showMinosToast(context, title: title); -} diff --git a/apps/mobile/test/application/agent_activity_provider_test.dart b/apps/mobile/test/application/agent_activity_provider_test.dart deleted file mode 100644 index 872daa5e..00000000 --- a/apps/mobile/test/application/agent_activity_provider_test.dart +++ /dev/null @@ -1,217 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:minos/application/agent_activity_provider.dart'; -import 'package:minos/domain/agent_profile.dart'; -import 'package:minos/infrastructure/platform_int64.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -void main() { - group('agentActivitySnapshotFromEvents', () { - test('returns null without concrete assistant activity events', () { - expect( - agentActivitySnapshotFromEvents( - sessionId: 'session-1', - events: const [], - ), - isNull, - ); - - expect( - agentActivitySnapshotFromEvents( - sessionId: 'session-1', - events: [ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1000), - ), - ], - ), - isNull, - ); - }); - - test('ignores user-only turns', () { - final snapshot = agentActivitySnapshotFromEvents( - sessionId: 'session-1', - events: [ - UiEventMessage.messageStarted( - messageId: 'user-1', - role: MessageRole.user, - startedAtMs: platformInt64FromInt(1000), - ), - const UiEventMessage.textDelta( - messageId: 'user-1', - text: DisplayPayload.inline(text: 'hello'), - ), - UiEventMessage.messageCompleted( - messageId: 'user-1', - finishedAtMs: platformInt64FromInt(1001), - ), - ], - ); - - expect(snapshot, isNull); - }); - - test( - 'surfaces concrete reasoning activity while assistant turn is live', - () { - final snapshot = agentActivitySnapshotFromEvents( - sessionId: 'session-1', - events: [ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1000), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'checking the repository'), - ), - ], - ); - - expect(snapshot, isNotNull); - expect(snapshot!.label, '思考中 · checking the repository'); - expect(snapshot.kind, AgentActivityKind.reasoning); - expect(snapshot.tone, AgentActivityTone.info); - }, - ); - - test('surfaces concrete tool activity while assistant turn is live', () { - final snapshot = agentActivitySnapshotFromEvents( - sessionId: 'session-1', - events: [ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1000), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tool-1', - name: 'rg', - argsJson: DisplayPayload.inline(text: '{}'), - ), - ], - ); - - expect(snapshot, isNotNull); - expect(snapshot!.label, '调用工具 · rg'); - expect(snapshot.kind, AgentActivityKind.tool); - }); - - test('hides activity after the assistant turn completes', () { - final snapshot = agentActivitySnapshotFromEvents( - sessionId: 'session-1', - events: [ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1000), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'done'), - ), - UiEventMessage.messageCompleted( - messageId: 'assistant-1', - finishedAtMs: platformInt64FromInt(1001), - ), - ], - ); - - expect(snapshot, isNull); - }); - }); - - group('debugIsRunnableSessionStatus', () { - test('idle is not runnable for the activity ticker', () { - expect(debugIsRunnableSessionStatus('idle'), isFalse); - expect(debugIsRunnableSessionStatus('Idle'), isFalse); - expect(debugIsRunnableSessionStatus('completed'), isFalse); - expect(debugIsRunnableSessionStatus('ended'), isFalse); - expect(debugIsRunnableSessionStatus('pending'), isFalse); - }); - - test('running / streaming / stopping are runnable', () { - expect(debugIsRunnableSessionStatus('running'), isTrue); - expect(debugIsRunnableSessionStatus('streaming'), isTrue); - expect(debugIsRunnableSessionStatus('stopping'), isTrue); - }); - }); - - group('debugSessionAgentHostOnline', () { - test('returns false when the matched agent host is offline', () { - final session = _session(agentId: 'agent-1'); - final agent = _agent(hostDeviceId: 'host-1'); - final host = _host(hostDeviceId: 'host-1', online: false); - - expect( - debugSessionAgentHostOnline( - session: session, - agents: [agent], - hosts: [host], - activeHostId: 'host-1', - connectionState: const ConnectionState.connected(), - ), - isFalse, - ); - }); - - test('returns true when the matched agent host is online', () { - final session = _session(agentId: 'agent-1'); - final agent = _agent(hostDeviceId: 'host-1'); - final host = _host(hostDeviceId: 'host-1', online: true); - - expect( - debugSessionAgentHostOnline( - session: session, - agents: [agent], - hosts: [host], - activeHostId: 'host-1', - connectionState: const ConnectionState.connected(), - ), - isTrue, - ); - }); - }); -} - -AgentSessionSummaryDto _session({required String agentId}) { - return AgentSessionSummaryDto( - sessionId: 'session-1', - conversationId: 'conversation-1', - agentId: agentId, - status: 'running', - startedAtMs: platformInt64FromInt(1000), - lastActivityAtMs: platformInt64FromInt(1000), - messageCount: 1, - ); -} - -AgentProfile _agent({required String hostDeviceId}) { - return AgentProfile( - id: 'agent-1', - agentId: 'agent-1', - name: 'Agent', - description: '', - runtimeAgent: AgentName.codex, - model: 'gpt-5', - reasoningEffort: AgentReasoningEffort.medium, - environmentVariables: const [], - hostDeviceId: hostDeviceId, - createdAtMs: 1000, - updatedAtMs: 1000, - ); -} - -HostSummaryDto _host({required String hostDeviceId, required bool online}) { - return HostSummaryDto( - hostDeviceId: hostDeviceId, - hostDisplayName: 'Mac', - pairedAtMs: platformInt64FromInt(1000), - pairedViaDeviceId: 'phone-1', - online: online, - ); -} diff --git a/apps/mobile/test/application/root_route_decision_test.dart b/apps/mobile/test/application/root_route_decision_test.dart new file mode 100644 index 00000000..2d12d87b --- /dev/null +++ b/apps/mobile/test/application/root_route_decision_test.dart @@ -0,0 +1,76 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:minos/application/root_route_decision.dart'; +import 'package:minos/domain/auth_state.dart'; +import 'package:minos/src/rust/api/minos.dart'; + +void main() { + group('decideRootRoute', () { + test('bootstrapping and refreshing stay on splash', () { + expect( + decideRootRoute( + authState: const AuthBootstrapping(), + connectionState: null, + ), + RootRoute.splash, + ); + expect( + decideRootRoute( + authState: const AuthRefreshing(), + connectionState: const ConnectionState.connected(), + ), + RootRoute.splash, + ); + }); + + test('unauthenticated and refresh-failed go to login', () { + expect( + decideRootRoute( + authState: const AuthUnauthenticated(), + connectionState: null, + ), + RootRoute.login, + ); + expect( + decideRootRoute( + authState: const AuthRefreshFailed( + MinosError.authRefreshFailed(message: 'expired'), + ), + connectionState: null, + ), + RootRoute.login, + ); + }); + + test('authenticated maps connection to shell or shellOffline', () { + const auth = AuthAuthenticated( + AuthSummary(accountId: 'acc', email: 'a@b.c'), + ); + + expect( + decideRootRoute( + authState: auth, + connectionState: const ConnectionState.connected(), + ), + RootRoute.shell, + ); + expect( + decideRootRoute( + authState: auth, + connectionState: const ConnectionState.reconnecting(attempt: 1), + ), + RootRoute.shell, + ); + expect( + decideRootRoute(authState: auth, connectionState: null), + RootRoute.shellOffline, + ); + expect( + decideRootRoute( + authState: auth, + connectionState: const ConnectionState.disconnected(), + ), + RootRoute.shellOffline, + ); + }); + }); +} diff --git a/apps/mobile/test/application/social_conversation_state_test.dart b/apps/mobile/test/application/social_conversation_state_test.dart new file mode 100644 index 00000000..20d0ec63 --- /dev/null +++ b/apps/mobile/test/application/social_conversation_state_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:minos/application/social/social_conversation_state.dart'; +import 'package:minos/domain/social_message.dart'; +import 'package:minos/src/rust/api/minos.dart'; + +void main() { + MessageSender sender() => const MessageSender.account( + accountId: 'a', + minosId: 'm', + displayName: 'n', + ); + + SocialChatMessage msg({ + required String id, + int? serverOrderKey, + SocialMessageDeliveryState delivery = SocialMessageDeliveryState.sent, + }) { + return SocialChatMessage( + localId: id, + conversationId: 'c1', + sender: sender(), + text: id, + createdAtMs: 0, + clientSeq: 0, + deliveryState: delivery, + serverOrderKey: serverOrderKey, + serverMessageId: serverOrderKey != null ? id : null, + ); + } + + group('SocialConversationState', () { + test('initial is loading with empty timeline', () { + final state = SocialConversationState.initial(); + expect(state.isLoading, isTrue); + expect(state.messages, isEmpty); + expect(state.error, isNull); + expect(state.minLoadedSeq, isNull); + expect(state.maxLoadedSeq, isNull); + expect(state.hasOlder, isFalse); + expect(state.loadingOlder, isFalse); + }); + + test('withMessages recomputes durable seq window only', () { + final state = SocialConversationState.initial().withMessages([ + msg(id: 'p', delivery: SocialMessageDeliveryState.sending), + msg(id: 'a', serverOrderKey: 3), + msg(id: 'b', serverOrderKey: 9), + ]); + + expect(state.messages.map((m) => m.localId).toList(), [ + 'p', + 'a', + 'b', + ]); + expect(state.minLoadedSeq, 3); + expect(state.maxLoadedSeq, 9); + }); + + test('copyWith can clear error without clobbering messages', () { + final loaded = SocialConversationState( + myAccountId: 'acc', + messages: [msg(id: 'a', serverOrderKey: 1)], + minLoadedSeq: 1, + maxLoadedSeq: 1, + isLoading: false, + error: 'boom', + ); + + final cleared = loaded.copyWith(error: null); + expect(cleared.error, isNull); + expect(cleared.messages, hasLength(1)); + expect(cleared.myAccountId, 'acc'); + expect(cleared.isLoading, isFalse); + }); + + test('freezed equality covers meta fields (messages use identity)', () { + // SocialChatMessage is not value-equal, so two withMessages builds are + // not ==. Meta fields still compare via freezed. + const base = SocialConversationState( + myAccountId: 'acc', + minLoadedSeq: 1, + maxLoadedSeq: 2, + hasOlder: true, + isLoading: false, + ); + final same = base.copyWith(); + final different = base.copyWith(hasOlder: false); + expect(same, equals(base)); + expect(same.hashCode, equals(base.hashCode)); + expect(different, isNot(equals(base))); + }); + }); +} diff --git a/apps/mobile/test/application/thread_event_timeline_test.dart b/apps/mobile/test/application/thread_event_timeline_test.dart deleted file mode 100644 index 093c2374..00000000 --- a/apps/mobile/test/application/thread_event_timeline_test.dart +++ /dev/null @@ -1,281 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:minos/application/thread_event_timeline.dart'; -import 'package:minos/infrastructure/platform_int64.dart'; -import 'package:minos/src/rust/api/minos.dart'; - -void main() { - group('buildThreadEventTimeline', () { - test('places late reasoning after tools, not under the user message', () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'user-1', - role: MessageRole.user, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.textDelta( - messageId: 'user-1', - text: DisplayPayload.inline(text: 'do the task'), - ), - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(2), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tc-1', - name: 'read_file', - argsJson: DisplayPayload.inline(text: '{"path":"a.rs"}'), - ), - const UiEventMessage.toolCallCompleted( - toolCallId: 'tc-1', - output: DisplayPayload.inline(text: 'ok'), - isError: false, - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'after tools'), - ), - ]); - - expect(rows, hasLength(3)); - expect(rows[0], isA()); - expect(rows[1], isA()); - expect(rows[2], isA()); - expect((rows[2] as TimelineReasoning).text, 'after tools'); - expect(rows[2].eventIndex, greaterThan(rows[1].eventIndex)); - }); - - test('opens a new reasoning segment after intervening tools', () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'first'), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tc-1', - name: 'grep', - argsJson: DisplayPayload.inline(text: '{}'), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'second'), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'done'), - ), - ]); - - expect(rows.map((row) => row.runtimeType).toList(), [ - TimelineReasoning, - TimelineToolCall, - TimelineReasoning, - TimelineAssistantText, - ]); - expect((rows[0] as TimelineReasoning).text, 'first'); - expect((rows[2] as TimelineReasoning).text, 'second'); - expect((rows[3] as TimelineAssistantText).text, 'done'); - }); - - test('streams contiguous reasoning deltas onto the same item', () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'think'), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: ' more'), - ), - ]); - - expect(rows, hasLength(1)); - expect((rows.single as TimelineReasoning).text, 'think more'); - }); - - test('shows live placeholder only before first content arrives', () { - final waiting = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - ], showLiveAssistantState: true); - expect(waiting, hasLength(1)); - expect(waiting.single, isA()); - - final withTool = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tc-1', - name: 'read_file', - argsJson: DisplayPayload.inline(text: '{}'), - ), - ], showLiveAssistantState: true); - expect(withTool, hasLength(1)); - expect(withTool.single, isA()); - }); - - test( - 'splits intermediate and final assistant text across tools (ACP/Grok)', - () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'user-1', - role: MessageRole.user, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.textDelta( - messageId: 'user-1', - text: DisplayPayload.inline(text: 'fix the bug'), - ), - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(2), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'Looking into it.'), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tc-1', - name: 'read_file', - argsJson: DisplayPayload.inline(text: '{}'), - ), - const UiEventMessage.toolCallCompleted( - toolCallId: 'tc-1', - output: DisplayPayload.inline(text: 'ok'), - isError: false, - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'found the issue'), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'Here is the fix.'), - ), - UiEventMessage.messageCompleted( - messageId: 'assistant-1', - finishedAtMs: platformInt64FromInt(3), - ), - ], showLiveAssistantState: true); - - expect(rows.map((row) => row.runtimeType).toList(), [ - TimelineUserMessage, - TimelineAssistantText, - TimelineToolCall, - TimelineReasoning, - TimelineAssistantText, - ]); - expect((rows[1] as TimelineAssistantText).text, 'Looking into it.'); - expect((rows[1] as TimelineAssistantText).showCursor, isFalse); - expect((rows[3] as TimelineReasoning).text, 'found the issue'); - expect((rows[3] as TimelineReasoning).isLive, isFalse); - expect((rows[4] as TimelineAssistantText).text, 'Here is the fix.'); - expect((rows[4] as TimelineAssistantText).showCursor, isFalse); - expect(rows[4].eventIndex, greaterThan(rows[3].eventIndex)); - }, - ); - - test('streams contiguous assistant text onto the same item', () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'Hel'), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'lo'), - ), - ], showLiveAssistantState: true); - - expect(rows, hasLength(1)); - final text = rows.single as TimelineAssistantText; - expect(text.text, 'Hello'); - expect(text.showCursor, isTrue); - }); - - test('only open reasoning segment is live while turn continues', () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'first thought'), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tc-1', - name: 'grep', - argsJson: DisplayPayload.inline(text: '{}'), - ), - const UiEventMessage.reasoningDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'second thought'), - ), - ], showLiveAssistantState: true); - - expect(rows.map((row) => row.runtimeType).toList(), [ - TimelineReasoning, - TimelineToolCall, - TimelineReasoning, - ]); - expect((rows[0] as TimelineReasoning).isLive, isFalse); - expect((rows[2] as TimelineReasoning).isLive, isTrue); - }); - - test('intermediate text loses cursor once tools begin', () { - final rows = buildThreadEventTimeline([ - UiEventMessage.messageStarted( - messageId: 'assistant-1', - role: MessageRole.assistant, - startedAtMs: platformInt64FromInt(1), - ), - const UiEventMessage.textDelta( - messageId: 'assistant-1', - text: DisplayPayload.inline(text: 'starting'), - ), - const UiEventMessage.toolCallPlaced( - messageId: 'assistant-1', - toolCallId: 'tc-1', - name: 'read_file', - argsJson: DisplayPayload.inline(text: '{}'), - ), - ], showLiveAssistantState: true); - - expect(rows.map((row) => row.runtimeType).toList(), [ - TimelineAssistantText, - TimelineToolCall, - ]); - expect((rows[0] as TimelineAssistantText).showCursor, isFalse); - }); - }); -} diff --git a/apps/mobile/test/ui/widgets/message_bubble_test.dart b/apps/mobile/test/ui/widgets/message_bubble_test.dart deleted file mode 100644 index 21f6b0e7..00000000 --- a/apps/mobile/test/ui/widgets/message_bubble_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:minos/ui/features/chat/widgets/message_bubble.dart'; -import 'package:minos/ui/theme/theme.dart'; - -void main() { - Widget wrap(Widget child) { - return MaterialApp( - theme: MinosTheme.light(), - home: Scaffold(body: child), - ); - } - - testWidgets('user bubble renders markdown content', (tester) async { - await tester.pumpWidget( - wrap( - const MessageBubble(isUser: true, markdownContent: 'Hello from phone'), - ), - ); - - expect(find.text('Hello from phone'), findsOneWidget); - }); - - testWidgets('assistant bubble shows streaming cursor', (tester) async { - await tester.pumpWidget( - wrap( - const MessageBubble( - isUser: false, - markdownContent: 'Thinking…', - isStreaming: true, - ), - ), - ); - - expect(find.text('Thinking…'), findsOneWidget); - expect( - find.byKey(const ValueKey('streaming-cursor')), - findsOneWidget, - ); - }); -} diff --git a/crates/minos-ffi-frb/src/api/minos.rs b/crates/minos-ffi-frb/src/api/minos.rs index 491d9c54..19b38809 100644 --- a/crates/minos-ffi-frb/src/api/minos.rs +++ b/crates/minos-ffi-frb/src/api/minos.rs @@ -286,14 +286,6 @@ impl MobileClient { self.0.my_profile().await } - pub async fn set_minos_id(&self, minos_id: String) -> Result { - self.0.set_minos_id(minos_id).await - } - - pub async fn search_users(&self, minos_id: String) -> Result, MinosError> { - self.0.search_users(minos_id).await - } - pub async fn friends(&self) -> Result { self.0.friends().await } @@ -356,31 +348,6 @@ impl MobileClient { self.0.list_agents().await } - pub async fn create_friend_request( - &self, - target_minos_id: String, - ) -> Result { - self.0.create_friend_request(target_minos_id).await - } - - pub async fn friend_requests(&self) -> Result { - self.0.friend_requests().await - } - - pub async fn accept_friend_request( - &self, - request_id: String, - ) -> Result { - self.0.accept_friend_request(request_id).await - } - - pub async fn reject_friend_request( - &self, - request_id: String, - ) -> Result { - self.0.reject_friend_request(request_id).await - } - pub async fn conversations(&self) -> Result { self.0.conversations().await } @@ -555,29 +522,6 @@ impl MobileClient { Ok(self.0.active_host().await?.map(|id| id.to_string())) } - /// Request a page of thread summaries. - pub async fn list_sessions( - &self, - req: ListSessionsParams, - ) -> Result { - self.0.list_sessions(req).await - } - - pub async fn list_agent_sessions( - &self, - conversation_id: Option, - limit: u32, - ) -> Result, MinosError> { - self.0 - .list_agent_sessions(conversation_id, limit) - .await - .map(|sessions| sessions.into_iter().map(Into::into).collect()) - } - - pub async fn subscribe_agent_session(&self, session_id: String) -> Result<(), MinosError> { - self.0.subscribe_agent_session(session_id).await - } - /// Open-chat live path: subscribe `conversation:{id}` for full T1 frames. pub async fn subscribe_conversation(&self, conversation_id: String) -> Result<(), MinosError> { self.0.subscribe_conversation(conversation_id).await @@ -596,14 +540,6 @@ impl MobileClient { self.0.ack_durable_applied(topic, topic_seq).await; } - /// Read a window of translated UI events for one session. - pub async fn read_session( - &self, - req: ReadSessionParams, - ) -> Result { - self.0.read_session(req).await - } - /// Export the current pairing snapshot so Dart can mirror it into secure /// storage after pairing succeeds. pub async fn persisted_pairing_state(&self) -> Result { @@ -738,96 +674,31 @@ impl MobileClient { } /// Send a follow-up user message to an existing agent session. - pub async fn send_user_message( - &self, - session_id: String, - text: String, - ) -> Result<(), MinosError> { - self.0.send_user_message(session_id, text).await - } /// Submit a user approval decision for a pending host request. /// /// `client_request_id` is the Hub Intent Outbox id. When omitted, /// the mobile client generates one so the wire body never hardcodes null. - pub async fn send_approval_decision( - &self, - request_id: String, - session_id: String, - decision_json: String, - client_request_id: Option, - ) -> Result<(), MinosError> { - let decision = - serde_json::from_str(&decision_json).map_err(|error| MinosError::RpcCallFailed { - method: "send_approval_decision".into(), - message: format!("invalid approval decision json: {error}"), - })?; - self.0 - .send_approval_decision(request_id, session_id, decision, client_request_id) - .await - } /// Submit an opencode question answer for a pending host request. - pub async fn respond_opencode_question( - &self, - session_id: String, - question_id: String, - answers_json: String, - ) -> Result<(), MinosError> { - let answers = - serde_json::from_str(&answers_json).map_err(|error| MinosError::RpcCallFailed { - method: "respond_opencode_question".into(), - message: format!("invalid opencode question answers json: {error}"), - })?; - self.0 - .respond_opencode_question(session_id, question_id, answers) - .await - } /// Pause an in-flight turn on the given thread. Best-effort. The thread /// transitions to `Suspended { UserInterrupt }` regardless of whether the /// codex side acknowledges in time. - pub async fn interrupt_session(&self, session_id: String) -> Result<(), MinosError> { - self.0.interrupt_session(session_id).await - } /// Permanently close the given thread. Idempotent. - pub async fn close_session(&self, session_id: String) -> Result<(), MinosError> { - self.0.close_session(session_id).await - } // ─────────────────────────── project rpcs ────────────────────────────── /// Create a new project on the daemon. - pub async fn create_project( - &self, - req: CreateProjectRequest, - ) -> Result { - self.0.create_project(req).await - } /// List all projects on the daemon. - pub async fn list_projects(&self) -> Result { - self.0.list_projects().await - } /// Update a project's name. - pub async fn update_project(&self, req: UpdateProjectRequest) -> Result<(), MinosError> { - self.0.update_project(req).await - } /// Delete a project. - pub async fn delete_project(&self, req: DeleteProjectRequest) -> Result<(), MinosError> { - self.0.delete_project(req).await - } /// List sessions within a project. - pub async fn list_project_sessions( - &self, - req: ListProjectSessionsParams, - ) -> Result { - self.0.list_project_sessions(req).await - } // ─────────────────────────── lifecycle hooks ─────────────────────────── diff --git a/crates/minos-ffi-frb/src/frb_generated.rs b/crates/minos-ffi-frb/src/frb_generated.rs index e86bd412..4553671b 100644 --- a/crates/minos-ffi-frb/src/frb_generated.rs +++ b/crates/minos-ffi-frb/src/frb_generated.rs @@ -39,7 +39,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.12.0"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -520281445; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -801214882; // Section: executor @@ -47,66 +47,6 @@ flutter_rust_bridge::frb_generated_default_handler!(); // Section: wire_funcs -fn wire__crate__api__minos__MobileClient_accept_friend_request_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_accept_friend_request", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_request_id = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::accept_friend_request( - &*api_that_guard, - api_request_id, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} fn wire__crate__api__minos__MobileClient_ack_durable_applied_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -351,7 +291,7 @@ fn wire__crate__api__minos__MobileClient_add_group_member_impl( }, ) } -fn wire__crate__api__minos__MobileClient_close_session_impl( +fn wire__crate__api__minos__MobileClient_conversation_members_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -359,7 +299,7 @@ fn wire__crate__api__minos__MobileClient_close_session_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_close_session", + debug_name: "MobileClient_conversation_members", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -376,7 +316,7 @@ fn wire__crate__api__minos__MobileClient_close_session_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_session_id = ::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -398,9 +338,9 @@ fn wire__crate__api__minos__MobileClient_close_session_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::close_session( + let output_ok = crate::api::minos::MobileClient::conversation_members( &*api_that_guard, - api_session_id, + api_conversation_id, ) .await?; Ok(output_ok) @@ -411,7 +351,7 @@ fn wire__crate__api__minos__MobileClient_close_session_impl( }, ) } -fn wire__crate__api__minos__MobileClient_conversation_members_impl( +fn wire__crate__api__minos__MobileClient_conversations_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -419,7 +359,7 @@ fn wire__crate__api__minos__MobileClient_conversation_members_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_conversation_members", + debug_name: "MobileClient_conversations", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -436,7 +376,6 @@ fn wire__crate__api__minos__MobileClient_conversation_members_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -458,11 +397,9 @@ fn wire__crate__api__minos__MobileClient_conversation_members_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::conversation_members( - &*api_that_guard, - api_conversation_id, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::conversations(&*api_that_guard) + .await?; Ok(output_ok) })() .await, @@ -471,7 +408,7 @@ fn wire__crate__api__minos__MobileClient_conversation_members_impl( }, ) } -fn wire__crate__api__minos__MobileClient_conversations_impl( +fn wire__crate__api__minos__MobileClient_create_group_conversation_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -479,7 +416,7 @@ fn wire__crate__api__minos__MobileClient_conversations_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_conversations", + debug_name: "MobileClient_create_group_conversation", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -496,6 +433,8 @@ fn wire__crate__api__minos__MobileClient_conversations_impl( let api_that = , >>::sse_decode(&mut deserializer); + let api_title = ::sse_decode(&mut deserializer); + let api_member_account_ids = >::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -517,9 +456,12 @@ fn wire__crate__api__minos__MobileClient_conversations_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::conversations(&*api_that_guard) - .await?; + let output_ok = crate::api::minos::MobileClient::create_group_conversation( + &*api_that_guard, + api_title, + api_member_account_ids, + ) + .await?; Ok(output_ok) })() .await, @@ -528,7 +470,55 @@ fn wire__crate__api__minos__MobileClient_conversations_impl( }, ) } -fn wire__crate__api__minos__MobileClient_create_friend_request_impl( +fn wire__crate__api__minos__MobileClient_current_state_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "MobileClient_current_state", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Result::<_, ()>::Ok( + crate::api::minos::MobileClient::current_state(&*api_that_guard), + )?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__minos__MobileClient_delete_conversation_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -536,7 +526,7 @@ fn wire__crate__api__minos__MobileClient_create_friend_request_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_create_friend_request", + debug_name: "MobileClient_delete_conversation", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -553,7 +543,7 @@ fn wire__crate__api__minos__MobileClient_create_friend_request_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_target_minos_id = ::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -575,9 +565,9 @@ fn wire__crate__api__minos__MobileClient_create_friend_request_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::create_friend_request( + let output_ok = crate::api::minos::MobileClient::delete_conversation( &*api_that_guard, - api_target_minos_id, + api_conversation_id, ) .await?; Ok(output_ok) @@ -588,7 +578,7 @@ fn wire__crate__api__minos__MobileClient_create_friend_request_impl( }, ) } -fn wire__crate__api__minos__MobileClient_create_group_conversation_impl( +fn wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -596,7 +586,7 @@ fn wire__crate__api__minos__MobileClient_create_group_conversation_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_create_group_conversation", + debug_name: "MobileClient_ensure_direct_conversation", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -613,8 +603,7 @@ fn wire__crate__api__minos__MobileClient_create_group_conversation_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_title = ::sse_decode(&mut deserializer); - let api_member_account_ids = >::sse_decode(&mut deserializer); + let api_friend_account_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -636,12 +625,12 @@ fn wire__crate__api__minos__MobileClient_create_group_conversation_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::create_group_conversation( - &*api_that_guard, - api_title, - api_member_account_ids, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::ensure_direct_conversation( + &*api_that_guard, + api_friend_account_id, + ) + .await?; Ok(output_ok) })() .await, @@ -650,7 +639,7 @@ fn wire__crate__api__minos__MobileClient_create_group_conversation_impl( }, ) } -fn wire__crate__api__minos__MobileClient_create_project_impl( +fn wire__crate__api__minos__MobileClient_forget_host_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -658,7 +647,7 @@ fn wire__crate__api__minos__MobileClient_create_project_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_create_project", + debug_name: "MobileClient_forget_host", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -675,7 +664,7 @@ fn wire__crate__api__minos__MobileClient_create_project_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_req = ::sse_decode(&mut deserializer); + let api_host_device_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -697,9 +686,9 @@ fn wire__crate__api__minos__MobileClient_create_project_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::create_project( + let output_ok = crate::api::minos::MobileClient::forget_host( &*api_that_guard, - api_req, + api_host_device_id, ) .await?; Ok(output_ok) @@ -710,16 +699,17 @@ fn wire__crate__api__minos__MobileClient_create_project_impl( }, ) } -fn wire__crate__api__minos__MobileClient_current_state_impl( +fn wire__crate__api__minos__MobileClient_friends_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_current_state", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + debug_name: "MobileClient_friends", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { @@ -735,30 +725,37 @@ fn wire__crate__api__minos__MobileClient_current_state_impl( flutter_rust_bridge::for_generated::RustAutoOpaqueInner, >>::sse_decode(&mut deserializer); deserializer.end(); - transform_result_sse::<_, ()>((move || { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ - flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - ), - ]); - for i in decode_indices_ { - match i { - 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok( - crate::api::minos::MobileClient::current_state(&*api_that_guard), - )?; - Ok(output_ok) - })()) + move |context| async move { + transform_result_sse::<_, crate::api::minos::MinosError>( + (move || async move { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => { + api_that_guard = + Some(api_that.lockable_decode_async_ref().await) + } + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::minos::MobileClient::friends(&*api_that_guard).await?; + Ok(output_ok) + })() + .await, + ) + } }, ) } -fn wire__crate__api__minos__MobileClient_delete_conversation_impl( +fn wire__crate__api__minos__MobileClient_list_agents_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -766,7 +763,7 @@ fn wire__crate__api__minos__MobileClient_delete_conversation_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_delete_conversation", + debug_name: "MobileClient_list_agents", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -783,7 +780,6 @@ fn wire__crate__api__minos__MobileClient_delete_conversation_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -805,11 +801,8 @@ fn wire__crate__api__minos__MobileClient_delete_conversation_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::delete_conversation( - &*api_that_guard, - api_conversation_id, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::list_agents(&*api_that_guard).await?; Ok(output_ok) })() .await, @@ -818,7 +811,7 @@ fn wire__crate__api__minos__MobileClient_delete_conversation_impl( }, ) } -fn wire__crate__api__minos__MobileClient_delete_project_impl( +fn wire__crate__api__minos__MobileClient_list_chat_messages_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -826,7 +819,7 @@ fn wire__crate__api__minos__MobileClient_delete_project_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_delete_project", + debug_name: "MobileClient_list_chat_messages", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -843,7 +836,10 @@ fn wire__crate__api__minos__MobileClient_delete_project_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_req = ::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); + let api_before_seq = >::sse_decode(&mut deserializer); + let api_after_seq = >::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -865,9 +861,12 @@ fn wire__crate__api__minos__MobileClient_delete_project_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::delete_project( + let output_ok = crate::api::minos::MobileClient::list_chat_messages( &*api_that_guard, - api_req, + api_conversation_id, + api_before_seq, + api_after_seq, + api_limit, ) .await?; Ok(output_ok) @@ -878,7 +877,7 @@ fn wire__crate__api__minos__MobileClient_delete_project_impl( }, ) } -fn wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( +fn wire__crate__api__minos__MobileClient_list_clis_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -886,7 +885,7 @@ fn wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_ensure_direct_conversation", + debug_name: "MobileClient_list_clis", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -903,7 +902,6 @@ fn wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_friend_account_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -926,11 +924,7 @@ fn wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::minos::MobileClient::ensure_direct_conversation( - &*api_that_guard, - api_friend_account_id, - ) - .await?; + crate::api::minos::MobileClient::list_clis(&*api_that_guard).await?; Ok(output_ok) })() .await, @@ -939,7 +933,7 @@ fn wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( }, ) } -fn wire__crate__api__minos__MobileClient_forget_host_impl( +fn wire__crate__api__minos__MobileClient_list_conversation_agents_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -947,7 +941,7 @@ fn wire__crate__api__minos__MobileClient_forget_host_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_forget_host", + debug_name: "MobileClient_list_conversation_agents", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -964,7 +958,7 @@ fn wire__crate__api__minos__MobileClient_forget_host_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_host_device_id = ::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -986,9 +980,9 @@ fn wire__crate__api__minos__MobileClient_forget_host_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::forget_host( + let output_ok = crate::api::minos::MobileClient::list_conversation_agents( &*api_that_guard, - api_host_device_id, + api_conversation_id, ) .await?; Ok(output_ok) @@ -999,7 +993,7 @@ fn wire__crate__api__minos__MobileClient_forget_host_impl( }, ) } -fn wire__crate__api__minos__MobileClient_friend_requests_impl( +fn wire__crate__api__minos__MobileClient_list_conversation_participants_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1007,7 +1001,7 @@ fn wire__crate__api__minos__MobileClient_friend_requests_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_friend_requests", + debug_name: "MobileClient_list_conversation_participants", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1024,6 +1018,7 @@ fn wire__crate__api__minos__MobileClient_friend_requests_impl( let api_that = , >>::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1046,8 +1041,11 @@ fn wire__crate__api__minos__MobileClient_friend_requests_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::minos::MobileClient::friend_requests(&*api_that_guard) - .await?; + crate::api::minos::MobileClient::list_conversation_participants( + &*api_that_guard, + api_conversation_id, + ) + .await?; Ok(output_ok) })() .await, @@ -1056,7 +1054,7 @@ fn wire__crate__api__minos__MobileClient_friend_requests_impl( }, ) } -fn wire__crate__api__minos__MobileClient_friends_impl( +fn wire__crate__api__minos__MobileClient_list_host_skills_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1064,7 +1062,7 @@ fn wire__crate__api__minos__MobileClient_friends_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_friends", + debug_name: "MobileClient_list_host_skills", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1081,6 +1079,8 @@ fn wire__crate__api__minos__MobileClient_friends_impl( let api_that = , >>::sse_decode(&mut deserializer); + let api_host_device_id = >::sse_decode(&mut deserializer); + let api_force_reload = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1102,8 +1102,12 @@ fn wire__crate__api__minos__MobileClient_friends_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::friends(&*api_that_guard).await?; + let output_ok = crate::api::minos::MobileClient::list_host_skills( + &*api_that_guard, + api_host_device_id, + api_force_reload, + ) + .await?; Ok(output_ok) })() .await, @@ -1112,7 +1116,7 @@ fn wire__crate__api__minos__MobileClient_friends_impl( }, ) } -fn wire__crate__api__minos__MobileClient_interrupt_session_impl( +fn wire__crate__api__minos__MobileClient_list_host_workspaces_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1120,7 +1124,7 @@ fn wire__crate__api__minos__MobileClient_interrupt_session_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_interrupt_session", + debug_name: "MobileClient_list_host_workspaces", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1137,7 +1141,9 @@ fn wire__crate__api__minos__MobileClient_interrupt_session_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_session_id = ::sse_decode(&mut deserializer); + let api_host_device_id = >::sse_decode(&mut deserializer); + let api_root = >::sse_decode(&mut deserializer); + let api_limit = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1159,9 +1165,11 @@ fn wire__crate__api__minos__MobileClient_interrupt_session_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::interrupt_session( + let output_ok = crate::api::minos::MobileClient::list_host_workspaces( &*api_that_guard, - api_session_id, + api_host_device_id, + api_root, + api_limit, ) .await?; Ok(output_ok) @@ -1172,7 +1180,7 @@ fn wire__crate__api__minos__MobileClient_interrupt_session_impl( }, ) } -fn wire__crate__api__minos__MobileClient_list_agent_sessions_impl( +fn wire__crate__api__minos__MobileClient_list_paired_hosts_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1180,7 +1188,7 @@ fn wire__crate__api__minos__MobileClient_list_agent_sessions_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_agent_sessions", + debug_name: "MobileClient_list_paired_hosts", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1197,8 +1205,6 @@ fn wire__crate__api__minos__MobileClient_list_agent_sessions_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_conversation_id = >::sse_decode(&mut deserializer); - let api_limit = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1220,12 +1226,9 @@ fn wire__crate__api__minos__MobileClient_list_agent_sessions_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_agent_sessions( - &*api_that_guard, - api_conversation_id, - api_limit, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::list_paired_hosts(&*api_that_guard) + .await?; Ok(output_ok) })() .await, @@ -1234,7 +1237,7 @@ fn wire__crate__api__minos__MobileClient_list_agent_sessions_impl( }, ) } -fn wire__crate__api__minos__MobileClient_list_agents_impl( +fn wire__crate__api__minos__MobileClient_login_with_supabase_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1242,7 +1245,7 @@ fn wire__crate__api__minos__MobileClient_list_agents_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_agents", + debug_name: "MobileClient_login_with_supabase", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1259,6 +1262,7 @@ fn wire__crate__api__minos__MobileClient_list_agents_impl( let api_that = , >>::sse_decode(&mut deserializer); + let api_supabase_access_token = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1280,8 +1284,11 @@ fn wire__crate__api__minos__MobileClient_list_agents_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::list_agents(&*api_that_guard).await?; + let output_ok = crate::api::minos::MobileClient::login_with_supabase( + &*api_that_guard, + api_supabase_access_token, + ) + .await?; Ok(output_ok) })() .await, @@ -1290,7 +1297,7 @@ fn wire__crate__api__minos__MobileClient_list_agents_impl( }, ) } -fn wire__crate__api__minos__MobileClient_list_chat_messages_impl( +fn wire__crate__api__minos__MobileClient_logout_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1298,7 +1305,7 @@ fn wire__crate__api__minos__MobileClient_list_chat_messages_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_chat_messages", + debug_name: "MobileClient_logout", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1315,10 +1322,6 @@ fn wire__crate__api__minos__MobileClient_list_chat_messages_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); - let api_before_seq = >::sse_decode(&mut deserializer); - let api_after_seq = >::sse_decode(&mut deserializer); - let api_limit = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1340,14 +1343,8 @@ fn wire__crate__api__minos__MobileClient_list_chat_messages_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_chat_messages( - &*api_that_guard, - api_conversation_id, - api_before_seq, - api_after_seq, - api_limit, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::logout(&*api_that_guard).await?; Ok(output_ok) })() .await, @@ -1356,7 +1353,7 @@ fn wire__crate__api__minos__MobileClient_list_chat_messages_impl( }, ) } -fn wire__crate__api__minos__MobileClient_list_clis_impl( +fn wire__crate__api__minos__MobileClient_mark_conversation_read_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1364,7 +1361,7 @@ fn wire__crate__api__minos__MobileClient_list_clis_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_clis", + debug_name: "MobileClient_mark_conversation_read", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1381,6 +1378,8 @@ fn wire__crate__api__minos__MobileClient_list_clis_impl( let api_that = , >>::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); + let api_read_up_to_message_seq = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1402,8 +1401,12 @@ fn wire__crate__api__minos__MobileClient_list_clis_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::list_clis(&*api_that_guard).await?; + let output_ok = crate::api::minos::MobileClient::mark_conversation_read( + &*api_that_guard, + api_conversation_id, + api_read_up_to_message_seq, + ) + .await?; Ok(output_ok) })() .await, @@ -1412,7 +1415,7 @@ fn wire__crate__api__minos__MobileClient_list_clis_impl( }, ) } -fn wire__crate__api__minos__MobileClient_list_conversation_agents_impl( +fn wire__crate__api__minos__MobileClient_my_profile_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1420,7 +1423,7 @@ fn wire__crate__api__minos__MobileClient_list_conversation_agents_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_conversation_agents", + debug_name: "MobileClient_my_profile", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -1437,7 +1440,6 @@ fn wire__crate__api__minos__MobileClient_list_conversation_agents_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -1459,11 +1461,8 @@ fn wire__crate__api__minos__MobileClient_list_conversation_agents_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_conversation_agents( - &*api_that_guard, - api_conversation_id, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::my_profile(&*api_that_guard).await?; Ok(output_ok) })() .await, @@ -1472,17 +1471,16 @@ fn wire__crate__api__minos__MobileClient_list_conversation_agents_impl( }, ) } -fn wire__crate__api__minos__MobileClient_list_conversation_participants_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, +fn wire__crate__api__minos__MobileClient_new_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_conversation_participants", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + debug_name: "MobileClient_new", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, move || { let message = unsafe { @@ -1494,56 +1492,26 @@ fn wire__crate__api__minos__MobileClient_list_conversation_participants_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); + let api_self_name = ::sse_decode(&mut deserializer); deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::list_conversation_participants( - &*api_that_guard, - api_conversation_id, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::minos::MobileClient::new(api_self_name))?; + Ok(output_ok) + })()) }, ) } -fn wire__crate__api__minos__MobileClient_list_host_skills_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, +fn wire__crate__api__minos__MobileClient_new_with_persisted_state_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_host_skills", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + debug_name: "MobileClient_new_with_persisted_state", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, move || { let message = unsafe { @@ -1555,57 +1523,32 @@ fn wire__crate__api__minos__MobileClient_list_host_skills_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_host_device_id = >::sse_decode(&mut deserializer); - let api_force_reload = ::sse_decode(&mut deserializer); + let api_self_name = ::sse_decode(&mut deserializer); + let api_state = + ::sse_decode(&mut deserializer); deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_host_skills( - &*api_that_guard, - api_host_device_id, - api_force_reload, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok( + crate::api::minos::MobileClient::new_with_persisted_state( + api_self_name, + api_state, + ), + )?; + Ok(output_ok) + })()) }, ) } -fn wire__crate__api__minos__MobileClient_list_host_workspaces_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, +fn wire__crate__api__minos__MobileClient_notify_backgrounded_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_host_workspaces", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + debug_name: "MobileClient_notify_backgrounded", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, move || { let message = unsafe { @@ -1620,1123 +1563,40 @@ fn wire__crate__api__minos__MobileClient_list_host_workspaces_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_host_device_id = >::sse_decode(&mut deserializer); - let api_root = >::sse_decode(&mut deserializer); - let api_limit = ::sse_decode(&mut deserializer); deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_host_workspaces( - &*api_that_guard, - api_host_device_id, - api_root, - api_limit, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_list_paired_hosts_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_paired_hosts", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::list_paired_hosts(&*api_that_guard) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_list_project_sessions_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_project_sessions", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_req = - ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_project_sessions( - &*api_that_guard, - api_req, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_list_projects_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_projects", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::list_projects(&*api_that_guard) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_list_sessions_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_list_sessions", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_req = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::list_sessions( - &*api_that_guard, - api_req, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_login_with_supabase_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_login_with_supabase", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_supabase_access_token = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::login_with_supabase( - &*api_that_guard, - api_supabase_access_token, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_logout_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_logout", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::logout(&*api_that_guard).await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_mark_conversation_read_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_mark_conversation_read", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); - let api_read_up_to_message_seq = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::mark_conversation_read( - &*api_that_guard, - api_conversation_id, - api_read_up_to_message_seq, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_my_profile_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_my_profile", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::my_profile(&*api_that_guard).await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_new_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_new", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_self_name = ::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse::<_, ()>((move || { - let output_ok = - Result::<_, ()>::Ok(crate::api::minos::MobileClient::new(api_self_name))?; - Ok(output_ok) - })()) - }, - ) -} -fn wire__crate__api__minos__MobileClient_new_with_persisted_state_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_new_with_persisted_state", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_self_name = ::sse_decode(&mut deserializer); - let api_state = - ::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse::<_, ()>((move || { - let output_ok = Result::<_, ()>::Ok( - crate::api::minos::MobileClient::new_with_persisted_state( - api_self_name, - api_state, - ), - )?; - Ok(output_ok) - })()) - }, - ) -} -fn wire__crate__api__minos__MobileClient_notify_backgrounded_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_notify_backgrounded", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse::<_, ()>((move || { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ - flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - ), - ]); - for i in decode_indices_ { - match i { - 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok({ - crate::api::minos::MobileClient::notify_backgrounded(&*api_that_guard); - })?; - Ok(output_ok) - })()) - }, - ) -} -fn wire__crate__api__minos__MobileClient_notify_foregrounded_impl( - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_notify_foregrounded", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - transform_result_sse::<_, ()>((move || { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ - flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - ), - ]); - for i in decode_indices_ { - match i { - 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok({ - crate::api::minos::MobileClient::notify_foregrounded(&*api_that_guard); - })?; - Ok(output_ok) - })()) - }, - ) -} -fn wire__crate__api__minos__MobileClient_persisted_pairing_state_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_persisted_pairing_state", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::persisted_pairing_state( - &*api_that_guard, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_read_session_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_read_session", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_req = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::read_session( - &*api_that_guard, - api_req, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_recall_chat_message_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_recall_chat_message", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); - let api_message_id = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::recall_chat_message( - &*api_that_guard, - api_conversation_id, - api_message_id, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_refresh_session_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_refresh_session", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::refresh_session(&*api_that_guard) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_register_agent_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_register_agent", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_name = ::sse_decode(&mut deserializer); - let api_description = ::sse_decode(&mut deserializer); - let api_runtime_agent = ::sse_decode(&mut deserializer); - let api_model = ::sse_decode(&mut deserializer); - let api_workspace_path = >::sse_decode(&mut deserializer); - let api_display_name = >::sse_decode(&mut deserializer); - let api_default_reasoning_effort = >::sse_decode(&mut deserializer); - let api_system_prompt = >::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::register_agent( - &*api_that_guard, - api_name, - api_description, - api_runtime_agent, - api_model, - api_workspace_path, - api_display_name, - api_default_reasoning_effort, - api_system_prompt, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_reject_friend_request_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_reject_friend_request", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_request_id = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::reject_friend_request( - &*api_that_guard, - api_request_id, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} -fn wire__crate__api__minos__MobileClient_remove_agent_from_conversation_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_remove_agent_from_conversation", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); - let api_agent_id = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::minos::MobileClient::remove_agent_from_conversation( - &*api_that_guard, - api_conversation_id, - api_agent_id, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Result::<_, ()>::Ok({ + crate::api::minos::MobileClient::notify_backgrounded(&*api_that_guard); + })?; + Ok(output_ok) + })()) }, ) } -fn wire__crate__api__minos__MobileClient_remove_group_member_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, +fn wire__crate__api__minos__MobileClient_notify_foregrounded_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_remove_group_member", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + debug_name: "MobileClient_notify_foregrounded", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, move || { let message = unsafe { @@ -2751,44 +1611,31 @@ fn wire__crate__api__minos__MobileClient_remove_group_member_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_conversation_id = ::sse_decode(&mut deserializer); - let api_member_account_id = ::sse_decode(&mut deserializer); deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::remove_group_member( - &*api_that_guard, - api_conversation_id, - api_member_account_id, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Result::<_, ()>::Ok({ + crate::api::minos::MobileClient::notify_foregrounded(&*api_that_guard); + })?; + Ok(output_ok) + })()) }, ) } -fn wire__crate__api__minos__MobileClient_respond_opencode_question_impl( +fn wire__crate__api__minos__MobileClient_persisted_pairing_state_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -2796,7 +1643,7 @@ fn wire__crate__api__minos__MobileClient_respond_opencode_question_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_respond_opencode_question", + debug_name: "MobileClient_persisted_pairing_state", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -2813,9 +1660,6 @@ fn wire__crate__api__minos__MobileClient_respond_opencode_question_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_session_id = ::sse_decode(&mut deserializer); - let api_question_id = ::sse_decode(&mut deserializer); - let api_answers_json = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -2837,11 +1681,8 @@ fn wire__crate__api__minos__MobileClient_respond_opencode_question_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::respond_opencode_question( + let output_ok = crate::api::minos::MobileClient::persisted_pairing_state( &*api_that_guard, - api_session_id, - api_question_id, - api_answers_json, ) .await?; Ok(output_ok) @@ -2852,7 +1693,7 @@ fn wire__crate__api__minos__MobileClient_respond_opencode_question_impl( }, ) } -fn wire__crate__api__minos__MobileClient_resume_persisted_session_impl( +fn wire__crate__api__minos__MobileClient_recall_chat_message_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -2860,7 +1701,7 @@ fn wire__crate__api__minos__MobileClient_resume_persisted_session_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_resume_persisted_session", + debug_name: "MobileClient_recall_chat_message", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -2877,6 +1718,8 @@ fn wire__crate__api__minos__MobileClient_resume_persisted_session_impl( let api_that = , >>::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); + let api_message_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -2898,8 +1741,10 @@ fn wire__crate__api__minos__MobileClient_resume_persisted_session_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::resume_persisted_session( + let output_ok = crate::api::minos::MobileClient::recall_chat_message( &*api_that_guard, + api_conversation_id, + api_message_id, ) .await?; Ok(output_ok) @@ -2910,7 +1755,7 @@ fn wire__crate__api__minos__MobileClient_resume_persisted_session_impl( }, ) } -fn wire__crate__api__minos__MobileClient_search_users_impl( +fn wire__crate__api__minos__MobileClient_refresh_session_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -2918,7 +1763,7 @@ fn wire__crate__api__minos__MobileClient_search_users_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_search_users", + debug_name: "MobileClient_refresh_session", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -2935,7 +1780,6 @@ fn wire__crate__api__minos__MobileClient_search_users_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_minos_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -2957,11 +1801,9 @@ fn wire__crate__api__minos__MobileClient_search_users_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::search_users( - &*api_that_guard, - api_minos_id, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::refresh_session(&*api_that_guard) + .await?; Ok(output_ok) })() .await, @@ -2970,7 +1812,7 @@ fn wire__crate__api__minos__MobileClient_search_users_impl( }, ) } -fn wire__crate__api__minos__MobileClient_send_approval_decision_impl( +fn wire__crate__api__minos__MobileClient_register_agent_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -2978,7 +1820,7 @@ fn wire__crate__api__minos__MobileClient_send_approval_decision_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_send_approval_decision", + debug_name: "MobileClient_register_agent", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -2995,10 +1837,14 @@ fn wire__crate__api__minos__MobileClient_send_approval_decision_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_request_id = ::sse_decode(&mut deserializer); - let api_session_id = ::sse_decode(&mut deserializer); - let api_decision_json = ::sse_decode(&mut deserializer); - let api_client_request_id = >::sse_decode(&mut deserializer); + let api_name = ::sse_decode(&mut deserializer); + let api_description = ::sse_decode(&mut deserializer); + let api_runtime_agent = ::sse_decode(&mut deserializer); + let api_model = ::sse_decode(&mut deserializer); + let api_workspace_path = >::sse_decode(&mut deserializer); + let api_display_name = >::sse_decode(&mut deserializer); + let api_default_reasoning_effort = >::sse_decode(&mut deserializer); + let api_system_prompt = >::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -3020,12 +1866,16 @@ fn wire__crate__api__minos__MobileClient_send_approval_decision_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::send_approval_decision( + let output_ok = crate::api::minos::MobileClient::register_agent( &*api_that_guard, - api_request_id, - api_session_id, - api_decision_json, - api_client_request_id, + api_name, + api_description, + api_runtime_agent, + api_model, + api_workspace_path, + api_display_name, + api_default_reasoning_effort, + api_system_prompt, ) .await?; Ok(output_ok) @@ -3036,7 +1886,7 @@ fn wire__crate__api__minos__MobileClient_send_approval_decision_impl( }, ) } -fn wire__crate__api__minos__MobileClient_send_chat_message_impl( +fn wire__crate__api__minos__MobileClient_remove_agent_from_conversation_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -3044,7 +1894,7 @@ fn wire__crate__api__minos__MobileClient_send_chat_message_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_send_chat_message", + debug_name: "MobileClient_remove_agent_from_conversation", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -3062,10 +1912,7 @@ fn wire__crate__api__minos__MobileClient_send_chat_message_impl( flutter_rust_bridge::for_generated::RustAutoOpaqueInner, >>::sse_decode(&mut deserializer); let api_conversation_id = ::sse_decode(&mut deserializer); - let api_text = ::sse_decode(&mut deserializer); - let api_reply_to_message_id = >::sse_decode(&mut deserializer); - let api_client_message_id = >::sse_decode(&mut deserializer); - let api_mentions_json = >::sse_decode(&mut deserializer); + let api_agent_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -3087,15 +1934,13 @@ fn wire__crate__api__minos__MobileClient_send_chat_message_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::send_chat_message( - &*api_that_guard, - api_conversation_id, - api_text, - api_reply_to_message_id, - api_client_message_id, - api_mentions_json, - ) - .await?; + let output_ok = + crate::api::minos::MobileClient::remove_agent_from_conversation( + &*api_that_guard, + api_conversation_id, + api_agent_id, + ) + .await?; Ok(output_ok) })() .await, @@ -3104,7 +1949,7 @@ fn wire__crate__api__minos__MobileClient_send_chat_message_impl( }, ) } -fn wire__crate__api__minos__MobileClient_send_user_message_impl( +fn wire__crate__api__minos__MobileClient_remove_group_member_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -3112,7 +1957,7 @@ fn wire__crate__api__minos__MobileClient_send_user_message_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_send_user_message", + debug_name: "MobileClient_remove_group_member", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -3129,8 +1974,8 @@ fn wire__crate__api__minos__MobileClient_send_user_message_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_session_id = ::sse_decode(&mut deserializer); - let api_text = ::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); + let api_member_account_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -3152,10 +1997,10 @@ fn wire__crate__api__minos__MobileClient_send_user_message_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::send_user_message( + let output_ok = crate::api::minos::MobileClient::remove_group_member( &*api_that_guard, - api_session_id, - api_text, + api_conversation_id, + api_member_account_id, ) .await?; Ok(output_ok) @@ -3166,7 +2011,7 @@ fn wire__crate__api__minos__MobileClient_send_user_message_impl( }, ) } -fn wire__crate__api__minos__MobileClient_set_active_host_impl( +fn wire__crate__api__minos__MobileClient_resume_persisted_session_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -3174,7 +2019,7 @@ fn wire__crate__api__minos__MobileClient_set_active_host_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_set_active_host", + debug_name: "MobileClient_resume_persisted_session", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -3191,7 +2036,6 @@ fn wire__crate__api__minos__MobileClient_set_active_host_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_host_device_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -3213,9 +2057,8 @@ fn wire__crate__api__minos__MobileClient_set_active_host_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::set_active_host( + let output_ok = crate::api::minos::MobileClient::resume_persisted_session( &*api_that_guard, - api_host_device_id, ) .await?; Ok(output_ok) @@ -3226,7 +2069,7 @@ fn wire__crate__api__minos__MobileClient_set_active_host_impl( }, ) } -fn wire__crate__api__minos__MobileClient_set_minos_id_impl( +fn wire__crate__api__minos__MobileClient_send_chat_message_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -3234,7 +2077,7 @@ fn wire__crate__api__minos__MobileClient_set_minos_id_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_set_minos_id", + debug_name: "MobileClient_send_chat_message", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -3251,7 +2094,11 @@ fn wire__crate__api__minos__MobileClient_set_minos_id_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_minos_id = ::sse_decode(&mut deserializer); + let api_conversation_id = ::sse_decode(&mut deserializer); + let api_text = ::sse_decode(&mut deserializer); + let api_reply_to_message_id = >::sse_decode(&mut deserializer); + let api_client_message_id = >::sse_decode(&mut deserializer); + let api_mentions_json = >::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -3273,9 +2120,13 @@ fn wire__crate__api__minos__MobileClient_set_minos_id_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::set_minos_id( + let output_ok = crate::api::minos::MobileClient::send_chat_message( &*api_that_guard, - api_minos_id, + api_conversation_id, + api_text, + api_reply_to_message_id, + api_client_message_id, + api_mentions_json, ) .await?; Ok(output_ok) @@ -3286,7 +2137,7 @@ fn wire__crate__api__minos__MobileClient_set_minos_id_impl( }, ) } -fn wire__crate__api__minos__MobileClient_subscribe_agent_session_impl( +fn wire__crate__api__minos__MobileClient_set_active_host_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -3294,7 +2145,7 @@ fn wire__crate__api__minos__MobileClient_subscribe_agent_session_impl( ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_subscribe_agent_session", + debug_name: "MobileClient_set_active_host", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, @@ -3311,7 +2162,7 @@ fn wire__crate__api__minos__MobileClient_subscribe_agent_session_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_session_id = ::sse_decode(&mut deserializer); + let api_host_device_id = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, crate::api::minos::MinosError>( @@ -3333,9 +2184,9 @@ fn wire__crate__api__minos__MobileClient_subscribe_agent_session_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::subscribe_agent_session( + let output_ok = crate::api::minos::MobileClient::set_active_host( &*api_that_guard, - api_session_id, + api_host_device_id, ) .await?; Ok(output_ok) @@ -3842,66 +2693,6 @@ fn wire__crate__api__minos__MobileClient_update_agent_impl( }, ) } -fn wire__crate__api__minos__MobileClient_update_project_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, - rust_vec_len_: i32, - data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "MobileClient_update_project", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let message = unsafe { - flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( - ptr_, - rust_vec_len_, - data_len_, - ) - }; - let mut deserializer = - flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = , - >>::sse_decode(&mut deserializer); - let api_req = ::sse_decode(&mut deserializer); - deserializer.end(); - move |context| async move { - transform_result_sse::<_, crate::api::minos::MinosError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::api::minos::MobileClient::update_project( - &*api_that_guard, - api_req, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} fn wire__crate__api__minos__MobileClient_write_host_skill_config_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -5431,20 +4222,6 @@ const _: fn() = || { let ConversationsResponse = None::.unwrap(); let _: Vec = ConversationsResponse.conversations; } - { - let CreateProjectRequest = None::.unwrap(); - let _: String = CreateProjectRequest.name; - let _: String = CreateProjectRequest.workspace_slug; - let _: Option = CreateProjectRequest.workspace_path; - } - { - let CreateProjectResponse = None::.unwrap(); - let _: crate::api::minos::ProjectSummary = CreateProjectResponse.project; - } - { - let DeleteProjectRequest = None::.unwrap(); - let _: String = DeleteProjectRequest.project_id; - } match None::.unwrap() { crate::api::minos::DisplayPayload::Inline { text } => { let _: String = text; @@ -5470,20 +4247,6 @@ const _: fn() = || { let _: crate::api::minos::ArtifactRef = artifact; } } - { - let FriendRequestSummary = None::.unwrap(); - let _: String = FriendRequestSummary.request_id; - let _: crate::api::minos::UserSummary = FriendRequestSummary.from; - let _: crate::api::minos::UserSummary = FriendRequestSummary.to; - let _: crate::api::minos::FriendRequestStatus = FriendRequestSummary.status; - let _: i64 = FriendRequestSummary.created_at_ms; - let _: Option = FriendRequestSummary.resolved_at_ms; - } - { - let FriendRequestsResponse = None::.unwrap(); - let _: Vec = FriendRequestsResponse.incoming; - let _: Vec = FriendRequestsResponse.outgoing; - } { let FriendSummary = None::.unwrap(); let _: String = FriendSummary.account_id; @@ -5538,35 +4301,8 @@ const _: fn() = || { { let ListHostWorkspacesResponse = None::.unwrap(); - let _: String = ListHostWorkspacesResponse.root; - let _: Vec = ListHostWorkspacesResponse.workspaces; - } - { - let ListProjectSessionsParams = - None::.unwrap(); - let _: String = ListProjectSessionsParams.project_id; - let _: u32 = ListProjectSessionsParams.limit; - let _: Option = ListProjectSessionsParams.before_ts_ms; - } - { - let ListProjectSessionsResponse = - None::.unwrap(); - let _: Vec = ListProjectSessionsResponse.sessions; - } - { - let ListProjectsResponse = None::.unwrap(); - let _: Vec = ListProjectsResponse.projects; - } - { - let ListSessionsParams = None::.unwrap(); - let _: u32 = ListSessionsParams.limit; - let _: Option = ListSessionsParams.before_ts_ms; - let _: Option = ListSessionsParams.agent; - } - { - let ListSessionsResponse = None::.unwrap(); - let _: Vec = ListSessionsResponse.sessions; - let _: Option = ListSessionsResponse.next_before_ts_ms; + let _: String = ListHostWorkspacesResponse.root; + let _: Vec = ListHostWorkspacesResponse.workspaces; } match None::.unwrap() { crate::api::minos::MessageSender::Account { @@ -5712,16 +4448,6 @@ const _: fn() = || { let _: String = MyProfileResponse.minos_id; let _: Option = MyProfileResponse.display_name; } - { - let ProjectSummary = None::.unwrap(); - let _: String = ProjectSummary.project_id; - let _: String = ProjectSummary.name; - let _: String = ProjectSummary.workspace_slug; - let _: Option = ProjectSummary.workspace_path; - let _: i64 = ProjectSummary.created_at_ms; - let _: i64 = ProjectSummary.updated_at_ms; - let _: u32 = ProjectSummary.thread_count; - } { let ReactionActor = None::.unwrap(); let _: String = ReactionActor.actor_id; @@ -5735,18 +4461,6 @@ const _: fn() = || { let _: bool = ReactionGroup.reacted_by_me; let _: Vec = ReactionGroup.actors; } - { - let ReadSessionParams = None::.unwrap(); - let _: String = ReadSessionParams.session_id; - let _: Option = ReadSessionParams.from_seq; - let _: u32 = ReadSessionParams.limit; - } - { - let ReadSessionResponse = None::.unwrap(); - let _: Vec = ReadSessionResponse.ui_events; - let _: Option = ReadSessionResponse.next_seq; - let _: Option = ReadSessionResponse.session_end_reason; - } match None::.unwrap() { crate::api::minos::SessionEndReason::UserStopped => {} crate::api::minos::SessionEndReason::AgentDone => {} @@ -5878,11 +4592,6 @@ const _: fn() = || { let _: String = payload_json; } } - { - let UpdateProjectRequest = None::.unwrap(); - let _: String = UpdateProjectRequest.project_id; - let _: String = UpdateProjectRequest.name; - } { let UserSummary = None::.unwrap(); let _: String = UserSummary.account_id; @@ -6089,37 +4798,6 @@ impl SseDecode for crate::api::minos::AgentName { } } -impl SseDecode for crate::api::minos::AgentSessionSummaryDto { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_sessionId = ::sse_decode(deserializer); - let mut var_conversationId = ::sse_decode(deserializer); - let mut var_agentId = >::sse_decode(deserializer); - let mut var_agent = >::sse_decode(deserializer); - let mut var_status = ::sse_decode(deserializer); - let mut var_startedAtMs = ::sse_decode(deserializer); - let mut var_endedAtMs = >::sse_decode(deserializer); - let mut var_title = >::sse_decode(deserializer); - let mut var_lastActivityAtMs = ::sse_decode(deserializer); - let mut var_messageCount = ::sse_decode(deserializer); - let mut var_endReason = - >::sse_decode(deserializer); - return crate::api::minos::AgentSessionSummaryDto { - session_id: var_sessionId, - conversation_id: var_conversationId, - agent_id: var_agentId, - agent: var_agent, - status: var_status, - started_at_ms: var_startedAtMs, - ended_at_ms: var_endedAtMs, - title: var_title, - last_activity_at_ms: var_lastActivityAtMs, - message_count: var_messageCount, - end_reason: var_endReason, - }; - } -} - impl SseDecode for crate::api::minos::AgentStatus { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -6444,40 +5122,6 @@ impl SseDecode for crate::api::minos::ConversationsResponse { } } -impl SseDecode for crate::api::minos::CreateProjectRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_name = ::sse_decode(deserializer); - let mut var_workspaceSlug = ::sse_decode(deserializer); - let mut var_workspacePath = >::sse_decode(deserializer); - return crate::api::minos::CreateProjectRequest { - name: var_name, - workspace_slug: var_workspaceSlug, - workspace_path: var_workspacePath, - }; - } -} - -impl SseDecode for crate::api::minos::CreateProjectResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_project = ::sse_decode(deserializer); - return crate::api::minos::CreateProjectResponse { - project: var_project, - }; - } -} - -impl SseDecode for crate::api::minos::DeleteProjectRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_projectId = ::sse_decode(deserializer); - return crate::api::minos::DeleteProjectRequest { - project_id: var_projectId, - }; - } -} - impl SseDecode for crate::api::minos::DisplayPayload { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -6567,54 +5211,6 @@ impl SseDecode for crate::api::minos::ErrorKind { } } -impl SseDecode for crate::api::minos::FriendRequestStatus { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut inner = ::sse_decode(deserializer); - return match inner { - 0 => crate::api::minos::FriendRequestStatus::Pending, - 1 => crate::api::minos::FriendRequestStatus::Accepted, - 2 => crate::api::minos::FriendRequestStatus::Rejected, - 3 => crate::api::minos::FriendRequestStatus::Canceled, - _ => unreachable!("Invalid variant for FriendRequestStatus: {}", inner), - }; - } -} - -impl SseDecode for crate::api::minos::FriendRequestSummary { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_requestId = ::sse_decode(deserializer); - let mut var_from = ::sse_decode(deserializer); - let mut var_to = ::sse_decode(deserializer); - let mut var_status = ::sse_decode(deserializer); - let mut var_createdAtMs = ::sse_decode(deserializer); - let mut var_resolvedAtMs = >::sse_decode(deserializer); - return crate::api::minos::FriendRequestSummary { - request_id: var_requestId, - from: var_from, - to: var_to, - status: var_status, - created_at_ms: var_createdAtMs, - resolved_at_ms: var_resolvedAtMs, - }; - } -} - -impl SseDecode for crate::api::minos::FriendRequestsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_incoming = - >::sse_decode(deserializer); - let mut var_outgoing = - >::sse_decode(deserializer); - return crate::api::minos::FriendRequestsResponse { - incoming: var_incoming, - outgoing: var_outgoing, - }; - } -} - impl SseDecode for crate::api::minos::FriendSummary { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -6747,18 +5343,6 @@ impl SseDecode for crate::api::minos::Lang { } } -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = Vec::with_capacity(len_ as usize); - for idx_ in 0..len_ { - ans_.push(::sse_decode(deserializer)); - } - return ans_; - } -} - impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -6785,20 +5369,6 @@ impl SseDecode for Vec { } } -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = Vec::with_capacity(len_ as usize); - for idx_ in 0..len_ { - ans_.push(::sse_decode( - deserializer, - )); - } - return ans_; - } -} - impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -6874,20 +5444,6 @@ impl SseDecode for Vec { } } -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = Vec::with_capacity(len_ as usize); - for idx_ in 0..len_ { - ans_.push(::sse_decode( - deserializer, - )); - } - return ans_; - } -} - impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -7015,54 +5571,6 @@ impl SseDecode for Vec { } } -impl SseDecode for crate::api::minos::ListProjectSessionsParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_projectId = ::sse_decode(deserializer); - let mut var_limit = ::sse_decode(deserializer); - let mut var_beforeTsMs = >::sse_decode(deserializer); - return crate::api::minos::ListProjectSessionsParams { - project_id: var_projectId, - limit: var_limit, - before_ts_ms: var_beforeTsMs, - }; - } -} - -impl SseDecode for crate::api::minos::ListProjectSessionsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_sessions = >::sse_decode(deserializer); - return crate::api::minos::ListProjectSessionsResponse { - sessions: var_sessions, - }; - } -} - -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = Vec::with_capacity(len_ as usize); - for idx_ in 0..len_ { - ans_.push(::sse_decode( - deserializer, - )); - } - return ans_; - } -} - -impl SseDecode for crate::api::minos::ListProjectsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_projects = >::sse_decode(deserializer); - return crate::api::minos::ListProjectsResponse { - projects: var_projects, - }; - } -} - impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -7101,46 +5609,6 @@ impl SseDecode for Vec { } } -impl SseDecode for crate::api::minos::ListSessionsParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_limit = ::sse_decode(deserializer); - let mut var_beforeTsMs = >::sse_decode(deserializer); - let mut var_agent = >::sse_decode(deserializer); - return crate::api::minos::ListSessionsParams { - limit: var_limit, - before_ts_ms: var_beforeTsMs, - agent: var_agent, - }; - } -} - -impl SseDecode for crate::api::minos::ListSessionsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_sessions = >::sse_decode(deserializer); - let mut var_nextBeforeTsMs = >::sse_decode(deserializer); - return crate::api::minos::ListSessionsResponse { - sessions: var_sessions, - next_before_ts_ms: var_nextBeforeTsMs, - }; - } -} - -impl SseDecode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut len_ = ::sse_decode(deserializer); - let mut ans_ = Vec::with_capacity(len_ as usize); - for idx_ in 0..len_ { - ans_.push(::sse_decode( - deserializer, - )); - } - return ans_; - } -} - impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -7495,17 +5963,6 @@ impl SseDecode for Option { } } -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); - } else { - return None; - } - } -} - impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -7576,17 +6033,6 @@ impl SseDecode for Option { } } -impl SseDecode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); - } else { - return None; - } - } -} - impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -7631,28 +6077,6 @@ impl SseDecode for crate::api::minos::PersistedPairingState { } } -impl SseDecode for crate::api::minos::ProjectSummary { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_projectId = ::sse_decode(deserializer); - let mut var_name = ::sse_decode(deserializer); - let mut var_workspaceSlug = ::sse_decode(deserializer); - let mut var_workspacePath = >::sse_decode(deserializer); - let mut var_createdAtMs = ::sse_decode(deserializer); - let mut var_updatedAtMs = ::sse_decode(deserializer); - let mut var_threadCount = ::sse_decode(deserializer); - return crate::api::minos::ProjectSummary { - project_id: var_projectId, - name: var_name, - workspace_slug: var_workspaceSlug, - workspace_path: var_workspacePath, - created_at_ms: var_createdAtMs, - updated_at_ms: var_updatedAtMs, - thread_count: var_threadCount, - }; - } -} - impl SseDecode for crate::api::minos::ReactionActor { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -7683,35 +6107,6 @@ impl SseDecode for crate::api::minos::ReactionGroup { } } -impl SseDecode for crate::api::minos::ReadSessionParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_sessionId = ::sse_decode(deserializer); - let mut var_fromSeq = >::sse_decode(deserializer); - let mut var_limit = ::sse_decode(deserializer); - return crate::api::minos::ReadSessionParams { - session_id: var_sessionId, - from_seq: var_fromSeq, - limit: var_limit, - }; - } -} - -impl SseDecode for crate::api::minos::ReadSessionResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_uiEvents = >::sse_decode(deserializer); - let mut var_nextSeq = >::sse_decode(deserializer); - let mut var_sessionEndReason = - >::sse_decode(deserializer); - return crate::api::minos::ReadSessionResponse { - ui_events: var_uiEvents, - next_seq: var_nextSeq, - session_end_reason: var_sessionEndReason, - }; - } -} - impl SseDecode for crate::api::minos::RequestTraceRecord { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -8071,18 +6466,6 @@ impl SseDecode for () { fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {} } -impl SseDecode for crate::api::minos::UpdateProjectRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_projectId = ::sse_decode(deserializer); - let mut var_name = ::sse_decode(deserializer); - return crate::api::minos::UpdateProjectRequest { - project_id: var_projectId, - name: var_name, - }; - } -} - impl SseDecode for crate::api::minos::UserSummary { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -8120,364 +6503,244 @@ fn pde_ffi_dispatcher_primary_impl( ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len: i32, data_len: i32, -) { - // Codec=Pde (Serialization + dispatch), see doc to use other codecs - match func_id { - 1 => wire__crate__api__minos__MobileClient_accept_friend_request_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 2 => wire__crate__api__minos__MobileClient_ack_durable_applied_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 3 => wire__crate__api__minos__MobileClient_active_host_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 4 => wire__crate__api__minos__MobileClient_add_agent_to_conversation_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 5 => wire__crate__api__minos__MobileClient_add_group_member_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 6 => wire__crate__api__minos__MobileClient_close_session_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 7 => wire__crate__api__minos__MobileClient_conversation_members_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 8 => wire__crate__api__minos__MobileClient_conversations_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 9 => wire__crate__api__minos__MobileClient_create_friend_request_impl( +) { + // Codec=Pde (Serialization + dispatch), see doc to use other codecs + match func_id { + 1 => wire__crate__api__minos__MobileClient_ack_durable_applied_impl( port, ptr, rust_vec_len, data_len, ), - 10 => wire__crate__api__minos__MobileClient_create_group_conversation_impl( + 2 => wire__crate__api__minos__MobileClient_active_host_impl( port, ptr, rust_vec_len, data_len, ), - 11 => wire__crate__api__minos__MobileClient_create_project_impl( + 3 => wire__crate__api__minos__MobileClient_add_agent_to_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 13 => wire__crate__api__minos__MobileClient_delete_conversation_impl( + 4 => wire__crate__api__minos__MobileClient_add_group_member_impl( port, ptr, rust_vec_len, data_len, ), - 14 => wire__crate__api__minos__MobileClient_delete_project_impl( + 5 => wire__crate__api__minos__MobileClient_conversation_members_impl( port, ptr, rust_vec_len, data_len, ), - 15 => wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( + 6 => wire__crate__api__minos__MobileClient_conversations_impl( port, ptr, rust_vec_len, data_len, ), - 16 => wire__crate__api__minos__MobileClient_forget_host_impl( + 7 => wire__crate__api__minos__MobileClient_create_group_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 17 => wire__crate__api__minos__MobileClient_friend_requests_impl( + 9 => wire__crate__api__minos__MobileClient_delete_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 18 => wire__crate__api__minos__MobileClient_friends_impl(port, ptr, rust_vec_len, data_len), - 19 => wire__crate__api__minos__MobileClient_interrupt_session_impl( + 10 => wire__crate__api__minos__MobileClient_ensure_direct_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 20 => wire__crate__api__minos__MobileClient_list_agent_sessions_impl( + 11 => wire__crate__api__minos__MobileClient_forget_host_impl( port, ptr, rust_vec_len, data_len, ), - 21 => wire__crate__api__minos__MobileClient_list_agents_impl( + 12 => wire__crate__api__minos__MobileClient_friends_impl(port, ptr, rust_vec_len, data_len), + 13 => wire__crate__api__minos__MobileClient_list_agents_impl( port, ptr, rust_vec_len, data_len, ), - 22 => wire__crate__api__minos__MobileClient_list_chat_messages_impl( + 14 => wire__crate__api__minos__MobileClient_list_chat_messages_impl( port, ptr, rust_vec_len, data_len, ), - 23 => { + 15 => { wire__crate__api__minos__MobileClient_list_clis_impl(port, ptr, rust_vec_len, data_len) } - 24 => wire__crate__api__minos__MobileClient_list_conversation_agents_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 25 => wire__crate__api__minos__MobileClient_list_conversation_participants_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 26 => wire__crate__api__minos__MobileClient_list_host_skills_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 27 => wire__crate__api__minos__MobileClient_list_host_workspaces_impl( + 16 => wire__crate__api__minos__MobileClient_list_conversation_agents_impl( port, ptr, rust_vec_len, data_len, ), - 28 => wire__crate__api__minos__MobileClient_list_paired_hosts_impl( + 17 => wire__crate__api__minos__MobileClient_list_conversation_participants_impl( port, ptr, rust_vec_len, data_len, ), - 29 => wire__crate__api__minos__MobileClient_list_project_sessions_impl( + 18 => wire__crate__api__minos__MobileClient_list_host_skills_impl( port, ptr, rust_vec_len, data_len, ), - 30 => wire__crate__api__minos__MobileClient_list_projects_impl( + 19 => wire__crate__api__minos__MobileClient_list_host_workspaces_impl( port, ptr, rust_vec_len, data_len, ), - 31 => wire__crate__api__minos__MobileClient_list_sessions_impl( + 20 => wire__crate__api__minos__MobileClient_list_paired_hosts_impl( port, ptr, rust_vec_len, data_len, ), - 32 => wire__crate__api__minos__MobileClient_login_with_supabase_impl( + 21 => wire__crate__api__minos__MobileClient_login_with_supabase_impl( port, ptr, rust_vec_len, data_len, ), - 33 => wire__crate__api__minos__MobileClient_logout_impl(port, ptr, rust_vec_len, data_len), - 34 => wire__crate__api__minos__MobileClient_mark_conversation_read_impl( + 22 => wire__crate__api__minos__MobileClient_logout_impl(port, ptr, rust_vec_len, data_len), + 23 => wire__crate__api__minos__MobileClient_mark_conversation_read_impl( port, ptr, rust_vec_len, data_len, ), - 35 => { + 24 => { wire__crate__api__minos__MobileClient_my_profile_impl(port, ptr, rust_vec_len, data_len) } - 40 => wire__crate__api__minos__MobileClient_persisted_pairing_state_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 41 => wire__crate__api__minos__MobileClient_read_session_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 42 => wire__crate__api__minos__MobileClient_recall_chat_message_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 43 => wire__crate__api__minos__MobileClient_refresh_session_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 44 => wire__crate__api__minos__MobileClient_register_agent_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 45 => wire__crate__api__minos__MobileClient_reject_friend_request_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 46 => wire__crate__api__minos__MobileClient_remove_agent_from_conversation_impl( + 29 => wire__crate__api__minos__MobileClient_persisted_pairing_state_impl( port, ptr, rust_vec_len, data_len, ), - 47 => wire__crate__api__minos__MobileClient_remove_group_member_impl( + 30 => wire__crate__api__minos__MobileClient_recall_chat_message_impl( port, ptr, rust_vec_len, data_len, ), - 48 => wire__crate__api__minos__MobileClient_respond_opencode_question_impl( + 31 => wire__crate__api__minos__MobileClient_refresh_session_impl( port, ptr, rust_vec_len, data_len, ), - 49 => wire__crate__api__minos__MobileClient_resume_persisted_session_impl( + 32 => wire__crate__api__minos__MobileClient_register_agent_impl( port, ptr, rust_vec_len, data_len, ), - 50 => wire__crate__api__minos__MobileClient_search_users_impl( + 33 => wire__crate__api__minos__MobileClient_remove_agent_from_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 51 => wire__crate__api__minos__MobileClient_send_approval_decision_impl( + 34 => wire__crate__api__minos__MobileClient_remove_group_member_impl( port, ptr, rust_vec_len, data_len, ), - 52 => wire__crate__api__minos__MobileClient_send_chat_message_impl( + 35 => wire__crate__api__minos__MobileClient_resume_persisted_session_impl( port, ptr, rust_vec_len, data_len, ), - 53 => wire__crate__api__minos__MobileClient_send_user_message_impl( + 36 => wire__crate__api__minos__MobileClient_send_chat_message_impl( port, ptr, rust_vec_len, data_len, ), - 54 => wire__crate__api__minos__MobileClient_set_active_host_impl( + 37 => wire__crate__api__minos__MobileClient_set_active_host_impl( port, ptr, rust_vec_len, data_len, ), - 55 => wire__crate__api__minos__MobileClient_set_minos_id_impl( + 38 => wire__crate__api__minos__MobileClient_subscribe_auth_state_impl( port, ptr, rust_vec_len, data_len, ), - 56 => wire__crate__api__minos__MobileClient_subscribe_agent_session_impl( + 39 => wire__crate__api__minos__MobileClient_subscribe_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 57 => wire__crate__api__minos__MobileClient_subscribe_auth_state_impl( + 40 => wire__crate__api__minos__MobileClient_subscribe_social_events_impl( port, ptr, rust_vec_len, data_len, ), - 58 => wire__crate__api__minos__MobileClient_subscribe_conversation_impl( + 41 => wire__crate__api__minos__MobileClient_subscribe_state_impl( port, ptr, rust_vec_len, data_len, ), - 59 => wire__crate__api__minos__MobileClient_subscribe_social_events_impl( + 42 => wire__crate__api__minos__MobileClient_subscribe_ui_events_impl( port, ptr, rust_vec_len, data_len, ), - 60 => wire__crate__api__minos__MobileClient_subscribe_state_impl( + 43 => wire__crate__api__minos__MobileClient_toggle_reaction_impl( port, ptr, rust_vec_len, data_len, ), - 61 => wire__crate__api__minos__MobileClient_subscribe_ui_events_impl( + 44 => wire__crate__api__minos__MobileClient_unsubscribe_conversation_impl( port, ptr, rust_vec_len, data_len, ), - 62 => wire__crate__api__minos__MobileClient_toggle_reaction_impl( + 45 => wire__crate__api__minos__MobileClient_update_agent_impl( port, ptr, rust_vec_len, data_len, ), - 63 => wire__crate__api__minos__MobileClient_unsubscribe_conversation_impl( + 46 => wire__crate__api__minos__MobileClient_write_host_skill_config_impl( port, ptr, rust_vec_len, data_len, ), - 64 => wire__crate__api__minos__MobileClient_update_agent_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 65 => wire__crate__api__minos__MobileClient_update_project_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 66 => wire__crate__api__minos__MobileClient_write_host_skill_config_impl( - port, - ptr, - rust_vec_len, - data_len, - ), - 91 => wire__crate__api__minos__init_logging_impl(port, ptr, rust_vec_len, data_len), - 95 => { + 71 => wire__crate__api__minos__init_logging_impl(port, ptr, rust_vec_len, data_len), + 75 => { wire__crate__api__minos__subscribe_log_records_impl(port, ptr, rust_vec_len, data_len) } - 96 => wire__crate__api__minos__subscribe_request_traces_impl( + 76 => wire__crate__api__minos__subscribe_request_traces_impl( port, ptr, rust_vec_len, @@ -8495,138 +6758,138 @@ fn pde_ffi_dispatcher_sync_impl( ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 12 => wire__crate__api__minos__MobileClient_current_state_impl(ptr, rust_vec_len, data_len), - 36 => wire__crate__api__minos__MobileClient_new_impl(ptr, rust_vec_len, data_len), - 37 => wire__crate__api__minos__MobileClient_new_with_persisted_state_impl( + 8 => wire__crate__api__minos__MobileClient_current_state_impl(ptr, rust_vec_len, data_len), + 25 => wire__crate__api__minos__MobileClient_new_impl(ptr, rust_vec_len, data_len), + 26 => wire__crate__api__minos__MobileClient_new_with_persisted_state_impl( ptr, rust_vec_len, data_len, ), - 38 => wire__crate__api__minos__MobileClient_notify_backgrounded_impl( + 27 => wire__crate__api__minos__MobileClient_notify_backgrounded_impl( ptr, rust_vec_len, data_len, ), - 39 => wire__crate__api__minos__MobileClient_notify_foregrounded_impl( + 28 => wire__crate__api__minos__MobileClient_notify_foregrounded_impl( ptr, rust_vec_len, data_len, ), - 67 => wire__crate__api__minos__SessionSummary_auto_accessor_get_agent_impl( + 47 => wire__crate__api__minos__SessionSummary_auto_accessor_get_agent_impl( ptr, rust_vec_len, data_len, ), - 68 => wire__crate__api__minos__SessionSummary_auto_accessor_get_end_reason_impl( + 48 => wire__crate__api__minos__SessionSummary_auto_accessor_get_end_reason_impl( ptr, rust_vec_len, data_len, ), - 69 => wire__crate__api__minos__SessionSummary_auto_accessor_get_ended_at_ms_impl( + 49 => wire__crate__api__minos__SessionSummary_auto_accessor_get_ended_at_ms_impl( ptr, rust_vec_len, data_len, ), - 70 => wire__crate__api__minos__SessionSummary_auto_accessor_get_first_ts_ms_impl( + 50 => wire__crate__api__minos__SessionSummary_auto_accessor_get_first_ts_ms_impl( ptr, rust_vec_len, data_len, ), - 71 => wire__crate__api__minos__SessionSummary_auto_accessor_get_last_ts_ms_impl( + 51 => wire__crate__api__minos__SessionSummary_auto_accessor_get_last_ts_ms_impl( ptr, rust_vec_len, data_len, ), - 72 => wire__crate__api__minos__SessionSummary_auto_accessor_get_message_count_impl( + 52 => wire__crate__api__minos__SessionSummary_auto_accessor_get_message_count_impl( ptr, rust_vec_len, data_len, ), - 73 => wire__crate__api__minos__SessionSummary_auto_accessor_get_needs_continue_impl( + 53 => wire__crate__api__minos__SessionSummary_auto_accessor_get_needs_continue_impl( ptr, rust_vec_len, data_len, ), - 74 => wire__crate__api__minos__SessionSummary_auto_accessor_get_parent_session_id_impl( + 54 => wire__crate__api__minos__SessionSummary_auto_accessor_get_parent_session_id_impl( ptr, rust_vec_len, data_len, ), - 75 => wire__crate__api__minos__SessionSummary_auto_accessor_get_session_id_impl( + 55 => wire__crate__api__minos__SessionSummary_auto_accessor_get_session_id_impl( ptr, rust_vec_len, data_len, ), - 76 => wire__crate__api__minos__SessionSummary_auto_accessor_get_state_impl( + 56 => wire__crate__api__minos__SessionSummary_auto_accessor_get_state_impl( ptr, rust_vec_len, data_len, ), - 77 => wire__crate__api__minos__SessionSummary_auto_accessor_get_title_impl( + 57 => wire__crate__api__minos__SessionSummary_auto_accessor_get_title_impl( ptr, rust_vec_len, data_len, ), - 78 => wire__crate__api__minos__SessionSummary_auto_accessor_set_agent_impl( + 58 => wire__crate__api__minos__SessionSummary_auto_accessor_set_agent_impl( ptr, rust_vec_len, data_len, ), - 79 => wire__crate__api__minos__SessionSummary_auto_accessor_set_end_reason_impl( + 59 => wire__crate__api__minos__SessionSummary_auto_accessor_set_end_reason_impl( ptr, rust_vec_len, data_len, ), - 80 => wire__crate__api__minos__SessionSummary_auto_accessor_set_ended_at_ms_impl( + 60 => wire__crate__api__minos__SessionSummary_auto_accessor_set_ended_at_ms_impl( ptr, rust_vec_len, data_len, ), - 81 => wire__crate__api__minos__SessionSummary_auto_accessor_set_first_ts_ms_impl( + 61 => wire__crate__api__minos__SessionSummary_auto_accessor_set_first_ts_ms_impl( ptr, rust_vec_len, data_len, ), - 82 => wire__crate__api__minos__SessionSummary_auto_accessor_set_last_ts_ms_impl( + 62 => wire__crate__api__minos__SessionSummary_auto_accessor_set_last_ts_ms_impl( ptr, rust_vec_len, data_len, ), - 83 => wire__crate__api__minos__SessionSummary_auto_accessor_set_message_count_impl( + 63 => wire__crate__api__minos__SessionSummary_auto_accessor_set_message_count_impl( ptr, rust_vec_len, data_len, ), - 84 => wire__crate__api__minos__SessionSummary_auto_accessor_set_needs_continue_impl( + 64 => wire__crate__api__minos__SessionSummary_auto_accessor_set_needs_continue_impl( ptr, rust_vec_len, data_len, ), - 85 => wire__crate__api__minos__SessionSummary_auto_accessor_set_parent_session_id_impl( + 65 => wire__crate__api__minos__SessionSummary_auto_accessor_set_parent_session_id_impl( ptr, rust_vec_len, data_len, ), - 86 => wire__crate__api__minos__SessionSummary_auto_accessor_set_session_id_impl( + 66 => wire__crate__api__minos__SessionSummary_auto_accessor_set_session_id_impl( ptr, rust_vec_len, data_len, ), - 87 => wire__crate__api__minos__SessionSummary_auto_accessor_set_state_impl( + 67 => wire__crate__api__minos__SessionSummary_auto_accessor_set_state_impl( ptr, rust_vec_len, data_len, ), - 88 => wire__crate__api__minos__SessionSummary_auto_accessor_set_title_impl( + 68 => wire__crate__api__minos__SessionSummary_auto_accessor_set_title_impl( ptr, rust_vec_len, data_len, ), - 89 => wire__crate__api__minos__clear_request_traces_impl(ptr, rust_vec_len, data_len), - 90 => wire__crate__api__minos__emit_log_impl(ptr, rust_vec_len, data_len), - 92 => wire__crate__api__minos__kind_message_impl(ptr, rust_vec_len, data_len), - 93 => wire__crate__api__minos__recent_log_records_impl(ptr, rust_vec_len, data_len), - 94 => wire__crate__api__minos__recent_request_traces_impl(ptr, rust_vec_len, data_len), + 69 => wire__crate__api__minos__clear_request_traces_impl(ptr, rust_vec_len, data_len), + 70 => wire__crate__api__minos__emit_log_impl(ptr, rust_vec_len, data_len), + 72 => wire__crate__api__minos__kind_message_impl(ptr, rust_vec_len, data_len), + 73 => wire__crate__api__minos__recent_log_records_impl(ptr, rust_vec_len, data_len), + 74 => wire__crate__api__minos__recent_request_traces_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -8732,36 +6995,6 @@ impl flutter_rust_bridge::IntoIntoDart> } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::minos::AgentSessionSummaryDto { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.session_id.into_into_dart().into_dart(), - self.conversation_id.into_into_dart().into_dart(), - self.agent_id.into_into_dart().into_dart(), - self.agent.into_into_dart().into_dart(), - self.status.into_into_dart().into_dart(), - self.started_at_ms.into_into_dart().into_dart(), - self.ended_at_ms.into_into_dart().into_dart(), - self.title.into_into_dart().into_dart(), - self.last_activity_at_ms.into_into_dart().into_dart(), - self.message_count.into_into_dart().into_dart(), - self.end_reason.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::api::minos::AgentSessionSummaryDto -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::api::minos::AgentSessionSummaryDto -{ - fn into_into_dart(self) -> crate::api::minos::AgentSessionSummaryDto { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self.0 { @@ -9169,62 +7402,6 @@ impl flutter_rust_bridge::IntoIntoDart { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.name.into_into_dart().into_dart(), - self.0.workspace_slug.into_into_dart().into_dart(), - self.0.workspace_path.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::CreateProjectRequest -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.0.project.into_into_dart().into_dart()].into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::CreateProjectResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.0.project_id.into_into_dart().into_dart()].into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::DeleteProjectRequest -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self.0 { @@ -9332,75 +7509,6 @@ impl flutter_rust_bridge::IntoIntoDart> } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - match self.0 { - crate::api::minos::FriendRequestStatus::Pending => 0.into_dart(), - crate::api::minos::FriendRequestStatus::Accepted => 1.into_dart(), - crate::api::minos::FriendRequestStatus::Rejected => 2.into_dart(), - crate::api::minos::FriendRequestStatus::Canceled => 3.into_dart(), - _ => unreachable!(), - } - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::FriendRequestStatus -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.request_id.into_into_dart().into_dart(), - self.0.from.into_into_dart().into_dart(), - self.0.to.into_into_dart().into_dart(), - self.0.status.into_into_dart().into_dart(), - self.0.created_at_ms.into_into_dart().into_dart(), - self.0.resolved_at_ms.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::FriendRequestSummary -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.incoming.into_into_dart().into_dart(), - self.0.outgoing.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::FriendRequestsResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -9569,185 +7677,86 @@ impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for FrbWrapper { } -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::Lang -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.0.agents.into_into_dart().into_dart()].into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListAgentsResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.messages.into_into_dart().into_dart(), - self.0.next_before_seq.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListChatMessagesResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.0.data.into_into_dart().into_dart()].into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListHostSkillsResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.root.into_into_dart().into_dart(), - self.0.workspaces.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListHostWorkspacesResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.project_id.into_into_dart().into_dart(), - self.0.limit.into_into_dart().into_dart(), - self.0.before_ts_ms.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListProjectSessionsParams +impl flutter_rust_bridge::IntoIntoDart> + for crate::api::minos::Lang { - fn into_into_dart(self) -> FrbWrapper { + fn into_into_dart(self) -> FrbWrapper { self.into() } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { +impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.0.sessions.into_into_dart().into_dart()].into_dart() + [self.0.agents.into_into_dart().into_dart()].into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper + for FrbWrapper { } -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListProjectSessionsResponse +impl flutter_rust_bridge::IntoIntoDart> + for crate::api::minos::ListAgentsResponse { - fn into_into_dart(self) -> FrbWrapper { + fn into_into_dart(self) -> FrbWrapper { self.into() } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { +impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.0.projects.into_into_dart().into_dart()].into_dart() + [ + self.0.messages.into_into_dart().into_dart(), + self.0.next_before_seq.into_into_dart().into_dart(), + ] + .into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper + for FrbWrapper { } -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListProjectsResponse +impl flutter_rust_bridge::IntoIntoDart> + for crate::api::minos::ListChatMessagesResponse { - fn into_into_dart(self) -> FrbWrapper { + fn into_into_dart(self) -> FrbWrapper { self.into() } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { +impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.limit.into_into_dart().into_dart(), - self.0.before_ts_ms.into_into_dart().into_dart(), - self.0.agent.into_into_dart().into_dart(), - ] - .into_dart() + [self.0.data.into_into_dart().into_dart()].into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper + for FrbWrapper { } -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListSessionsParams +impl flutter_rust_bridge::IntoIntoDart> + for crate::api::minos::ListHostSkillsResponse { - fn into_into_dart(self) -> FrbWrapper { + fn into_into_dart(self) -> FrbWrapper { self.into() } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { +impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ - self.0.sessions.into_into_dart().into_dart(), - self.0.next_before_ts_ms.into_into_dart().into_dart(), + self.0.root.into_into_dart().into_dart(), + self.0.workspaces.into_into_dart().into_dart(), ] .into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper + for FrbWrapper { } -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ListSessionsResponse +impl flutter_rust_bridge::IntoIntoDart> + for crate::api::minos::ListHostWorkspacesResponse { - fn into_into_dart(self) -> FrbWrapper { + fn into_into_dart(self) -> FrbWrapper { self.into() } } @@ -10090,32 +8099,6 @@ impl flutter_rust_bridge::IntoIntoDart } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.project_id.into_into_dart().into_dart(), - self.0.name.into_into_dart().into_dart(), - self.0.workspace_slug.into_into_dart().into_dart(), - self.0.workspace_path.into_into_dart().into_dart(), - self.0.created_at_ms.into_into_dart().into_dart(), - self.0.updated_at_ms.into_into_dart().into_dart(), - self.0.thread_count.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ProjectSummary -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -10161,50 +8144,6 @@ impl flutter_rust_bridge::IntoIntoDart { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.session_id.into_into_dart().into_dart(), - self.0.from_seq.into_into_dart().into_dart(), - self.0.limit.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ReadSessionParams -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for FrbWrapper { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.ui_events.into_into_dart().into_dart(), - self.0.next_seq.into_into_dart().into_dart(), - self.0.session_end_reason.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::ReadSessionResponse -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::minos::RequestTraceRecord { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -10586,27 +8525,6 @@ impl flutter_rust_bridge::IntoIntoDart { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.0.project_id.into_into_dart().into_dart(), - self.0.name.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for FrbWrapper -{ -} -impl flutter_rust_bridge::IntoIntoDart> - for crate::api::minos::UpdateProjectRequest -{ - fn into_into_dart(self) -> FrbWrapper { - self.into() - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for FrbWrapper { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -10806,23 +8724,6 @@ impl SseEncode for crate::api::minos::AgentName { } } -impl SseEncode for crate::api::minos::AgentSessionSummaryDto { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.session_id, serializer); - ::sse_encode(self.conversation_id, serializer); - >::sse_encode(self.agent_id, serializer); - >::sse_encode(self.agent, serializer); - ::sse_encode(self.status, serializer); - ::sse_encode(self.started_at_ms, serializer); - >::sse_encode(self.ended_at_ms, serializer); - >::sse_encode(self.title, serializer); - ::sse_encode(self.last_activity_at_ms, serializer); - ::sse_encode(self.message_count, serializer); - >::sse_encode(self.end_reason, serializer); - } -} - impl SseEncode for crate::api::minos::AgentStatus { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11055,29 +8956,6 @@ impl SseEncode for crate::api::minos::ConversationsResponse { } } -impl SseEncode for crate::api::minos::CreateProjectRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.name, serializer); - ::sse_encode(self.workspace_slug, serializer); - >::sse_encode(self.workspace_path, serializer); - } -} - -impl SseEncode for crate::api::minos::CreateProjectResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.project, serializer); - } -} - -impl SseEncode for crate::api::minos::DeleteProjectRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.project_id, serializer); - } -} - impl SseEncode for crate::api::minos::DisplayPayload { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11169,44 +9047,6 @@ impl SseEncode for crate::api::minos::ErrorKind { } } -impl SseEncode for crate::api::minos::FriendRequestStatus { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode( - match self { - crate::api::minos::FriendRequestStatus::Pending => 0, - crate::api::minos::FriendRequestStatus::Accepted => 1, - crate::api::minos::FriendRequestStatus::Rejected => 2, - crate::api::minos::FriendRequestStatus::Canceled => 3, - _ => { - unimplemented!(""); - } - }, - serializer, - ); - } -} - -impl SseEncode for crate::api::minos::FriendRequestSummary { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.request_id, serializer); - ::sse_encode(self.from, serializer); - ::sse_encode(self.to, serializer); - ::sse_encode(self.status, serializer); - ::sse_encode(self.created_at_ms, serializer); - >::sse_encode(self.resolved_at_ms, serializer); - } -} - -impl SseEncode for crate::api::minos::FriendRequestsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.incoming, serializer); - >::sse_encode(self.outgoing, serializer); - } -} - impl SseEncode for crate::api::minos::FriendSummary { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11304,16 +9144,6 @@ impl SseEncode for crate::api::minos::Lang { } } -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11334,16 +9164,6 @@ impl SseEncode for Vec { } } -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11399,16 +9219,6 @@ impl SseEncode for Vec { } } -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11504,39 +9314,6 @@ impl SseEncode for Vec { } } -impl SseEncode for crate::api::minos::ListProjectSessionsParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.project_id, serializer); - ::sse_encode(self.limit, serializer); - >::sse_encode(self.before_ts_ms, serializer); - } -} - -impl SseEncode for crate::api::minos::ListProjectSessionsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.sessions, serializer); - } -} - -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - -impl SseEncode for crate::api::minos::ListProjectsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.projects, serializer); - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11567,33 +9344,6 @@ impl SseEncode for Vec { } } -impl SseEncode for crate::api::minos::ListSessionsParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.limit, serializer); - >::sse_encode(self.before_ts_ms, serializer); - >::sse_encode(self.agent, serializer); - } -} - -impl SseEncode for crate::api::minos::ListSessionsResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.sessions, serializer); - >::sse_encode(self.next_before_ts_ms, serializer); - } -} - -impl SseEncode for Vec { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.len() as _, serializer); - for item in self { - ::sse_encode(item, serializer); - } - } -} - impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11878,16 +9628,6 @@ impl SseEncode for Option { } } -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11948,16 +9688,6 @@ impl SseEncode for Option { } } -impl SseEncode for Option { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.is_some(), serializer); - if let Some(value) = self { - ::sse_encode(value, serializer); - } - } -} - impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -11997,19 +9727,6 @@ impl SseEncode for crate::api::minos::PersistedPairingState { } } -impl SseEncode for crate::api::minos::ProjectSummary { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.project_id, serializer); - ::sse_encode(self.name, serializer); - ::sse_encode(self.workspace_slug, serializer); - >::sse_encode(self.workspace_path, serializer); - ::sse_encode(self.created_at_ms, serializer); - ::sse_encode(self.updated_at_ms, serializer); - ::sse_encode(self.thread_count, serializer); - } -} - impl SseEncode for crate::api::minos::ReactionActor { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -12029,27 +9746,6 @@ impl SseEncode for crate::api::minos::ReactionGroup { } } -impl SseEncode for crate::api::minos::ReadSessionParams { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.session_id, serializer); - >::sse_encode(self.from_seq, serializer); - ::sse_encode(self.limit, serializer); - } -} - -impl SseEncode for crate::api::minos::ReadSessionResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - >::sse_encode(self.ui_events, serializer); - >::sse_encode(self.next_seq, serializer); - >::sse_encode( - self.session_end_reason, - serializer, - ); - } -} - impl SseEncode for crate::api::minos::RequestTraceRecord { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -12366,14 +10062,6 @@ impl SseEncode for () { fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {} } -impl SseEncode for crate::api::minos::UpdateProjectRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.project_id, serializer); - ::sse_encode(self.name, serializer); - } -} - impl SseEncode for crate::api::minos::UserSummary { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { diff --git a/crates/minos-mobile/src/client.rs b/crates/minos-mobile/src/client.rs index 1443b98e..5a178a2d 100644 --- a/crates/minos-mobile/src/client.rs +++ b/crates/minos-mobile/src/client.rs @@ -23,16 +23,13 @@ use http::{Method, Request}; use minos_domain::{ConnectionState, DeviceId, MinosError}; use minos_protocol::{ realtime::ClientFrame, AddAgentToGroupRequest, AddGroupMemberRequest, AgentSummary, - ApprovalDecisionRequest, AuthSummary, ChatMessageSummary, ConversationAgentMembersResponse, - ConversationMembersResponse, ConversationParticipantsResponse, ConversationReadResponse, - ConversationResponse, ConversationsResponse, CreateFriendRequestRequest, - CreateGroupConversationRequest, EnsureDirectConversationRequest, FriendRequestSummary, - FriendRequestsResponse, FriendsResponse, GetSessionLastSeqParams, GetSessionLastSeqResponse, - HostSummary, ListAgentsResponse, ListChatMessagesResponse, ListClisResponse, - ListHostSkillsResponse, ListSessionsParams, ListSessionsResponse, MyProfileResponse, - ReadSessionParams, ReadSessionResponse, RefreshResponse, RegisterAgentRequest, - RemoveAgentFromGroupRequest, RemoveGroupMemberRequest, SetMinosIdRequest, UpdateAgentRequest, - UserSummary, WriteHostSkillConfigResponse, + AuthSummary, ChatMessageSummary, ConversationAgentMembersResponse, ConversationMembersResponse, + ConversationParticipantsResponse, ConversationReadResponse, ConversationResponse, + ConversationsResponse, CreateGroupConversationRequest, EnsureDirectConversationRequest, + FriendsResponse, GetSessionLastSeqParams, GetSessionLastSeqResponse, HostSummary, + ListAgentsResponse, ListChatMessagesResponse, ListClisResponse, ListHostSkillsResponse, + MyProfileResponse, RefreshResponse, RegisterAgentRequest, RemoveAgentFromGroupRequest, + RemoveGroupMemberRequest, UpdateAgentRequest, WriteHostSkillConfigResponse, }; use minos_ui_protocol::UiEventMessage; use openwire::websocket::WebSocket; @@ -402,35 +399,7 @@ impl MobileClient { Ok(()) } - // ─────────────────────────── history rpcs ──────────────────────────── - - /// Request a page of thread summaries from the backend. Bearer-only. - pub async fn list_sessions( - &self, - req: ListSessionsParams, - ) -> Result { - auth_http_call!(self, |http, access| http.list_sessions(&access, req)) - } - - pub async fn list_agent_sessions( - &self, - conversation_id: Option, - limit: u32, - ) -> Result, MinosError> { - auth_http_call!(self, |http, access| { - http.list_agent_sessions(&access, conversation_id, limit) - }) - } - - pub async fn subscribe_agent_session(&self, session_id: String) -> Result<(), MinosError> { - let topic = format!("agent_session:{session_id}"); - let needs = self.subscription_mgr.desire_topic(&topic, 0).await; - if !needs || !matches!(*self.state_rx.borrow(), ConnectionState::Connected) { - return Ok(()); - } - self.send_subscribe_topics(vec![topic]).await; - Ok(()) - } + // ─────────────────────────── conversation realtime ─────────────────── /// Open-chat live path: subscribe `conversation:{id}` for full T1 /// message/reaction frames. Account topic remains digest-only for inbox. @@ -524,14 +493,6 @@ impl MobileClient { } } - /// Read a window of translated UI events from one session. - pub async fn read_session( - &self, - req: ReadSessionParams, - ) -> Result { - auth_http_call!(self, |http, access| http.read_session(&access, req)) - } - /// Host-only helper (mobile rarely uses this; included for parity). pub async fn get_session_last_seq( &self, @@ -552,19 +513,6 @@ impl MobileClient { auth_http_call!(self, |http, access| http.my_profile(&access)) } - pub async fn set_minos_id(&self, minos_id: String) -> Result { - auth_http_call!(self, |http, access| { - http.set_minos_id(&access, SetMinosIdRequest { minos_id }) - }) - } - - pub async fn search_users(&self, minos_id: String) -> Result, MinosError> { - let resp = auth_http_call!(self, |http, access| { - http.search_users(&access, &minos_id) - })?; - Ok(resp.users) - } - pub async fn friends(&self) -> Result { auth_http_call!(self, |http, access| http.friends(&access)) } @@ -657,37 +605,6 @@ impl MobileClient { auth_http_call!(self, |http, access| http.list_agents(&access)) } - pub async fn create_friend_request( - &self, - target_minos_id: String, - ) -> Result { - auth_http_call!(self, |http, access| { - http.create_friend_request(&access, CreateFriendRequestRequest { target_minos_id }) - }) - } - - pub async fn friend_requests(&self) -> Result { - auth_http_call!(self, |http, access| http.friend_requests(&access)) - } - - pub async fn accept_friend_request( - &self, - request_id: String, - ) -> Result { - auth_http_call!(self, |http, access| { - http.accept_friend_request(&access, &request_id) - }) - } - - pub async fn reject_friend_request( - &self, - request_id: String, - ) -> Result { - auth_http_call!(self, |http, access| { - http.reject_friend_request(&access, &request_id) - }) - } - pub async fn conversations(&self) -> Result { auth_http_call!(self, |http, access| http.conversations(&access)) } @@ -1155,115 +1072,6 @@ impl MobileClient { }) } - /// Send a user message into an existing agent session via REST. - pub async fn send_user_message( - &self, - session_id: String, - text: String, - ) -> Result<(), MinosError> { - auth_http_call!(self, |http, access| { - http.send_agent_input(&access, &session_id, &text) - })?; - Ok(()) - } - - /// Submit a user approval decision back to the backend relay. - /// - /// `client_request_id` is the Hub Intent Outbox id. When `None`, a - /// fresh id is generated so the wire body never hardcodes null (retries - /// from callers that stable-id should pass the same value). - pub async fn send_approval_decision( - &self, - request_id: String, - session_id: String, - decision: serde_json::Value, - client_request_id: Option, - ) -> Result<(), MinosError> { - let client_request_id = client_request_id - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| format!("approval-{}", uuid::Uuid::new_v4())); - auth_http_call!(self, |http, access| { - http.submit_approval_decision( - &access, - ApprovalDecisionRequest { - request_id: request_id.clone(), - session_id: session_id.clone(), - decision: decision.clone(), - }, - Some(&client_request_id), - ) - }) - } - - /// Submit an opencode question answer back to the host that owns the - /// agent session. - pub async fn respond_opencode_question( - &self, - session_id: String, - question_id: String, - answers: Vec>, - ) -> Result<(), MinosError> { - auth_http_call!(self, |http, access| { - http.respond_opencode_question(&access, &session_id, &question_id, answers) - }) - } - - /// Pause an in-flight turn on the named thread via REST. - pub async fn interrupt_session(&self, session_id: String) -> Result<(), MinosError> { - auth_http_call!(self, |http, access| { - http.stop_agent_session(&access, &session_id) - }) - } - - /// Permanently close the named thread via REST. Idempotent. - pub async fn close_session(&self, session_id: String) -> Result<(), MinosError> { - auth_http_call!(self, |http, access| { - http.stop_agent_session(&access, &session_id) - }) - } - - // ─────────────────────────── project rpcs ────────────────────────────── - - /// Create a project in the account-scoped backend store. - pub async fn create_project( - &self, - req: minos_protocol::CreateProjectRequest, - ) -> Result { - auth_http_call!(self, |http, access| http.create_project(&access, req)) - } - - /// List account-scoped projects from the backend. - pub async fn list_projects(&self) -> Result { - auth_http_call!(self, |http, access| http.list_projects(&access)) - } - - /// Update a project's name in the backend. - pub async fn update_project( - &self, - req: minos_protocol::UpdateProjectRequest, - ) -> Result<(), MinosError> { - auth_http_call!(self, |http, access| http.update_project(&access, req)) - } - - /// Delete a project from the backend. - pub async fn delete_project( - &self, - req: minos_protocol::DeleteProjectRequest, - ) -> Result<(), MinosError> { - auth_http_call!(self, |http, access| http.delete_project(&access, req)) - } - - /// List backend-known sessions within a project. - pub async fn list_project_sessions( - &self, - req: minos_protocol::ListProjectSessionsParams, - ) -> Result { - auth_http_call!(self, |http, access| { - http.list_project_sessions(&access, req) - }) - } - /// Subscribe to auth-state transitions. The first read on the receiver /// returns the current cached frame. #[must_use] @@ -2257,25 +2065,6 @@ mod tests { assert_eq!(url, "wss://edge.example/ws/client?ticket=edge-ticket"); } - #[tokio::test] - async fn list_sessions_without_persisted_state_errors_unauthorized() { - // list_sessions is bearer-only. With no auth_session it surfaces - // Unauthorized (not StoreCorrupt — device-secret is not required). - let client = MobileClient::new_with_in_memory_store("test".into()); - let err = client - .list_sessions(ListSessionsParams { - limit: 10, - before_ts_ms: None, - agent: None, - }) - .await - .expect_err("HTTP query with no creds must error"); - assert!( - matches!(err, MinosError::Unauthorized { .. }), - "unexpected error: {err:?}" - ); - } - #[test] fn forbidden_handshake_maps_to_unauthorized_with_status_in_reason() { let err = connect_error_to_minos( @@ -2373,36 +2162,6 @@ mod tests { } } - #[tokio::test] - async fn send_user_message_requires_authentication() { - let client = MobileClient::new_with_in_memory_store("iPhone".into()); - let res = client - .send_user_message("thr_1".into(), "ping".into()) - .await; - assert!(matches!(res, Err(MinosError::Unauthorized { .. }))); - } - - #[tokio::test] - async fn close_session_requires_authentication() { - let client = MobileClient::new_with_in_memory_store("iPhone".into()); - let res = client.close_session("thr".into()).await; - assert!(matches!(res, Err(MinosError::Unauthorized { .. }))); - } - - #[tokio::test] - async fn send_approval_decision_requires_authentication() { - let client = MobileClient::new_with_in_memory_store("iPhone".into()); - let res = client - .send_approval_decision( - "req-1".into(), - "thr-1".into(), - serde_json::json!({ "decision": "accept" }), - Some("approval-op-1".into()), - ) - .await; - assert!(matches!(res, Err(MinosError::Unauthorized { .. }))); - } - #[tokio::test] async fn subscribe_auth_state_emits_unauthenticated_initially() { let client = MobileClient::new_with_in_memory_store("iPhone".into()); diff --git a/docs/architecture-mobile.md b/docs/architecture-mobile.md index 8ff188ab..dc72bf12 100644 --- a/docs/architecture-mobile.md +++ b/docs/architecture-mobile.md @@ -21,24 +21,34 @@ lib/ architecture.dart # 架构文档(dartdoc) domain/ # 纯 Dart 模型 + 协议 auth_state.dart # 认证状态机 - active_session.dart # Agent 会话状态机 - agent_profile.dart # Agent 配置文件 - minos_core_protocol.dart # 抽象 Dart 契约(~60 方法) + agent_profile.dart # 本地 bot cache / draft + social_message.dart # 协作消息模型 + minos_core_protocol.dart # 抽象 Dart 契约(IM/auth/hosts/realtime) infrastructure/ # 具体实现 - minos_core.dart # FRB 实现(599 行) + minos_core.dart # FRB 实现 secure_pairing_store.dart # iOS Keychain 持久化 + social_cache_store.dart # SQLite cache + outbox SQL + im_outbox_store.dart # Outbox 策略 data/ # 仓库 + 服务 cloud/ # 纯 Dart 云控制面(exchange / hosts mapper) - repositories/ # 各功能仓库(含 HostsRepository) + repositories/ # 各功能仓库(含 HostsRepository / SocialRepository) services/ # 服务 application/ # Riverpod providers / ViewModels auth_provider.dart # 认证状态 - active_session_provider.dart # Agent 会话 - thread_events_provider.dart # 线程事件 - minos_providers.dart # 连接 / linked hosts / 设备 - project_providers.dart # 项目 - social_providers.dart # 社交 - thread_commands.dart # 命令门面 + minos_providers.dart # 连接 / linked hosts / presence + social/ # Conversation IM feature modules + social_conversation_state.dart # freezed timeline state + social_conversation_notifier.dart + social_inbox_notifier.dart + social_chat_view_model.dart # feature ViewModel 聚合 + social_chat_actions.dart # 意图化 Action + social_ui_state.dart + social_friends_providers.dart + social_realtime_sync.dart + social_providers.dart # 兼容 barrel(re-export social/*) + im_outbox_worker.dart # 本地 IM outbox drain + agent_profiles_provider.dart # 本地 bot cache(compose 选 bot) + group_agent_provider.dart # participants / mention roster root_route_decision.dart # 根路由决策 ui/ # 功能组织 UI theme/ # Minos design tokens(color/spacing/radius/type) @@ -46,16 +56,13 @@ lib/ features/ shell/ # 应用壳(消息 / Hosts / 账户) messages/ # Golden-path conversation inbox - sessions/ # Agent session inbox(次级) hosts/ # Linked hosts 列表 account/ # 账户 / 退出登录 auth/ # 登录注册 - chat/ # Agent session transcript stream + composer - social/ # 协作 IM 聊天 / 成员(次级路由) + social/ # 协作 IM 聊天 / 成员 lib/message_grouping.dart # 10min 分组 + day divider(对齐 Desktop) widgets/ # Slack/Buzz 全宽行 chrome / row / actions - projects/ # 项目(次级路由) - agents/ # Agent profile(次级路由) + debug/ # 日志与请求追踪 src/rust/ # 自动生成的 FRB 代码(勿手改) ``` @@ -75,16 +82,17 @@ lib/ | Provider | 类型 | 用途 | |----------|------|------| | `authControllerProvider` | `@Riverpod(keepAlive: true)` | 认证状态 | -| `activeSessionControllerProvider` | `@Riverpod(keepAlive: true)` | Agent 会话状态机 | -| `threadEventsProvider(sessionId)` | `@Riverpod(keepAlive: true)` | 线程事件 | -| `connectionStateProvider` | `@Riverpod(keepAlive: true)` | 连接状态 | +| `connectionStateProvider` | `@Riverpod(keepAlive: true)` | 连接状态(Account `/ws/client`) | | `pairedMacsProvider` | `AsyncNotifierProvider` | Linked hosts(`GET /v1/hosts`) | | `hostsRepositoryProvider` | `Provider` | 纯 Dart hosts 列表 + FRB fallback | -| `projectListProvider` | `@Riverpod(keepAlive: true)` | 项目 CRUD | -| `conversationsProvider` | `AsyncNotifierProvider` | 对话列表 | -| `friendsProvider` | `AsyncNotifierProvider` | 好友列表 | +| `conversationsProvider` | `AsyncNotifierProvider` | 对话列表(InboxSync) | +| `socialConversationProvider` | `@riverpod` family | 打开会话时间线(TimelineSync) | +| `socialChatViewModelProvider` | `@riverpod` family | SocialChat feature 聚合状态 | +| `socialChatActionsProvider` | `Provider.family` | SocialChat 意图化 action | +| `friendsProvider` | `AsyncNotifierProvider` | 好友列表(Messages 选人) | +| `imOutboxWorkerProvider` | `Provider` | 本地 IM outbox drain | -**模式**: 每个 Provider 是 `AsyncNotifier` / `Notifier`,包裹 Repository。Repository 调用 `MinosCoreProtocol`。UI 只 watch provider。 +**模式**: 保留 Riverpod + codegen;复杂 feature 使用 **ViewModel 聚合 + Action 层 + freezed 状态机**。UI 优先 `socialChatViewModelProvider` / `socialChatActionsProvider`,而不是直接编排几十个细粒度 provider。协作发送唯一路径:`SocialChatActions.send` → `SocialConversation.sendMessage` → outbox → `sendChatMessage`。 ## 路由系统 @@ -95,34 +103,33 @@ lib/ | `/splash` | `_SplashScreen` | 启动加载 | | `/login` | `LoginPage` | 登录/注册 | | `/` | `AppShellPage` | 主壳(消息 / Hosts / 账户) | -| `/sessions` | `SessionsPage` | Agent session 列表(次级) | -| `/thread/:sessionId` | `ThreadViewPage` | Agent 线程对话 | -| `/thread/new` | `ThreadViewPage` | 新线程 | -| `/agent-start` | `AgentStartPage` | Agent 选择(次级) | -| `/project/:projectId` | `ProjectDetailPage` | 项目详情(次级) | | `/social` | redirect → `/` | 旧消息入口,兼容跳转到 shell 消息 Tab | | `/social/chat/:conversationId` | `SocialChatPage` | Conversation 协作 IM(Hub 气泡;Slack/Buzz 全宽左对齐行) | +| `/social/chat/:conversationId/members` | `GroupMembersPage` | 群成员 | +| `/log-viewer` | `LogViewerPage` | 开发者日志 | + +**已下线(不再作为产品面)**:`/thread/*`、`/sessions`、`/agent-start`、`/agent-profile/*`、`/project/*`,以及 Agent session transcript / Projects / Agents Hub UI。 ### 根路由决策 (`root_route_decision.dart`) ``` AuthBootstrapping / AuthRefreshing → splash AuthUnauthenticated / AuthRefreshFailed → login -AuthAuthenticated + Connected → projectList -AuthAuthenticated + offline → projectListOffline +AuthAuthenticated + Connected → shell +AuthAuthenticated + offline → shellOffline ``` `createAppRouter` redirect only reads synchronous `authControllerProvider`. -`projectList` and `projectListOffline` both map to shell `/` (offline chrome is -in-shell). Do not seed login-page provider state from widget `initState` — +`shell` and `shellOffline` both map to shell `/` (offline chrome is in-shell). +Do not seed login-page provider state from widget `initState` — `LoginPageStateController.build` reads `AuthRefreshFailed` once when the provider is created. ### App Shell(3 个 Tab) -- **Tab 0 (消息)**: `MessagesPage` — 全部 conversation,按 `lastMessageAtMs` 倒序 -- **Tab 1 (Hosts)**: `HostsPage` — linked hosts -- **Tab 2 (账户)**: `AccountPage` — profile / logout;入口可进次级「Agent 会话」 +- **Tab 0 (消息)**: `MessagesPage` — 全部 conversation,按 `lastMessageAtMs` 倒序;可新建 DM / 群 / agent conversation +- **Tab 1 (Hosts)**: `HostsPage` — linked hosts(bot runtime 身体) +- **Tab 2 (账户)**: `AccountPage` — profile / logout / 开发者工具 UI 使用自研 **Minos design tokens**(iOS 向手感),不再依赖 `shadcn_ui`。 @@ -137,14 +144,14 @@ UI 使用自研 **Minos design tokens**(iOS 向手感),不再依赖 `shadc | 分隔 | 日历日 `ConversationDayDivider`(今天 / 昨天 / 日期) | | 撤回 | 居中 `ConversationSystemMessage` | | 交互 | 长按:引用 / 复制 / 重试 / 撤回;失败红 `!` 重试;stick-to-bottom + 跳转最新 FAB | -| 实时 | Composer 上 Agent activity ticker;深链 Agent 气泡 → `/thread/:sessionId` | +| 发送 | 唯一主链路:outbox + `sendChatMessage`(Account WS `AppendMessage`) | | TimelineSync | `SocialConversationState` 维护 `minLoadedSeq` / `maxLoadedSeq` / `hasOlder`;`loadOlder()` → Hub `before_seq`;近顶滚动触发 | | InboxSync | `ConversationsController` 事件 → 单行 patch + unread bump;**禁止**每事件 `invalidateSelf` / 全量 REST | | SnapshotRequired | Rust `UiEvent raw(kind=snapshot_required)` → `imSnapshotSyncProvider`:conversation 仅 `ref.exists` 时 range reconcile(不 cold-start / 不 mark-read);account → inbox hydrate | | 排序 | durable 仅 `server_order_key`(message_seq);禁止 `COALESCE(seq, created_at_ms)` | | parse 失败 | Rust `parse_chat_message` 返回 `None`,不入空壳气泡 | -**注意**:Agent session transcript(`ThreadViewPage` / `MessageBubble`)仍是执行面,可保留 L/R 或 transcript rail,不与协作 IM 行壳混用。 +**注意**:Mobile 不再提供 Agent session transcript 产品面。Bot 结果以 Hub conversation 气泡呈现;执行审批/transcript 若后续恢复,应做成 conversation-scoped Attention,而不是独立 `/thread` 发送主链路。 ## Rust FFI 桥接 @@ -177,13 +184,14 @@ Rust crate (minos-mobile::MobileClient) - **认证**: `register`, `login`, `loginWithSupabase`, `refreshSession`, `logout`, `subscribeAuthState` - **Hosts**: `listPairedHosts`(内部 `GET /v1/hosts`), `activeHost`, `setActiveHost`, `forgetHost`(`POST /v1/hosts/unlink`) -- **社交**: `conversations`, `sendChatMessage`, `friends`, `friendRequests`, `searchUsers` -- **项目**: `createProject`, `listProjects`, `updateProject`, `deleteProject` -- **线程**: `listThreads`, `readThread`, `sendUserMessage`, `interruptThread`, `closeThread` -- **Agent 请求**: `sendApprovalDecision`, `respondOpencodeQuestion` -- **实时**: `subscribeState`, `subscribeUiEvents`, `subscribeSocialEvents` +- **社交 IM**: `conversations`, `sendChatMessage`, `friends`, participants / membership +- **实时**: `subscribeState`, `subscribeUiEvents`, `subscribeSocialEvents`, conversation topic subscribe/ack +- **Hosts**: `listPairedHosts`, `activeHost`, `setActiveHost`, `forgetHost` +- **Auth**: `loginWithSupabase`, `refreshSession`, `logout`, `subscribeAuthState` - **生命周期**: `notifyForegrounded`, `notifyBackgrounded` +Mobile 不再暴露 thread transcript / project CRUD / agent-session compose / friend-search 管理 API;这些能力若存在于 backend/Desktop,也不再经 Mobile 协议面。 + ## 认证流程 ### 状态机 @@ -235,41 +243,15 @@ QR pairing is removed (Phase D). Desktop links the Mac with the same account; Mo 2. On failure, falls back to FRB `listPairedHosts` (Rust also uses `GET /v1/hosts`) 3. `pairedMacsProvider` drives Hosts UI; empty state points users to Desktop **Link this Mac** 4. If no active host is set, auto-select the first online host (else first listed) as routing target -5. Session list / stream / send stay on `/v1/agent-sessions/*` + `/ws/client` (account bearer) +5. Mobile 不提供独立 Agent session 发送/transcript 产品面;bot 结果以 Hub conversation 气泡呈现 6. Forget host uses `POST /v1/hosts/unlink` -## Agent 会话管理 - -### 状态机 - -``` -SessionIdle --send()--> SessionSending --first UI frame--> SessionStreaming - | | - +--error--> SessionError | - v - SessionStreaming --MessageCompleted--> SessionAwaitingInput - | | - +--stop()/SessionClosed--> SessionSuspended | - | | - +--error--> SessionError<--send failure------+ - <-----------send() (follow-up)---------------+ -``` - -### 线程事件 Provider +## Agent / Bot 在 Mobile 中的角色 -- 加载初始页: `readThread()` -- 订阅实时 `UiEventFrame` 流 -- 基于 seq 水位线去重 -- `keepAlive: true`,导航离开不丢失状态 -- `UiEventMessage` 文本字段使用 `DisplayPayload`,Dart 通过 `display_payload_preview.dart` 渲染 inline/windowed preview;artifact 引用保留在线程归属内,后续完整展开走 range read API。 -- 聊天 transcript 投影由 `application/thread_event_timeline.dart` 的 `buildThreadEventTimeline` 完成:按事件**首次出现**顺序生成 row(user / reasoning / tool / assistant text),**连续**流式片段原地更新;Gemini/Grok ACP 虽把 thinking、tool、text 挂在同一 `message_id` 上,也必须按时间线切开——中间产物(早期 `agent_message_chunk` / thought)与 tool 之后的最终回复各自独立 row,不能拼成一条钉在用户消息后的“假最终回复”。tool / text 插入后新 thinking 开新 reasoning 段;tool / reasoning 插入后新 text 开新 assistant text 段,都排在时间线末尾。仅仍 open 的 text 段在 live turn 上显示 streaming cursor;已结束的中间消息与 thinking 不带光标。 -- `Raw(kind="opencode/question.asked")` 由 `ThreadViewPage` 解析为 `AgentQuestionRequestData`,通过 `agent_question_sheet.dart` 展示问题和选项;提交后走 `ThreadCommands.respondOpencodeQuestion()` → `ThreadRepository` → `MinosCore` → FRB → `MobileClient.respond_opencode_question()` → `POST /v1/agent-sessions/respond-opencode-question`。 - -### Agent 配置文件 - -`AgentProfile` 不可变模型: id, agentId, name, description, runtimeAgent, model, reasoningEffort, environmentVariables, hostDeviceId, workspacePath - -持久化为 JSON 文件。 +- **Hub bot identity** 是多端 SSOT;`AgentProfile` 本地 JSON 仅作 compose 选 bot 的 cache/draft。 +- Messages 可新建 agent conversation(`createAgentConversation` → 建 group + addAgent)。 +- 协作发送与 @bot 都走 conversation 时间线;Host 只是 bot runtime 身体(Hosts tab 可见性)。 +- Mobile 当前**不**承载 session transcript / approval / opencode question UI。若后续恢复,应做成 conversation-scoped Attention,而不是复活 `/thread` 发送主链路。 ## Rust WebSocket 架构 @@ -311,38 +293,23 @@ SessionIdle --send()--> SessionSending --first UI frame--> SessionStreaming | `register` | 严格注册 → 配对(`EmailTaken` 不降级) | | `smoke-session` | 完整流程: 注册 → 配对 → `send_user_message` → 流式接收 | -## 数据流(端到端聊天消息) - -``` -用户在 InputBar 输入 - → ThreadCommands.sendUserMessage() - → ThreadRepository.sendUserMessage() - → MinosCore.sendUserMessage() - → MobileClient.send_user_message() [Rust, via FRB] - → MobileHttpClient.send_agent_input() [HTTP POST] - -后端通过 WS 广播: - → ServerFrame::StreamEvent (topic: agent_session:xxx) - → RealtimeSession.run() 接收 - → handle_server_frame() → dispatch_event() - → UiEventFrame broadcast - → ActiveSessionController._onUiEvent() [Dart] - → 状态机转换 - → ThreadEvents [Dart] - → 追加事件列表 - → ThreadViewPage 渲染 DisplayPayload preview 并重建 UI -``` +## 数据流(端到端协作 IM 消息) -### Agent question 数据流 - -``` -opencode question.asked - → daemon projection Raw(kind="opencode/question.asked") - → backend StreamEvent → mobile UiEventFrame - → ThreadViewPage.showAgentQuestionSheet() - → 用户选择/输入答案 - → ThreadCommands.respondOpencodeQuestion() - → POST /v1/agent-sessions/respond-opencode-question - → host command minos_respond_opencode_question - → daemon AgentGlue → AgentManager → opencode POST /question/{requestID}/reply ``` +用户在 SocialChatPage composer 输入 + → SocialConversation.sendMessage() + → SocialCacheStore.insertPendingMessageWithOutbox [TX: sending + outbox] + → UI 乐观展示 + → ImOutboxWorker.flush() + → SocialRepository.sendChatMessage() + → MinosCore.sendChatMessage() + → MobileClient.send_chat_message() [Rust FRB] + → WS ClientFrame::AppendMessage + → wait ChatSendAck / Nack + +后端 durable fanout: + → ServerFrame::DurableEvent (conversation / account topics) + → RealtimeSession → social_events broadcast + → SocialConversation / ConversationsController 投影 + → Dart commit cache 后 ackDurableApplied +``` \ No newline at end of file