diff --git a/mobile/ios/NativeControlTests/MeAgentAccessibilityTests.swift b/mobile/ios/NativeControlTests/MeAgentAccessibilityTests.swift index 3261ba27f8..c1baec99a0 100644 --- a/mobile/ios/NativeControlTests/MeAgentAccessibilityTests.swift +++ b/mobile/ios/NativeControlTests/MeAgentAccessibilityTests.swift @@ -70,6 +70,7 @@ struct MeAgentAccessibilityTests { precondition(submitted?["assistant"] == (canSubmit ? "agent" : nil)) } } + messageTests() avatarTests() print("Me agent accessibility and bounded avatar loading passed") } @@ -171,3 +172,61 @@ private final class AvatarProtocol: URLProtocol { } loader.cancelAll() } + +@MainActor private func messageTests() { + let message = String(repeating: "Plan my trip. ", count: 20) + for locked in [false, true] { + var submitted: [String: String]? + let controller = NativeProfileTextEditorViewController( + title: "New chat", initialValue: message, placeholder: "Message", + multiline: true, pageBackgroundColor: .systemGroupedBackground, + containerBackgroundColor: .secondarySystemGroupedBackground, + containerCornerRadius: 16, allowUnchangedSubmission: false, + channelDescription: nil, originalName: nil, originalDescription: nil, + canEditDetails: true, canEditCanvas: false, canvasContent: "", + canvasLoaded: false, + chatOptions: ["messageMode": true, "presentationId": "message", "fieldsLocked": locked, + "selectedAssistant": locked ? "saved" : NSNull(), + "savedAssistant": ["id": "saved", "name": "Saved agent"], "assistants": []], + onCancel: {}, onSet: { submitted = $0 as? [String: String] } + ) + controller.loadViewIfNeeded() + let cell = controller.tableView(controller.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) + let input = cell.contentView.subviews.compactMap { $0 as? UITextView }.first! + precondition(input.accessibilityLabel == "Message") + precondition(input.isEditable == !locked) + precondition(controller.navigationItem.rightBarButtonItem?.title == (locked ? "Retry" : "Send")) + precondition(controller.navigationItem.rightBarButtonItem?.isEnabled == locked) + controller.updateChatAssistants(["presentationId": "stale", "defaultAssistant": "bestie", + "assistants": [["id": "bestie", "name": "Bestie"]]]) + precondition(controller.navigationItem.rightBarButtonItem?.isEnabled == locked) + controller.updateChatAssistants(["presentationId": "message", "defaultAssistant": "missing", + "assistants": [["id": "bestie", "name": "Bestie"]]]) + precondition(controller.navigationItem.rightBarButtonItem?.isEnabled == locked) + controller.updateChatAssistants(["presentationId": "message", "defaultAssistant": "bestie", + "assistants": [["id": "bestie", "name": "Bestie"]]]) + precondition(controller.navigationItem.rightBarButtonItem?.isEnabled == true) + controller.updateChatAssistants(["presentationId": "message", "defaultAssistant": "other", + "assistants": [["id": "bestie", "name": "Bestie"], ["id": "other", "name": "Other"]]]) + if !locked { + let navigation = UINavigationController(rootViewController: controller) + controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: 0, section: 2)) + let picker = navigation.topViewController as! MeAssistantListController + picker.tableView(picker.tableView, didSelectRowAt: IndexPath(row: 0, section: 0)) + controller.updateChatAssistants(["presentationId": "message", "defaultAssistant": "other", + "assistants": [["id": "bestie", "name": "Bestie"], ["id": "other", "name": "Other"]]]) + } + _ = controller.perform(NSSelectorFromString("setTapped")) + precondition(submitted?["name"] == message) + precondition(submitted?["assistant"] == (locked ? "saved" : "bestie")) + if !locked { + submitted = nil + input.text = String(repeating: "🐝", count: 2049) + controller.textViewDidChange(input) + _ = controller.perform(NSSelectorFromString("setTapped")) + precondition(submitted == nil) + precondition(input.isEditable) + } + precondition(controller.tableView(controller.tableView, heightForRowAt: IndexPath(row: 0, section: 1)) == 52) + } +} diff --git a/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift b/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift index 05f017f722..0f88c4f4ef 100644 --- a/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift +++ b/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift @@ -23,6 +23,21 @@ private final class SettingMenuMessenger: NSObject, FlutterBinaryMessenger { @main struct SettingMenuSelectionTests { @MainActor static func main() { + let merging = MergingNavigationGlass(frame: CGRect(x: 0, y: 0, width: 256, height: 56)) + merging.layoutIfNeeded() + UIView.setAnimationsEnabled(false) + merging.setMenuOpen(true, animator: nil) + precondition(merging.leftSurface.transform.tx == 100) + precondition(merging.rightSurface.transform.tx == -100) + precondition(merging.leftSurface.transform.a == 0.9) + precondition(merging.leftSurface.alpha == 0 && merging.rightSurface.alpha == 0) + precondition(merging.centerSurface.alpha == 1) + merging.setMenuOpen(false, animator: nil) + precondition(merging.leftSurface.transform == .identity) + precondition(merging.rightSurface.transform == .identity) + precondition(merging.leftSurface.alpha == 1 && merging.rightSurface.alpha == 1) + UIView.setAnimationsEnabled(true) + for deferred in [false, true] { let messenger = SettingMenuMessenger() let view = NavigationGlassButtonPlatformView( @@ -59,6 +74,25 @@ struct SettingMenuSelectionTests { precondition(messenger.selections == [0]) } } + let messenger = SettingMenuMessenger() + let grouped = NavigationGlassButtonPlatformView( + frame: CGRect(x: 0, y: 0, width: 112, height: 56), + viewIdentifier: 2, + arguments: ["deferMenuActions": false, "menu": [ + ["id": 0, "label": "New chat", "sectionTitle": "Solo", "enabled": true], + ["id": 1, "label": "New workspace", "enabled": true], + ["id": 2, "label": "New DM", "sectionTitle": "Team", "dividerBefore": true, "enabled": true], + ["id": 3, "label": "New channel", "enabled": true], + ]], messenger: messenger + ) + let button = grouped.view().subviews.compactMap { $0 as? NavigationGlassButton }.first! + precondition(button.preferredMenuElementOrder == .fixed) + let groups = button.menu!.children.compactMap { $0 as? UIMenu } + precondition(groups.map(\.title) == ["Solo", "Team"]) + precondition(groups.map { $0.children.count } == [2, 2]) + let teamAction = groups[1].children[0] as! UIAction + UIButton(primaryAction: teamAction).sendActions(for: .touchUpInside) + precondition(messenger.selections == [2]) print("Native setting menu selection checks passed") } } diff --git a/mobile/ios/Runner/JumpToLatestGlassButton.swift b/mobile/ios/Runner/JumpToLatestGlassButton.swift index 7be37f80e4..6352717777 100644 --- a/mobile/ios/Runner/JumpToLatestGlassButton.swift +++ b/mobile/ios/Runner/JumpToLatestGlassButton.swift @@ -43,6 +43,9 @@ private final class JumpToLatestGlassButton: UIButton { final class NavigationGlassButton: UIButton { var hitTargetInsets = UIEdgeInsets.zero var pendingMenuAction: (() -> Void)? + var menuVisibilityChanged: ((Bool) -> Void)? + var animateMenu: ((Bool, UIContextMenuInteractionAnimating?) -> Void)? + weak var glassPreview: UIView? override func contextMenuInteraction( _ interaction: UIContextMenuInteraction, @@ -50,6 +53,8 @@ final class NavigationGlassButton: UIButton { animator: UIContextMenuInteractionAnimating? ) { super.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: animator) + animateMenu?(true, animator) + menuVisibilityChanged?(true) UIImpactFeedbackGenerator(style: .light).impactOccurred() } @@ -59,6 +64,8 @@ final class NavigationGlassButton: UIButton { animator: UIContextMenuInteractionAnimating? ) { super.contextMenuInteraction(interaction, willEndFor: configuration, animator: animator) + animateMenu?(false, animator) + menuVisibilityChanged?(false) let action = pendingMenuAction pendingMenuAction = nil // Flutter routes must start after UIKit removes the glass menu and its @@ -70,6 +77,16 @@ final class NavigationGlassButton: UIButton { } } + override func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + previewForHighlightingMenuWithConfiguration configuration: UIContextMenuConfiguration + ) -> UITargetedPreview? { + guard let glassPreview else { + return super.contextMenuInteraction(interaction, previewForHighlightingMenuWithConfiguration: configuration) + } + return UITargetedPreview(view: glassPreview) + } + override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard isEnabled, isUserInteractionEnabled, !isHidden, alpha > 0.01 else { return false @@ -195,6 +212,7 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { private let containerView: UIView private let channel: FlutterMethodChannel private let button = NavigationGlassButton(type: .system) + private var navigationGlass: MergingNavigationGlass? private let activityIndicator = UIActivityIndicatorView(style: .medium) private let swatchView = UIView() private var labelForegroundColor: UIColor? @@ -220,6 +238,9 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { ) super.init() + button.menuVisibilityChanged = { [weak self] visible in + self?.channel.invokeMethod("menuVisibilityChanged", arguments: visible) + } containerView.backgroundColor = .clear containerView.isOpaque = false let arguments = args as? [String: Any] @@ -242,7 +263,7 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { configuration = .gray() configuration.baseBackgroundColor = UIColor.secondarySystemBackground } - if arguments?["plain"] as? Bool == true { configuration = .plain() } + if arguments?["plain"] as? Bool == true || arguments?["mergingNavigation"] as? Bool == true { configuration = .plain() } configuration.cornerStyle = .capsule button.configuration = configuration applyContent(from: arguments) @@ -303,6 +324,24 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { result(nil) } + if arguments?["mergingNavigation"] as? Bool == true { + let glass = MergingNavigationGlass(frame: containerView.bounds) + glass.autoresizingMask = [.flexibleWidth, .flexibleHeight] + containerView.addSubview(glass) + navigationGlass = glass + glass.centerSurface.contentView.addSubview(button) + button.glassPreview = glass.centerSurface + button.animateMenu = { [weak glass] visible, animator in + glass?.setMenuOpen(visible, animator: animator) + } + NSLayoutConstraint.activate([ + button.leadingAnchor.constraint(equalTo: glass.centerSurface.contentView.leadingAnchor), + button.trailingAnchor.constraint(equalTo: glass.centerSurface.contentView.trailingAnchor), + button.topAnchor.constraint(equalTo: glass.centerSurface.contentView.topAnchor), + button.bottomAnchor.constraint(equalTo: glass.centerSurface.contentView.bottomAnchor), + ]) + return + } containerView.addSubview(button) NSLayoutConstraint.activate([ button.centerYAnchor.constraint(equalTo: containerView.centerYAnchor), @@ -432,10 +471,18 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { button.accessibilityLabel = accessibilityLabel } if let menu = arguments?["menu"] as? [[String: Any]] { + // Keep titled sections in reading order even above a bottom-bar trigger. + button.preferredMenuElementOrder = menu.contains { $0["sectionTitle"] is String } ? .fixed : .automatic var groups: [[UIMenuElement]] = [[]] + var groupTitles = [""] for item in menu { - if item["dividerBefore"] as? Bool == true, !groups[groups.count - 1].isEmpty { + if item["dividerBefore"] as? Bool == true || item["sectionTitle"] is String, + !groups[groups.count - 1].isEmpty { groups.append([]) + groupTitles.append("") + } + if let title = item["sectionTitle"] as? String { + groupTitles[groupTitles.count - 1] = title } let symbol = (item["symbol"] as? String).flatMap { // A transparent image keeps the native menu's icon column aligned. @@ -459,7 +506,9 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { } groups[groups.count - 1].append(action) } - button.menu = UIMenu(children: groups.map { UIMenu(options: .displayInline, children: $0) }) + button.menu = UIMenu(children: groups.enumerated().map { index, children in + UIMenu(title: groupTitles[index], options: .displayInline, children: children) + }) button.showsMenuAsPrimaryAction = !menu.isEmpty } switch icon { @@ -688,3 +737,96 @@ final class NativeSegmentedControlPlatformView: NSObject, FlutterPlatformView { channel.setMethodCallHandler(nil) } } + +/// Three native glass elements share a compositor so their surfaces merge. +final class MergingNavigationGlass: UIView { + let leftSurface: UIVisualEffectView + let centerSurface: UIVisualEffectView + let rightSurface: UIVisualEffectView + private let group: UIVisualEffectView + private var movementAnimator: UIViewPropertyAnimator? + + override init(frame: CGRect) { + if #available(iOS 26.0, *) { + let container = UIGlassContainerEffect() + container.spacing = 12 + group = UIVisualEffectView(effect: container) + leftSurface = UIVisualEffectView(effect: UIGlassEffect(style: .regular)) + centerSurface = UIVisualEffectView(effect: UIGlassEffect(style: .regular)) + rightSurface = UIVisualEffectView(effect: UIGlassEffect(style: .regular)) + } else { + group = UIVisualEffectView(effect: nil) + leftSurface = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial)) + centerSurface = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial)) + rightSurface = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial)) + } + super.init(frame: frame) + group.frame = bounds + group.autoresizingMask = [.flexibleWidth, .flexibleHeight] + addSubview(group) + for surface in [leftSurface, rightSurface, centerSurface] { + if #available(iOS 26.0, *) { + surface.cornerConfiguration = .capsule() + } else { + surface.layer.cornerRadius = 28 + surface.clipsToBounds = true + } + group.contentView.addSubview(surface) + } + leftSurface.isUserInteractionEnabled = false + rightSurface.isUserInteractionEnabled = false + } + + required init?(coder: NSCoder) { nil } + + override func layoutSubviews() { + super.layoutSubviews() + // Use bounds/center rather than frame: side views may be transformed. + leftSurface.bounds = CGRect(x: 0, y: 0, width: 56, height: 56) + rightSurface.bounds = leftSurface.bounds + centerSurface.bounds = CGRect(x: 0, y: 0, width: 112, height: 56) + leftSurface.center = CGPoint(x: 28, y: bounds.midY) + rightSurface.center = CGPoint(x: bounds.width - 28, y: bounds.midY) + centerSurface.center = CGPoint(x: bounds.midX, y: bounds.midY) + } + + func setMenuOpen(_ open: Bool, animator: UIContextMenuInteractionAnimating?) { + layoutIfNeeded() + let movement = bounds.midX - 28 + let changes = { [weak self] in + guard let self else { return } + self.leftSurface.transform = open + ? CGAffineTransform(translationX: movement, y: 0).scaledBy(x: 0.9, y: 0.9) : .identity + self.rightSurface.transform = open + ? CGAffineTransform(translationX: -movement, y: 0).scaledBy(x: 0.9, y: 0.9) : .identity + } + let opacity = { [weak self] in + self?.leftSurface.alpha = open ? 0 : 1 + self?.rightSurface.alpha = open ? 0 : 1 + } + // The live Flutter artwork uses this same 180 ms easeOutCubic curve. + // UIKit's menu animator has different timing, which makes the glass outrun + // its artwork. Start both from the visibility callback instead. + if let movementAnimator, movementAnimator.state == .active { + movementAnimator.stopAnimation(false) + movementAnimator.finishAnimation(at: .current) + } + movementAnimator = nil + if UIAccessibility.isReduceMotionEnabled { + UIView.performWithoutAnimation { + changes() + opacity() + } + } else { + let timing = UICubicTimingParameters( + controlPoint1: CGPoint(x: 0.215, y: 0.61), + controlPoint2: CGPoint(x: 0.355, y: 1) + ) + let movement = UIViewPropertyAnimator(duration: 0.18, timingParameters: timing) + movement.addAnimations(changes) + movement.addAnimations(opacity, delayFactor: open ? 0.5 : 0) + movementAnimator = movement + movement.startAnimation() + } + } +} diff --git a/mobile/ios/Runner/NativeProfileTextEditor.swift b/mobile/ios/Runner/NativeProfileTextEditor.swift index c8544b926f..41f4ee3a83 100644 --- a/mobile/ios/Runner/NativeProfileTextEditor.swift +++ b/mobile/ios/Runner/NativeProfileTextEditor.swift @@ -256,11 +256,13 @@ private final class NativeProfileTextEditorViewController: private var hasFocusedEditor = false private var selectedAssistantAvatar: UIImage? private var selectedAssistant: String? + private var assistantChosenManually = false private var selectedProject: String? private var projects: [[String: String]] { chatOptions?["projects"] as? [[String: String]] ?? [] } private var isChatEditor: Bool { chatOptions != nil } + private var isMessageEditor: Bool { chatOptions?["messageMode"] as? Bool ?? false } private var isProjectEditor: Bool { chatOptions?["projectOnly"] as? Bool ?? false } private var assistants: [[String: String]] { chatOptions?["assistants"] as? [[String: String]] ?? [] @@ -291,7 +293,7 @@ private final class NativeProfileTextEditorViewController: let view = UITextView() view.translatesAutoresizingMaskIntoConstraints = false view.text = channelDescription ?? initialValue - view.isEditable = canEditDetails + view.isEditable = canEditDetails && !fieldsLocked view.accessibilityLabel = isChannelEditor ? "Description" : placeholder view.font = .preferredFont(forTextStyle: .body) view.adjustsFontForContentSizeCategory = true @@ -386,7 +388,7 @@ private final class NativeProfileTextEditorViewController: action: #selector(cancelTapped) ) navigationItem.rightBarButtonItem = UIBarButtonItem( - title: isChatEditor ? (fieldsLocked ? "Retry" : "Create") : (isChannelEditor ? "Save" : "Set"), + title: isChatEditor ? (fieldsLocked ? "Retry" : (isMessageEditor ? "Send" : "Create")) : (isChannelEditor ? "Save" : "Set"), style: .done, target: self, action: #selector(setTapped) @@ -445,6 +447,11 @@ private final class NativeProfileTextEditorViewController: chatOptions?["assistants"] = arguments["assistants"] chatOptions?["assistantsLoading"] = false chatOptions?["assistantError"] = arguments["assistantError"] + if !assistantChosenManually && !fieldsLocked && arguments.keys.contains("defaultAssistant") { + let bestie = arguments["defaultAssistant"] as? String + selectedAssistant = assistants.contains(where: { $0["id"] == bestie }) ? bestie : nil + selectedAssistantAvatar = nil + } tableView.reloadSections(IndexSet(integer: 2), with: .none) updateNavigation() } @@ -461,7 +468,7 @@ private final class NativeProfileTextEditorViewController: && (!isChannelEditor || !canonicalChannelName.isEmpty) && (!isChatEditor || ( !currentValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - && currentValue.count <= 120 + && (isMessageEditor || currentValue.count <= 120) && (isProjectEditor || canSubmitAssistant) )) navigationController?.isModalInPresentation = hasUnsavedChanges @@ -503,10 +510,16 @@ private final class NativeProfileTextEditorViewController: guard !name.isEmpty, currentValue.count <= 120 else { return } onSet(name) } else if isChatEditor { + if isMessageEditor && currentValue.trimmingCharacters(in: .whitespacesAndNewlines).utf8.count > 8192 { + let alert = UIAlertController(title: "Message too long", message: "Keep your first message under 8 KB.", preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + return + } guard let selectedAssistant, canSubmitAssistant, !currentValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - currentValue.count <= 120 else { return } + (isMessageEditor || currentValue.count <= 120) else { return } onSet(["name": currentValue, "assistant": selectedAssistant, "project": selectedProject ?? ""]) } else if isChannelEditor { guard !canonicalChannelName.isEmpty else { return } @@ -543,6 +556,7 @@ private final class NativeProfileTextEditorViewController: view.endEditing(true) let picker = MeAssistantListController(assistants: assistants, selected: selectedAssistant, pageColor: pageBackgroundColor, rowColor: containerBackgroundColor, avatars: assistantAvatars) { [weak self] id, avatar in self?.selectedAssistantAvatar = avatar + self?.assistantChosenManually = true self?.selectedAssistant = id self?.tableView.reloadSections(IndexSet(integer: 2), with: .none) self?.updateNavigation() @@ -587,7 +601,7 @@ private final class NativeProfileTextEditorViewController: ) -> CGFloat { if isChatEditor && indexPath.section == 2 && selectedAssistant != nil { return 64 } if isChannelEditor && indexPath.section >= 2 { return UITableView.automaticDimension } - return (isChannelEditor ? indexPath.section == 1 : multiline) ? 132 : 52 + return (isChannelEditor ? indexPath.section == 1 : multiline && indexPath.section == 0) ? 132 : 52 } override func tableView( diff --git a/mobile/ios/Runner/NativeTabler.swift b/mobile/ios/Runner/NativeTabler.swift index 2efef0c0cc..9bfdb463c8 100644 --- a/mobile/ios/Runner/NativeTabler.swift +++ b/mobile/ios/Runner/NativeTabler.swift @@ -75,6 +75,7 @@ enum NativeTabler { "doc": 0xeaa4, // file "plus": 0xeb0b, // plus "building.2.crop.circle": 0xebf6, // building-community + "workspace": 0xecd7, // cube-3d-sphere "folder.badge.plus": 0xeaab, // folder-plus "headphones": 0xeabd, // headphones "line.3.horizontal.decrease": 0xeaa5, // filter diff --git a/mobile/lib/features/channels/channel_detail_page.dart b/mobile/lib/features/channels/channel_detail_page.dart index ba0745e39d..d35b78c070 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -25,6 +25,7 @@ import '../../shared/me/me_sync.dart'; import '../../shared/me/me_search_placement.dart'; import 'me/me_assistant_picker.dart'; import 'me/me_chat_assistant.dart'; +import 'me/me_workspace_picker.dart'; import 'me/me_messages_provider.dart'; import '../../shared/huddle/huddle.dart'; import '../../shared/identity_names/identity_names.dart'; @@ -302,6 +303,12 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { personalChat ? meSendMessageProvider : sendMessageProvider, ); final messagesState = ref.watch(messagesProvider); + final workspace = useMeWorkspace( + context, + ref, + enabled: personalChat, + channelId: channel.id, + ); final assistant = useMeChatAssistant( context, ref, @@ -743,6 +750,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { messagesNotifier.isCatchingUp, onNativeTitlePressed: openChannelDetails, nativeActions: [ + if (personalChat) workspace.nativeAction, if (personalChat) assistant.nativeAction else if (resolvedChannel.isDm ? showsHuddleAction : showsComposer) @@ -763,6 +771,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { onTap: openChannelDetails, ), actions: [ + if (personalChat) workspace.action, if (personalChat) assistant.action else if (resolvedChannel.isDm ? showsHuddleAction : showsComposer) diff --git a/mobile/lib/features/channels/compose_bar.dart b/mobile/lib/features/channels/compose_bar.dart index 74cabb7c81..aae3d39e90 100644 --- a/mobile/lib/features/channels/compose_bar.dart +++ b/mobile/lib/features/channels/compose_bar.dart @@ -13,6 +13,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:image_picker/image_picker.dart'; diff --git a/mobile/lib/features/channels/compose_bar/attachments.dart b/mobile/lib/features/channels/compose_bar/attachments.dart index 1ba99bb0eb..33962f27c6 100644 --- a/mobile/lib/features/channels/compose_bar/attachments.dart +++ b/mobile/lib/features/channels/compose_bar/attachments.dart @@ -132,6 +132,7 @@ class _AttachmentSurfacePanel extends HookWidget { final Future> Function() onPickAllPhotos; final Future Function(List photos) onChoosePhotos; final Future Function(List photos) onChooseAllPhotos; + final Future Function(Future Function()) preparePhotos; const _AttachmentSurfacePanel({ super.key, @@ -147,6 +148,7 @@ class _AttachmentSurfacePanel extends HookWidget { required this.onPickAllPhotos, required this.onChoosePhotos, required this.onChooseAllPhotos, + required this.preparePhotos, }); @override @@ -225,6 +227,7 @@ class _AttachmentSurfacePanel extends HookWidget { onPickAllPhotos: onPickAllPhotos, onChoosePhotos: onChoosePhotos, onChooseAllPhotos: onChooseAllPhotos, + preparePhotos: preparePhotos, ), ), _AttachmentSurface.closed || @@ -809,3 +812,17 @@ class _MemoryAttachmentImage extends HookConsumerWidget { ); } } + +// Keep a new-chat draft mounted until a selected attachment has been retained. +Future _prepareComposerAttachment( + BuildContext context, + ValueNotifier pending, + Future Function() action, +) async { + pending.value++; + try { + return await action(); + } finally { + if (context.mounted) pending.value--; + } +} diff --git a/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart b/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart index f1eab0e214..8db1b577a6 100644 --- a/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart +++ b/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart @@ -6,6 +6,16 @@ class ComposeBar extends HookConsumerWidget { final String? hintText; final ComposeBarOnSend onSend; + /// Temporarily freezes composition while its destination is being changed. + final bool interactionLocked; + + /// Intended recipients before a new Solo channel exists. Suppresses typing + /// and membership writes; other mentions are references until creation. + final List? draftMembers; + + /// Reports whether a send or upload is in flight. + final ValueChanged? onSendingChanged; + /// Lets a parent prepare its layout before the editor requests focus. final VoidCallback? onFocusRequested; @@ -21,8 +31,11 @@ class ComposeBar extends HookConsumerWidget { const ComposeBar({ super.key, required this.channelId, + this.interactionLocked = false, this.channelName = '', this.hintText, + this.draftMembers, + this.onSendingChanged, this.threadHeadId, this.rootId, this.focusNode, @@ -73,6 +86,25 @@ class ComposeBar extends HookConsumerWidget { final uploadError = useState(null); final uploadingCount = useState(0); final uploadProgress = useState(0.0); + final preparingAttachments = useState(0); + final lockedNow = useRef(interactionLocked); + lockedNow.value = interactionLocked; + bool rejectsAttachment() => + draftMembers != null && + (isSending.value || uploadingCount.value > 0 || lockedNow.value); + Future prepare(Future Function() action) => + _prepareComposerAttachment(context, preparingAttachments, action); + final sending = + isSending.value || + uploadingCount.value > 0 || + (draftMembers != null && preparingAttachments.value > 0); + _useComposerBusy( + isSending: isSending, + uploadingCount: uploadingCount, + preparingAttachments: preparingAttachments, + isDraft: draftMembers != null, + onChanged: onSendingChanged, + ); final uploadGeneration = useRef(0); final activeUploadCancellation = useRef(null); final voiceNote = _useComposerVoiceNote( @@ -236,7 +268,9 @@ class ComposeBar extends HookConsumerWidget { final channelsAsync = ref.watch(channelsProvider); _useComposerChannelNames(controller, channelsAsync); - final membersAsync = ref.watch(channelMembersProvider(channelId)); + final membersAsync = draftMembers == null + ? ref.watch(channelMembersProvider(channelId)) + : AsyncData(draftMembers!); final sessionStatus = ref.watch(relaySessionProvider).status; final cachedMembers = channelsAsync.asData == null ? const [] @@ -337,7 +371,7 @@ class ComposeBar extends HookConsumerWidget { final textChanged = text != previousValue.text; // Broadcast typing indicator (throttled). - if (textChanged && text.isNotEmpty) { + if (draftMembers == null && textChanged && text.isNotEmpty) { final now = DateTime.now().millisecondsSinceEpoch; if (now - lastTypingSentMs.value > _typingThrottleMs) { lastTypingSentMs.value = now; @@ -506,7 +540,9 @@ class ComposeBar extends HookConsumerWidget { // Send the message. Future send() async { final text = controller.text.trim(); - if ((text.isEmpty && !hasAttachments) || + if ((draftMembers != null && preparingAttachments.value > 0) || + interactionLocked || + (text.isEmpty && !hasAttachments) || isSending.value || uploadingCount.value > 0) { return; @@ -579,12 +615,25 @@ class ComposeBar extends HookConsumerWidget { final channelActions = ref.read(channelActionsProvider); final _NonMemberMentionScan scan; try { - scan = await _scanNonMemberMentions( - ref, - channelId: channelId, - selectedMentions: selectedMentions, - currentPubkey: currentPubkey, - ); + scan = draftMembers != null + ? _NonMemberMentionScan( + channelId: channelId, + outside: selectedMentions + .where( + (candidate) => !draftMembers!.any( + (member) => member.pubkey == candidate.pubkey, + ), + ) + .toList(), + canAddMembers: false, + isDm: true, + ) + : await _scanNonMemberMentions( + ref, + channelId: channelId, + selectedMentions: selectedMentions, + currentPubkey: currentPubkey, + ); } catch (_) { // Nothing was sent and the draft is untouched, so Retry sends it again. if (context.mounted) { @@ -734,12 +783,16 @@ class ComposeBar extends HookConsumerWidget { } } - final queueAttachment = useCallback( - ( - XFile file, - _PendingAttachmentKind kind, { - bool deleteAfterUse = false, - }) => _queueComposerAttachment( + final queueAttachment = useCallback(( + XFile file, + _PendingAttachmentKind kind, { + bool deleteAfterUse = false, + }) { + if (rejectsAttachment()) { + if (deleteAfterUse) unawaited(_deleteXFile(file)); + return; + } + _queueComposerAttachment( file, kind, voiceNoteRef, @@ -747,9 +800,8 @@ class ComposeBar extends HookConsumerWidget { uploadError, draftRevision, deleteAfterUse: deleteAfterUse, - ), - [voiceNoteRef, draftRevision, uploadError, attachments], - ); + ); + }, [voiceNoteRef, draftRevision, uploadError, attachments]); Future pickThenQueue({ required Future Function() pick, required _PendingAttachmentKind kind, @@ -767,6 +819,7 @@ class ComposeBar extends HookConsumerWidget { } bool queueImages(List images, {bool deleteAfterUse = false}) => + !rejectsAttachment() && _queueComposerImages( images, voiceNote, @@ -777,24 +830,26 @@ class ComposeBar extends HookConsumerWidget { ); Future retainAndQueueImages(List images) => - _retainAndQueueImages(context, images, queueImages); + prepare(() => _retainAndQueueImages(context, images, queueImages)); final pasteClipboardImage = useCallback(() { ContextMenuController.removeAny(); - unawaited(() async { - try { - final image = await ref - .read(mediaUploadServiceProvider) - .readClipboardImage(); - if (image != null && context.mounted) { - queueAttachment(image, _PendingAttachmentKind.image); - } else if (context.mounted) { - uploadError.value = 'Unable to read pasted image'; + unawaited( + prepare(() async { + try { + final image = await ref + .read(mediaUploadServiceProvider) + .readClipboardImage(); + if (image != null && context.mounted) { + queueAttachment(image, _PendingAttachmentKind.image); + } else if (context.mounted) { + uploadError.value = 'Unable to read pasted image'; + } + } catch (error) { + if (context.mounted) uploadError.value = _formatUploadError(error); } - } catch (error) { - if (context.mounted) uploadError.value = _formatUploadError(error); - } - }()); + }), + ); }, [context, ref, queueAttachment, uploadError]); final buildContextMenu = useCallback(( @@ -887,7 +942,7 @@ class ComposeBar extends HookConsumerWidget { context, attachmentSurface, uploadError, - choose, + () => prepare(choose), errorMessage: errorMessage, ); @@ -1002,6 +1057,7 @@ class ComposeBar extends HookConsumerWidget { ); Widget buildOverlayPanel(_AttachmentSurface surface) { return _composerAttachmentPanel( + preparePhotos: prepare, surface: surface, suggestionPanel: suggestionPanel, onBack: () => attachmentSurface.value = _AttachmentSurface.menu, @@ -1029,7 +1085,8 @@ class ComposeBar extends HookConsumerWidget { attachmentSurface.value = _AttachmentSurface.closed; await retainAndQueueImages([image]); }, - onPickAllPhotos: ref.read(mediaUploadServiceProvider).pickGalleryImages, + onPickAllPhotos: () => + prepare(ref.read(mediaUploadServiceProvider).pickGalleryImages), onChoosePhotos: (photos) async { attachmentSurface.value = _AttachmentSurface.closed; await retainAndQueueImages(photos); @@ -1068,52 +1125,57 @@ class ComposeBar extends HookConsumerWidget { onDismissAttachmentSurface: () { attachmentSurface.value = _AttachmentSurface.closed; }, - child: _ComposeBarLayout( - surfaceKey: sendSurfaceKey, - voiceNoteRecorder: voiceNote.recorder, - attachments: attachments.value, - onRemoveAttachment: removeAttachment, - uploadError: uploadError.value, - isExpanded: isComposerExpanded.value, - controller: controller, - focusNode: focusNode, - contextMenuBuilder: buildContextMenu, - onContentInserted: uploadPastedImage, - onSend: () => unawaited(send()), - resolvedHint: resolvedHint, - attachmentSurface: attachmentSurface.value, - onAttachmentTap: handleAttachmentTap, - onExpand: expandComposer, - expansionAnimation: composerExpansionController, - formattingOpen: showFormatting.value, - onCloseFormatting: () => showFormatting.value = false, - motionDuration: motionDuration, - resizeDuration: resizeDuration, - onFormat: applyFormat, - onMention: () { - attachmentSurface.value = _AttachmentSurface.closed; - triggerMention(); - }, - onChannel: () { - attachmentSurface.value = _AttachmentSurface.closed; - triggerChannel(); - }, - onEmoji: () { - attachmentSurface.value = _AttachmentSurface.closed; - isEmojiPickerOpen.value = true; - _showComposerEmojiPicker(context, insertEmoji, () { - if (!context.mounted) return; - isEmojiPickerOpen.value = false; - focusNode.requestFocus(); - }); - }, - onOpenFormatting: () { - attachmentSurface.value = _AttachmentSurface.closed; - showFormatting.value = true; - }, - hasPendingUploads: hasPendingUploads, - canSend: composerText.trim().isNotEmpty || hasAttachments, - isSending: isSending.value, + child: AbsorbPointer( + absorbing: interactionLocked || (draftMembers != null && sending), + child: _ComposeBarLayout( + surfaceKey: sendSurfaceKey, + voiceNoteRecorder: voiceNote.recorder, + attachments: attachments.value, + onRemoveAttachment: removeAttachment, + uploadError: uploadError.value, + isExpanded: isComposerExpanded.value, + controller: controller, + focusNode: focusNode, + contextMenuBuilder: buildContextMenu, + onContentInserted: uploadPastedImage, + onSend: () => unawaited(send()), + resolvedHint: resolvedHint, + attachmentSurface: attachmentSurface.value, + onAttachmentTap: handleAttachmentTap, + onExpand: expandComposer, + expansionAnimation: composerExpansionController, + formattingOpen: showFormatting.value, + onCloseFormatting: () => showFormatting.value = false, + motionDuration: motionDuration, + resizeDuration: resizeDuration, + onFormat: applyFormat, + onMention: () { + attachmentSurface.value = _AttachmentSurface.closed; + triggerMention(); + }, + onChannel: () { + attachmentSurface.value = _AttachmentSurface.closed; + triggerChannel(); + }, + onEmoji: () { + attachmentSurface.value = _AttachmentSurface.closed; + isEmojiPickerOpen.value = true; + _showComposerEmojiPicker(context, insertEmoji, () { + if (!context.mounted) return; + isEmojiPickerOpen.value = false; + focusNode.requestFocus(); + }); + }, + onOpenFormatting: () { + attachmentSurface.value = _AttachmentSurface.closed; + showFormatting.value = true; + }, + hasPendingUploads: hasPendingUploads, + canSend: composerText.trim().isNotEmpty || hasAttachments, + isSending: isSending.value || (draftMembers != null && sending), + readOnly: + interactionLocked || (draftMembers != null && sending), + ), ), ), ], diff --git a/mobile/lib/features/channels/compose_bar/draft_lifecycle.dart b/mobile/lib/features/channels/compose_bar/draft_lifecycle.dart index 2e30d300e2..7d15e55d4c 100644 --- a/mobile/lib/features/channels/compose_bar/draft_lifecycle.dart +++ b/mobile/lib/features/channels/compose_bar/draft_lifecycle.dart @@ -179,3 +179,53 @@ void _useComposeDraftLifecycle({ return () => controller.removeListener(persistDraft); }, [controller, draftKey, draftIdentity, onDraftIdentityChanged]); } + +// Report aggregate work independently of rebuilds, including sub-frame failures. +void _useComposerBusy({ + required ValueNotifier isSending, + required ValueNotifier uploadingCount, + required ValueNotifier preparingAttachments, + required bool isDraft, + required ValueChanged? onChanged, +}) { + final busyCallback = useRef(onChanged); + busyCallback.value = onChanged; + useEffect(() { + var active = true; + void reportCurrent() { + if (!active) return; + busyCallback.value?.call( + isSending.value || + uploadingCount.value > 0 || + (isDraft && preparingAttachments.value > 0), + ); + } + + void reportBusy() { + // Scope changes can reset the composer from a build-time effect. + // Ordinary operation completions still release the parent immediately. + if (SchedulerBinding.instance.schedulerPhase == + SchedulerPhase.persistentCallbacks) { + WidgetsBinding.instance.addPostFrameCallback((_) => reportCurrent()); + } else { + reportCurrent(); + } + } + + final sources = [isSending, uploadingCount, preparingAttachments]; + for (final source in sources) { + source.addListener(reportBusy); + } + return () { + active = false; + for (final source in sources) { + source.removeListener(reportBusy); + } + // Disposal can happen during a parent build. Release after that frame. + final callback = busyCallback.value; + WidgetsBinding.instance.addPostFrameCallback( + (_) => callback?.call(false), + ); + }; + }, [isSending, uploadingCount, preparingAttachments, isDraft]); +} diff --git a/mobile/lib/features/channels/compose_bar/helpers.dart b/mobile/lib/features/channels/compose_bar/helpers.dart index 9515373dda..50889c059a 100644 --- a/mobile/lib/features/channels/compose_bar/helpers.dart +++ b/mobile/lib/features/channels/compose_bar/helpers.dart @@ -203,6 +203,7 @@ Widget _composerAttachmentPanel({ required Future> Function() onPickAllPhotos, required Future Function(List photos) onChoosePhotos, required Future Function(List photos) onChooseAllPhotos, + required Future Function(Future Function()) preparePhotos, }) => _AttachmentSurfacePanel( key: ValueKey( surface == _AttachmentSurface.closed @@ -221,6 +222,7 @@ Widget _composerAttachmentPanel({ onPickAllPhotos: onPickAllPhotos, onChoosePhotos: onChoosePhotos, onChooseAllPhotos: onChooseAllPhotos, + preparePhotos: preparePhotos, ); const _pastedImageMimeTypes = [ diff --git a/mobile/lib/features/channels/compose_bar/ios_photo_picker.dart b/mobile/lib/features/channels/compose_bar/ios_photo_picker.dart index 460358615b..d4552fb7d4 100644 --- a/mobile/lib/features/channels/compose_bar/ios_photo_picker.dart +++ b/mobile/lib/features/channels/compose_bar/ios_photo_picker.dart @@ -10,6 +10,7 @@ class _IOSInlinePhotoPicker extends HookWidget { final Future> Function() onPickAllPhotos; final Future Function(List photos) onChoosePhotos; final Future Function(List photos) onChooseAllPhotos; + final Future Function(Future Function()) preparePhotos; final Widget fallback; const _IOSInlinePhotoPicker({ @@ -17,6 +18,7 @@ class _IOSInlinePhotoPicker extends HookWidget { required this.onPickAllPhotos, required this.onChoosePhotos, required this.onChooseAllPhotos, + required this.preparePhotos, required this.fallback, }); @@ -74,7 +76,7 @@ class _IOSInlinePhotoPicker extends HookWidget { !isPreparingSelection.value && !isProcessing.value; - Future submitSelection() async { + Future submitSelection() => preparePhotos(() async { if (!canSelect) return; isProcessing.value = true; try { @@ -91,7 +93,7 @@ class _IOSInlinePhotoPicker extends HookWidget { } finally { if (context.mounted) isProcessing.value = false; } - } + }); Future openAllPhotos() async { if (isPreparingSelection.value || isProcessing.value) return; diff --git a/mobile/lib/features/channels/compose_bar/layout.dart b/mobile/lib/features/channels/compose_bar/layout.dart index 9017bc4ce1..3a9a70cdae 100644 --- a/mobile/lib/features/channels/compose_bar/layout.dart +++ b/mobile/lib/features/channels/compose_bar/layout.dart @@ -29,6 +29,7 @@ class _ComposeBarLayout extends HookWidget { final bool canSend; final bool hasPendingUploads; final bool isSending; + final bool readOnly; const _ComposeBarLayout({ required this.surfaceKey, @@ -59,6 +60,7 @@ class _ComposeBarLayout extends HookWidget { required this.canSend, required this.hasPendingUploads, required this.isSending, + this.readOnly = false, }); @override @@ -331,6 +333,7 @@ class _ComposeBarLayout extends HookWidget { return TextField( controller: controller, focusNode: focusNode, + readOnly: readOnly, keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, contextMenuBuilder: contextMenuBuilder, diff --git a/mobile/lib/features/channels/compose_bar/photo_gallery_picker.dart b/mobile/lib/features/channels/compose_bar/photo_gallery_picker.dart index 7c1e3158b1..eaccb00b66 100644 --- a/mobile/lib/features/channels/compose_bar/photo_gallery_picker.dart +++ b/mobile/lib/features/channels/compose_bar/photo_gallery_picker.dart @@ -5,12 +5,14 @@ class _PhotoGalleryPicker extends StatelessWidget { final Future> Function() onPickAllPhotos; final Future Function(List photos) onChoosePhotos; final Future Function(List photos) onChooseAllPhotos; + final Future Function(Future Function()) preparePhotos; const _PhotoGalleryPicker({ required this.onBack, required this.onPickAllPhotos, required this.onChoosePhotos, required this.onChooseAllPhotos, + required this.preparePhotos, }); @override @@ -20,6 +22,7 @@ class _PhotoGalleryPicker extends StatelessWidget { onPickAllPhotos: onPickAllPhotos, onChoosePhotos: onChoosePhotos, onChooseAllPhotos: onChooseAllPhotos, + preparePhotos: preparePhotos, ); if (defaultTargetPlatform != TargetPlatform.iOS) return fallback; return _IOSInlinePhotoPicker( @@ -27,6 +30,7 @@ class _PhotoGalleryPicker extends StatelessWidget { onPickAllPhotos: onPickAllPhotos, onChoosePhotos: onChoosePhotos, onChooseAllPhotos: onChooseAllPhotos, + preparePhotos: preparePhotos, fallback: fallback, ); } @@ -37,12 +41,14 @@ class _RecentPhotoGalleryPicker extends HookConsumerWidget { final Future> Function() onPickAllPhotos; final Future Function(List photos) onChoosePhotos; final Future Function(List photos) onChooseAllPhotos; + final Future Function(Future Function()) preparePhotos; const _RecentPhotoGalleryPicker({ required this.onBack, required this.onPickAllPhotos, required this.onChoosePhotos, required this.onChooseAllPhotos, + required this.preparePhotos, }); @override @@ -68,7 +74,7 @@ class _RecentPhotoGalleryPicker extends HookConsumerWidget { ]; } - Future choosePhotos() async { + Future choosePhotos() => preparePhotos(() async { if (isResolving.value) return; isResolving.value = true; actionError.value = null; @@ -92,7 +98,7 @@ class _RecentPhotoGalleryPicker extends HookConsumerWidget { } finally { if (context.mounted) isResolving.value = false; } - } + }); final selectedCount = selection.value.length; final actionLabel = selectedCount == 0 diff --git a/mobile/lib/features/channels/me/me_assistant_list.dart b/mobile/lib/features/channels/me/me_assistant_list.dart index 16183e863f..7594e05771 100644 --- a/mobile/lib/features/channels/me/me_assistant_list.dart +++ b/mobile/lib/features/channels/me/me_assistant_list.dart @@ -23,11 +23,17 @@ class MeAssistantList extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final profiles = ref.watch(userCacheProvider); - return SizedBox( - height: (MediaQuery.sizeOf(context).height * 0.6).clamp(0.0, 400.0), + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.6, + ), child: choices.isEmpty - ? const Center(child: Text('No agents are available.')) + ? const Padding( + padding: EdgeInsets.all(Grid.gutter), + child: Text('No agents are available.'), + ) : ListView( + shrinkWrap: true, padding: const EdgeInsets.fromLTRB( Grid.gutter, 0, diff --git a/mobile/lib/features/channels/me/me_chat_assistant.dart b/mobile/lib/features/channels/me/me_chat_assistant.dart index 736b8f3c46..2cb68a3e34 100644 --- a/mobile/lib/features/channels/me/me_chat_assistant.dart +++ b/mobile/lib/features/channels/me/me_chat_assistant.dart @@ -229,6 +229,7 @@ useMeChatAssistant( nativeAction: IosNavigationAction( label: label, symbol: 'person.crop.circle', + sharesBackground: false, avatarIdentity: selected, avatarIsAgent: selected != null, imageUrl: profile?.avatarUrl, diff --git a/mobile/lib/features/channels/me/me_chat_draft.dart b/mobile/lib/features/channels/me/me_chat_draft.dart new file mode 100644 index 0000000000..aafc9024ef --- /dev/null +++ b/mobile/lib/features/channels/me/me_chat_draft.dart @@ -0,0 +1,256 @@ +part of 'me_page.dart'; + +/// A conversation draft: no channel is created until the first send. +class _MeChatDraft extends HookConsumerWidget { + const _MeChatDraft(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final sync = ref.watch(meSyncProvider); + final originalScope = useMemoized(() => (sync.community, sync.pubkey)); + final pending = useState(MeChatCreation.pending(sync)); + final channelId = useMemoized(() => pending.value?.id ?? const Uuid().v4()); + final manualAgent = useState(null); + final project = useState(pending.value?.project); + final created = useState(null); + final busy = useState(false); + final composerBusy = useState(false); + final error = useState(null); + final directory = ref.watch(meAssistantsProvider); + final bestie = ref.watch(defaultAgentProvider).value; + final choices = directory.value ?? []; + final selected = + pending.value?.agent ?? + manualAgent.value ?? + (choices.any((agent) => agent.pubkey == bestie) ? bestie : null); + final profile = ref.watch(userCacheProvider)[selected]; + final agent = choices + .where((agent) => agent.pubkey == selected) + .firstOrNull; + final name = + agent?.displayName ?? + profile?.label ?? + (selected == null ? 'Choose an agent' : 'Agent'); + final avatarInitial = name.isEmpty ? 'A' : name.characters.first; + final scopeChanged = originalScope != (sync.community, sync.pubkey); + final frozen = + pending.value != null || + busy.value || + composerBusy.value || + scopeChanged; + final workspace = useMeWorkspace( + context, + ref, + enabled: !scopeChanged, + selected: project.value, + locked: frozen, + onSelected: (value) { + if (!busy.value && pending.value == null && !sync.disposed) { + project.value = value; + } + }, + ); + if (created.value case final channel?) { + return ChannelDetailPage( + channel: channel, + personalChat: true, + initialAssistant: selected, + ); + } + + Future choose() async { + final picked = await showBuzzModalBottomSheet( + context: context, + title: 'Agent', + isScrollControlled: true, + showDragHandle: true, + builder: (_) => MeAssistantPickerSheet(selected: selected), + ); + if (context.mounted && picked != null && !sync.disposed) { + manualAgent.value = picked; + } + } + + Future send( + String content, + List mentions, { + List> mediaTags = const [], + }) async { + if (workspace.busy) { + throw Exception('Wait for the workspace to finish saving.'); + } + if (busy.value) throw Exception('Wait for this chat to finish sending.'); + if (scopeChanged || sync.disposed) { + throw Exception('Your account or community changed. Return to Solo.'); + } + final saved = pending.value; + final recipient = saved?.agent ?? selected; + if (recipient == null) { + throw Exception('Choose an agent in the chat header before sending.'); + } + if (saved == null && !choices.any((agent) => agent.pubkey == recipient)) { + throw Exception('Choose an available agent in the chat header.'); + } + if (utf8.encode(content).length > 8192 || + utf8.encode(jsonEncode(mediaTags)).length > 16384) { + throw Exception( + 'Message is too long. Keep your first message under 8 KB.', + ); + } + busy.value = true; + error.value = null; + try { + final result = await _createMeChat( + ref, + sync, + channelId, + saved?.name ?? startingMeChatTitle(content), + recipient, + saved?.project ?? project.value, + initialContent: saved?.initialMessage?.content ?? content, + initialMediaTags: mediaTags, + ); + if (context.mounted) { + manualAgent.value = recipient; + created.value = result; + } + } catch (failure) { + if (context.mounted) { + composerBusy.value = false; + pending.value = MeChatCreation.pending(sync); + error.value = failure.toString().replaceFirst('Bad state: ', ''); + } + // ComposeBar treats StateError as a community switch. Preserve the + // actual failure and its draft through its ordinary error path. + throw Exception(failure.toString().replaceFirst('Bad state: ', '')); + } finally { + if (context.mounted) busy.value = false; + } + } + + final label = selected == null ? 'Choose an agent' : 'Change agent: $name'; + return PopScope( + canPop: !busy.value && !composerBusy.value && !workspace.busy, + child: FrostedScaffold( + appBar: FrostedAppBar( + leading: BackButton( + onPressed: () => Navigator.of(context).maybePop(), + ), + nativeLeading: IosNavigationAction( + label: 'Back', + symbol: 'chevron.backward', + onPressed: () => Navigator.of(context).maybePop(), + ), + title: const Text('New chat'), + nativeTitle: 'New chat', + centerTitle: true, + nativeActions: [ + workspace.nativeAction, + IosNavigationAction( + label: label, + symbol: 'person.crop.circle', + sharesBackground: false, + avatarIdentity: selected, + avatarIsAgent: selected != null, + imageUrl: agent?.avatarUrl ?? profile?.avatarUrl, + avatarInitial: avatarInitial, + onPressed: frozen || workspace.busy ? null : choose, + ), + ], + actions: [ + workspace.action, + IconButton( + key: const ValueKey('new-chat-agent'), + tooltip: label, + onPressed: frozen || workspace.busy ? null : choose, + icon: AvatarImage( + imageUrl: agent?.avatarUrl ?? profile?.avatarUrl, + radius: 16, + isAgent: selected != null, + backgroundColor: context.controlSurface, + fallback: selected == null + ? const Icon(BuzzIcons.plus, size: 20) + : Text(avatarInitial), + ), + ), + ], + ), + body: Padding( + padding: EdgeInsets.only(top: frostedAppBarHeight(context)), + child: Column( + children: [ + if (directory.isLoading) const LinearProgressIndicator(), + Expanded( + child: Center( + child: Padding( + padding: const EdgeInsets.all(Grid.gutter), + child: Text( + scopeChanged + ? 'Your account or community changed. Return to Solo to start a chat.' + : pending.value?.initialMessage?.content ?? + 'What would you like to work on?', + textAlign: TextAlign.center, + style: context.textTheme.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ), + ), + if (error.value != null) + Padding( + padding: const EdgeInsets.all(Grid.gutter), + child: Semantics(liveRegion: true, child: Text(error.value!)), + ), + if (!scopeChanged && pending.value != null) + SafeArea( + child: Padding( + padding: const EdgeInsets.all(Grid.gutter), + child: FilledButton( + onPressed: busy.value + ? null + : () async { + try { + await send( + pending.value!.initialMessage!.content, + const [], + ); + } catch (_) { + /* The durable error is shown above. */ + } + }, + child: Text(busy.value ? 'Sending…' : 'Retry'), + ), + ), + ), + if (!scopeChanged && pending.value == null) + ComposeBar( + channelId: 'new-solo', + interactionLocked: workspace.busy, + hintText: 'Message $name', + draftMembers: [ + ChannelMember( + pubkey: sync.pubkey, + role: 'owner', + joinedAt: DateTime(2026), + ), + if (selected != null) + ChannelMember( + pubkey: selected, + role: 'bot', + joinedAt: DateTime(2026), + displayName: name, + ), + ], + onSendingChanged: (value) { + if (context.mounted) composerBusy.value = value; + }, + onSend: send, + ), + ], + ), + ), + ), + ); + } +} diff --git a/mobile/lib/features/channels/me/me_page.dart b/mobile/lib/features/channels/me/me_page.dart index 2ad9980e74..542c54eab8 100644 --- a/mobile/lib/features/channels/me/me_page.dart +++ b/mobile/lib/features/channels/me/me_page.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; @@ -19,8 +20,10 @@ import 'solo_working_dots.dart'; import 'me_unread_provider.dart'; import '../../../shared/widgets/avatar_image.dart'; import '../../../shared/me/me_groups.dart'; +import '../../../shared/me/default_agent.dart'; +import '../../../shared/me/me_chat_title.dart'; +import '../../../shared/crypto/event_signing.dart'; import '../../../shared/me/me_chat_creation.dart'; -import '../../../shared/me/me_project_creation.dart'; import '../../../shared/me/me_sync.dart'; import '../../../shared/relay/relay.dart'; import '../../../shared/me/me_recovery.dart'; @@ -32,6 +35,11 @@ import '../../../shared/widgets/frosted_scaffold.dart'; import '../../../shared/widgets/buzz_loading_indicator.dart'; import '../../../shared/widgets/modal_presentation.dart'; import '../channel.dart'; +import '../compose_bar.dart'; +import 'me_assistant_picker_sheet.dart'; +import 'new_me_project.dart'; +import 'me_workspace_picker.dart'; +import 'me_recovery_dialog.dart'; import '../channel_detail_page.dart'; import '../channel_management_provider.dart'; import '../channels_provider.dart'; @@ -39,8 +47,8 @@ import '../channels_provider.dart'; part 'me_page_helpers.dart'; part 'me_empty_state.dart'; part 'new_me_chat.dart'; +part 'me_chat_draft.dart'; part 'native_new_me_chat.dart'; -part 'new_me_project.dart'; /// Personal chats and projects shared with the desktop Me workspace. class MePage extends HookConsumerWidget { @@ -74,6 +82,7 @@ class MePage extends HookConsumerWidget { ); // Warm the directory while browsing Me, before the creation form opens. final assistants = ref.watch(meAssistantsProvider).value; + ref.watch(defaultAgentProvider); useEffect(() { if (assistants != null) { ref.read(userCacheProvider.notifier).preload([ @@ -96,7 +105,7 @@ class MePage extends HookConsumerWidget { await action(); } catch (error) { if (error is MeRecoveryConflict && context.mounted) { - await _offerMeRecovery(context, ref.read(meSyncProvider)); + await offerMeRecovery(context, ref.read(meSyncProvider)); } if (context.mounted) { ScaffoldMessenger.of(context).showFeedbackSnackBar( @@ -114,7 +123,7 @@ class MePage extends HookConsumerWidget { final VoidCallback? newProject = busy.value || !groups.hasValue ? null : () => perform(() async { - await _createMeProject(context, ref); + await createMeProject(context, ref); }); final VoidCallback? newChat = busy.value || !groups.hasValue ? null @@ -232,8 +241,8 @@ class MePage extends HookConsumerWidget { if (!visible.any( (c) => organization.assignments[c.id] == group['id'], )) - const ListTile( - title: Text('No chats in this project'), + const _MeSectionEmpty( + 'No chats in this workspace yet', ), ], ), @@ -252,7 +261,7 @@ class MePage extends HookConsumerWidget { if (!visible.any( (c) => !organization.assignments.containsKey(c.id), )) - const ListTile(title: Text('No chats yet')), + const _MeSectionEmpty('No chats yet'), ], ), ], @@ -315,8 +324,7 @@ class MePage extends HookConsumerWidget { nativeActions: [ IosNavigationAction( label: 'New project', - symbol: 'folder.badge.plus', - icon: BuzzIcons.folderPlus, + icon: BuzzIcons.workspace, onPressed: newProject, ), if (newChatAction == null) @@ -343,7 +351,7 @@ class MePage extends HookConsumerWidget { children: [ IconButton( tooltip: 'New project', - icon: const Icon(BuzzIcons.folderPlus, size: 20), + icon: const Icon(BuzzIcons.workspace, size: 20), onPressed: newProject, ), if (newChatAction == null) diff --git a/mobile/lib/features/channels/me/me_page_helpers.dart b/mobile/lib/features/channels/me/me_page_helpers.dart index 4344f953e0..a0ee92d285 100644 --- a/mobile/lib/features/channels/me/me_page_helpers.dart +++ b/mobile/lib/features/channels/me/me_page_helpers.dart @@ -15,77 +15,6 @@ class _MeRetry extends StatelessWidget { ); } -Future _name( - BuildContext context, - String title, { - String initialValue = '', -}) async { - if (defaultTargetPlatform == TargetPlatform.iOS) { - final theme = utilitySurfaceThemeData(Theme.of(context)); - try { - return await const MethodChannel( - 'buzz/profile_text_editor', - ).invokeMethod('presentProject', { - 'title': title, - 'initialValue': initialValue, - 'placeholder': 'Project name', - 'multiline': false, - 'brightness': theme.brightness.name, - 'pageBackgroundArgb': theme.colorScheme.surface.toARGB32(), - 'containerBackgroundArgb': theme.colorScheme.surfaceContainerHighest - .toARGB32(), - 'containerCornerRadius': Radii.container, - }); - } on MissingPluginException { - // Use the shared sheet when the native editor is unavailable. - } - } - if (!context.mounted) return null; - return showBuzzModalBottomSheet( - context: context, - title: title, - isScrollControlled: true, - requestFocus: true, - builder: (_) => _NewMeProject(initialValue: initialValue), - ); -} - -class _NewMeProject extends HookConsumerWidget { - final String initialValue; - const _NewMeProject({this.initialValue = ''}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final controller = useTextEditingController(text: initialValue); - useListenable(controller); - final name = controller.text.trim(); - return Padding( - padding: EdgeInsets.fromLTRB( - Grid.gutter, - Grid.md, - Grid.gutter, - MediaQuery.viewInsetsOf(context).bottom + Grid.gutter, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: controller, - autofocus: true, - maxLength: 120, - decoration: const InputDecoration(labelText: 'Project name'), - ), - const SizedBox(height: Grid.md), - FilledButton( - onPressed: name.isEmpty ? null : () => Navigator.pop(context, name), - child: const Text('Create project'), - ), - ], - ), - ); - } -} - class _MeChatRow extends ConsumerWidget { const _MeChatRow({ required this.channelId, @@ -149,31 +78,6 @@ class _MeChatRow extends ConsumerWidget { } } -Future _offerMeRecovery(BuildContext context, MeSync sync) async { - final pending = sync.prefs?.getString(sync.pendingKey); - if (pending == null) return; - final discard = await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Conflicting Solo changes'), - content: const Text( - 'Desktop and this phone changed the same project or chat. Keep the pending phone change to retry later, or discard it and use the current desktop organization. Your chat messages will be kept.', - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context, false), - child: const Text('Keep pending'), - ), - TextButton( - onPressed: () => Navigator.pop(context, true), - child: const Text('Discard phone change'), - ), - ], - ), - ); - if (discard == true) await sync.discardPending(pending); -} - // Reconnects replace the transport service while an editor may still be open. // Retain the reviewed account/community boundary but use its current connection. MeSync _currentMeSync(WidgetRef ref, MeSync reviewed) { @@ -184,3 +88,25 @@ MeSync _currentMeSync(WidgetRef ref, MeSync reviewed) { } return current; } + +class _MeSectionEmpty extends StatelessWidget { + const _MeSectionEmpty(this.label); + final String label; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric( + horizontal: Grid.xxs, + vertical: Grid.half, + ), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + label, + style: contentListBodyTextStyle.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ); +} diff --git a/mobile/lib/features/channels/me/me_recovery_dialog.dart b/mobile/lib/features/channels/me/me_recovery_dialog.dart new file mode 100644 index 0000000000..925ccd95c5 --- /dev/null +++ b/mobile/lib/features/channels/me/me_recovery_dialog.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; + +import '../../../shared/me/me_sync.dart'; + +/// Offers an explicit choice for conflicting pending Solo organization edits. +Future offerMeRecovery(BuildContext context, MeSync sync) async { + final pending = sync.prefs?.getString(sync.pendingKey); + if (pending == null) return; + final discard = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Conflicting Solo changes'), + content: const Text( + 'Desktop and this phone changed the same project or chat. Keep the pending phone change to retry later, or discard it and use the current desktop organization. Your chat messages will be kept.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Keep pending'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Discard phone change'), + ), + ], + ), + ); + if (discard == true) await sync.discardPending(pending); +} diff --git a/mobile/lib/features/channels/me/me_workspace_picker.dart b/mobile/lib/features/channels/me/me_workspace_picker.dart new file mode 100644 index 0000000000..c63ceff028 --- /dev/null +++ b/mobile/lib/features/channels/me/me_workspace_picker.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../../shared/me/me_sync.dart'; +import '../../../shared/me/me_recovery.dart'; +import 'me_recovery_dialog.dart'; +import '../../../shared/theme/buzz_icons.dart'; +import '../../../shared/widgets/feedback_snackbar.dart'; +import '../../../shared/widgets/frosted_app_bar.dart'; + +/// The workspace control shared by draft and existing Solo conversations. +({Widget action, IosNavigationAction nativeAction, bool busy}) useMeWorkspace( + BuildContext context, + WidgetRef ref, { + required bool enabled, + String? channelId, + String? selected, + ValueChanged? onSelected, + bool locked = false, +}) { + final busy = useState(false); + final sync = enabled ? ref.watch(meSyncProvider) : null; + final groupState = enabled ? ref.watch(meGroupsProvider) : null; + final groups = groupState?.value; + final current = channelId == null ? selected : groups?.assignments[channelId]; + final name = + groups?.groups + .where((group) => group['id'] == current) + .firstOrNull?['name'] + as String?; + final label = current == null + ? 'Choose workspace' + : 'Workspace: ${name ?? "Unavailable workspace"}'; + Future choose(String picked) async { + if (sync == null || busy.value) return; + if (picked == '+reload') { + ref.invalidate(meGroupsProvider); + return; + } + busy.value = true; + try { + sync.check(); + final project = picked.isEmpty ? null : picked; + if (channelId == null) { + onSelected?.call(project); + } else { + await sync.update( + (groups) => groups.place( + channelId, + group: project, + clearGroup: project == null, + ), + ); + } + } catch (error) { + if (context.mounted && error is MeRecoveryConflict) { + await offerMeRecovery(context, sync); + } else if (context.mounted) { + ScaffoldMessenger.of(context).showFeedbackSnackBar( + SnackBar( + content: Text(error.toString().replaceFirst('Bad state: ', '')), + ), + kind: ToastKind.error, + ); + } + } finally { + if (context.mounted) busy.value = false; + } + } + + final available = + enabled && + !locked && + !busy.value && + (groups != null || groupState?.hasError == true); + return ( + busy: busy.value, + action: PopupMenuButton( + key: const ValueKey('me-workspace-button'), + tooltip: label, + enabled: available, + icon: const Icon(BuzzIcons.workspace), + onSelected: choose, + itemBuilder: (_) => [ + CheckedPopupMenuItem( + value: '', + checked: current == null, + child: const Text('No Workspace'), + ), + for (final group in groups?.groups ?? >[]) + CheckedPopupMenuItem( + value: group['id'] as String, + checked: current == group['id'], + child: Text(group['name'] as String), + ), + if (groupState?.hasError == true) + const PopupMenuItem( + value: '+reload', + child: Text('Reload workspaces'), + ), + ], + ), + nativeAction: IosNavigationAction( + label: label, + icon: BuzzIcons.workspace, + sharesBackground: false, + children: !available + ? const [] + : [ + IosNavigationAction( + label: 'No Workspace', + selected: current == null, + onPressed: () => choose(''), + ), + for (final group in groups?.groups ?? >[]) + IosNavigationAction( + label: group['name'] as String, + selected: current == group['id'], + onPressed: () => choose(group['id'] as String), + ), + if (groupState?.hasError == true) + IosNavigationAction( + label: 'Reload workspaces', + onPressed: () => choose('+reload'), + ), + ], + ), + ); +} diff --git a/mobile/lib/features/channels/me/native_new_me_chat.dart b/mobile/lib/features/channels/me/native_new_me_chat.dart index daf72977cd..1ea35820dc 100644 --- a/mobile/lib/features/channels/me/native_new_me_chat.dart +++ b/mobile/lib/features/channels/me/native_new_me_chat.dart @@ -37,11 +37,19 @@ Future<(Channel, String)?> _showNewMeChat( } } if (!context.mounted) return null; + final pendingDraft = MeChatCreation.pending(ref.read(meSyncProvider)); + if (pendingDraft == null || pendingDraft.initialMessage != null) { + await Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const _MeChatDraft())); + return null; + } if (defaultTargetPlatform == TargetPlatform.iOS) { final sync = ref.read(meSyncProvider); final pending = MeChatCreation.pending(sync); final id = pending?.id ?? const Uuid().v4(); - String name = pending?.name ?? ''; + final messageMode = pending == null || pending.initialMessage != null; + String name = pending?.initialMessage?.content ?? pending?.name ?? ''; String? assistant = pending?.agent; String? project = pending?.project; String? error = pending == null ? null : 'Resume your unfinished chat.'; @@ -59,6 +67,7 @@ Future<(Channel, String)?> _showNewMeChat( if (!context.mounted) return null; final theme = utilitySurfaceThemeData(Theme.of(context)); Map? draft; + ProviderSubscription>? bestieSubscription; try { final presentation = const MethodChannel('buzz/profile_text_editor') .invokeMethod>('presentChat', { @@ -66,8 +75,9 @@ Future<(Channel, String)?> _showNewMeChat( 'presentationId': presentationId, 'assistantsLoading': directory == null, 'initialValue': name, - 'placeholder': 'Chat name', - 'multiline': false, + 'placeholder': messageMode ? 'Message' : 'Chat name', + 'multiline': messageMode, + 'messageMode': messageMode, 'brightness': theme.brightness.name, 'pageBackgroundArgb': theme.colorScheme.surface.toARGB32(), 'containerBackgroundArgb': theme @@ -75,7 +85,8 @@ Future<(Channel, String)?> _showNewMeChat( .surfaceContainerHighest .toARGB32(), 'containerCornerRadius': Radii.container, - 'selectedAssistant': assistant, + 'selectedAssistant': + assistant ?? _availableBestie(ref, directory ?? []), if (retry && assistant != null) 'savedAssistant': { 'id': assistant, @@ -110,6 +121,7 @@ Future<(Channel, String)?> _showNewMeChat( ).invokeMethod('updateChatAssistants', { 'presentationId': presentationId, 'assistants': _nativeMeAssistants(agents), + 'defaultAssistant': _availableBestie(ref, agents), }); } catch (_) { if (!active || !context.mounted || sync.disposed) return; @@ -131,11 +143,15 @@ Future<(Channel, String)?> _showNewMeChat( } loadAssistants(); + bestieSubscription = ref.listenManual(defaultAgentProvider, (_, next) { + if (next.hasValue) loadAssistants(); + }); draft = await presentation; } on MissingPluginException { break; } finally { active = false; + bestieSubscription?.close(); } if (draft == null || !context.mounted) return null; name = (draft['name'] as String? ?? '').trim(); @@ -149,14 +165,15 @@ Future<(Channel, String)?> _showNewMeChat( ref, sync, id, - name, + messageMode ? startingMeChatTitle(name) : name, assistant, project, + initialContent: messageMode ? name : null, ); return (created, assistant); } catch (failure) { if (failure is MeRecoveryConflict && context.mounted) { - await _offerMeRecovery(context, sync); + await offerMeRecovery(context, sync); } error = '${failure.toString().replaceFirst('Bad state: ', '')}\nRetry continues this same chat.'; @@ -179,10 +196,34 @@ Future _createMeChat( String channelId, String name, String assistant, - String? project, -) async { + String? project, { + String? initialContent, + List> initialMediaTags = const [], +}) async { sync = _currentMeSync(ref, sync); - final intent = MeChatCreation(channelId, name, assistant, project: project); + final pending = MeChatCreation.pending(sync); + final initialMessage = initialContent == null + ? null + : pending?.initialMessage ?? + NostrEvent.fromJson( + signNostrEvent( + kind: EventKind.streamMessage, + content: initialContent, + tags: [ + ['h', channelId], + ['p', assistant], + ...initialMediaTags, + ], + secretKey: sync.privateHex, + ).toMap(), + ); + final intent = MeChatCreation( + channelId, + name, + assistant, + project: project, + initialMessage: initialMessage, + ); await intent.save(sync); final actions = ref.read(channelActionsProvider); final preflight = await Future.wait([ @@ -242,3 +283,8 @@ List> _nativeMeAssistants( 'avatarUrl': agent.avatarUrl ?? '', }, ]; + +String? _availableBestie(WidgetRef ref, List choices) { + final bestie = ref.read(defaultAgentProvider).value; + return choices.any((agent) => agent.pubkey == bestie) ? bestie : null; +} diff --git a/mobile/lib/features/channels/me/new_me_chat.dart b/mobile/lib/features/channels/me/new_me_chat.dart index d57657f05a..3afb454f3d 100644 --- a/mobile/lib/features/channels/me/new_me_chat.dart +++ b/mobile/lib/features/channels/me/new_me_chat.dart @@ -6,8 +6,12 @@ class _NewMeChat extends HookConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final sync = ref.watch(meSyncProvider); final pending = useMemoized(() => MeChatCreation.pending(sync)); - final name = useTextEditingController(text: pending?.name ?? ''); + final messageMode = pending == null || pending.initialMessage != null; + final name = useTextEditingController( + text: pending?.initialMessage?.content ?? pending?.name ?? '', + ); final selected = useState(pending?.agent); + final manuallySelected = useState(false); final project = useState(pending?.project); final groups = ref.watch(meGroupsProvider); final channelId = useMemoized(() => pending?.id ?? const Uuid().v4()); @@ -28,6 +32,13 @@ class _NewMeChat extends HookConsumerWidget { ); } final choices = directory.asData?.value ?? []; + final bestie = ref.watch(defaultAgentProvider).value; + useEffect(() { + if (!manuallySelected.value && frozenAgent.value == null) { + selected.value = choices.any((a) => a.pubkey == bestie) ? bestie : null; + } + return null; + }, [bestie, choices]); final profile = ref.watch(userCacheProvider)[selected.value]; final chosen = choices.where((agent) => agent.pubkey == selected.value).firstOrNull ?? @@ -54,8 +65,13 @@ class _NewMeChat extends HookConsumerWidget { autofocus: true, textCapitalization: TextCapitalization.sentences, enabled: !busy.value && frozenName.value == null, - maxLength: 120, - decoration: const InputDecoration(hintText: 'Chat name'), + maxLength: messageMode ? null : 120, + minLines: messageMode ? 3 : 1, + maxLines: messageMode ? 6 : 1, + decoration: InputDecoration( + labelText: messageMode ? 'Message' : 'Chat name', + hintText: messageMode ? 'What would you like to work on?' : null, + ), onChanged: (_) => error.value = null, ), const SizedBox(height: Grid.xs), @@ -120,6 +136,7 @@ class _NewMeChat extends HookConsumerWidget { ), ); if (context.mounted && picked != null) { + manuallySelected.value = true; selected.value = picked; } }, @@ -150,13 +167,22 @@ class _NewMeChat extends HookConsumerWidget { ? null : () async { if (name.text.trim().isEmpty || selected.value == null) { - error.value = 'Enter a name and choose an agent.'; + error.value = messageMode + ? 'Enter a message and choose an agent.' + : 'Enter a name and choose an agent.'; + return; + } + if (messageMode && + utf8.encode(name.text.trim()).length > 8192) { + error.value = 'Message is too long. Keep it under 8 KB.'; return; } busy.value = true; error.value = null; try { - frozenName.value ??= name.text.trim(); + frozenName.value ??= messageMode + ? startingMeChatTitle(name.text) + : name.text.trim(); frozenAgent.value ??= selected.value; final created = await _createMeChat( ref, @@ -165,6 +191,7 @@ class _NewMeChat extends HookConsumerWidget { frozenName.value!, frozenAgent.value!, project.value, + initialContent: messageMode ? name.text.trim() : null, ); if (context.mounted) { Navigator.of( @@ -173,7 +200,7 @@ class _NewMeChat extends HookConsumerWidget { } } catch (e) { if (e is MeRecoveryConflict && context.mounted) { - await _offerMeRecovery(context, sync); + await offerMeRecovery(context, sync); } if (context.mounted) { error.value = @@ -188,6 +215,8 @@ class _NewMeChat extends HookConsumerWidget { ? 'Creating chat…' : frozenName.value != null ? 'Retry' + : messageMode + ? 'Send' : 'Create chat', ), ), diff --git a/mobile/lib/features/channels/me/new_me_project.dart b/mobile/lib/features/channels/me/new_me_project.dart index 6e8e3b946e..65c433478c 100644 --- a/mobile/lib/features/channels/me/new_me_project.dart +++ b/mobile/lib/features/channels/me/new_me_project.dart @@ -1,6 +1,23 @@ -part of 'me_page.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:uuid/uuid.dart'; +import '../../../shared/me/me_sync.dart'; +import '../../../shared/me/me_project_creation.dart'; +import '../../../shared/me/me_recovery.dart'; +import '../../../shared/theme/theme.dart'; +import '../../../shared/widgets/modal_presentation.dart'; -Future _createMeProject(BuildContext context, WidgetRef ref) async { +/// Creates or resumes a workspace and returns its stable ID. +Future createMeProject( + BuildContext context, + WidgetRef ref, { + bool workspace = false, + String? channelId, +}) async { + final noun = workspace ? 'workspace' : 'project'; final sync = ref.read(meSyncProvider); var intent = MeProjectCreation.pending(sync); if (intent != null) { @@ -10,7 +27,7 @@ Future _createMeProject(BuildContext context, WidgetRef ref) async { builder: (context) => AlertDialog( title: const Text('Unfinished project'), content: Text( - 'Resume “${reviewed.name}”, or discard its setup to start another project. Any project already sent or awaiting confirmation is kept.', + 'Resume “${reviewed.name}”, or discard its setup to start another project. Resuming also finishes the original chat placement, if any. Any project already sent or awaiting confirmation is kept.', ), actions: [ TextButton( @@ -28,22 +45,27 @@ Future _createMeProject(BuildContext context, WidgetRef ref) async { ], ), ); - if (resume == null || !context.mounted) return; + if (resume == null || !context.mounted) return null; if (!resume) { await reviewed.discard(sync); intent = null; } } - if (!context.mounted) return; + if (!context.mounted) return null; if (intent == null) { - final name = await _name(context, 'New project'); - if (name == null) return; - intent = MeProjectCreation(const Uuid().v4(), name); + final name = await _name(context, 'New $noun', noun: noun); + if (name == null) return null; + intent = MeProjectCreation(const Uuid().v4(), name, channelId: channelId); } while (context.mounted) { try { - await intent!.complete(_currentMeSync(ref, sync)); - return; + final current = ref.read(meSyncProvider); + if (current.community != sync.community || + current.pubkey != sync.pubkey) { + throw StateError('Your account or community changed. Open Solo again.'); + } + await intent!.complete(current); + return intent.channelId == channelId ? intent.id : null; } catch (error) { if (error is MeRecoveryConflict) rethrow; // A failed preferences write can still update its optimistic cache. @@ -80,14 +102,91 @@ Future _createMeProject(BuildContext context, WidgetRef ref) async { ], ), ); - if (retry != true || !context.mounted) return; + if (retry != true || !context.mounted) return null; final name = await _name( context, - 'New project', + 'New $noun', + noun: noun, initialValue: intent!.name, ); - if (name == null) return; - intent = MeProjectCreation(intent.id, name); + if (name == null) return null; + intent = MeProjectCreation(intent.id, name, channelId: intent.channelId); } } + return null; +} + +Future _name( + BuildContext context, + String title, { + String initialValue = '', + String noun = 'project', +}) async { + if (defaultTargetPlatform == TargetPlatform.iOS) { + final theme = utilitySurfaceThemeData(Theme.of(context)); + try { + return await const MethodChannel( + 'buzz/profile_text_editor', + ).invokeMethod('presentProject', { + 'title': title, + 'initialValue': initialValue, + 'placeholder': '${noun[0].toUpperCase()}${noun.substring(1)} name', + 'multiline': false, + 'brightness': theme.brightness.name, + 'pageBackgroundArgb': theme.colorScheme.surface.toARGB32(), + 'containerBackgroundArgb': theme.colorScheme.surfaceContainerHighest + .toARGB32(), + 'containerCornerRadius': Radii.container, + }); + } on MissingPluginException { + // Use the shared sheet when the native editor is unavailable. + } + } + if (!context.mounted) return null; + return showBuzzModalBottomSheet( + context: context, + title: title, + isScrollControlled: true, + requestFocus: true, + builder: (_) => _NewMeProject(initialValue: initialValue, noun: noun), + ); +} + +class _NewMeProject extends HookConsumerWidget { + final String initialValue; + final String noun; + const _NewMeProject({this.initialValue = '', this.noun = 'project'}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final controller = useTextEditingController(text: initialValue); + useListenable(controller); + final name = controller.text.trim(); + return Padding( + padding: EdgeInsets.fromLTRB( + Grid.gutter, + Grid.md, + Grid.gutter, + MediaQuery.viewInsetsOf(context).bottom + Grid.gutter, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: controller, + autofocus: true, + maxLength: 120, + decoration: InputDecoration( + labelText: '${noun[0].toUpperCase()}${noun.substring(1)} name', + ), + ), + const SizedBox(height: Grid.md), + FilledButton( + onPressed: name.isEmpty ? null : () => Navigator.pop(context, name), + child: Text('Create $noun'), + ), + ], + ), + ); + } } diff --git a/mobile/lib/features/home/home_page.dart b/mobile/lib/features/home/home_page.dart index d98efc3781..b3b3261800 100644 --- a/mobile/lib/features/home/home_page.dart +++ b/mobile/lib/features/home/home_page.dart @@ -201,7 +201,7 @@ class HomePage extends HookConsumerWidget { ), ( label: 'New workspace', - symbol: 'folder.badge.plus', + symbol: 'workspace', onPressed: newWorkspace.value, ), ( diff --git a/mobile/lib/features/home/messages_navigation_bar.dart b/mobile/lib/features/home/messages_navigation_bar.dart index 53ce5aafd4..a90f229b3d 100644 --- a/mobile/lib/features/home/messages_navigation_bar.dart +++ b/mobile/lib/features/home/messages_navigation_bar.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; import '../../shared/theme/theme.dart'; import '../../shared/theme/buzz_icons.dart'; @@ -11,7 +12,7 @@ import '../../shared/widgets/android_expanding_menu_button.dart'; import '../../shared/widgets/ios_message_create_button.dart'; /// Separate glass shortcuts for search and creation. -class MessagesNavigationBar extends StatelessWidget { +class MessagesNavigationBar extends HookWidget { const MessagesNavigationBar({ super.key, required this.onSearch, @@ -24,38 +25,129 @@ class MessagesNavigationBar extends StatelessWidget { creationActions; @override - Widget build(BuildContext context) => Row( - mainAxisSize: MainAxisSize.min, - children: [ - NavigationButtonSurface( - child: SizedBox.square( - dimension: 56, - child: IconButton( - tooltip: 'Search', - onPressed: () { - unawaited(HapticFeedback.lightImpact()); - onSearch(); - }, - color: context.colors.onSurface, - icon: const Icon(BuzzIcons.search300, size: 24), - ), + Widget build(BuildContext context) { + final menuOpen = useState(false); + if (defaultTargetPlatform == TargetPlatform.iOS) { + return SizedBox( + width: 256, + height: 56, + child: Stack( + children: [ + IosMessageCreateButton( + mergingNavigation: true, + onMenuVisibilityChanged: (visible) => menuOpen.value = visible, + actions: creationActions, + dividerBefore: const {2}, + sectionTitles: const {0: 'Solo', 2: 'Team'}, + label: 'New', + showIconWithLabel: true, + accessibilityLabel: 'New', + width: 256, + height: 56, + plain: false, + ), + Positioned( + left: 0, + width: 72, + top: 0, + bottom: 0, + child: ClipRect( + child: Align( + alignment: Alignment.centerLeft, + child: _MenuNudge( + offset: menuOpen.value ? 100 : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + child: _search(context), + ), + ), + ), + ), + Positioned( + right: 0, + width: 72, + top: 0, + bottom: 0, + child: ClipRect( + child: Align( + alignment: Alignment.centerRight, + child: _MenuNudge( + offset: menuOpen.value ? -100 : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + child: NavigationGlassGroup(child: agent), + ), + ), + ), + ), + ], ), + ); + } + return Builder( + builder: (controlsContext) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + NavigationButtonSurface(child: _search(context)), + const SizedBox(width: Grid.xs), + AndroidExpandingMenuButton( + expansionBoundsContext: controlsContext, + actions: creationActions, + dividerBefore: const {2}, + sectionTitles: const {0: 'Solo', 2: 'Team'}, + ), + const SizedBox(width: Grid.xs), + agent, + ], ), - const SizedBox(width: Grid.xs), - if (defaultTargetPlatform == TargetPlatform.iOS) - IosMessageCreateButton( - actions: creationActions, - label: 'New', - showIconWithLabel: true, - accessibilityLabel: 'New', - width: 112, - height: 56, - plain: false, - ) - else - AndroidExpandingMenuButton(actions: creationActions), - const SizedBox(width: Grid.xs), - agent, - ], + ); + } + + Widget _search(BuildContext context) => SizedBox.square( + dimension: 56, + child: IconButton( + tooltip: 'Search', + onPressed: () { + unawaited(HapticFeedback.lightImpact()); + onSearch(); + }, + color: context.colors.onSurface, + icon: const Icon(BuzzIcons.search300, size: 24), + ), ); } + +class _MenuNudge extends StatelessWidget { + const _MenuNudge({ + required this.offset, + required this.menuOpen, + required this.alignment, + required this.child, + }); + final double offset; + final bool menuOpen; + final Alignment alignment; + final Widget child; + + @override + Widget build(BuildContext context) { + final duration = MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 180); + final scale = menuOpen ? .9 : 1.0; + return IgnorePointer( + ignoring: menuOpen, + child: ExcludeSemantics( + excluding: menuOpen, + child: AnimatedContainer( + duration: duration, + curve: Curves.easeOutCubic, + transformAlignment: alignment, + transform: Matrix4.translationValues(offset, 0, 0) + ..scaleByDouble(scale, scale, 1, 1), + child: child, + ), + ), + ); + } +} diff --git a/mobile/lib/shared/me/me_chat_creation.dart b/mobile/lib/shared/me/me_chat_creation.dart index f366fb0df5..58c001ead3 100644 --- a/mobile/lib/shared/me/me_chat_creation.dart +++ b/mobile/lib/shared/me/me_chat_creation.dart @@ -1,6 +1,8 @@ import 'dart:convert'; import '../crypto/nip44.dart'; +import '../crypto/event_signing.dart'; +import '../relay/nostr_models.dart'; import 'me_sync.dart'; import 'me_journal.dart'; @@ -9,7 +11,7 @@ class MeChatCreation { /// Stable channel UUID, reused for every retry. final String id; - /// User-supplied name frozen before the first relay mutation. + /// Initial name frozen before the first relay mutation. final String name; /// Selected agent public key. @@ -18,8 +20,17 @@ class MeChatCreation { /// Optional Solo project, frozen with the rest of the creation intent. final String? project; + /// Signed first message, reused verbatim after interrupted delivery. + final NostrEvent? initialMessage; + /// Create a new intent; persistence happens before [complete] performs writes. - const MeChatCreation(this.id, this.name, this.agent, {this.project}); + const MeChatCreation( + this.id, + this.name, + this.agent, { + this.project, + this.initialMessage, + }); /// Account and community boundary for durable creation storage. static String storageKey(MeSync sync) => @@ -36,18 +47,28 @@ class MeChatCreation { value['name'] as String, value['agent'] as String, project: value['project'] as String?, + initialMessage: value['initialMessage'] == null + ? null + : NostrEvent.fromJson( + value['initialMessage'] as Map, + ), ); } /// Persist before any relay mutation. Do not replace another pending intent. - Future save(MeSync sync) async { + Future save(MeSync sync) => _save(sync); + + Future _save(MeSync sync, {String? replacingMessageId}) async { if (sync.disposed) throw StateError('Your community changed. Try again.'); final previous = pending(sync); if (previous != null && (previous.id != id || previous.name != name || previous.agent != agent || - previous.project != project)) { + previous.project != project || + (previous.initialMessage?.id != initialMessage?.id && + (replacingMessageId == null || + previous.initialMessage?.id != replacingMessageId)))) { throw StateError('Resume the pending chat before starting another.'); } // A matching cached value does not prove a previous disk write succeeded. @@ -61,6 +82,8 @@ class MeChatCreation { 'name': name, 'agent': agent, 'project': project, + if (initialMessage != null) + 'initialMessage': initialMessage!.toJson(), }), ), )) { @@ -77,7 +100,8 @@ class MeChatCreation { if (current?.id != id || current?.name != name || current?.agent != agent || - current?.project != project) { + current?.project != project || + current?.initialMessage?.id != initialMessage?.id) { throw StateError('The unfinished chat changed. Review it again.'); } await clearMeJournal( @@ -103,7 +127,7 @@ class MeChatCreation { required Future Function() place, }) async { await save(sync); - final record = sync.prefs!.getString(storageKey(sync))!; + var record = sync.prefs!.getString(storageKey(sync))!; sync.check(); final existing = await findChannel(); sync.check(); @@ -121,6 +145,10 @@ class MeChatCreation { await place(); } sync.check(); + if (initialMessage != null) { + record = await _deliverInitialMessage(sync, record); + sync.check(); + } await clearMeJournal( sync.prefs!, storageKey(sync), @@ -129,4 +157,55 @@ class MeChatCreation { ); return result; } + + // Relay ingestion rejects events older than 15 minutes, even duplicates. + // Confirm acceptance before replacing an expired identity; a lost OK must + // never turn one first message into two messages. + Future _deliverInitialMessage(MeSync sync, String record) async { + var message = initialMessage!; + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + if ((message.createdAt - now).abs() >= 14 * 60) { + final existing = await sync.session.fetchHistory( + NostrFilter( + kinds: const [9], + authors: [sync.pubkey], + ids: [message.id], + tags: { + '#h': [id], + }, + limit: 1, + ), + ); + sync.check(); + if (existing.any( + (event) => + event.id == message.id && + event.pubkey == sync.pubkey && + event.kind == 9 && + event.getTagValue('h') == id, + )) { + return record; + } + message = NostrEvent.fromJson( + signNostrEvent( + kind: message.kind, + content: message.content, + tags: message.tags, + secretKey: sync.privateHex, + ).toMap(), + ); + await MeChatCreation( + id, + name, + agent, + project: project, + initialMessage: message, + )._save(sync, replacingMessageId: initialMessage!.id); + sync.check(); + record = sync.prefs!.getString(storageKey(sync))!; + } + await sync.session.publish(message); + sync.check(); + return record; + } } diff --git a/mobile/lib/shared/me/me_chat_title.dart b/mobile/lib/shared/me/me_chat_title.dart new file mode 100644 index 0000000000..4c5244e935 --- /dev/null +++ b/mobile/lib/shared/me/me_chat_title.dart @@ -0,0 +1,13 @@ +/// Desktop-compatible starting title for a plain-text Solo message. +String startingMeChatTitle(String message) { + var body = message.trim(); + // Source links are context rather than a useful chat title. + while (body.toLowerCase().startsWith('buzz://')) { + final end = body.indexOf(RegExp(r'\s')); + body = end < 0 ? '' : body.substring(end).trimLeft(); + } + final title = String.fromCharCodes( + body.replaceAll(RegExp(r'\s+'), ' ').runes.take(80), + ).trim().replaceFirst(RegExp(r'^[#\s]+'), '').trim(); + return title.isEmpty ? 'Chat' : title; +} diff --git a/mobile/lib/shared/me/me_groups.dart b/mobile/lib/shared/me/me_groups.dart index 117b4dc4f1..67e0751ea4 100644 --- a/mobile/lib/shared/me/me_groups.dart +++ b/mobile/lib/shared/me/me_groups.dart @@ -88,13 +88,17 @@ class MeGroups { return result; } - MeGroups place(String channel, {String? group}) { + MeGroups place(String channel, {String? group, bool clearGroup = false}) { if (group != null && !groups.any((g) => g['id'] == group)) { throw StateError('This project changed. Refresh and try again.'); } return MeGroups( groups: groups, - assignments: {...assignments, channel: ?group}, + assignments: { + for (final entry in assignments.entries) + if (!clearGroup || entry.key != channel) entry.key: entry.value, + channel: ?group, + }, channels: [...channels, if (!channels.contains(channel)) channel], ); } diff --git a/mobile/lib/shared/me/me_project_creation.dart b/mobile/lib/shared/me/me_project_creation.dart index 2503e3366c..9a34215cb4 100644 --- a/mobile/lib/shared/me/me_project_creation.dart +++ b/mobile/lib/shared/me/me_project_creation.dart @@ -14,7 +14,10 @@ class MeProjectCreation { final String name; /// Build an intent; [complete] persists it before syncing. - const MeProjectCreation(this.id, this.name); + const MeProjectCreation(this.id, this.name, {this.channelId}); + + /// Existing Solo chat to place in this workspace in the same synced write. + final String? channelId; /// Isolate private drafts by both account and community. static String storageKey(MeSync sync) => @@ -26,7 +29,11 @@ class MeProjectCreation { if (saved == null) return null; final value = jsonDecode(nip44Decrypt(sync.key, saved)) as Map; - return MeProjectCreation(value['id'] as String, value['name'] as String); + return MeProjectCreation( + value['id'] as String, + value['name'] as String, + channelId: value['channelId'] as String?, + ); } void _checkScope(MeSync sync) { @@ -39,7 +46,10 @@ class MeProjectCreation { Future save(MeSync sync) async { _checkScope(sync); final previous = pending(sync); - if (previous != null && (previous.id != id || previous.name != name)) { + if (previous != null && + (previous.id != id || + previous.name != name || + previous.channelId != channelId)) { throw StateError( 'Review your unfinished project before starting another.', ); @@ -47,7 +57,10 @@ class MeProjectCreation { if (sync.prefs == null || !await sync.prefs!.setString( storageKey(sync), - nip44Encrypt(sync.key, jsonEncode({'id': id, 'name': name})), + nip44Encrypt( + sync.key, + jsonEncode({'id': id, 'name': name, 'channelId': ?channelId}), + ), )) { throw StateError('Couldn’t save this project on your phone. Try again.'); } @@ -58,7 +71,9 @@ class MeProjectCreation { Future discard(MeSync sync) async { _checkScope(sync); final current = pending(sync); - if (current?.id != id || current?.name != name) { + if (current?.id != id || + current?.name != name || + current?.channelId != channelId) { throw StateError('The unfinished project changed. Review it again.'); } await clearMeJournal( @@ -74,11 +89,14 @@ class MeProjectCreation { await save(sync); final record = sync.prefs!.getString(storageKey(sync))!; final head = await sync.head(); + final confirmed = head == null ? null : sync.decode(head); final exists = - head != null && sync.decode(head).groups.any((g) => g['id'] == id); + confirmed != null && + confirmed.groups.any((g) => g['id'] == id) && + (channelId == null || confirmed.assignments[channelId] == id); if (!exists || sync.prefs?.getString(sync.pendingKey) != null) { - await sync.update( - (current) => current.groups.any((g) => g['id'] == id) + await sync.update((current) { + final groups = current.groups.any((g) => g['id'] == id) ? current : MeGroups( groups: [ @@ -87,8 +105,9 @@ class MeProjectCreation { ], assignments: current.assignments, channels: current.channels, - ), - ); + ); + return channelId == null ? groups : groups.place(channelId!, group: id); + }); } await clearMeJournal( sync.prefs!, diff --git a/mobile/lib/shared/theme/buzz_icons.dart b/mobile/lib/shared/theme/buzz_icons.dart index c631b39527..485c6aeff6 100644 --- a/mobile/lib/shared/theme/buzz_icons.dart +++ b/mobile/lib/shared/theme/buzz_icons.dart @@ -157,6 +157,9 @@ abstract final class BuzzIcons { /// Tabler `flag`. static const flag = IconData(0xeaa6, fontFamily: 'BuzzTabler'); + /// Tabler `cube-3d-sphere`, matching the desktop workspace control. + static const workspace = IconData(0xecd7, fontFamily: 'BuzzTabler'); + /// Tabler `folder`. static const folder = IconData(0xeaad, fontFamily: 'BuzzTabler'); diff --git a/mobile/lib/shared/widgets/android_expanding_menu_button.dart b/mobile/lib/shared/widgets/android_expanding_menu_button.dart index 89738f3b56..a16618796d 100644 --- a/mobile/lib/shared/widgets/android_expanding_menu_button.dart +++ b/mobile/lib/shared/widgets/android_expanding_menu_button.dart @@ -15,17 +15,22 @@ class AndroidExpandingMenuButton extends HookWidget { const AndroidExpandingMenuButton({ required this.actions, this.label = 'New', + this.expansionBoundsContext, this.trigger, this.width = 112, this.height = 56, this.dividerBefore = const {}, + this.sectionTitles = const {}, super.key, }); + /// Optional control row whose bounds the expanded menu should cover. + final BuildContext? expansionBoundsContext; final String label; final Widget? trigger; final double width, height; final Set dividerBefore; + final Map sectionTitles; final List<({String label, String symbol, VoidCallback? onPressed})> actions; @@ -57,12 +62,22 @@ class AndroidExpandingMenuButton extends HookWidget { box.getTransformTo(overlay), Offset.zero & box.size, ); + final expansionBox = + expansionBoundsContext?.findRenderObject() as RenderBox?; + final expansionBounds = expansionBox == null + ? null + : MatrixUtils.transformRect( + expansionBox.getTransformTo(overlay), + Offset.zero & expansionBox.size, + ); final captured = actions; final route = _CreateMenuRoute( anchor: rect, + expansionBounds: expansionBounds, label: label, trigger: trigger ?? const _NewLabel(), dividerBefore: dividerBefore, + sectionTitles: sectionTitles, actions: captured, reducedMotion: MediaQuery.disableAnimationsOf(context), dismissLabel: MaterialLocalizations.of( @@ -111,17 +126,21 @@ class _NewLabel extends StatelessWidget { class _CreateMenuRoute extends PopupRoute { _CreateMenuRoute({ required this.anchor, + required this.expansionBounds, required this.label, required this.trigger, required this.dividerBefore, + required this.sectionTitles, required this.actions, required this.reducedMotion, required this.dismissLabel, }); final Rect anchor; + final Rect? expansionBounds; final String label; final Widget trigger; final Set dividerBefore; + final Map sectionTitles; final List<({String label, String symbol, VoidCallback? onPressed})> actions; final bool reducedMotion; final String dismissLabel; @@ -146,23 +165,30 @@ class _CreateMenuRoute extends PopupRoute { ) { final media = MediaQuery.of(context); final width = math.min( - 240.0, + expansionBounds?.width ?? 240.0, media.size.width - media.padding.horizontal - Grid.lg, ); final rowHeight = math.max(48.0, media.textScaler.scale(20) + Grid.sm); + final sectionHeight = media.textScaler.scale(12) + Grid.sm; final height = math.min( - actions.length * rowHeight + Grid.xs + dividerBefore.length, + actions.length * rowHeight + + Grid.xs + + dividerBefore.length + + sectionTitles.length * sectionHeight, media.size.height - media.padding.vertical - Grid.lg, ); final expandDown = anchor.center.dy < media.size.height / 2; final left = - (expandDown ? anchor.right - width : anchor.center.dx - width / 2) + (expansionBounds?.left ?? + (expandDown + ? anchor.right - width + : anchor.center.dx - width / 2)) .clamp( media.padding.left + Grid.xs, media.size.width - media.padding.right - Grid.xs - width, ) .toDouble(); - final bottom = anchor.bottom + final bottom = (expansionBounds ?? anchor).bottom .clamp( media.padding.top + Grid.xs + height, media.size.height - media.padding.bottom, @@ -246,6 +272,33 @@ class _CreateMenuRoute extends PopupRoute { ) ...[ if (dividerBefore.contains(i)) const Divider(height: 1), + if (sectionTitles[i] + case final title?) + SizedBox( + height: sectionHeight, + child: Padding( + padding: + const EdgeInsets.symmetric( + horizontal: Grid.gutter, + ), + child: Align( + alignment: + Alignment.centerLeft, + child: Semantics( + header: true, + child: Text( + title, + style: TextStyle( + fontSize: 12, + color: context + .colors + .onSurfaceVariant, + ), + ), + ), + ), + ), + ), SizedBox( height: rowHeight, child: InkWell( @@ -276,6 +329,8 @@ class _CreateMenuRoute extends PopupRoute { .desktop_windows_outlined, 'square.and.pencil' => BuzzIcons.edit, + 'workspace' => + BuzzIcons.workspace, 'folder.badge.plus' => BuzzIcons.folderPlus, 'bubble.left' => diff --git a/mobile/lib/shared/widgets/ios_message_create_button.dart b/mobile/lib/shared/widgets/ios_message_create_button.dart index 15302cd635..619569a8c7 100644 --- a/mobile/lib/shared/widgets/ios_message_create_button.dart +++ b/mobile/lib/shared/widgets/ios_message_create_button.dart @@ -19,6 +19,7 @@ class IosMessageCreateButton extends HookWidget { this.avatarUrl, this.avatarInitial, this.dividerBefore = const {}, + this.sectionTitles = const {}, this.icon = 'plus', this.accessibilityLabel = 'Create', this.width = 64, @@ -30,9 +31,12 @@ class IosMessageCreateButton extends HookWidget { this.eagerGestures = true, this.deferMenuActions = true, this.showIconWithLabel = false, + this.onMenuVisibilityChanged, + this.mergingNavigation = false, }); final Set dividerBefore; + final Map sectionTitles; final String? label; final double? labelFontSize; final String? avatarUrl, avatarInitial; @@ -54,6 +58,10 @@ class IosMessageCreateButton extends HookWidget { /// Wait for menu dismissal before actions that navigate to another route. final bool deferMenuActions; final bool showIconWithLabel; + final ValueChanged? onMenuVisibilityChanged; + + /// Hosts the Search/New/Bestie glass surfaces in one native container. + final bool mergingNavigation; final List<({String label, String symbol, VoidCallback? onPressed})> actions; @@ -89,12 +97,15 @@ class IosMessageCreateButton extends HookWidget { final avatar = useFuture(avatarFuture, preserveState: false).data; final channel = useState(null); final latest = useRef(actions)..value = actions; + final latestVisibility = useRef(onMenuVisibilityChanged) + ..value = onMenuVisibilityChanged; final latestEnabled = useRef(enabled)..value = enabled; final menu = [ for (var i = 0; i < actions.length; i++) { 'id': i, 'dividerBefore': dividerBefore.contains(i), + 'sectionTitle': ?sectionTitles[i], 'label': actions[i].label, 'symbol': actions[i].symbol, 'enabled': enabled && actions[i].onPressed != null, @@ -117,6 +128,10 @@ class IosMessageCreateButton extends HookWidget { final current = channel.value; if (current == null) return null; current.setMethodCallHandler((call) async { + if (call.method == 'menuVisibilityChanged') { + latestVisibility.value?.call(call.arguments as bool); + return; + } if (call.method != 'menuAction') return; final index = call.arguments as int; if (index >= 0 && index < latest.value.length) { @@ -152,6 +167,7 @@ class IosMessageCreateButton extends HookWidget { deferMenuActions, showIconWithLabel, ...dividerBefore, + ...sectionTitles.entries.expand((e) => [e.key, e.value]), ...actions.expand((a) => [a.label, a.symbol, a.onPressed != null]), brightness, foreground, @@ -176,7 +192,8 @@ class IosMessageCreateButton extends HookWidget { 'plain': plain, 'fillWidth': fillWidth, 'buttonCenterX': width / 2, - 'controlWidth': width, + 'controlWidth': mergingNavigation ? 112.0 : width, + 'mergingNavigation': mergingNavigation, 'controlSize': height, 'hitTargetWidth': width, 'hitTargetHeight': height, diff --git a/mobile/lib/shared/widgets/navigation_button_surface.dart b/mobile/lib/shared/widgets/navigation_button_surface.dart index ee7d55b3b6..1f9abfc18d 100644 --- a/mobile/lib/shared/widgets/navigation_button_surface.dart +++ b/mobile/lib/shared/widgets/navigation_button_surface.dart @@ -12,6 +12,7 @@ class NavigationButtonSurface extends StatelessWidget { @override Widget build(BuildContext context) { + if (NavigationGlassGroup.maybeOf(context)) return child; if (defaultTargetPlatform != TargetPlatform.iOS) { return Material( color: context.controlSurface, @@ -31,3 +32,15 @@ class NavigationButtonSurface extends StatelessWidget { ); } } + +/// Uses the shared native navigation glass instead of a separate surface. +class NavigationGlassGroup extends InheritedWidget { + const NavigationGlassGroup({super.key, required super.child}); + + static bool maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType() != + null; + + @override + bool updateShouldNotify(NavigationGlassGroup oldWidget) => false; +} diff --git a/mobile/test/features/channels/compose_bar_test.dart b/mobile/test/features/channels/compose_bar_test.dart index 794c194572..46ebf72e1f 100644 --- a/mobile/test/features/channels/compose_bar_test.dart +++ b/mobile/test/features/channels/compose_bar_test.dart @@ -1,3 +1,4 @@ +import 'package:flutter/scheduler.dart'; import 'dart:async'; import 'package:buzz/features/channels/composer_send_origin.dart'; import 'dart:convert'; @@ -39,6 +40,7 @@ import 'package:buzz/shared/widgets/mobile_tab_footer_backdrop.dart'; import 'package:shared_preferences/shared_preferences.dart'; part 'compose_bar_test/exact_mention_tests.dart'; +part 'compose_bar_test/solo_draft_tests.dart'; part 'compose_bar_test/durable_mention_tests.dart'; final _pngBytes = Uint8List.fromList([ @@ -183,6 +185,8 @@ late SharedPreferences _testPrefs; Widget _buildComposeBar({ required MediaUploadService uploadService, required ComposeBarOnSend onSend, + List? draftMembers, + ValueChanged? onSendingChanged, List members = const [], Future>? membersFuture, Future> Function()? loadMembers, @@ -288,6 +292,8 @@ Widget _buildComposeBar({ final composeBar = ComposeBar( key: ValueKey(composeBarKey), channelId: 'channel-1', + draftMembers: draftMembers, + onSendingChanged: onSendingChanged, threadHeadId: threadHeadId, focusNode: focusNode, onFocusRestorerChanged: onFocusRestorerChanged, @@ -689,6 +695,7 @@ class _FakeChannelsNotifier extends ChannelsNotifier { } void main() { + soloDraftTests(); exactMentionTests(); durableMentionTests(); TestWidgetsFlutterBinding.ensureInitialized(); @@ -3838,19 +3845,25 @@ void main() { }, ); + var busy = false; + final delivery = Completer(); String? sentContent; List> sentMediaTags = const []; await tester.pumpWidget( _buildComposeBar( uploadService: uploadService, + draftMembers: const [], + onSendingChanged: (value) => busy = value, onSend: ( content, mentionPubkeys, { mediaTags = const >[], }) async { + expect(busy, isTrue); sentContent = content; sentMediaTags = mediaTags; + await delivery.future; }, ), ); @@ -3884,8 +3897,16 @@ void main() { ); await tester.tap(find.byIcon(BuzzIcons.arrowUp)); - await tester.pumpAndSettle(); + for (var frame = 0; frame < 100 && sentContent == null; frame++) { + await tester.pump(); + } + expect(sentContent, isNotNull); + expect(busy, isTrue); + delivery.completeError(Exception('First send failed')); + await tester.pumpAndSettle(); + expect(busy, isFalse); + expect(find.byTooltip('Remove attachment'), findsOneWidget); expect(uploadedBytes, _pngBytes); expect(uploadedMimeType, 'image/png'); expect(sentContent, '\n![image](https://relay.example/media/pasted.png)'); @@ -4133,6 +4154,7 @@ void main() { ) async { final previousPlatform = debugDefaultTargetPlatformOverride; debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + var busy = false; try { final uploadService = MediaUploadService( baseUrl: 'https://relay.example', @@ -4144,6 +4166,8 @@ void main() { await tester.pumpWidget( _buildComposeBar( uploadService: uploadService, + draftMembers: const [], + onSendingChanged: (value) => busy = value, onSend: ( content, @@ -4169,6 +4193,7 @@ void main() { .onPressed!(); await tester.pumpAndSettle(); + expect(busy, isFalse); expect(find.text('Unable to read pasted image'), findsOneWidget); expect(find.byTooltip('Remove attachment'), findsNothing); } finally { diff --git a/mobile/test/features/channels/compose_bar_test/solo_draft_tests.dart b/mobile/test/features/channels/compose_bar_test/solo_draft_tests.dart new file mode 100644 index 0000000000..18ad3895fb --- /dev/null +++ b/mobile/test/features/channels/compose_bar_test/solo_draft_tests.dart @@ -0,0 +1,116 @@ +part of '../compose_bar_test.dart'; + +class _SlowDraftPhotoLibrary extends _FakePhotoLibrary { + final result = Completer>(); + _SlowDraftPhotoLibrary() + : super([RecentPhoto(id: 'one', thumbnailBytes: _gifBytes)]); + @override + Future> resolveSelectedPhotos(List photos) => + result.future; +} + +void soloDraftTests() { + testWidgets('Solo draft stays busy while selected photos resolve', ( + tester, + ) async { + final library = _SlowDraftPhotoLibrary(); + var busy = false; + await tester.pumpWidget( + _buildComposeBar( + uploadService: _testUploadService(nostr.Keys.generate().nsec), + draftMembers: const [], + photoLibrary: library, + onSendingChanged: (value) => busy = value, + onSend: + (content, mentions, {mediaTags = const >[]}) async {}, + ), + ); + await _openAttachmentMenu(tester); + await tester.tap(find.text('Photos')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('recent-photo-one'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Add 1 photo')); + await tester.pump(); + expect(busy, isTrue); + library.result.completeError(Exception('Photo unavailable')); + await tester.pumpAndSettle(); + expect(busy, isFalse); + expect(find.text('Couldn’t prepare photos'), findsOneWidget); + }); + + testWidgets( + 'Solo draft freezes editing during first send and restores on failure', + (tester) async { + var delivery = Completer(); + final keys = nostr.Keys.generate(); + var busy = false; + await tester.pumpWidget( + _buildComposeBar( + uploadService: _testUploadService(keys.nsec), + relayConfig: () => _SwitchableRelayConfigNotifier( + RelayConfig(baseUrl: 'https://relay.example', nsec: keys.nsec), + ), + draftMembers: const [], + onSendingChanged: (value) { + expect( + SchedulerBinding.instance.schedulerPhase, + isNot(SchedulerPhase.persistentCallbacks), + ); + busy = value; + }, + onSend: (content, mentions, {mediaTags = const >[]}) => + delivery.future, + ), + ); + await _expandComposer(tester); + await tester.enterText(find.byType(TextField), 'First message'); + await tester.pumpAndSettle(); + await tester.tap(find.byIcon(BuzzIcons.arrowUp)); + await tester.pump(); + expect(busy, isTrue); + expect(tester.widget(find.byType(TextField)).readOnly, isTrue); + delivery.completeError(Exception('Offline')); + await tester.pumpAndSettle(); + expect(busy, isFalse); + expect( + tester.widget(find.byType(TextField)).readOnly, + isFalse, + ); + expect(find.text('First message'), findsOneWidget); + ScaffoldMessenger.of( + tester.element(find.byType(ComposeBar)), + ).clearSnackBars(); + await tester.pumpAndSettle(); + // A second attempt fails before a build observes sending=true. + await tester.tap(find.byIcon(BuzzIcons.arrowUp)); + await tester.pumpAndSettle(); + expect(busy, isFalse); + expect( + tester.widget(find.byType(TextField)).readOnly, + isFalse, + ); + ScaffoldMessenger.of( + tester.element(find.byType(ComposeBar)), + ).clearSnackBars(); + await tester.pumpAndSettle(); + // Same-origin URL changes reset the mounted composer during build. + delivery = Completer(); + await tester.tap(find.byIcon(BuzzIcons.arrowUp)); + await tester.pump(); + expect(busy, isTrue); + final container = ProviderScope.containerOf( + tester.element(find.byType(ComposeBar)), + ); + container + .read(relayConfigProvider.notifier) + .update(baseUrl: 'https://relay.example/alternate', nsec: keys.nsec); + await tester.pump(); + expect(busy, isFalse); + delivery.complete(); + await tester.pump(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }, + ); +} diff --git a/mobile/test/features/channels/me/chat_preflight_test.dart b/mobile/test/features/channels/me/chat_preflight_test.dart index ab0ef8495e..c227a0a70c 100644 --- a/mobile/test/features/channels/me/chat_preflight_test.dart +++ b/mobile/test/features/channels/me/chat_preflight_test.dart @@ -1,3 +1,7 @@ +import 'package:buzz/features/channels/compose_bar.dart'; +import 'package:buzz/shared/mentions/agent_identity_provider.dart'; +import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart'; +import 'package:buzz/shared/me/default_agent.dart'; import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/features/channels/channels_provider.dart'; @@ -10,7 +14,6 @@ import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/widgets/frosted_app_bar.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:nostr/nostr.dart' as nostr; @@ -60,39 +63,23 @@ void main() { relay.beforeRead = () => expectSync(MeChatCreation.pending(sync)?.name, 'Saved chat'); late ProviderContainer container; - var forms = 0; - const bridge = MethodChannel('buzz/profile_text_editor'); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(bridge, ( - call, - ) async { - if (call.method == 'updateChatAssistants') return null; - forms++; - if (forms > 1) return null; - if (disconnect) { - sync.disposed = true; - sync = MeSync(relay, config, prefs: prefs, connected: false); - container.invalidate(meSyncProvider); - } - return { - 'name': 'Saved chat', - 'assistant': 'agent', - 'project': 'mobile', - }; - }); - addTearDown( - () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - bridge, - null, - ), - ); await tester.pumpWidget( ProviderScope( overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + agentDirectoryProvider.overrideWith((ref) async => []), + agentOwnersProvider.overrideWith((ref) async => {}), + customEmojiListProvider.overrideWithValue([]), + defaultAgentProvider.overrideWith((ref) => Stream.value('agent')), meSyncProvider.overrideWith((ref) => sync), meGroupsProvider.overrideWith( (ref) => Stream.value(const MeGroups()), ), - meAssistantsProvider.overrideWith((ref) async => []), + meAssistantsProvider.overrideWith( + (ref) async => const [ + AgentDirectoryEntry(pubkey: 'agent', displayName: 'Agent'), + ], + ), channelsProvider.overrideWith(_Channels.new), channelActionsProvider.overrideWith( (ref) => ChannelActions( @@ -119,6 +106,19 @@ void main() { .firstWhere((a) => a.label == 'New chat') .onPressed!(); await tester.pumpAndSettle(); + if (disconnect) { + sync.disposed = true; + sync = MeSync(relay, config, prefs: prefs, connected: false); + container.invalidate(meSyncProvider); + await tester.pumpAndSettle(); + } + await expectLater( + tester + .widget(find.byType(ComposeBar)) + .onSend('Saved chat', const []), + throwsException, + ); + await tester.pumpAndSettle(); final saved = MeChatCreation.pending( MeSync(relay, config, prefs: prefs), ); @@ -129,7 +129,7 @@ void main() { ); expect(saved!.name, 'Saved chat'); expect(saved.agent, 'agent'); - expect(saved.project, 'mobile'); + expect(saved.project, isNull); expect( prefs.getString(MeChatCreation.storageKey(sync)), isNot(contains('Saved chat')), diff --git a/mobile/test/features/channels/me/me_page_test.dart b/mobile/test/features/channels/me/me_page_test.dart index a4b7669acf..47537b33da 100644 --- a/mobile/test/features/channels/me/me_page_test.dart +++ b/mobile/test/features/channels/me/me_page_test.dart @@ -1,14 +1,15 @@ +import 'package:buzz/features/channels/compose_bar.dart'; +import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart'; import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:buzz/shared/me/me_chat_creation.dart'; +import 'package:buzz/shared/me/default_agent.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:nostr/nostr.dart' as nostr; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/me/me_assistants.dart'; import 'package:buzz/shared/mentions/agent_identity_provider.dart'; -import 'package:buzz/shared/profile/user_cache_provider.dart'; -import 'package:buzz/shared/profile/user_profile.dart'; import 'package:buzz/shared/theme/buzz_icons.dart'; import 'package:buzz/shared/widgets/frosted_app_bar.dart'; import 'package:flutter/material.dart'; @@ -21,6 +22,19 @@ import 'package:buzz/shared/me/me_groups.dart'; import 'package:buzz/shared/me/me_sync.dart'; import 'package:buzz/shared/theme/theme.dart'; +class _UnavailableRelay extends RelaySessionNotifier { + @override + Future> queryRelay( + List filters, { + Duration timeout = const Duration(seconds: 8), + }) async => throw StateError('Agent unavailable'); + @override + Future> fetchHistory( + NostrFilter filter, { + Duration timeout = const Duration(seconds: 8), + }) async => []; +} + class FakeChannels extends ChannelsNotifier { @override Future> build() async => [ @@ -74,6 +88,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + defaultAgentProvider.overrideWith((ref) => Stream.value(null)), myPubkeyProvider.overrideWithValue('owner'), channelsProvider.overrideWith(LabeledChannels.new), meGroupsProvider.overrideWith( @@ -112,6 +127,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + defaultAgentProvider.overrideWith((ref) => Stream.value(null)), meGroupsProvider.overrideWith( (ref) => Stream.value(const MeGroups()), ), @@ -141,6 +157,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + defaultAgentProvider.overrideWith((ref) => Stream.value(null)), meGroupsProvider.overrideWith((ref) => updates.stream), channelsProvider.overrideWith(FakeChannels.new), ], @@ -160,11 +177,11 @@ void main() { expect(find.text('Search chats'), findsNothing); expect(find.byType(TextField), findsNothing); expect(find.byIcon(BuzzIcons.edit), findsOneWidget); - expect(find.byIcon(BuzzIcons.folderPlus), findsOneWidget); + expect(find.byIcon(BuzzIcons.workspace), findsOneWidget); final header = tester.widget(find.byType(FrostedAppBar)); expect(header.nativeLargeTitle, isTrue); expect(header.nativeActions!.map((action) => action.icon), [ - BuzzIcons.folderPlus, + BuzzIcons.workspace, BuzzIcons.edit, ]); expect(find.text('App work'), findsOneWidget); @@ -187,12 +204,12 @@ void main() { ), ); await tester.pumpAndSettle(); - expect(find.text('No chats in this project'), findsOneWidget); + expect(find.text('No chats in this workspace yet'), findsOneWidget); expect(find.text('Design agent'), findsOneWidget); await tester.tap(find.text('Chats')); await tester.pumpAndSettle(); expect(find.text('Design agent'), findsNothing); - expect(find.text('No chats in this project'), findsOneWidget); + expect(find.text('No chats in this workspace yet'), findsOneWidget); await tester.tap(find.text('Chats')); await tester.pumpAndSettle(); expect(find.text('Design agent'), findsOneWidget); @@ -204,24 +221,28 @@ void main() { }, ); testWidgets( - 'footer new chat offers project selection without losing its name', + 'new chat opens a conversation with Bestie and workspace controls', (tester) async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); final action = ValueNotifier(null); addTearDown(action.dispose); + final bestie = StreamController(); + addTearDown(bestie.close); final sync = MeSync( - RelaySessionNotifier(), + _UnavailableRelay(), RelayConfig( baseUrl: 'https://relay.test', - nsec: nostr.Nip19.encode( - prefix: nostr.Nip19Prefix.nsec, - data: - '0000000000000000000000000000000000000000000000000000000000000001', - ), + nsec: nostr.Keys.generate().nsec, ), + prefs: prefs, ); await tester.pumpWidget( ProviderScope( overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + defaultAgentProvider.overrideWith((ref) => bestie.stream), + meSyncProvider.overrideWithValue(sync), meGroupsProvider.overrideWith( (ref) => Stream.value( const MeGroups( @@ -235,14 +256,19 @@ void main() { ), ), ), - meSyncProvider.overrideWithValue(sync), channelsProvider.overrideWith(FakeChannels.new), meAssistantsProvider.overrideWith( (ref) async => const [ - AgentDirectoryEntry(pubkey: 'agent', displayName: 'Owner Name'), + AgentDirectoryEntry(pubkey: 'bestie', displayName: 'My Bestie'), + AgentDirectoryEntry( + pubkey: 'other', + displayName: 'Other agent', + ), ], ), - userCacheProvider.overrideWith(_ConfusableProfiles.new), + agentDirectoryProvider.overrideWith((ref) async => []), + agentOwnersProvider.overrideWith((ref) async => {}), + customEmojiListProvider.overrideWithValue([]), ], child: MaterialApp( theme: AppTheme.light(), @@ -251,147 +277,95 @@ void main() { ), ); await tester.pumpAndSettle(); - expect(find.byTooltip('New chat'), findsNothing); - expect(action.value, isNotNull); action.value!(); await tester.pumpAndSettle(); - expect(find.byType(BottomSheet), findsOneWidget); - expect( - find.byKey(const ValueKey('new-session-name')).hitTestable(), - findsOneWidget, - ); - expect( - find.byKey(const ValueKey('new-session-assistant')).hitTestable(), - findsOneWidget, - ); - await tester.enterText( - find.byKey(const ValueKey('new-session-name')), - 'Design session', - ); - await tester.tap(find.byKey(const ValueKey('new-session-project'))); + expect(find.byType(ComposeBar), findsOneWidget); + expect(find.byType(BottomSheet), findsNothing); + // Missing agent fails before the next frame and must unlock the header. + await tester.tap(find.text('Message Choose an agent')); await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'Hello'); + await tester.tap(find.byIcon(BuzzIcons.arrowUp).hitTestable().last); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(const ValueKey('new-chat-agent'))) + .onPressed, + isNotNull, + ); + ScaffoldMessenger.of( + tester.element(find.byType(ComposeBar)), + ).clearSnackBars(); + await tester.pumpAndSettle(); + bestie.add('bestie'); + await tester.pumpAndSettle(); + expect(find.byTooltip('Change agent: My Bestie'), findsOneWidget); + bestie.addError(StateError('Cache write failed')); + await tester.pumpAndSettle(); + expect(find.byTooltip('Change agent: My Bestie'), findsOneWidget); + final bar = tester.widget(find.byType(FrostedAppBar).last); + expect(bar.nativeActions!.map((action) => action.label), [ + 'Choose workspace', + 'Change agent: My Bestie', + ]); + expect(bar.nativeLeading?.symbol, 'chevron.backward'); + expect( + bar.nativeActions!.every((action) => !action.sharesBackground), + isTrue, + ); + await tester.tap(find.byTooltip('Choose workspace')); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsNothing); + expect( + find.widgetWithText(CheckedPopupMenuItem, 'No Workspace'), + findsOneWidget, + ); + expect(find.text('Create workspace'), findsNothing); await tester.tap(find.text('Mobile app').last); await tester.pumpAndSettle(); - expect(find.text('Design session'), findsOneWidget); - expect(find.text('Mobile app'), findsWidgets); - await tester.tap(find.byKey(const ValueKey('new-session-project'))); + expect(find.byTooltip('Workspace: Mobile app'), findsOneWidget); + await tester.tap(find.byTooltip('Change agent: My Bestie')); await tester.pumpAndSettle(); - await tester.tap(find.text('No project').last); + expect(tester.getSize(find.byType(ListView).last).height, lessThan(300)); + await tester.tap(find.text('Other agent')); await tester.pumpAndSettle(); - await tester.tap(find.text('Create chat')); + bestie.add(null); await tester.pumpAndSettle(); - expect(find.text('Enter a name and choose an agent.'), findsOneWidget); - expect(find.text('Design session'), findsOneWidget); - // The owner's label and its initial outrank the agent's own profile. - await tester.tap(find.byKey(const ValueKey('new-session-assistant'))); + expect(find.byTooltip('Change agent: Other agent'), findsOneWidget); + await tester.tap(find.text('Hello').last); await tester.pumpAndSettle(); - await tester.tap(find.text('Owner Name').last); + await tester.enterText(find.byType(TextField), 'Plan our launch'); + await tester.pageBack(); + await tester.pumpAndSettle(); + action.value!(); + await tester.pumpAndSettle(); + expect(find.text('Plan our launch'), findsOneWidget); + expect(MeChatCreation.pending(sync), isNull); + await tester.tap(find.byTooltip('Choose an agent')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Other agent')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Plan our launch').last); + await tester.pumpAndSettle(); + await tester.tap(find.byIcon(BuzzIcons.arrowUp).hitTestable().last); + await tester.pumpAndSettle(); + expect(MeChatCreation.pending(sync), isNotNull); + expect(find.text('Retry'), findsOneWidget); + ScaffoldMessenger.of(tester.element(find.text('Retry'))).clearSnackBars(); + await tester.pumpAndSettle(); + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + await tester.pageBack(); + await tester.pumpAndSettle(); + expect(find.text('Retry'), findsNothing); + expect(find.byType(ComposeBar), findsNothing); + + await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpAndSettle(); - final row = find.byKey(const ValueKey('new-session-assistant')); - expect( - find.descendant(of: row, matching: find.text('Owner Name')), - findsOneWidget, - ); - expect( - find.descendant(of: row, matching: find.text('O')), - findsOneWidget, - ); - expect(find.textContaining('Confusable'), findsNothing); }, ); - testWidgets('iOS new chat uses the native profile form with project choices', ( - tester, - ) async { - debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - addTearDown(() => debugDefaultTargetPlatformOverride = null); - const channel = MethodChannel('buzz/profile_text_editor'); - final calls = []; - var directoryLoads = 0; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( - call, - ) async { - calls.add(call); - return null; - }); - addTearDown( - () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - channel, - null, - ), - ); - final sync = MeSync( - RelaySessionNotifier(), - RelayConfig( - baseUrl: 'https://relay.test', - nsec: nostr.Nip19.encode( - prefix: nostr.Nip19Prefix.nsec, - data: - '0000000000000000000000000000000000000000000000000000000000000001', - ), - ), - ); - await tester.pumpWidget( - ProviderScope( - overrides: [ - meGroupsProvider.overrideWith( - (ref) => Stream.value( - const MeGroups( - groups: [ - { - 'id': 'mobile', - 'name': 'Mobile app', - 'defaultTemplateId': '', - }, - ], - ), - ), - ), - meSyncProvider.overrideWithValue(sync), - channelsProvider.overrideWith(FakeChannels.new), - meAssistantsProvider.overrideWith((ref) async { - directoryLoads++; - return const [ - AgentDirectoryEntry(pubkey: 'agent', displayName: 'Owner Name'), - ]; - }), - userCacheProvider.overrideWith(_ConfusableProfiles.new), - ], - child: MaterialApp(theme: AppTheme.light(), home: const MePage()), - ), - ); - await tester.pumpAndSettle(); - - final bar = tester.widget(find.byType(FrostedAppBar)); - bar.nativeActions! - .firstWhere((action) => action.label == 'New chat') - .onPressed!(); - await tester.pumpAndSettle(); - expect(directoryLoads, 1); - expect(calls, hasLength(1)); - expect(calls.single.method, 'presentChat'); - final args = calls.single.arguments as Map; - expect(args['title'], 'New chat'); - expect(args['placeholder'], 'Chat name'); - expect(args['assistants'], [ - { - 'id': 'agent', - 'name': 'Owner Name', - 'artworkScale': '1', - 'avatarUrl': '', - }, - ]); - expect(args['projects'], [ - {'id': 'mobile', 'name': 'Mobile app'}, - ]); - expect(args['selectedProject'], isNull); - expect(args['containerCornerRadius'], Radii.container); - expect(find.byType(BottomSheet), findsNothing); - await tester.pumpWidget(const SizedBox.shrink()); - debugDefaultTargetPlatformOverride = null; - }); - - for (final resume in [true, false]) { + for (final resume in [true]) { testWidgets('iOS new chat recovers a durable creation: resume=$resume', ( tester, ) async { @@ -440,6 +414,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + defaultAgentProvider.overrideWith((ref) => Stream.value(null)), meGroupsProvider.overrideWith( (ref) => Stream.value(const MeGroups()), ), @@ -476,7 +451,7 @@ void main() { MeChatCreation.pending(restarted)?.id, resume ? 'same-id' : isNull, ); - expect(args['placeholder'], 'Chat name'); + expect(args['placeholder'], resume ? 'Chat name' : 'Message'); expect(args['assistants'], isEmpty); expect(args['containerCornerRadius'], Radii.container); expect(find.byType(BottomSheet), findsNothing); @@ -491,6 +466,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + defaultAgentProvider.overrideWith((ref) => Stream.value(null)), meGroupsProvider.overrideWith( (ref) => Stream.error(StateError('offline')), ), @@ -504,10 +480,3 @@ void main() { expect(find.text('A place to work with your agents'), findsNothing); }); } - -class _ConfusableProfiles extends UserCacheNotifier { - @override - Map build() => { - 'agent': const UserProfile(pubkey: 'agent', displayName: 'Confusable Name'), - }; -} diff --git a/mobile/test/features/channels/me/project_creation_test.dart b/mobile/test/features/channels/me/project_creation_test.dart index d1387f07dc..d5a3a4754c 100644 --- a/mobile/test/features/channels/me/project_creation_test.dart +++ b/mobile/test/features/channels/me/project_creation_test.dart @@ -1,6 +1,10 @@ +import 'dart:convert'; +import 'package:buzz/shared/crypto/nip44.dart'; +import 'package:buzz/features/channels/me/me_workspace_picker.dart'; import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channels_provider.dart'; import 'package:buzz/features/channels/me/me_page.dart'; +import 'package:buzz/features/channels/me/new_me_project.dart'; import 'package:buzz/shared/me/me_assistants.dart'; import 'package:buzz/shared/me/me_groups.dart'; import 'package:buzz/shared/me/me_project_creation.dart'; @@ -59,6 +63,40 @@ class _Relay extends RelaySessionNotifier { } } +class _WorkspaceHeader extends HookConsumerWidget { + const _WorkspaceHeader(); + @override + Widget build(BuildContext context, WidgetRef ref) { + final workspace = useMeWorkspace( + context, + ref, + enabled: true, + channelId: '10000000-0000-4000-8000-000000000001', + ); + return Scaffold( + appBar: AppBar(actions: [workspace.action]), + body: TextButton( + onPressed: () async { + try { + await createMeProject( + context, + ref, + workspace: true, + channelId: '10000000-0000-4000-8000-000000000001', + ); + } on StateError catch (error) { + expect( + error.message, + contains('Project setup saved on this phone'), + ); + } + }, + child: const Text('Open workspace creation'), + ), + ); + } +} + void main() { final config = RelayConfig( baseUrl: 'https://relay.test', @@ -67,6 +105,120 @@ void main() { data: '0' * 63 + '1', ), ); + testWidgets( + 'workspace creation assigns the chat and resumes a lost acknowledgement', + (tester) async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final relay = _Relay()..failAfterPublish = true; + final sync = MeSync(relay, config, prefs: prefs); + await tester.pumpWidget( + ProviderScope( + overrides: [ + meSyncProvider.overrideWithValue(sync), + meGroupsProvider.overrideWith( + (ref) => Stream.value(const MeGroups()), + ), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: const _WorkspaceHeader(), + ), + ), + ); + await tester.pumpAndSettle(); + Future open() async { + await tester.tap(find.text('Open workspace creation')); + await tester.pumpAndSettle(); + } + + await open(); + await tester.enterText(find.byType(TextField), 'Launch'); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(FilledButton, 'Create workspace')); + await tester.pumpAndSettle(); + final saved = MeProjectCreation.pending(sync)!; + expect(saved.channelId, '10000000-0000-4000-8000-000000000001'); + expect( + sync + .decode(relay.events.single) + .assignments['10000000-0000-4000-8000-000000000001'], + saved.id, + ); + expect(sync.decode(relay.events.single).groups.single['name'], 'Launch'); + relay.failAfterPublish = false; + for (var attempt = 0; attempt < 2; attempt++) { + await open(); + await tester.tap(find.text('Resume')); + await tester.pumpAndSettle(); + } + expect(MeProjectCreation.pending(sync), isNull); + expect(relay.writes, 1); + expect( + sync + .decode(relay.events.single) + .assignments['10000000-0000-4000-8000-000000000001'], + saved.id, + ); + + // A conflicting, unconfirmed phone move remains recoverable in-place. + const chat = '10000000-0000-4000-8000-000000000001'; + MeGroups organization(String group) => MeGroups( + groups: [ + for (final id in ['original', 'phone', 'desktop']) + {'id': id, 'name': id, 'defaultTemplateId': ''}, + ], + assignments: {chat: group}, + channels: const [chat], + ); + NostrEvent signed(String group, int timestamp) => NostrEvent.fromJson( + nostr.Event.from( + kind: 30078, + content: nip44Encrypt( + sync.key, + organization(group).encode(sync.community), + ), + secretKey: sync.privateHex, + createdAt: timestamp, + tags: [ + ['d', MeGroups.coordinate(sync.community)], + ['t', MeGroups.tag], + ], + verify: false, + ).toMap(), + ); + final pending = jsonEncode({ + 'base': signed('original', 1).toJson(), + 'event': signed('phone', 2).toJson(), + }); + await prefs.setString(sync.pendingKey, pending); + relay.events = [signed('desktop', 3)]; + Future move() async { + await tester.tap(find.byKey(const ValueKey('me-workspace-button'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('No Workspace')); + await tester.pumpAndSettle(); + } + + await move(); + expect(find.text('Conflicting Solo changes'), findsOneWidget); + await tester.tap(find.text('Keep pending')); + await tester.pumpAndSettle(); + expect(prefs.getString(sync.pendingKey), pending); + await move(); + await tester.tap(find.text('Discard phone change')); + await tester.pumpAndSettle(); + expect(prefs.getString(sync.pendingKey), isNull); + expect(sync.decode(relay.events.single).assignments[chat], 'desktop'); + await move(); + expect( + sync.decode(relay.events.single).assignments.containsKey(chat), + isFalse, + ); + expect(find.text('Conflicting Solo changes'), findsNothing); + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + ); for (final throws in [false, true]) { testWidgets( 'failed project write ($throws) reopens the entered name without claiming recovery', @@ -275,7 +427,11 @@ void main() { final prefs = await SharedPreferences.getInstance(); final relay = _Relay()..failAfterPublish = true; final sync = MeSync(relay, config, prefs: prefs); - const intent = MeProjectCreation('project', 'Name'); + const intent = MeProjectCreation( + 'project', + 'Name', + channelId: '10000000-0000-4000-8000-000000000001', + ); await expectLater(intent.complete(sync), throwsStateError); final restarted = MeSync(relay, config, prefs: prefs); relay.failAfterPublish = false; @@ -287,6 +443,12 @@ void main() { expect(MeProjectCreation.pending(restarted), isNull); expect(relay.writes, 1); expect(restarted.decode(relay.events.single).groups, hasLength(1)); + expect( + restarted + .decode(relay.events.single) + .assignments['10000000-0000-4000-8000-000000000001'], + 'project', + ); }, ); } diff --git a/mobile/test/features/channels/me/solo_creation_tags_test.dart b/mobile/test/features/channels/me/solo_creation_tags_test.dart index e9dad011bc..8081b65a13 100644 --- a/mobile/test/features/channels/me/solo_creation_tags_test.dart +++ b/mobile/test/features/channels/me/solo_creation_tags_test.dart @@ -1,3 +1,6 @@ +import 'package:buzz/features/channels/compose_bar.dart'; +import 'package:buzz/shared/me/default_agent.dart'; +import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart'; import 'dart:async'; import 'dart:convert'; @@ -67,6 +70,17 @@ void main() { ? 'interrupted Solo recovery uses fresh membership before creating' : 'New Solo chat submits its discovery label through the production action', (tester) async { + const mediaChannel = MethodChannel('buzz/media_upload'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + mediaChannel, + (call) async => call.method == 'clipboardHasImage' ? false : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + mediaChannel, + null, + ), + ); final flutterSheet = defaultTargetPlatform == TargetPlatform.android; SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); @@ -159,7 +173,16 @@ void main() { } }); final directory = Completer>(); - if (flutterSheet) directory.complete([]); + if (!recoverExisting) { + directory.complete([ + AgentDirectoryEntry( + pubkey: agent.public, + displayName: 'Owned agent', + ), + ]); + } else if (flutterSheet) { + directory.complete([]); + } final draft = Completer>(); String? presentationId; Map? agentUpdate; @@ -187,6 +210,13 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + defaultAgentProvider.overrideWith( + (ref) => Stream.value(agent.public), + ), + agentDirectoryProvider.overrideWith((ref) async => []), + agentOwnersProvider.overrideWith((ref) async => {}), + customEmojiListProvider.overrideWithValue([]), meSyncProvider.overrideWithValue(sync), relaySessionProvider.overrideWith(() => relay), meGroupsProvider.overrideWith( @@ -224,26 +254,13 @@ void main() { await tester.tap(find.text('Resume')); await tester.pumpAndSettle(); } - if (flutterSheet) { + if (!recoverExisting) { + final composer = tester.widget(find.byType(ComposeBar)); + unawaited( + composer.onSend('Mobile Solo', const []).catchError((_) {}), + ); + } else if (flutterSheet) { final row = find.byKey(const ValueKey('new-session-assistant')); - if (!recoverExisting) { - expect(find.text('Choose an agent'), findsOneWidget); - await tester.enterText( - find.byKey(const ValueKey('new-session-name')), - 'Mobile Solo', - ); - await tester.tap(find.text('Create chat')); - await tester.pumpAndSettle(); - expect( - find.text('Enter a name and choose an agent.'), - findsOneWidget, - ); - expect(relay.submitted, isEmpty); - expect(MeChatCreation.pending(sync), isNull); - await tester.pumpWidget(const SizedBox.shrink()); - await tester.pumpAndSettle(); - return; - } final semantics = tester.ensureSemantics(); await tester.pump(); expect(find.text('Choose an agent'), findsNothing); @@ -311,6 +328,15 @@ void main() { expect(MeChatCreation.pending(sync)?.id, channelId); expect(command.tags, contains(equals(['p', agent.public]))); } else { + final pending = MeChatCreation.pending(sync)!; + expect(pending.name, 'Mobile Solo'); + expect(pending.initialMessage?.content, 'Mobile Solo'); + expect(pending.initialMessage?.pubkey, owner.public); + expect( + pending.initialMessage?.tags, + contains(equals(['p', agent.public])), + ); + expect(pending.initialMessage?.getTagValue('h'), pending.id); expect(command.kind, 9007); expect(command.pubkey, owner.public); expect(command.tags, contains(equals(['t', 'buzz.solo']))); diff --git a/mobile/test/features/home/home_page_test.dart b/mobile/test/features/home/home_page_test.dart index 8b0abe1176..af17ae6914 100644 --- a/mobile/test/features/home/home_page_test.dart +++ b/mobile/test/features/home/home_page_test.dart @@ -223,9 +223,33 @@ void main() { await tester.pumpAndSettle(); chat!.value = () => created++; await tester.pumpAndSettle(); + final controlsBounds = tester.getRect(find.byType(MessagesNavigationBar)); await tester.tap(find.byTooltip('New')); await tester.pumpAndSettle(); expect(find.text('New workspace'), findsOneWidget); + final menuBounds = tester.getRect( + find + .ancestor( + of: find.text('New workspace'), + matching: find.byType(Material), + ) + .first, + ); + expect(menuBounds.left, closeTo(controlsBounds.left, .01)); + expect(menuBounds.right, closeTo(controlsBounds.right, .01)); + expect(menuBounds.bottom, closeTo(controlsBounds.bottom, .01)); + expect( + tester.getTopLeft(find.text('Solo').last).dy, + lessThan(tester.getTopLeft(find.text('New chat')).dy), + ); + expect( + tester.getTopLeft(find.text('Team').last).dy, + greaterThan(tester.getBottomLeft(find.text('New workspace')).dy), + ); + expect( + tester.getTopLeft(find.text('Team').last).dy, + lessThan(tester.getTopLeft(find.text('New DM')).dy), + ); expect(find.text('New DM'), findsOneWidget); expect(find.text('New channel'), findsOneWidget); await tester.tap(find.text('New chat')); @@ -259,6 +283,36 @@ void main() { .map((a) => a.label), ['New chat', 'New workspace', 'New DM', 'New channel'], ); + final creationMenu = tester.widget( + find.byWidgetPredicate( + (w) => w is IosMessageCreateButton && w.label == 'New', + ), + ); + final search = find.byTooltip('Search'); + final initialX = tester.getCenter(search).dx; + final initialWidth = + (tester.getTopRight(search).dx - tester.getTopLeft(search).dx); + creationMenu.onMenuVisibilityChanged!(true); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 90)); + final midwayX = tester.getCenter(search).dx; + expect(midwayX, greaterThan(initialX + 50)); + expect(midwayX, lessThan(initialX + 100)); + await tester.pumpAndSettle(); + expect(tester.getCenter(search).dx, closeTo(initialX + 100, .01)); + expect( + (tester.getTopRight(search).dx - tester.getTopLeft(search).dx), + closeTo(initialWidth * .9, .01), + ); + expect(search.hitTestable(), findsNothing); + creationMenu.onMenuVisibilityChanged!(false); + await tester.pumpAndSettle(); + expect(tester.getCenter(search).dx, closeTo(initialX, .01)); + expect( + (tester.getTopRight(search).dx - tester.getTopLeft(search).dx), + closeTo(initialWidth, .01), + ); + expect(search.hitTestable(), findsOneWidget); final communityMenu = tester.widget( find.byWidgetPredicate( (w) => diff --git a/mobile/test/shared/me/me_chat_creation_test.dart b/mobile/test/shared/me/me_chat_creation_test.dart index a7e79ccdc6..31fb344ec1 100644 --- a/mobile/test/shared/me/me_chat_creation_test.dart +++ b/mobile/test/shared/me/me_chat_creation_test.dart @@ -1,4 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; +import 'package:buzz/shared/crypto/event_signing.dart'; +import 'package:buzz/shared/me/me_chat_title.dart'; import 'package:nostr/nostr.dart' as nostr; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; @@ -7,6 +9,138 @@ import 'package:buzz/shared/me/me_sync.dart'; import 'package:buzz/shared/relay/relay.dart'; void main() { + test('first-message title follows desktop plain-text rules', () { + for (final (message, title) in [ + (' Plan\n my trip ', 'Plan my trip'), + ('@Alice help me', '@Alice help me'), + ( + 'buzz://message?channel=source Plan the next step', + 'Plan the next step', + ), + ('buzz://message?channel=source', 'Chat'), + ('### Heading', 'Heading'), + ('🐝' * 90, '🐝' * 80), + ]) { + expect(startingMeChatTitle(message), title); + } + }); + test( + 'accepted first message survives a lost acknowledgement and restart', + () async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final owner = nostr.Keys.generate(); + final agent = nostr.Keys.generate().public; + final relay = _MessageRelay(); + final config = RelayConfig( + baseUrl: 'https://relay.test', + nsec: owner.nsec, + ); + MeSync service() => MeSync(relay, config, prefs: prefs); + final message = NostrEvent.fromJson( + signNostrEvent( + kind: 9, + content: 'Plan my trip', + tags: [ + ['h', 'chat'], + ['p', agent], + ], + secretKey: owner.secret, + ).toMap(), + ); + final intent = MeChatCreation( + 'chat', + 'Plan my trip', + agent, + initialMessage: message, + ); + Future send(MeChatCreation intent) => intent.complete( + service(), + findChannel: () async => 'chat', + createChannel: () async => throw StateError('already created'), + hasAgent: () async => true, + addAgent: () async => throw StateError('already joined'), + isPlaced: () async => true, + place: () async => throw StateError('already placed'), + ); + await expectLater(send(intent), throwsStateError); + await prefs.reload(); + final pending = MeChatCreation.pending(service())!; + expect(pending.initialMessage?.toJson(), message.toJson()); + expect( + prefs.getString(MeChatCreation.storageKey(service())), + isNot(contains('Plan my trip')), + ); + await expectLater( + MeChatCreation('chat', intent.name, agent).save(service()), + throwsStateError, + ); + expect(await send(pending), 'chat'); + expect(relay.attempts, [message.id, message.id]); + expect(relay.messages.length, 1); + expect(MeChatCreation.pending(service()), isNull); + }, + ); + for (final accepted in [false, true]) { + test( + 'expired first message resumes without duplication: accepted=$accepted', + () async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final owner = nostr.Keys.generate(); + final relay = _MessageRelay(); + final sync = MeSync( + relay, + RelayConfig(baseUrl: 'https://relay.test', nsec: owner.nsec), + prefs: prefs, + ); + final old = NostrEvent.fromJson( + signNostrEvent( + kind: 9, + content: 'Yesterday’s draft', + tags: [ + ['h', 'chat'], + ['p', 'agent'], + ], + secretKey: owner.secret, + createdAt: DateTime.now().millisecondsSinceEpoch ~/ 1000 - 86400, + ).toMap(), + ); + if (accepted) relay.messages[old.id] = old; + final intent = MeChatCreation( + 'chat', + 'Yesterday’s draft', + 'agent', + initialMessage: old, + ); + Future run(MeChatCreation intent) => intent.complete( + sync, + findChannel: () async => 'chat', + createChannel: () async => throw StateError('already created'), + hasAgent: () async => true, + addAgent: () async => throw StateError('already joined'), + isPlaced: () async => true, + place: () async => throw StateError('already placed'), + ); + if (!accepted) { + await expectLater(run(intent), throwsStateError); + await prefs.reload(); + final pending = MeChatCreation.pending(sync)!; + expect(pending.initialMessage!.id, isNot(old.id)); + expect(pending.initialMessage!.content, old.content); + expect(pending.initialMessage!.pubkey, owner.public); + expect(pending.initialMessage!.tags, old.tags); + expect(await run(pending), 'chat'); + expect(relay.attempts.toSet(), {pending.initialMessage!.id}); + } else { + expect(await run(intent), 'chat'); + expect(relay.attempts, isEmpty); + } + expect(relay.messages.length, 1); + expect(MeChatCreation.pending(sync), isNull); + }, + ); + } test( 'retry confirms persistence after a failed cached journal write', () async { @@ -211,3 +345,26 @@ class _FailingStore extends InMemorySharedPreferencesStore { return super.setValue(valueType, key, value); } } + +class _MessageRelay extends RelaySessionNotifier { + final messages = {}; + final attempts = []; + @override + Future> fetchHistory( + NostrFilter filter, { + Duration timeout = const Duration(seconds: 8), + }) async => [ + for (final message in messages.values) + if (filter.ids!.contains(message.id)) message, + ]; + @override + Future publish( + NostrEvent event, { + Duration timeout = const Duration(seconds: 8), + }) async { + attempts.add(event.id); + messages[event.id] = event; + if (attempts.length == 1) throw StateError('Acknowledgement lost'); + return event; + } +} diff --git a/mobile/test/shared/me/me_groups_test.dart b/mobile/test/shared/me/me_groups_test.dart index 0dce29f48b..a12e762345 100644 --- a/mobile/test/shared/me/me_groups_test.dart +++ b/mobile/test/shared/me/me_groups_test.dart @@ -3,6 +3,25 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:buzz/shared/me/me_groups.dart'; void main() { + test( + 'moving to No workspace removes the old assignment and retains the chat', + () { + const groups = MeGroups( + groups: [ + {'id': 'work', 'name': 'Work', 'defaultTemplateId': ''}, + ], + channels: ['chat', 'other'], + assignments: {'chat': 'work', 'other': 'work'}, + ); + final unfiled = groups.place('chat', clearGroup: true); + expect(unfiled.assignments, {'other': 'work'}); + expect(unfiled.channels, ['chat', 'other']); + expect( + unfiled.place('chat', group: 'work').assignments, + groups.assignments, + ); + }, + ); const origin = 'https://buzz.block.builderlab.xyz'; const channel = '11111111-1111-4111-8111-111111111111'; Map record() => { diff --git a/scripts/test-mobile-setting-menu.sh b/scripts/test-mobile-setting-menu.sh index 59e79f8bac..c282408d39 100755 --- a/scripts/test-mobile-setting-menu.sh +++ b/scripts/test-mobile-setting-menu.sh @@ -7,6 +7,8 @@ flutter_root=$(sed -n 's/^FLUTTER_ROOT=//p' "$repo_root/mobile/ios/Flutter/Gener frameworks="$flutter_root/bin/cache/artifacts/engine/ios/Flutter.xcframework/ios-arm64_x86_64-simulator" fixture=$(mktemp -d) trap 'rm -r "$fixture"' EXIT +mkdir -p "$fixture/Frameworks/App.framework/flutter_assets/assets/fonts" +cp "$repo_root/mobile/assets/fonts/TablerIcons.ttf" "$fixture/Frameworks/App.framework/flutter_assets/assets/fonts/TablerIcons.ttf" # Compile the production menu and invoke its actual UIKit UIActions. cat "$repo_root/mobile/ios/Runner/NativeTabler.swift" \ "$repo_root/mobile/ios/Runner/JumpToLatestGlassButton.swift" \