Merge main into chat tab re-tap

This commit is contained in:
2026-11-12 03:52:20 +00:00
66 changed files with 4417 additions and 530 deletions
+3 -1
View File
@@ -376,7 +376,9 @@ class _PipelinesAppState extends State<PipelinesApp>
},
sessionTitle: _chatSessionTitle,
openChat: (id) {
if (mounted) _delegate.goTo(AppRoute.chatSession(id));
if (!mounted) return;
widget.servers?.requestChatOpen(id);
_delegate.goTo(AppRoute.chatSession(id));
},
bridge: _notifications.bridge,
);
+36 -29
View File
@@ -5,6 +5,7 @@ import '../../core/servers/server_context.dart';
import '../../shell/destination.dart';
import '../../shell/detail_page.dart';
import 'chat_runtime.dart';
import 'conversation/chat_seen_interaction.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/composer_focus_request.dart';
import 'workspace/chat_pane_commands.dart';
@@ -79,36 +80,42 @@ Widget buildChatPaneContent({
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
ChatSeenInteraction(
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) => runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) => runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
paneCommands: placement.paneCommands,
onInteract: () => runtime.sessions.reportInteraction(sessionId),
child: ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) =>
runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) =>
runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
paneCommands: placement.paneCommands,
),
),
),
);
@@ -46,6 +46,7 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
final pane = _workspace.detach(paneId);
if (pane == null) return;
widget.windows?.float(pane.sessionId);
_syncOpenWorkspace();
// Floating the last tiled chat leaves the list, as closing it does.
if (_workspace.paneCount == 0) _back();
}
@@ -61,6 +62,7 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
_floatPane(pane.id);
} else {
windows.float(id);
_syncOpenWorkspace();
}
}
@@ -69,6 +71,7 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
_workspaceVisible = true;
if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true;
_workspace.dock(sessionId);
_syncOpenWorkspace();
_composerFocus.request(sessionId);
}
@@ -80,11 +80,61 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
void _openSidebarSession(JsonMap session);
final ChatWorkspaceController _workspace = ChatWorkspaceController();
ChatOpenWorkspaceController? _openWorkspace;
bool _applyingServerWorkspace = false;
ChatWorkspaceBinding? _workspaceBinding;
String? _workspaceScope;
Iterable<ChatOpenWorkspaceEntry> _serverWorkspaceEntries() sync* {
final floating =
widget.windows?.floatingSessionIds.toSet() ?? const <String>{};
for (final pane in _workspace.panes) {
yield ChatOpenWorkspaceEntry(
pane.sessionId,
floating: floating.contains(pane.sessionId),
);
}
for (final sessionId in floating) {
if (!_workspace.holdsSession(sessionId)) {
yield ChatOpenWorkspaceEntry(sessionId, floating: true);
}
}
}
/// Sends this device's open chats to the server, unless the change is the
/// server's own snapshot being applied.
void _syncOpenWorkspace() {
if (_applyingServerWorkspace) return;
_openWorkspace?.replace(_serverWorkspaceEntries());
}
/// Binds the server's open-chat set for [widget.gateway], disposing the
/// previous binding (its subscription and queued writes) first. A
/// federated list spans several servers, so it keeps its local layout.
void _bindOpenWorkspace({required Future<void> after}) {
_openWorkspace?.dispose();
_openWorkspace = null;
_openWorkspaceApplied = false;
if (!widget.persistWorkspace || widget.gateway is FederatedChatGateway) {
return;
}
final open = ChatOpenWorkspaceController(gateway: widget.gateway)
..onChanged = _applyOpenWorkspace;
_openWorkspace = open;
// Seed from the restored local layout once it is restored.
unawaited(
after.then((_) async {
if (!mounted || open.disposed) return;
await open.start(local: _serverWorkspaceEntries());
}),
);
}
void _bindWorkspacePersistence() {
if (!widget.persistWorkspace) return;
if (!widget.persistWorkspace) {
_bindOpenWorkspace(after: Future.value());
return;
}
final scope = serverStorageScope(serverIdentity(widget.gateway));
_workspaceScope = scope;
_workspaceBinding = ChatWorkspaceBinding(
@@ -112,19 +162,105 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
_publishWorkspaceRoute();
},
);
unawaited(
_workspaceBinding!.start(initialSessionId: widget.initialSessionId),
_bindOpenWorkspace(
after: _workspaceBinding!.start(
initialSessionId: widget.initialSessionId,
),
);
}
/// Whether a server snapshot was applied since binding. The first one keeps
/// the chat this visit was opened on (a deep link) and adds it if absent.
bool _openWorkspaceApplied = false;
/// Applies the server's membership: windows and panes for chats it no
/// longer lists close, floating state follows it, and tiled chats take its
/// order while this device's split geometry stays.
void _applyOpenWorkspace(ChatOpenWorkspaceSnapshot snapshot) {
if (!mounted) return;
final initial = widget.initialSessionId ?? '';
final first = !_openWorkspaceApplied;
final keepInitial =
first &&
initial.isNotEmpty &&
!snapshot.entries.any((entry) => entry.sessionId == initial);
_openWorkspaceApplied = true;
if (keepInitial) {
snapshot = ChatOpenWorkspaceSnapshot(snapshot.revision, [
...snapshot.entries,
ChatOpenWorkspaceEntry(initial),
]);
}
_applyingServerWorkspace = true;
try {
final windows = widget.windows;
if (windows != null) {
final entriesBySession = {
for (final entry in snapshot.entries) entry.sessionId: entry,
};
for (final window in windows.windows.toList()) {
if (!entriesBySession.containsKey(window.contentId)) {
windows.manager.close(window.id);
}
}
for (final entry in snapshot.entries) {
final localWindow = windows.windows
.where((window) => window.contentId == entry.sessionId)
.firstOrNull;
if (entry.floating && localWindow == null) {
final pane = _workspace.panes
.where((pane) => pane.sessionId == entry.sessionId)
.firstOrNull;
if (pane != null) _workspace.close(pane.id);
windows.float(entry.sessionId);
} else if (!entry.floating && localWindow != null) {
windows.dock(localWindow);
}
}
}
_workspace.reconcileSessions(
snapshot.entries
.where((entry) => !entry.floating)
.map((entry) => entry.sessionId),
);
if (keepInitial) {
final pane = _workspace.panes
.where((pane) => pane.sessionId == initial)
.firstOrNull;
if (pane != null) _workspace.activate(pane.id);
}
if (_workspace.paneCount == 0 && _workspaceVisible) _back();
} finally {
_applyingServerWorkspace = false;
}
// The first snapshot shows the server's chats as a restored layout does;
// later ones never pull this device into a chat another one opened.
if (first && _workspace.paneCount > 0 && !_workspaceVisible) {
setState(() {
_usedWorkspace = true;
_workspaceVisible = true;
});
_publishWorkspaceRoute();
}
if (keepInitial) _syncOpenWorkspace();
}
bool _updateWorkspacePersistence(ChatScreen oldWidget) {
final scope = serverStorageScope(serverIdentity(widget.gateway));
if (oldWidget.persistWorkspace == widget.persistWorkspace &&
(!widget.persistWorkspace || scope == _workspaceScope)) {
// Another connection to the same server: only the open-chat sync
// follows the gateway.
if (widget.persistWorkspace &&
!identical(oldWidget.gateway, widget.gateway)) {
_bindOpenWorkspace(after: Future.value());
}
return false;
}
_workspaceBinding?.dispose();
_workspaceBinding = null;
_openWorkspace?.dispose();
_openWorkspace = null;
if (_workspaceScope != null && scope != _workspaceScope) {
_workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!);
_workspaceVisible = false;
@@ -200,6 +336,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
if (_workspaceSignature == signature) return;
_workspaceSignature = signature;
_syncOpenWorkspace();
void update() {
if (!mounted) return;
setState(() {});
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import 'chat_background_tasks_controller.dart';
import 'chat_background_tasks_dialog.dart';
import 'chat_task_spinner.dart';
/// Compact live task count: a quiet control inside the composer beside Send,
/// shown only while tasks run. Details live only in its modal.
@@ -146,10 +147,13 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
visualDensity: VisualDensity.compact,
),
onPressed: _open,
icon: Icon(
automationOnly ? Icons.schedule : Icons.layers_outlined,
size: 16,
),
// The layers turn only while a task runs; automations stay still.
icon: automationOnly
? const Icon(Icons.schedule, size: 16)
: ChatTaskSpinner(
spinning: count > 0,
child: const Icon(Icons.layers_outlined, size: 16),
),
label: caption(),
);
return Padding(
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import '../../../ui/scale/ui_scale.dart';
import '../../../ui/motion/surface_visibility.dart';
import 'chat_stop_icon.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
@@ -30,6 +29,7 @@ import 'composer_focus_request.dart';
import 'composer_focus_restore.dart';
import 'chat_bar_tint.dart';
import 'composer_focus_ring.dart';
import 'composer_running_border.dart';
import '../shell/chat_shell_command.dart';
import '../shell/chat_shell_mode_indicator.dart';
@@ -70,8 +70,10 @@ double chatComposerBottomMargin([TargetPlatform? platform]) =>
? kChatComposerDesktopBottomMargin
: kChatComposerBottomMargin;
/// The single primary control's words while a turn is and is not running.
/// The single primary control's words.
const String chatSendLabel = 'Send';
/// The chat's More-menu word for stopping a running turn.
const String chatStopLabel = 'Stop';
/// The primary control's words while the draft is a `!` shell command.
@@ -95,7 +97,8 @@ const String chatQueuedNotice =
'Queued — it will send when the current turn finishes.';
/// The foot of one conversation: a native multiline field and Send control,
/// with a separate Stop while a turn runs, driven by [ChatComposerController].
/// driven by [ChatComposerController]. A running turn shows a travelling
/// border, not a stop control.
///
/// The field owns only its [TextEditingController] and focus; the durable draft
/// text lives in the composer controller, so a live transcript rebuild never
@@ -153,7 +156,7 @@ class ChatComposerBar extends StatefulWidget {
/// session (null) keeps those commands on the unavailable report.
final ChatCommandActions? commands;
/// The thread controller's running bit; shows Stop without hiding Send.
/// The thread controller's running bit; shows the running border.
final bool running;
/// The host picker seam; production uses [hostChatAttachmentPicker].
@@ -400,6 +403,13 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
}
/// Whether a send completes the palette's highlighted row instead of running
/// the draft. A draft that already names a whole command (`/stop`) runs on
/// the first send; only a partial word is completed first.
bool _paletteCompletes() =>
_paletteCommands().isNotEmpty &&
chatCommandNamed(widget.composer.draft) == null;
/// The recorded commands matching the current draft while the palette is
/// open. A dismissed or completed draft keeps its palette closed until the
/// operator types something newer.
@@ -512,8 +522,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
(keyboard.isShiftPressed || keyboard.isAltPressed)) {
return;
}
final commands = _paletteCommands();
if (commands.isNotEmpty) {
if (_paletteCompletes()) {
final commands = _paletteCommands();
_completeCommand(commands[_selectedCommand % commands.length]);
return;
}
@@ -943,10 +953,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
),
child: widget.backgroundTasks!,
),
if (widget.running) ...[
_primary(context, stop: true),
const SizedBox(width: 4),
],
_primary(context),
],
),
@@ -973,21 +979,41 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// the transcript, so the composer reads as a single input rather than a
/// row of separate controls, and the conversation shows through it. While
/// the field has focus a ring in the chat's colour runs along its edge.
Widget _pill(BuildContext context, Widget child) => ComposerFocusRing(
focus: _focus,
accent: chatFocusRingColor(context, widget.chatColor),
shape: _pillShape,
child: GlassPill(
key: const Key('chat-composer-pill'),
shape: _pillShape,
// The end controls keep the same gap from the pill's sides as from
// its bottom (and its top while the field is one line).
child: Padding(
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
child: child,
),
),
);
///
/// While a turn runs a highlight travels around the same edge
/// ([ComposerRunningBorder]); it is mounted only for that time.
Widget _pill(BuildContext context, Widget child) {
final accent = chatFocusRingColor(context, widget.chatColor);
return Stack(
children: [
ComposerFocusRing(
focus: _focus,
accent: accent,
shape: _pillShape,
child: GlassPill(
key: const Key('chat-composer-pill'),
shape: _pillShape,
// The end controls keep the same gap from the pill's sides as from
// its bottom (and its top while the field is one line).
child: Padding(
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
child: child,
),
),
),
if (widget.running)
Positioned.fill(
child: IgnorePointer(
child: ComposerRunningBorder(
shape: _pillShape,
primary: accent,
tertiary: Theme.of(context).colorScheme.tertiary,
),
),
),
],
);
}
/// The attach control: a host button that opens the picker, disabled when the
/// host has no picker or one prompt is already awaiting its reply.
@@ -1167,21 +1193,19 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
}
Widget _primary(BuildContext context, {bool stop = false}) {
/// The single primary control: Send (or Run command for a `!` draft). A
/// prompt sent while a turn runs takes the server's queued-prompt path; the
/// running turn is stopped by Escape twice, `/stop`, or the More menu.
Widget _primary(BuildContext context) {
final composer = widget.composer;
final enabled = stop
? !composer.stopping
: !_uploading &&
!_shellStarting &&
!composer.sending &&
composer.draft.trim().isNotEmpty;
final enabled =
!_uploading &&
!_shellStarting &&
!composer.sending &&
composer.draft.trim().isNotEmpty;
void press() {
if (stop) {
unawaited(composer.stop());
return;
}
final commands = _paletteCommands();
if (commands.isNotEmpty) {
if (_paletteCompletes()) {
final commands = _paletteCommands();
_completeCommand(commands[_selectedCommand % commands.length]);
} else if (chatDraftIsShell(composer.draft)) {
unawaited(_runShellDraft());
@@ -1192,36 +1216,23 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
}
}
// Sending while the turn runs uses the server's existing queued-prompt path.
// Stopping is always a separate, explicitly named action.
final label = stop
? chatStopLabel
: chatDraftIsShell(composer.draft)
final label = chatDraftIsShell(composer.draft)
? chatRunShellLabel
: chatSendLabel;
final key = Key(stop ? 'chat-composer-stop' : 'chat-composer-primary');
// A coloured chat's send button takes the chat's colour (its seeded
// primary, like the focus ring); stop stays the host's error red.
// primary, like the focus ring).
final tinted = chatSchemeOf(context, widget.chatColor);
final scheme = Theme.of(context).colorScheme;
return IconButton.filled(
key: key,
key: const Key('chat-composer-primary'),
tooltip: label,
style: stop
? IconButton.styleFrom(
backgroundColor: scheme.error,
foregroundColor: scheme.onError,
)
: tinted == null
style: tinted == null
? null
: IconButton.styleFrom(
backgroundColor: tinted.primary,
foregroundColor: tinted.onPrimary,
),
onPressed: enabled ? press : null,
icon: stop
? const ChatStopIcon(child: Icon(Icons.stop))
: const Icon(Icons.arrow_upward),
icon: const Icon(Icons.arrow_upward),
);
}
@@ -0,0 +1,119 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// The longest gap between two Escape presses that still stops a running turn.
const Duration chatEscapeStopWindow = Duration(seconds: 1);
/// The hint shown after the first Escape while a turn runs.
const String chatEscapeStopHint = 'Press Esc again to stop';
/// Two presses of Escape stop a running turn: the first shows [chatEscapeStopHint]
/// and the second, inside [chatEscapeStopWindow], stops it. Pure timing, so the
/// clock is the caller's.
class ChatEscapeStopTracker {
DateTime? _firstAt;
/// Records one plain Escape press at [now]. Returns true when it completes a
/// pair; a press that completes nothing starts a new pair.
bool press(DateTime now) {
final first = _firstAt;
if (first != null && now.difference(first) <= chatEscapeStopWindow) {
_firstAt = null;
return true;
}
_firstAt = now;
return false;
}
/// Forgets a pending first press, for example once the turn has ended.
void reset() => _firstAt = null;
}
/// Lets two presses of Escape stop the turn while focus is anywhere inside
/// [child] (the composer or the transcript). It only consumes Escape while
/// [running]; an idle chat, and any Escape a descendant already handled (a
/// command palette, a notice), pass through untouched.
class ChatEscapeStop extends StatefulWidget {
const ChatEscapeStop({
super.key,
required this.running,
required this.onStop,
required this.child,
this.clock = DateTime.now,
});
final bool running;
/// Stops the running turn; called on the second press.
final VoidCallback onStop;
/// Injected time source, so tests control the window.
final DateTime Function() clock;
final Widget child;
@override
State<ChatEscapeStop> createState() => _ChatEscapeStopState();
}
class _ChatEscapeStopState extends State<ChatEscapeStop> {
final ChatEscapeStopTracker _tracker = ChatEscapeStopTracker();
@override
void didUpdateWidget(covariant ChatEscapeStop oldWidget) {
super.didUpdateWidget(oldWidget);
if (!widget.running) _tracker.reset();
}
KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {
if (event.logicalKey != LogicalKeyboardKey.escape || !widget.running) {
return KeyEventResult.ignored;
}
final keyboard = HardwareKeyboard.instance;
if (keyboard.isControlPressed ||
keyboard.isMetaPressed ||
keyboard.isShiftPressed ||
keyboard.isAltPressed) {
return KeyEventResult.ignored;
}
// Holding Escape is one press, and releasing it is not a press at all.
if (event is! KeyDownEvent) {
return event is KeyRepeatEvent
? KeyEventResult.handled
: KeyEventResult.ignored;
}
if (_tracker.press(widget.clock())) {
_tracker.reset();
_hideHint();
widget.onStop();
} else {
_showHint();
}
return KeyEventResult.handled;
}
void _showHint() {
final messenger = ScaffoldMessenger.maybeOf(context);
if (messenger == null) return;
messenger
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(
key: Key('chat-escape-stop-hint'),
content: Text(chatEscapeStopHint),
duration: chatEscapeStopWindow,
behavior: SnackBarBehavior.floating,
),
);
}
void _hideHint() => ScaffoldMessenger.maybeOf(context)?.hideCurrentSnackBar();
@override
Widget build(BuildContext context) => Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: _onKeyEvent,
child: widget.child,
);
}
@@ -0,0 +1,128 @@
import 'package:flutter/rendering.dart' show ScrollDirection;
import 'package:flutter/services.dart'
show HardwareKeyboard, KeyDownEvent, KeyEvent;
import 'package:flutter/widgets.dart';
import '../../../core/servers/server_context.dart';
import '../../settings/server_connections.dart';
/// Reports the user's own actions in one open chat, so the chat can be read.
///
/// Counted: a pointer press anywhere in the pane (click or tap, which also
/// makes it the active pane), a user-driven scroll of its transcript, a key
/// press while focus is inside it (typing, Tab), focus arriving in it from a
/// key press outside it (Tab into the pane), and a notification tap that
/// opened it. Showing the pane, rebuilding it, receiving content, or focus
/// moved in code with no key press does not report anything. [onInteract]
/// decides whether the window is focused.
class ChatSeenInteraction extends StatefulWidget {
const ChatSeenInteraction({
super.key,
required this.sessionId,
required this.onInteract,
required this.child,
});
final String sessionId;
final VoidCallback onInteract;
final Widget child;
@override
State<ChatSeenInteraction> createState() => _ChatSeenInteractionState();
}
class _ChatSeenInteractionState extends State<ChatSeenInteraction> {
ServerConnections? _connections;
/// True from a key-down until the next frame. Focus changes are applied in a
/// microtask queued by the key dispatch, which runs before that frame, so a
/// focus change caused by the key sees the flag. A focus change with no key
/// press (restoration, code-driven focus) never does.
bool _keyDownInProgress = false;
@override
void initState() {
super.initState();
HardwareKeyboard.instance.addHandler(_onKeyEvent);
}
bool _onKeyEvent(KeyEvent event) {
if (event is KeyDownEvent && !_keyDownInProgress) {
_keyDownInProgress = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_keyDownInProgress = false;
});
WidgetsBinding.instance.scheduleFrame();
}
return false;
}
void _onFocusChange(bool hasFocus) {
if (hasFocus && _keyDownInProgress) widget.onInteract();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final connections = ServerContext.maybeOf(context)?.notifier;
if (identical(connections, _connections)) return;
_connections?.removeListener(_takeNotificationOpen);
_connections = connections;
connections?.addListener(_takeNotificationOpen);
_takeNotificationOpen();
}
@override
void didUpdateWidget(covariant ChatSeenInteraction oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.sessionId != widget.sessionId) _takeNotificationOpen();
}
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_onKeyEvent);
_connections?.removeListener(_takeNotificationOpen);
super.dispose();
}
/// A notification tap that named this chat is the user opening it. It is
/// reported after the frame, so the list has taken the chat as active first.
void _takeNotificationOpen() {
final connections = _connections;
if (connections == null ||
!connections.takeChatOpenIntent(widget.sessionId)) {
return;
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) widget.onInteract();
});
}
static bool _userScrolled(ScrollNotification notification) =>
(notification is UserScrollNotification &&
notification.direction != ScrollDirection.idle) ||
(notification is ScrollStartNotification &&
notification.dragDetails != null);
@override
Widget build(BuildContext context) => Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) => widget.onInteract(),
child: NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (_userScrolled(notification)) widget.onInteract();
return false;
},
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onFocusChange: _onFocusChange,
onKeyEvent: (node, event) {
if (event is KeyDownEvent) widget.onInteract();
return KeyEventResult.ignored;
},
child: widget.child,
),
),
);
}
@@ -1,48 +0,0 @@
import 'package:flutter/widgets.dart';
/// Slow, continuous progress motion confined to the Stop glyph. The native
/// button, hit target and semantics never rotate. TickerMode pauses hidden UI.
class ChatStopIcon extends StatefulWidget {
const ChatStopIcon({super.key, required this.child});
final Widget child;
static const period = Duration(seconds: 8);
@override
State<ChatStopIcon> createState() => _ChatStopIconState();
}
class _ChatStopIconState extends State<ChatStopIcon>
with SingleTickerProviderStateMixin {
late final _rotation = AnimationController(
vsync: this,
duration: ChatStopIcon.period,
);
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (MediaQuery.maybeDisableAnimationsOf(context) ?? false) {
_rotation.stop();
_rotation.value = 0;
} else if (!_rotation.isAnimating) {
_rotation.repeat();
}
}
@override
void dispose() {
_rotation.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RepaintBoundary(
key: const Key('chat-stop-paint-boundary'),
child: RotationTransition(
key: const Key('chat-stop-rotation'),
turns: _rotation,
child: widget.child,
),
);
}
@@ -0,0 +1,71 @@
import 'package:flutter/widgets.dart';
/// Turns [child] once every [period] while [spinning]; static otherwise. With
/// reduced motion it never turns. Hidden UI is silenced by TickerMode.
class ChatTaskSpinner extends StatefulWidget {
const ChatTaskSpinner({
super.key,
required this.spinning,
required this.child,
});
final bool spinning;
final Widget child;
/// One full turn while tasks run.
static const Duration period = Duration(milliseconds: 2500);
@override
State<ChatTaskSpinner> createState() => _ChatTaskSpinnerState();
}
class _ChatTaskSpinnerState extends State<ChatTaskSpinner>
with SingleTickerProviderStateMixin {
late final AnimationController _turns = AnimationController(
vsync: this,
duration: ChatTaskSpinner.period,
);
bool _reduced = false;
@override
void initState() {
super.initState();
_sync();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
_sync();
}
@override
void didUpdateWidget(covariant ChatTaskSpinner oldWidget) {
super.didUpdateWidget(oldWidget);
_sync();
}
void _sync() {
if (widget.spinning && !_reduced) {
if (!_turns.isAnimating) _turns.repeat();
} else {
_turns
..stop()
..value = 0;
}
}
@override
void dispose() {
_turns.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RotationTransition(
key: const Key('chat-background-tasks-spinner'),
turns: _turns,
child: widget.child,
);
}
@@ -42,6 +42,7 @@ import 'chat_background_tasks.dart';
import 'chat_command_actions.dart';
import 'chat_composer_bar.dart';
import 'chat_composer_controller.dart';
import 'chat_escape_stop.dart';
import 'chat_delivery_indicator.dart';
import 'chat_draft_store.dart';
import 'chat_effort_control.dart';
@@ -1383,7 +1384,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// The bar and the jump control float over the transcript and the
// composer sits below it; the wheel over them scrolls it, as a page
// scrolls under fixed bars.
final column = VerticalWheelForwarder(controller: _scroll, child: page);
// Two Escape presses stop a running turn while the conversation has
// the keyboard; the wheel over the page still scrolls it.
final column = ChatEscapeStop(
running: _controller.running,
onStop: _stopTurn,
child: VerticalWheelForwarder(controller: _scroll, child: page),
);
final wideFiles =
_filesVisible && MediaQuery.sizeOf(context).width >= 700;
_reportCenterStageFilesWidth();
@@ -1482,6 +1489,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
],
moreActions: [
?widget.sidebarControl,
// Touch devices have no Escape key; the menu is their way to stop.
if (_controller.running)
ChatBarAction(
key: const Key('chat-thread-stop-menu'),
label: chatStopLabel,
identifier: 'chat-thread-stop',
onPressed: _stopTurn,
materialIcon: Icons.stop,
),
// A window's own title bar names the chat, and its narrow action
// bar has no room for the title that opens the details.
if (WindowScope.maybeOf(context) != null)
@@ -1537,6 +1553,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
onChanged: widget.onModeChanged,
);
/// Stops the running turn, as the composer's `/stop` does.
void _stopTurn() => unawaited(_composer.stop());
void _runShellFromMenu() => unawaited(
runChatShellFromMenu(context, _shellRuns, showNotice: _showCommandNotice),
);
@@ -0,0 +1,146 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
/// The composer's "agent is working" edge: a soft highlight that travels once
/// around the pill's rounded border in [primary] and [tertiary], with a faint
/// glow beneath it. Mount it only while a turn runs; disposing it stops the
/// animation, so the border ends cleanly with the turn.
///
/// With reduced motion (the platform's disable-animations setting) it draws
/// a static, evenly highlighted border instead and never ticks.
class ComposerRunningBorder extends StatefulWidget {
const ComposerRunningBorder({
super.key,
required this.shape,
required this.primary,
required this.tertiary,
});
/// The pill's shape, so the highlight follows its edge.
final OutlinedBorder shape;
final Color primary;
final Color tertiary;
/// One lap of the highlight around the border.
static const Duration period = Duration(seconds: 4);
/// The stroke drawn just inside the pill's edge.
static const double strokeWidth = 2;
/// The static border's opacity under reduced motion.
static const double staticOpacity = 0.7;
@override
State<ComposerRunningBorder> createState() => _ComposerRunningBorderState();
}
class _ComposerRunningBorderState extends State<ComposerRunningBorder>
with SingleTickerProviderStateMixin {
late final AnimationController _lap = AnimationController(
vsync: this,
duration: ComposerRunningBorder.period,
);
bool _reduced = false;
@override
void initState() {
super.initState();
_lap.repeat();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
if (reduced == _reduced) return;
_reduced = reduced;
if (reduced) {
_lap.stop();
} else {
_lap.repeat();
}
}
@override
void dispose() {
_lap.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RepaintBoundary(
key: const Key('chat-composer-running-border'),
child: CustomPaint(
painter: _RunningBorderPainter(
shape: widget.shape,
primary: widget.primary,
tertiary: widget.tertiary,
lap: _reduced ? null : _lap,
),
),
);
}
class _RunningBorderPainter extends CustomPainter {
_RunningBorderPainter({
required this.shape,
required this.primary,
required this.tertiary,
required this.lap,
}) : super(repaint: lap);
final OutlinedBorder shape;
final Color primary;
final Color tertiary;
/// The lap's progress, or null for the static reduced-motion border.
final Animation<double>? lap;
@override
void paint(Canvas canvas, Size size) {
if (size.isEmpty) return;
const width = ComposerRunningBorder.strokeWidth;
final rect = Offset.zero & size;
final path = shape.getOuterPath(rect.deflate(width / 2));
final glow = Paint()
..style = PaintingStyle.stroke
..strokeWidth = width * 3
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4);
final line = Paint()
..style = PaintingStyle.stroke
..strokeWidth = width;
final progress = lap?.value;
if (progress == null) {
final solid = primary.withValues(
alpha: ComposerRunningBorder.staticOpacity,
);
glow.color = solid.withValues(alpha: solid.a * .4);
line.color = solid;
} else {
final shader = SweepGradient(
colors: [
primary.withValues(alpha: 0),
primary,
tertiary,
tertiary.withValues(alpha: 0),
primary.withValues(alpha: 0),
],
stops: const [0, .12, .24, .38, 1],
transform: GradientRotation(progress * 2 * math.pi),
).createShader(rect);
glow.shader = shader;
line.shader = shader;
}
canvas
..drawPath(path, glow)
..drawPath(path, line);
}
@override
bool shouldRepaint(_RunningBorderPainter oldDelegate) =>
oldDelegate.shape != shape ||
oldDelegate.primary != primary ||
oldDelegate.tertiary != tertiary ||
oldDelegate.lap != lap;
}
+3
View File
@@ -31,6 +31,8 @@ import 'workspace/chat_float_shortcut.dart';
import 'workspace/chat_workspace_binding.dart';
import 'workspace/chat_workspace_snapshot.dart';
import 'workspace/chat_workspace_store.dart';
import 'workspace/chat_open_workspace_controller.dart';
import 'workspace/chat_open_workspace_gateway.dart';
import 'conversation/chat_bar_tint.dart';
import 'conversation/chat_pane_picker.dart';
import 'conversation/chat_add_pane_picker.dart';
@@ -383,6 +385,7 @@ class _ChatScreenState extends State<ChatScreen>
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
_page.dispose();
_workspaceBinding?.dispose();
_openWorkspace?.dispose();
_unbindWindows();
_workspace.removeListener(_workspaceChanged);
_workspace.dispose();
@@ -0,0 +1,46 @@
import 'package:flutter/widgets.dart';
/// Whether the app window is focused and visible: the only state in which a
/// chat can be read. A backgrounded or unfocused window never marks a chat
/// seen, so a reply that arrives there stays New until the user interacts.
class ChatSeenFocus extends ChangeNotifier {
ChatSeenFocus({bool focused = true}) {
_focused = focused;
}
/// The app's own focus, driven by the framework's lifecycle state. A null
/// lifecycle state (before the first report) counts as focused, so a window
/// that starts visible is not stuck unread.
static final ChatSeenFocus app = ChatSeenFocus._observingApp();
factory ChatSeenFocus._observingApp() {
final focus = ChatSeenFocus(
focused: _isFocusedState(WidgetsBinding.instance.lifecycleState),
);
WidgetsBinding.instance.addObserver(_LifecycleFocus(focus));
return focus;
}
late bool _focused;
bool get focused => _focused;
set focused(bool value) {
if (value == _focused) return;
_focused = value;
notifyListeners();
}
static bool _isFocusedState(AppLifecycleState? state) =>
state == null || state == AppLifecycleState.resumed;
}
class _LifecycleFocus with WidgetsBindingObserver {
_LifecycleFocus(this._focus);
final ChatSeenFocus _focus;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
_focus.focused = ChatSeenFocus._isFocusedState(state);
}
}
@@ -12,6 +12,7 @@ import '../../../attention/runtime/attention_ack_sync.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
import 'chat_seen_focus.dart';
import 'chat_session_local.dart';
import 'session_attention.dart';
@@ -23,8 +24,10 @@ import 'session_attention.dart';
/// read watermark are local.
///
/// With an [AttentionAckSync] (bound to the gateway by the app, or passed in),
/// reading is shared: opening a chat acknowledges a `chat_seen` watermark to
/// every device, and a watermark acknowledged elsewhere that is newer than this
/// reading is shared: a user interaction with a chat (opening it, or acting in
/// its pane while the window is focused, see [reportInteraction]) acknowledges
/// a `chat_seen` watermark to every device. Being visible, restored or
/// receiving a reply never does. A watermark acknowledged elsewhere that is newer than this
/// device's own clears the chat's New badge here. The local store remains the
/// offline cache of both.
class ChatSessionsController extends ChangeNotifier {
@@ -33,8 +36,10 @@ class ChatSessionsController extends ChangeNotifier {
ChatSessionLocalStore? localStore,
AttentionAckSync? ackSync,
int Function()? nowMillis,
ChatSeenFocus? seenFocus,
this.activeAckDelay = const Duration(milliseconds: 1500),
}) : _localStore =
}) : _focus = seenFocus ?? ChatSeenFocus.app,
_localStore =
localStore ??
(repository.gateway is FederatedChatGateway
? FederatedChatSessionLocalStore(
@@ -46,12 +51,27 @@ class ChatSessionsController extends ChangeNotifier {
),
)),
_nowMillis = nowMillis ?? _wallClockMillis {
_focus.addListener(_focusChanged);
_listenFrames();
_bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway));
}
static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch;
final ChatSeenFocus _focus;
/// The open chat the user has interacted with while the window was focused.
/// Only such a chat acknowledges new content as it arrives; any other reply
/// in the open chat stays New until the next interaction. Cleared when the
/// window loses focus or another chat becomes the open one.
final Set<String> _engaged = {};
void _focusChanged() {
if (_focus.focused) return;
_engaged.clear();
_cancelPendingActiveAck();
}
/// How long the open chat stays quiet before its new content is
/// acknowledged to the other devices; streaming text arrives in many frames.
final Duration activeAckDelay;
@@ -61,6 +81,8 @@ class ChatSessionsController extends ChangeNotifier {
final int Function() _nowMillis;
AttentionAckSync? _ackSync;
Timer? _activeAck;
// The chat whose quiet-period acknowledgement [_activeAck] is waiting on.
String? _pendingAckId;
ChatSessionLocal _local = const ChatSessionLocal();
final Map<String, String> _actionErrors = {};
List<JsonMap> _sessions = const [];
@@ -78,7 +100,17 @@ class ChatSessionsController extends ChangeNotifier {
// older snapshot that arrives later never replaces it.
final Map<String, ChatListActivity> _activity = {};
StreamSubscription<JsonMap>? _frameSubscription;
String? activeSessionId;
String? _activeSessionId;
/// The chat open above the list. Opening another chat ends the engagement
/// with the previous one; setting the same id changes nothing.
String? get activeSessionId => _activeSessionId;
set activeSessionId(String? id) {
if (id == _activeSessionId) return;
_activeSessionId = id;
_engaged.clear();
_cancelPendingActiveAck();
}
void _listenFrames() {
_frameSubscription?.cancel();
@@ -98,8 +130,14 @@ class ChatSessionsController extends ChangeNotifier {
final row = session.first;
if (row['closed_at'] != null || row['closed'] == true) return;
if (effect.running != null) _setRunning(id, effect.running!);
if (effect.attention && id != activeSessionId) unawaited(_markUnseen(id));
if (effect.attention && id == activeSessionId) _scheduleActiveAck(id);
if (!effect.attention) return;
if (id == activeSessionId && _focus.focused && _engaged.contains(id)) {
_scheduleActiveAck(id);
} else {
// Passive: the window is unfocused, or the chat was open with no
// interaction since, so the reply is New until the user acts.
unawaited(_markUnseen(id));
}
}
/// Another device changed a chat's shared colour, star or title: the row
@@ -210,12 +248,45 @@ class ChatSessionsController extends ChangeNotifier {
void _scheduleActiveAck(String id) {
if (_ackSync == null) return;
_activeAck?.cancel();
_pendingAckId = id;
_activeAck = Timer(activeAckDelay, () {
if (_disposed || id != activeSessionId) return;
_activeAck = null;
_pendingAckId = null;
// Losing focus or the chat during the quiet period ends the engagement;
// [_cancelPendingActiveAck] has already marked the reply New by then.
if (_disposed || id != activeSessionId || !_engaged.contains(id)) return;
unawaited(_acknowledgeSeen(id, 0));
});
}
/// Ends a quiet period that has not fired yet. The reply it was waiting on
/// arrived while the user was engaged, but the engagement ends before the
/// quiet period does, so that reply is marked New here rather than dropped.
void _cancelPendingActiveAck() {
final pending = _pendingAckId;
if (pending == null) return;
_activeAck?.cancel();
_activeAck = null;
_pendingAckId = null;
unawaited(_markUnseen(pending));
}
/// The user acted in [id]: a click, tap, scroll, key press in its pane, or
/// opening it. Only while the window is focused; a passive state is ignored.
/// Everything up to the latest message is marked seen and acknowledged to
/// every device. Repeated interactions (every scroll tick) send nothing once
/// the chat is engaged and has no unread content.
void reportInteraction(String id) {
if (_disposed || id.isEmpty || !_focus.focused) return;
final firstInChat = id == activeSessionId && _engaged.add(id);
if (!firstInChat && !_local.isUnseen(id)) return;
final row = _sessions.where((row) => '${row['id'] ?? ''}' == id);
final updatedAt = row.isEmpty
? 0
: chatSessionMillis(row.first['updated_at']);
unawaited(_acknowledgeSeen(id, updatedAt));
}
/// Applies watermarks acknowledged on any device: one newer than this
/// device's own marks the chat read here (clearing its New badge) and raises
/// the local watermark, so a later badge is not cleared by the same ack.
@@ -265,9 +336,9 @@ class ChatSessionsController extends ChangeNotifier {
Future<void> _markUnseen(String id) async {
await _ensureLocal();
// Loading device preferences may race an operator opening this chat. The
// open is authoritative even when the triggering frame arrived first.
if (_disposed || id == activeSessionId) return;
// Loading device preferences may race an operator engaging this chat. The
// interaction is authoritative even when the triggering frame arrived first.
if (_disposed || (id == activeSessionId && _engaged.contains(id))) return;
final next = _local.markUnseen(id);
if (identical(next, _local)) return;
_local = next;
@@ -443,11 +514,15 @@ class ChatSessionsController extends ChangeNotifier {
_notify();
}
/// Records that this device has read [session]'s current recency.
/// Records that this device has read [session]'s current recency. Called
/// only for the user's own open (a list row, a shortcut, a notification), so
/// it also engages the chat. Showing a chat that was already open, such as a
/// restored layout, never calls this.
Future<void> markOpened(JsonMap session) async {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
activeSessionId = id;
if (_focus.focused) _engaged.add(id);
await _ensureLocal();
if (_disposed) return;
final updatedAt = chatSessionMillis(session['updated_at']);
@@ -564,6 +639,7 @@ class ChatSessionsController extends ChangeNotifier {
unawaited(_frameSubscription?.cancel());
_activeAck?.cancel();
_ackSync?.removeListener(_ackChanged);
_focus.removeListener(_focusChanged);
super.dispose();
}
}
@@ -112,7 +112,6 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
final _search = TextEditingController();
late final ChatSectionFolds _folds = widget.folds ?? ChatSectionFolds();
Timer? _undoTimer;
String? _markedActiveSessionId;
@override
void initState() {
@@ -123,7 +122,6 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
/// Reports the loaded rows at the end of the frame: the destination learns a
/// routed row without this screen calling back inside its own build.
void _reportSessions() {
_markActiveSessionRead();
if (widget.onSessions == null) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
@@ -131,28 +129,10 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
});
}
void _markActiveSessionRead() {
final id = widget.activeSessionId;
if (id == null) {
_markedActiveSessionId = null;
return;
}
if (id == _markedActiveSessionId) return;
for (final session in _controller.sessions) {
if (_sessionId(session) != id) continue;
// Mark synchronously so row activation and subsequent list notifications
// cannot write the same read watermark twice.
_markedActiveSessionId = id;
unawaited(_controller.markOpened(session));
return;
}
}
@override
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
_controller.activeSessionId = widget.activeSessionId;
_markActiveSessionRead();
if (oldWidget.gateway != widget.gateway) {
_controller.replaceRepository(ChatRepository(widget.gateway));
} else if (oldWidget.syncToken != widget.syncToken) {
@@ -252,10 +232,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
if (session != null && mounted) widget.onOpen(session);
}
void _markOpened(JsonMap session) {
_markedActiveSessionId = _sessionId(session);
unawaited(_controller.markOpened(session));
}
void _markOpened(JsonMap session) =>
unawaited(_controller.markOpened(session));
void _openBeside(JsonMap session) {
_markOpened(session);
@@ -75,6 +75,9 @@ class ChatWindows {
Iterable<WindowEntry> get windows =>
manager.windows.where((w) => w.kind == chatWindowKind);
Iterable<String> get floatingSessionIds =>
windows.map((window) => window.contentId);
/// Registers the kind and starts answering the chord. Call before the
/// manager restores, so saved chat windows are kept.
void start() {
@@ -0,0 +1,115 @@
import 'dart:async';
import '../../../core/api_gateway.dart';
import 'chat_open_workspace_gateway.dart';
/// Keeps one device's open chats in step with the server's open-chat set.
///
/// Writes are serialized: one is in flight at a time, and changes made while
/// it is pending coalesce into the latest full snapshot, sent next from the
/// revision the reply reported. Every reply and push is reconciled by server
/// revision, so a late or reordered one never overwrites newer state. A
/// snapshot from another device (or a refused stale write) wins over local
/// changes not yet sent, and reaches [onChanged].
class ChatOpenWorkspaceController {
ChatOpenWorkspaceController({required ApiGateway gateway})
: _gateway = ChatOpenWorkspaceGateway(gateway);
final ChatOpenWorkspaceGateway _gateway;
StreamSubscription<ChatOpenWorkspaceSnapshot>? _subscription;
bool _disposed = false;
bool _writing = false;
List<ChatOpenWorkspaceEntry>? _pending;
ChatOpenWorkspaceSnapshot? _current;
/// Applies a server snapshot to the device's panes and windows.
void Function(ChatOpenWorkspaceSnapshot snapshot)? onChanged;
/// The latest server revision this device has seen; 0 before any.
int get revision => _current?.revision ?? 0;
/// Whether the server answered, so local changes are sent. Before that (or
/// against a server without the request) the device keeps its own layout.
bool get ready => _current != null;
bool get disposed => _disposed;
/// Subscribes to pushes, then seeds the server from [local] (the device's
/// restored layout, migrated once from the old local snapshot) or, with no
/// local chats, reads the server's set. The server's answer is applied.
Future<void> start({
Iterable<ChatOpenWorkspaceEntry> local = const [],
}) async {
if (_subscription != null || _disposed) return;
_subscription = _gateway.changes.listen(_accept);
final entries = local.toList(growable: false);
ChatOpenWorkspaceSnapshot? snapshot;
try {
snapshot = entries.isEmpty
? await _gateway.read()
: await _gateway.replace(entries, seed: true);
} on Object {
return;
}
if (snapshot != null) _accept(snapshot, force: true);
}
/// Sends the device's full open-chat set. Ignored until [ready]; coalesced
/// while a write is in flight.
void replace(Iterable<ChatOpenWorkspaceEntry> entries) {
if (_disposed || !ready) return;
_pending = entries.toList(growable: false);
if (!_writing) unawaited(_drain());
}
Future<void> _drain() async {
_writing = true;
try {
while (!_disposed) {
final sent = _pending;
_pending = null;
if (sent == null) return;
final current = _current;
if (current != null && current.sameEntries(sent)) continue;
ChatOpenWorkspaceSnapshot? reply;
try {
reply = await _gateway.replace(sent, baseRevision: revision);
} on Object {
reply = null;
}
if (_disposed || reply == null || reply.revision < revision) continue;
if (reply.rejected) {
// Another change landed first: the server's state wins over this
// write and anything queued behind it.
_accept(reply, force: true);
} else {
// The server may have left out closed or unknown chats. This device
// keeps showing them (a closed chat can still be read here); the
// other devices never receive them.
_current = reply;
}
}
} finally {
_writing = false;
}
}
void _accept(ChatOpenWorkspaceSnapshot snapshot, {bool force = false}) {
if (_disposed) return;
final current = _current;
if (current != null &&
(snapshot.revision < current.revision ||
(!force && snapshot.revision == current.revision))) {
return;
}
_current = snapshot;
_pending = null;
onChanged?.call(snapshot);
}
void dispose() {
_disposed = true;
_pending = null;
onChanged = null;
unawaited(_subscription?.cancel());
_subscription = null;
}
}
@@ -0,0 +1,107 @@
import '../../../core/api_gateway.dart';
/// One chat in the server-owned open-chat set: its session and whether it is
/// floating. Geometry stays on the device.
class ChatOpenWorkspaceEntry {
const ChatOpenWorkspaceEntry(this.sessionId, {this.floating = false});
final String sessionId;
final bool floating;
Map<String, dynamic> toJson() => {
'session_id': sessionId,
if (floating) 'floating': true,
};
static ChatOpenWorkspaceEntry? fromJson(Object? value) {
if (value is! Map) return null;
final id = '${value['session_id'] ?? ''}'.trim();
return id.isEmpty
? null
: ChatOpenWorkspaceEntry(id, floating: value['floating'] == true);
}
}
/// The complete open-chat set at one server revision. [rejected] marks the
/// reply to a write from a stale base: the write was not applied and this is
/// the current state.
class ChatOpenWorkspaceSnapshot {
const ChatOpenWorkspaceSnapshot(
this.revision,
this.entries, {
this.rejected = false,
});
final int revision;
final List<ChatOpenWorkspaceEntry> entries;
final bool rejected;
bool sameEntries(Iterable<ChatOpenWorkspaceEntry> other) {
final list = other.toList(growable: false);
if (list.length != entries.length) return false;
for (var i = 0; i < list.length; i++) {
if (list[i].sessionId != entries[i].sessionId ||
list[i].floating != entries[i].floating) {
return false;
}
}
return true;
}
static ChatOpenWorkspaceSnapshot? fromJson(Object? value) {
if (value is! Map || value['entries'] is! List) return null;
final entries = <ChatOpenWorkspaceEntry>[];
for (final item in value['entries'] as List) {
final entry = ChatOpenWorkspaceEntry.fromJson(item);
if (entry == null ||
entries.any((old) => old.sessionId == entry.sessionId)) {
return null;
}
entries.add(entry);
}
if (entries.length > 64) return null;
return ChatOpenWorkspaceSnapshot(
(value['revision'] as num?)?.toInt() ?? 0,
List.unmodifiable(entries),
rejected: value['rejected'] == true,
);
}
}
/// The `chat_open_workspace` request and its `chat_open_workspace_changed`
/// push, decoded.
class ChatOpenWorkspaceGateway {
ChatOpenWorkspaceGateway(this.gateway);
final ApiGateway gateway;
/// The current snapshot, without changing it.
Future<ChatOpenWorkspaceSnapshot?> read() async {
final response = await gateway.call('chat_open_workspace');
return ChatOpenWorkspaceSnapshot.fromJson(response['chat_open_workspace']);
}
/// Replaces the set, derived from [baseRevision]. A [seed] applies only
/// when the server never stored a set and otherwise returns the stored one.
Future<ChatOpenWorkspaceSnapshot?> replace(
Iterable<ChatOpenWorkspaceEntry> entries, {
int baseRevision = 0,
bool seed = false,
}) async {
final response = await gateway.call('chat_open_workspace', {
'chat_open_workspace_request': {
'entries': entries
.map((entry) => entry.toJson())
.toList(growable: false),
'base_revision': baseRevision,
if (seed) 'seed': true,
},
});
return ChatOpenWorkspaceSnapshot.fromJson(response['chat_open_workspace']);
}
Stream<ChatOpenWorkspaceSnapshot> get changes async* {
await for (final frame in gateway.frames) {
if (frame['type'] != 'chat_open_workspace_changed') continue;
final snapshot = ChatOpenWorkspaceSnapshot.fromJson(
frame['chat_open_workspace'],
);
if (snapshot != null) yield snapshot;
}
}
}
@@ -1,6 +1,7 @@
import 'package:flutter/foundation.dart';
import 'chat_workspace_nodes.dart';
import 'chat_workspace_reconcile.dart';
import 'chat_workspace_snapshot.dart';
export 'chat_workspace_nodes.dart';
@@ -203,6 +204,23 @@ class ChatWorkspaceController extends ChangeNotifier {
_changed();
}
/// Tiles exactly [sessionIds] in order, as the server's open-chat set
/// names them, keeping this device's geometry (see
/// [reconcileChatWorkspaceTree]). Floating membership is the window host's.
void reconcileSessions(Iterable<String> sessionIds) {
final wanted = <String>[];
final seen = <String>{};
for (final id in sessionIds) {
if (id.isNotEmpty && seen.add(id)) wanted.add(id);
}
final next = reconcileChatWorkspaceTree(_root, wanted, _id);
if (identical(next, _root)) return;
_root = next;
final ids = panes.map((pane) => pane.id).toSet();
if (!ids.contains(_active)) _active = ids.firstOrNull;
_changed();
}
void replaceSession(String oldId, String newId) {
if (oldId == newId || newId.isEmpty || _replaceFloating(oldId, newId)) {
return;
@@ -0,0 +1,118 @@
import 'chat_workspace_nodes.dart';
/// Returns [root] tiled with exactly [wanted] (distinct session ids) in
/// order, keeping the local geometry: panes whose chat left are removed with
/// their splits, surviving panes keep their ids and split sizes and move
/// between slots to follow the order, and new chats split off the last pane.
/// Returns [root] itself when it already matches.
ChatWorkspaceNode? reconcileChatWorkspaceTree(
ChatWorkspaceNode? root,
List<String> wanted,
String Function(String kind) newId,
) {
if (wanted.isEmpty) return null;
final keep = wanted.toSet();
final seen = <String>{};
var node = root == null ? null : _retain(root, keep, seen);
final leaves = node == null ? <ChatWorkspacePane>[] : _leaves(node).toList();
final bySession = {for (final pane in leaves) pane.sessionId: pane};
final order = wanted.where(bySession.containsKey).toList();
var slot = 0;
if (node != null) {
node = _reorder(node, () => bySession[order[slot++]]!);
}
for (final id in wanted.where((id) => !bySession.containsKey(id))) {
final added = ChatWorkspacePane(newId('pane'), id);
if (node == null) {
node = added;
continue;
}
final last = _leaves(node).last;
node = _swapLeaf(
node,
last.id,
ChatWorkspaceSplit(newId('split'), ChatSplitAxis.horizontal, last, added),
);
}
return _same(node, root) ? root : node;
}
Iterable<ChatWorkspacePane> _leaves(ChatWorkspaceNode node) sync* {
if (node is ChatWorkspacePane) yield node;
if (node is ChatWorkspaceSplit) {
yield* _leaves(node.first);
yield* _leaves(node.second);
}
}
/// Drops panes outside [keep] and repeats of a session already kept.
ChatWorkspaceNode? _retain(
ChatWorkspaceNode node,
Set<String> keep,
Set<String> seen,
) {
if (node is ChatWorkspacePane) {
return keep.contains(node.sessionId) && seen.add(node.sessionId)
? node
: null;
}
final split = node as ChatWorkspaceSplit;
final first = _retain(split.first, keep, seen);
final second = _retain(split.second, keep, seen);
if (first == null) return second;
if (second == null) return first;
return ChatWorkspaceSplit(
split.id,
split.axis,
first,
second,
ratio: split.ratio,
);
}
ChatWorkspaceNode _reorder(
ChatWorkspaceNode node,
ChatWorkspacePane Function() next,
) {
if (node is ChatWorkspacePane) return next();
final split = node as ChatWorkspaceSplit;
final first = _reorder(split.first, next);
return ChatWorkspaceSplit(
split.id,
split.axis,
first,
_reorder(split.second, next),
ratio: split.ratio,
);
}
ChatWorkspaceNode _swapLeaf(
ChatWorkspaceNode node,
String id,
ChatWorkspaceNode replacement,
) {
if (node.id == id) return replacement;
if (node is! ChatWorkspaceSplit) return node;
return ChatWorkspaceSplit(
node.id,
node.axis,
_swapLeaf(node.first, id, replacement),
_swapLeaf(node.second, id, replacement),
ratio: node.ratio,
);
}
bool _same(ChatWorkspaceNode? a, ChatWorkspaceNode? b) {
if (a == null || b == null) return a == b;
if (a is ChatWorkspacePane && b is ChatWorkspacePane) {
return a.id == b.id && a.sessionId == b.sessionId;
}
if (a is ChatWorkspaceSplit && b is ChatWorkspaceSplit) {
return a.id == b.id &&
a.axis == b.axis &&
a.ratio == b.ratio &&
_same(a.first, b.first) &&
_same(a.second, b.second);
}
return false;
}
@@ -125,6 +125,7 @@ class _RunDetailViewState extends State<RunDetailView> {
titleSemanticLabel: 'Run title $title',
onBack: widget.onBack,
actions: [more],
hideNavigation: true,
child: detail,
);
}
@@ -168,6 +169,7 @@ class _RunDetailViewState extends State<RunDetailView> {
return ShellBar(
title: 'Run',
onBack: widget.onBack,
hideNavigation: true,
child: _placeholderBody(loading, message),
);
}
@@ -46,6 +46,23 @@ class ServerConnections extends ChangeNotifier {
return true;
}
String? _chatOpenId;
/// A chat the user opened from a notification. The tap is the user's own
/// interaction, so the chat it opens is read; a route restored without a tap
/// never sets this.
void requestChatOpen(String sessionId) {
_chatOpenId = sessionId;
notifyListeners();
}
/// Consumes the notification open of [sessionId], once.
bool takeChatOpenIntent(String sessionId) {
if (sessionId.isEmpty || sessionId != _chatOpenId) return false;
_chatOpenId = null;
return true;
}
/// Keep the intent outside the app that selecting another machine disposes.
Future<bool> requestNewChat(String id) async {
if (_busy || _disposed) return false;
+18 -12
View File
@@ -8,6 +8,7 @@ import 'attention_badge.dart';
import 'destination.dart';
import 'list_detail.dart';
import 'navigation_rail.dart';
import 'shell_navigation_bar.dart';
import 'shell_rail_scope.dart';
import 'list_pane_widths.dart';
import 'shell_bar.dart';
@@ -167,7 +168,6 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
// only after the outgoing page has finished its native animation.
// Settings is shown as a page of the Pipelines tab: the tab bar keeps
// Pipelines selected and the bar offers Back to it.
final index = shellTabDestinations.indexOf(shellTabFor(_selected));
final page = !shellTabDestinations.contains(_selected);
final details = destinationDetails(_selected);
final contents = AppDestination.values.map((destination) {
@@ -193,23 +193,29 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
// Only the bar shows the registry's state, so a published bar or badge
// rebuilds its bar alone; the destinations and scaffold stay as built.
_bar.focus = _selected;
// One floating glass tab bar at every width: sized to its tabs at the
// right edge, near the thumb. Content keeps the whole width and scrolls
// behind it, learning the bar's height as its bottom media padding.
// A phone (narrower than the list-detail split) gets a full-width Material
// NavigationBar at the bottom, with Settings as its last destination. Wider
// windows without the rail keep the floating glass tab bar, which the list
// beside an open item needs (see below). Content keeps the whole width and
// scrolls behind the bar, learning its height as its bottom media padding.
// Neither scaffold's structure depends on the width, so resizing never
// remounts a destination.
//
// While the tab shows its list beside an open item the bar moves under
// the leading edge of the list pane, so the open item
// keeps its whole height: the list clears the bar and the item clears
// only the system inset (see ListDetailPanes). The bar keeps its place
// in the tree, so a split never replays its entrance.
// remounts a destination. Pushed detail routes cover the shell, and a
// bar-less spec (a chat workspace) hides the bar.
final phone = !showsListBesideDetail(context);
final bar = ListenableBuilder(
listenable: Listenable.merge([_bar.badges, _bar.bar, _paneWidths]),
builder: (context, _) {
if (_bar.specFor(_selected)?.hideNavigation ?? false) {
return const SizedBox.shrink();
}
if (phone) {
return ShellNavigationBar(
selected: _selected,
icon: (destination) =>
_icon(destination, destinationDetails(destination).icon),
onSelected: _tapDestination,
);
}
// On a wide window the bar stays under the list column even when no
// item is open (Search, a list alone), so it never jumps sides. A page
// (Settings) has no list column, so its bar stays at the right edge.
@@ -221,7 +227,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
alignment: AlignmentDirectional.bottomStart,
child: FloatingDestinationBar(
showLabels: true,
currentIndex: index,
currentIndex: shellTabDestinations.indexOf(shellTabFor(_selected)),
onTap: (value) => _tapDestination(shellTabDestinations[value]),
items: _destinationItems(),
alignment: split ? AlignmentDirectional.bottomStart : null,
+64
View File
@@ -0,0 +1,64 @@
import 'package:flutter/material.dart';
import 'destination.dart';
/// The destinations the phone's bottom bar offers, in order: the tabs, then
/// Settings. The rail pins Settings at its foot; a narrow window has no foot,
/// so Settings is the bar's last destination and is selected while it is open.
const List<AppDestination> shellBarDestinations = [
...shellTabDestinations,
AppDestination.settings,
];
/// The phone layout's bottom navigation: a full-width Material
/// [NavigationBar] with an icon and a label per destination, the current
/// destination marked by the bar's indicator.
///
/// [icon] builds each destination's icon (its running, needs-you or unread
/// badge included), the same builder the desktop rail uses, so both layouts
/// show the same counts. [selected] is the shell's destination. A re-tap of
/// the selected destination still calls [onSelected], which is how the shell's
/// destination-reselected hook fires.
///
/// The bar keeps the bottom system inset (gesture bar) clear and leaves while
/// the keyboard is open, so a field's text is never covered by the bar.
class ShellNavigationBar extends StatelessWidget {
const ShellNavigationBar({
super.key,
required this.selected,
required this.icon,
required this.onSelected,
});
final AppDestination selected;
final Widget Function(AppDestination destination) icon;
final ValueChanged<AppDestination> onSelected;
@override
Widget build(BuildContext context) {
// The keyboard takes the bottom of the window: the bar leaves with it.
if (MediaQuery.viewInsetsOf(context).bottom > 0) {
return const SizedBox.shrink();
}
return SafeArea(
top: false,
child: NavigationBar(
key: const ValueKey('shell.navigation-bar'),
selectedIndex: shellBarDestinations.indexOf(selected),
onDestinationSelected: (value) =>
onSelected(shellBarDestinations[value]),
destinations: [
for (final destination in shellBarDestinations)
NavigationDestination(
icon: KeyedSubtree(
key: ValueKey('shell.destination.${destination.name}'),
child: icon(destination),
),
label: destinationDetails(destination).label,
tooltip: destinationDetails(destination).label,
),
],
),
);
}
}