Files
buzz/mobile/lib/shared/widgets/adaptive_conversation_pane.dart
Tom Brow 42dc2a8c58 feat(mobile): add screen breadcrumbs to diagnostic reports (#9823)
feat(mobile): add screen breadcrumbs to diagnostic reports
Adds screen breadcrumbs to mobile diagnostic reports, so a hang or error
report shows which screens the person was on before it happened. Today
the only breadcrumbs are foreground and background changes.

## Changes

- **Observers:** one `DiagnosticScreenTrail` is shared by an observer on
the root navigator and one on each conversation pane's nested navigator,
where channels, threads, search and activity open. A breadcrumb is left
on push, replace, and when a page is shown again after a pop, a frame
later and only for the page that ends up visible.
- **The screen the person is on:** a route that hosts a pane with a page
open past its first (a phone conversation over the channel list, or a
wide conversation beside it) is named by that page. So closing a
full-screen cover, such as a huddle, over an open channel records
`channel`, not `channelList`.
- **No repeats:** a screen equal to the last one is skipped. A pane host
and its pane's empty first page both name the host, and wide Settings
sections all show Settings, so these leave one crumb. The empty first
page still gives Home its crumb after sign-in.
- **Names come from a fixed list owned by the app:**
`lib/diagnostic_screens.dart` maps page widgets to names such as
`channelList`, `channel`, `thread`, `settings` or `addCommunity`, and
reaches the observers through `diagnosticScreenClassifierProvider`,
which the root scope overrides. Any other page is `other`. Route
settings and page content are never read, so no channel name, ID or text
can reach a breadcrumb.
- **Dialogs, sheets and menus are skipped:** popup routes leave nothing,
and the Duo channel sheet, which is a page route, opts out with
`DiagnosticSheetRoute`.
- **Filter:** adds a `navigation` category to the breadcrumb list. A
navigation breadcrumb leaves with only its screen name, and it is
dropped if that name isn't on the list.
- **No destination:** a build without a reporting destination does
nothing; the observers don't even inspect routes.
- **Spec:** the breadcrumb list, user story 7, and the out-of-scope line
about behavior data.

## Regressions

- **Architecture:** the screen list lives with the app, so `shared/`
gains no imports from features. The shared conversation pane's import
closure is unchanged from main.
- **Performance:** the route walk costs well under a millisecond per
navigation (28 to 155 µs measured, against 58 to 143 ms for the push
frame). Rebuild counts are unchanged with reporting on and off, and
nothing new goes over the network.
- **Confined to reporting builds:** in a build without a destination the
observers return before touching a route.

## Validation

New tests in
[`diagnostic_navigation_test.dart`](https://github.com/block/buzz/blob/tomb/mobile-diag-screen-breadcrumbs/mobile/test/shared/diagnostics/diagnostic_navigation_test.dart):
- the app's list, including `addCommunity` for adding a community and an
unlisted page;
- a root journey: a route whose settings carry an ID records only the
plain name, a dialog and a sheet route leave nothing, and two pops at
once leave only where they end;
- a phone journey with the real pane: Home once, channel, thread and
back, a cover closing back onto the open channel, closing the channel,
and a page with its own pane named once;
- a wide Settings pane where changing sections adds nothing;
- a build with no reporting destination.

Plus filter rows for nameless, unlisted and valid navigation
breadcrumbs.


Full-app run on an iOS simulator at 85a72de, signed in to a test
community: channel list, a channel and its details page, a message's
actions sheet, a thread and back, Search, Activity, Agents, Settings and
its status sheet, the identity-to-desktop confirmation, and the
community switcher's Add Community page. Every flow opened and closed
normally with no Flutter exceptions or error screens.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-22 09:10:13 -08:00

692 lines
27 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:duo_kit/duo_kit.dart';
import '../diagnostics/diagnostic_navigation_observer.dart';
import 'duo_toolbar.dart';
import 'app_route_observer.dart';
import 'covered_route_keyboard_insets.dart';
import 'ios_navigation_metrics.dart';
import 'duo_workspace_scaffold.dart';
import '../theme/theme.dart';
/// Duo uses the phone navigation model in portrait, even on its large display.
/// Callers inside a pane supply the full window size.
bool usesConversationPanes(
BuildContext context, {
FoldStrip? strip,
Size? windowSize,
}) {
final size = windowSize ?? MediaQuery.sizeOf(context);
final rail = strip ?? FoldGeometry.of(context).strip;
// The portrait Duo status cluster becomes a tall top inset, not a side
// strip. Keep that phone layout compact without excluding ordinary iPads.
final phoneStatusCluster = MediaQuery.viewPaddingOf(context).top > 50;
if (defaultTargetPlatform == TargetPlatform.iOS &&
size.height >= size.width &&
(rail != null || phoneStatusCluster || size.shortestSide < 600)) {
return false;
}
final bookDivision = bookDivisionOf(context);
// A landscape phone is wide enough for the breakpoint, but not for two
// usable panes. Fold geometry keeps Duo eligible in its supported poses.
if (size.shortestSide < 600 && rail == null && bookDivision == null) {
return false;
}
return bookDivision != null || size.width - (rail?.width ?? 0) >= 640;
}
/// The active vertical fold, in window coordinates, when held like a book.
Rect? bookDivisionOf(BuildContext context) {
final geometry = FoldGeometry.of(context);
final division = geometry.division;
if (division != null &&
division.axis == Axis.vertical &&
division.isHalfOpened) {
return division.bounds;
}
final native = IosNavigationMetrics.of(context);
return native.windowSize == geometry.size ? native.bookDivision : null;
}
final _compactPaneNavigators = Expando<GlobalKey<NavigatorState>>();
/// Unwinds a compact destination for a shortcut, without bypassing page vetoes.
/// Returns false for other layouts or when a nested page refuses to close.
bool popCompactConversationDestination(Route<dynamic> route) {
final navigator = _compactPaneNavigators[route]?.currentState;
if (navigator == null) return false;
var cleared = false;
navigator.popUntil((nested) {
if (nested.popDisposition == RoutePopDisposition.doNotPop) return true;
cleared = nested.isFirst;
return cleared;
});
return cleared;
}
/// Selection belongs to the workspace, rather than to a particular display pose.
class ConversationPaneController extends ChangeNotifier {
final _nativeHeaderKey = GlobalKey();
String? selectedId;
WidgetBuilder? detailBuilder;
bool animateSelection = true;
int _request = 0;
// Deep-link requests may target the same item after its nested route popped.
// A fresh page identity reruns initialization without clearing the selection
// when Navigator removes the previous page.
LocalKey get selectionKey => ValueKey((selectedId, _request));
void open(
String id,
WidgetBuilder builder, {
bool animate = true,
bool reopen = false,
}) {
if (id == selectedId && !reopen) return;
if (reopen) _request++;
selectedId = id;
detailBuilder = builder;
animateSelection = animate;
notifyListeners();
}
void clear() {
if (selectedId == null) return;
selectedId = null;
detailBuilder = null;
notifyListeners();
}
}
class ConversationPaneScope
extends InheritedNotifier<ConversationPaneController> {
ConversationPaneScope({
required ConversationPaneController controller,
required Widget child,
bool active = true,
super.key,
}) : super(
notifier: controller,
child: _ConversationPaneActive(active: active, child: child),
);
/// Only the selected page owns the pane's implicit root navigation.
/// Imperatively pushed pages retain ordinary Back navigation.
static bool isBaseRouteOf(BuildContext context) {
final controller = maybeOf(context);
final settings = ModalRoute.of(context)?.settings;
return controller?.selectedId != null &&
settings is Page &&
settings.key == controller!.selectionKey;
}
/// Keeps the native header surface alive across immediate sidebar selections.
/// Conversation state still belongs to its separately keyed route.
static GlobalKey? nativeHeaderKeyOf(BuildContext context) {
final controller = maybeOf(context);
if (!isBaseRouteOf(context) || !_isWide(context)) return null;
return controller?._nativeHeaderKey;
}
/// A replaced zero-duration page can remain mounted until frame cleanup.
/// It must relinquish the shared header before the next page adopts it.
static bool isReplacedBaseRouteOf(BuildContext context) {
final settings = ModalRoute.of(context)?.settings;
return settings is _ConversationDetailPage &&
!isBaseRouteOf(context) &&
_isWide(context);
}
static bool _isWide(BuildContext context) => usesConversationPanes(
context,
windowSize:
View.of(context).physicalSize / View.of(context).devicePixelRatio,
);
/// Depends only on [active], which flips whenever a route covers the pane,
/// so readers of [maybeOf] (rows, the list) don't rebuild with it.
static bool isActiveOf(BuildContext context) =>
context
.dependOnInheritedWidgetOfExactType<_ConversationPaneActive>()
?.active ??
true;
static ConversationPaneController? maybeOf(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<ConversationPaneScope>()
?.notifier;
}
class _ConversationPaneActive extends InheritedWidget {
const _ConversationPaneActive({required this.active, required super.child});
final bool active;
@override
bool updateShouldNotify(_ConversationPaneActive oldWidget) =>
active != oldWidget.active;
}
/// Keeps both the list and its detail navigator mounted across compact/regular
/// layouts, so opening or closing Duo does not recreate the composer or thread.
class AdaptiveConversationPane extends HookConsumerWidget {
const AdaptiveConversationPane({
required this.controller,
required this.list,
this.active = true,
this.strip,
this.emptyLabel = 'Select a conversation',
this.emptyContent,
this.listWidthFraction,
this.preferredListWidth,
this.persistentSelection = false,
this.listToolbarSlots = 0,
super.key,
});
final bool persistentSelection;
/// Rail slots reserved for workspace controls that stay active in wide mode.
final int listToolbarSlots;
/// Optional list share of the usable width; defaults to the compact sidebar.
final double? listWidthFraction;
/// Preferred sidebar width, capped at half the usable area for narrow windows.
final double? preferredListWidth;
final String emptyLabel;
final Widget? emptyContent;
final FoldStrip? strip;
final ConversationPaneController controller;
final Widget list;
final bool active;
@override
Widget build(BuildContext context, WidgetRef ref) {
final routeObserver = useMemoized(appRouteObserver.createNestedObserver);
final screenObserver = useMemoized(
ref.read(diagnosticScreenTrailProvider).observer,
);
useEffect(() => screenObserver.dispose, [screenObserver]);
final navigator = useMemoized(() => GlobalKey<NavigatorState>());
final ownerRoute = ModalRoute.of(context);
useEffect(() {
return () {
if (ownerRoute != null &&
_compactPaneNavigators[ownerRoute] == navigator) {
_compactPaneNavigators[ownerRoute] = null;
}
};
}, [ownerRoute, navigator]);
// The compact detail route that fully covers the list. While a detail
// pushes, pops or follows a back swipe, the list stays painted beneath it.
final coveringDetail = useValueNotifier<Route<Object?>?>(null);
// Compact detail routes still mounted. A pop clears the selection as it
// starts, so the detail stays onstage until its reverse transition ends.
// Not disposed with the pane: a detail unmounting with the pane reports
// after the frame, once the pane is gone.
final mountedDetails = useMemoized(() => ValueNotifier(0));
return ConversationPaneScope(
controller: controller,
active: active && (ModalRoute.isCurrentOf(context) ?? true),
child: ListenableBuilder(
listenable: controller,
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final stripWidth = strip?.width ?? 0;
final leftInset = strip?.side == FoldStripSide.left
? stripWidth
: 0.0;
final rightInset = strip?.side == FoldStripSide.right
? stripWidth
: 0.0;
final contentWidth = constraints.maxWidth - stripWidth;
final wide = usesConversationPanes(context, strip: strip);
final book = wide ? bookDivisionOf(context) : null;
final selected = controller.selectedId;
if (ownerRoute != null) {
_compactPaneNavigators[ownerRoute] =
active && !wide && selected != null ? navigator : null;
}
// Pane surfaces meet at the fold so their header backdrops remain
// continuous. Content insets below keep controls out of its bounds.
final listWidth = book != null
? book.center.dx - leftInset
: wide
? listWidthFraction == null
? preferredListWidth?.clamp(
0.0,
(contentWidth - 1) / 2,
) ??
(contentWidth / 3).clamp(280.0, 360.0)
: (contentWidth - 1) * listWidthFraction!
: constraints.maxWidth;
final detailLeft =
book?.center.dx ?? (wide ? listWidth + leftInset + 1 : 0.0);
return TweenAnimationBuilder<Offset>(
tween: Tween(end: Offset(listWidth, detailLeft)),
duration: wide && !MediaQuery.disableAnimationsOf(context)
? const Duration(milliseconds: 240)
: Duration.zero,
curve: Curves.easeInOutCubic,
builder: (context, geometry, _) {
final listWidth = geometry.dx;
final detailLeft = geometry.dy;
final detailWidth = constraints.maxWidth - detailLeft;
return Stack(
fit: StackFit.expand,
children: [
Positioned(
left: 0,
top: 0,
bottom: 0,
width: wide ? listWidth + leftInset : listWidth,
child: ValueListenableBuilder(
valueListenable: coveringDetail,
builder: (context, covering, list) => Offstage(
offstage:
!wide &&
selected != null &&
(covering?.isActive ?? false),
child: list,
),
child: _CoveredList(
covered: !wide && selected != null,
child: MediaQueryOverride(
transform: (media) => media.copyWith(
size: Size(listWidth, constraints.maxHeight),
),
child: DuoToolbarScope(
strip: strip,
contentInsets: EdgeInsets.only(
left: leftInset,
right: wide
? (book?.width ?? 0) / 2
: rightInset,
),
active:
active &&
(selected == null ||
(wide &&
(persistentSelection ||
listToolbarSlots > 0))) &&
(ModalRoute.isCurrentOf(context) ?? true),
child: list,
),
),
),
),
),
Positioned(
left: detailLeft,
top: 0,
bottom: 0,
width: detailWidth,
child: ValueListenableBuilder<int>(
valueListenable: mountedDetails,
builder: (context, mounted, detail) {
final shown = wide || selected != null || mounted > 0;
return Offstage(
offstage: !shown,
child: TickerMode(enabled: shown, child: detail!),
);
},
child: MediaQueryOverride(
transform: (media) => media.copyWith(
size: Size(detailWidth, constraints.maxHeight),
),
child: DuoToolbarScope(
strip: strip,
leadingSlots: wide ? listToolbarSlots : 0,
contentInsets: EdgeInsets.only(
left: wide ? (book?.width ?? 0) / 2 : leftInset,
right: rightInset,
),
active:
active &&
selected != null &&
(ModalRoute.isCurrentOf(context) ?? true),
child: Semantics(
container: true,
explicitChildNodes: true,
child: PopScope<Object?>(
canPop:
!active ||
selected == null ||
(wide && persistentSelection),
onPopInvokedWithResult: (didPop, result) {
if (!didPop &&
active &&
selected != null &&
!(wide && persistentSelection)) {
navigator.currentState!.maybePop(result);
}
},
child: ExcludeFocus(
excluding: selected == null,
child: NavigatorPopHandler<Object?>(
enabled: wide && persistentSelection,
onPopWithResult: (result) =>
navigator.currentState!.pop(result),
child: Navigator(
requestFocus: selected != null,
key: navigator,
observers: [
routeObserver,
screenObserver,
],
pages: [
if (!(wide &&
persistentSelection &&
selected != null))
MaterialPage<void>(
key: const ValueKey(
'conversation-placeholder',
),
// Compact panes show the list
// through this page while a
// detail pushes or pops.
child: !wide
? const SizedBox.shrink()
: Material(
color:
context.colors.surface,
child: Center(
child:
emptyContent ??
Text(
emptyLabel,
textAlign: TextAlign
.center,
style: Theme.of(context)
.textTheme
.bodyLarge
?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
decoration:
TextDecoration
.none,
),
),
),
),
),
if (selected != null)
_ConversationDetailPage(
key: controller.selectionKey,
animate:
!wide &&
controller.animateSelection,
child: _CoveringDetail(
covering: coveringDetail,
mounted: mountedDetails,
builder:
controller.detailBuilder!,
),
),
],
onDidRemovePage: (page) {
if (page.key ==
controller.selectionKey) {
controller.clear();
}
},
),
),
),
),
),
),
),
),
),
if (wide)
Positioned(
left: listWidth + leftInset,
top: 0,
bottom: 0,
width: 1,
child: IgnorePointer(
child: ColoredBox(
color: context.colors.outlineVariant,
),
),
),
],
);
},
);
},
),
),
);
}
}
/// Hides the compact list from input, focus and screen readers while a
/// detail sits above it, even during a transition that still paints it.
class _CoveredList extends StatelessWidget {
const _CoveredList({required this.covered, required this.child});
final bool covered;
final Widget child;
@override
Widget build(BuildContext context) => TickerMode(
enabled: !covered,
child: IgnorePointer(
ignoring: covered,
child: ExcludeFocus(
excluding: covered,
child: ExcludeSemantics(
excluding: covered,
// A detail's keyboard must not relayout the list it covers. The
// scope keeps the detail's focus from counting as the list's own.
child: FocusScope(
child: CoveredRouteKeyboardInsets(isCovered: covered, child: child),
),
),
),
),
);
}
/// Derives [child]'s [MediaQuery] in a leaf, so the caller's build does not
/// depend on every field (keyboard insets change on each animation frame).
class MediaQueryOverride extends StatelessWidget {
const MediaQueryOverride({
required this.transform,
required this.child,
super.key,
});
final MediaQueryData Function(MediaQueryData) transform;
final Widget child;
@override
Widget build(BuildContext context) =>
MediaQuery(data: transform(MediaQuery.of(context)), child: child);
}
/// Reports its route as [covering] once the route fully covers the compact
/// list, and withdraws it while the route pushes, pops or follows a back swipe.
class _CoveringDetail extends HookWidget {
const _CoveringDetail({
required this.covering,
required this.mounted,
required this.builder,
});
final ValueNotifier<Route<Object?>?> covering;
/// Counts mounted details. A popped route unmounts its content only once
/// its reverse transition has finished.
final ValueNotifier<int> mounted;
final WidgetBuilder builder;
@override
Widget build(BuildContext context) {
final route = ModalRoute.of(context);
final navigator = Navigator.of(context);
useEffect(() {
// The count rebuilds an ancestor, which cannot rebuild while this
// mounts or unmounts.
WidgetsBinding.instance.addPostFrameCallback((_) => mounted.value++);
return () =>
WidgetsBinding.instance.addPostFrameCallback((_) => mounted.value--);
}, [mounted]);
useEffect(() {
if (route == null) return null;
void sync() {
final settled =
route.animation?.status != AnimationStatus.forward &&
route.animation?.status != AnimationStatus.reverse &&
!navigator.userGestureInProgress;
if (settled && route.isCurrent) {
covering.value = route;
} else if (covering.value == route) {
covering.value = null;
}
}
void syncStatus(AnimationStatus _) => sync();
route.animation?.addStatusListener(syncStatus);
navigator.userGestureInProgressNotifier.addListener(sync);
// An immediate route can settle before these listeners attach.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (context.mounted) sync();
});
return () {
route.animation?.removeStatusListener(syncStatus);
navigator.userGestureInProgressNotifier.removeListener(sync);
};
}, [route, navigator]);
return builder(context);
}
}
/// Keeps the route identity stable across layout changes. Sidebar selections
/// are immediate; compact navigation retains the platform push and back swipe.
class _ConversationDetailPage extends MaterialPage<void> {
const _ConversationDetailPage({
required this.animate,
required super.child,
super.key,
});
final bool animate;
@override
Route<void> createRoute(BuildContext context) =>
_ConversationDetailRoute(this);
}
class _ConversationDetailRoute extends MaterialPageRoute<void> {
_ConversationDetailRoute(_ConversationDetailPage page)
: super(builder: (_) => page.child, settings: page);
_ConversationDetailPage get _page => settings as _ConversationDetailPage;
@override
Widget buildContent(BuildContext context) => _page.child;
@override
Duration get transitionDuration =>
_page.animate ? super.transitionDuration : Duration.zero;
@override
Duration get reverseTransitionDuration =>
_page.animate ? super.reverseTransitionDuration : Duration.zero;
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) => super.buildTransitions(
context,
_page.animate ? animation : kAlwaysCompleteAnimation,
secondaryAnimation,
child,
);
}
/// Opens a result in its workspace's detail pane, or an ordinary pushed route.
Future<void> openConversationPane(
BuildContext context,
String selectionId,
WidgetBuilder builder, {
bool reopen = false,
}) async {
final pane = ConversationPaneScope.maybeOf(context);
if (pane != null) {
pane.open(selectionId, builder, reopen: reopen);
} else {
await Navigator.of(context).push(MaterialPageRoute<void>(builder: builder));
}
}
/// A list/detail workspace for destinations such as Search and Inbox.
class AdaptiveConversationDestination extends HookConsumerWidget {
const AdaptiveConversationDestination({
required this.child,
this.emptyLabel = 'Select a conversation',
this.listWidthFraction,
this.controller,
this.persistentSelection = false,
this.listToolbarSlots = 0,
this.preferredListWidth,
super.key,
});
/// Optional list share of the usable width; defaults to the compact sidebar.
final ConversationPaneController? controller;
final bool persistentSelection;
/// Rail slots reserved for workspace controls that stay active in wide mode.
final int listToolbarSlots;
/// Preferred sidebar width, capped to preserve room for its detail pane.
final double? preferredListWidth;
final double? listWidthFraction;
final String emptyLabel;
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final ownedController = useMemoized(ConversationPaneController.new);
useEffect(() => ownedController.dispose, [ownedController]);
final controller = this.controller ?? ownedController;
final strip = FoldGeometry.of(context).strip;
return ColoredBox(
color: context.colors.surface,
child: DuoWorkspaceScaffold(
navigationBuilder: (_, _) => const SizedBox.shrink(),
body: MediaQueryOverride(
transform: (media) => media.removePadding(
removeLeft: strip?.side == FoldStripSide.left,
removeRight: strip?.side == FoldStripSide.right,
),
child: AdaptiveConversationPane(
active: DuoToolbarScope.maybeOf(context)?.active ?? true,
controller: controller,
persistentSelection: persistentSelection,
listToolbarSlots: listToolbarSlots,
emptyLabel: emptyLabel,
listWidthFraction: listWidthFraction,
preferredListWidth: preferredListWidth,
strip: strip,
list: child,
),
),
),
);
}
}