Merge commit '9999e0912e9c38bd24a8754d64e7a14c589b1646' into pipelines/run-20261112-0206-composer-border-shows-the-agent-working-fd87

This commit is contained in:
2026-11-12 03:26:25 +00:00
31 changed files with 2257 additions and 79 deletions
@@ -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(() {});
+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();
@@ -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;
}