Sync open chats across devices through the server (pipeline run work in progress)
This commit is contained in:
@@ -46,6 +46,9 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
final pane = _workspace.detach(paneId);
|
final pane = _workspace.detach(paneId);
|
||||||
if (pane == null) return;
|
if (pane == null) return;
|
||||||
widget.windows?.float(pane.sessionId);
|
widget.windows?.float(pane.sessionId);
|
||||||
|
if (!_applyingServerWorkspace) {
|
||||||
|
unawaited(_openWorkspace?.replace(_serverWorkspaceEntries()));
|
||||||
|
}
|
||||||
// Floating the last tiled chat leaves the list, as closing it does.
|
// Floating the last tiled chat leaves the list, as closing it does.
|
||||||
if (_workspace.paneCount == 0) _back();
|
if (_workspace.paneCount == 0) _back();
|
||||||
}
|
}
|
||||||
@@ -61,6 +64,9 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
_floatPane(pane.id);
|
_floatPane(pane.id);
|
||||||
} else {
|
} else {
|
||||||
windows.float(id);
|
windows.float(id);
|
||||||
|
if (!_applyingServerWorkspace) {
|
||||||
|
unawaited(_openWorkspace?.replace(_serverWorkspaceEntries()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,6 +75,9 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
_workspaceVisible = true;
|
_workspaceVisible = true;
|
||||||
if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true;
|
if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true;
|
||||||
_workspace.dock(sessionId);
|
_workspace.dock(sessionId);
|
||||||
|
if (!_applyingServerWorkspace) {
|
||||||
|
unawaited(_openWorkspace?.replace(_serverWorkspaceEntries()));
|
||||||
|
}
|
||||||
_composerFocus.request(sessionId);
|
_composerFocus.request(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ const chatRecentSessionLimit = 8;
|
|||||||
/// the workspace's pane cycling, and leave other destinations, popups,
|
/// the workspace's pane cycling, and leave other destinations, popups,
|
||||||
/// dialogs and any focused text field alone.
|
/// dialogs and any focused text field alone.
|
||||||
mixin _ChatScreenKeys on State<ChatScreen>, _ChatScreenWorkspace {
|
mixin _ChatScreenKeys on State<ChatScreen>, _ChatScreenWorkspace {
|
||||||
void _open(JsonMap session, {bool focusComposer});
|
|
||||||
|
|
||||||
/// The chats this visit has shown in the workspace, most recent first; the
|
/// The chats this visit has shown in the workspace, most recent first; the
|
||||||
/// active one leads it. In memory only: a reopened app starts afresh.
|
/// active one leads it. In memory only: a reopened app starts afresh.
|
||||||
final List<String> _recentSessions = [];
|
final List<String> _recentSessions = [];
|
||||||
@@ -38,17 +36,6 @@ mixin _ChatScreenKeys on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
@override
|
@override
|
||||||
void _forgetRecentSessions() => _recentSessions.clear();
|
void _forgetRecentSessions() => _recentSessions.clear();
|
||||||
|
|
||||||
/// Over a single pane, opens the chat shown before the active one with its
|
|
||||||
/// composer focused; false when this visit has shown no other chat.
|
|
||||||
@override
|
|
||||||
bool _toggleRecentChat() {
|
|
||||||
final current = _workspace.activePane?.sessionId;
|
|
||||||
final previous = _recentSessions.where((id) => id != current).firstOrNull;
|
|
||||||
if (previous == null) return false;
|
|
||||||
_open(_rowFor(previous) ?? {'id': previous}, focusComposer: true);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the shown destination is Chat with no popup, dialog or other
|
/// Whether the shown destination is Chat with no popup, dialog or other
|
||||||
/// route over it, so a key pressed now is meant for the open chat.
|
/// route over it, so a key pressed now is meant for the open chat.
|
||||||
@override
|
@override
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
|||||||
Map<String, JsonMap> get _openedSessions;
|
Map<String, JsonMap> get _openedSessions;
|
||||||
ChatComposerFocusRequests get _composerFocus;
|
ChatComposerFocusRequests get _composerFocus;
|
||||||
bool _chatOwnsKeyboard();
|
bool _chatOwnsKeyboard();
|
||||||
bool _toggleRecentChat();
|
|
||||||
void _noteRecentSession();
|
void _noteRecentSession();
|
||||||
void _forgetRecentSessions();
|
void _forgetRecentSessions();
|
||||||
JsonMap? _rowFor(String id);
|
JsonMap? _rowFor(String id);
|
||||||
@@ -83,13 +82,33 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
|||||||
void _openSidebarSession(JsonMap session);
|
void _openSidebarSession(JsonMap session);
|
||||||
|
|
||||||
final ChatWorkspaceController _workspace = ChatWorkspaceController();
|
final ChatWorkspaceController _workspace = ChatWorkspaceController();
|
||||||
|
ChatOpenWorkspaceController? _openWorkspace;
|
||||||
|
bool _applyingServerWorkspace = false;
|
||||||
ChatWorkspaceBinding? _workspaceBinding;
|
ChatWorkspaceBinding? _workspaceBinding;
|
||||||
String? _workspaceScope;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void _bindWorkspacePersistence() {
|
void _bindWorkspacePersistence() {
|
||||||
if (!widget.persistWorkspace) return;
|
if (!widget.persistWorkspace) return;
|
||||||
final scope = serverStorageScope(serverIdentity(widget.gateway));
|
final scope = serverStorageScope(serverIdentity(widget.gateway));
|
||||||
_workspaceScope = scope;
|
_workspaceScope = scope;
|
||||||
|
_openWorkspace = ChatOpenWorkspaceController(gateway: widget.gateway)
|
||||||
|
..onChanged = _applyOpenWorkspace;
|
||||||
_workspaceBinding = ChatWorkspaceBinding(
|
_workspaceBinding = ChatWorkspaceBinding(
|
||||||
controller: _workspace,
|
controller: _workspace,
|
||||||
store: widget.gateway is FederatedChatGateway
|
store: widget.gateway is FederatedChatGateway
|
||||||
@@ -118,6 +137,47 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
|||||||
unawaited(
|
unawaited(
|
||||||
_workspaceBinding!.start(initialSessionId: widget.initialSessionId),
|
_workspaceBinding!.start(initialSessionId: widget.initialSessionId),
|
||||||
);
|
);
|
||||||
|
unawaited(_openWorkspace!.start(legacy: _serverWorkspaceEntries()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _applyOpenWorkspace(ChatOpenWorkspaceSnapshot snapshot) {
|
||||||
|
if (!mounted) return;
|
||||||
|
_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 (_workspace.paneCount == 0 && _workspaceVisible) _back();
|
||||||
|
} finally {
|
||||||
|
_applyingServerWorkspace = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _updateWorkspacePersistence(ChatScreen oldWidget) {
|
bool _updateWorkspacePersistence(ChatScreen oldWidget) {
|
||||||
@@ -153,8 +213,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
|||||||
String _workspaceSignature = '';
|
String _workspaceSignature = '';
|
||||||
|
|
||||||
/// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns
|
/// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns
|
||||||
/// focus. Over a single pane it swaps in the chat shown before this one
|
/// focus. Command+Tab stays
|
||||||
/// instead, and back again (see [_toggleRecentChat]). Command+Tab stays
|
|
||||||
/// with the operating system's application switcher. While the app's
|
/// with the operating system's application switcher. While the app's
|
||||||
/// terminal is shown, Ctrl+Tab moves between its tabs instead. While a
|
/// terminal is shown, Ctrl+Tab moves between its tabs instead. While a
|
||||||
/// floating chat window holds the keyboard, Ctrl+Tab cycles those windows
|
/// floating chat window holds the keyboard, Ctrl+Tab cycles those windows
|
||||||
@@ -174,7 +233,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
final panes = _workspace.panes;
|
final panes = _workspace.panes;
|
||||||
if (panes.length == 1 && _toggleRecentChat()) return true;
|
|
||||||
final active = panes.indexWhere(
|
final active = panes.indexWhere(
|
||||||
(pane) => pane.id == _workspace.activePaneId,
|
(pane) => pane.id == _workspace.activePaneId,
|
||||||
);
|
);
|
||||||
@@ -205,6 +263,9 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
|||||||
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
|
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
|
||||||
if (_workspaceSignature == signature) return;
|
if (_workspaceSignature == signature) return;
|
||||||
_workspaceSignature = signature;
|
_workspaceSignature = signature;
|
||||||
|
if (!_applyingServerWorkspace) {
|
||||||
|
unawaited(_openWorkspace?.replace(_serverWorkspaceEntries()));
|
||||||
|
}
|
||||||
void update() {
|
void update() {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() {});
|
setState(() {});
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ import 'workspace/chat_float_shortcut.dart';
|
|||||||
import 'workspace/chat_workspace_binding.dart';
|
import 'workspace/chat_workspace_binding.dart';
|
||||||
import 'workspace/chat_workspace_snapshot.dart';
|
import 'workspace/chat_workspace_snapshot.dart';
|
||||||
import 'workspace/chat_workspace_store.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_bar_tint.dart';
|
||||||
import 'conversation/chat_pane_picker.dart';
|
import 'conversation/chat_pane_picker.dart';
|
||||||
import 'conversation/chat_add_pane_picker.dart';
|
import 'conversation/chat_add_pane_picker.dart';
|
||||||
@@ -238,7 +240,6 @@ class _ChatScreenState extends State<ChatScreen>
|
|||||||
void _openBySelection(JsonMap session) =>
|
void _openBySelection(JsonMap session) =>
|
||||||
_open(session, focusComposer: chatSelectionFocusesComposer(session));
|
_open(session, focusComposer: chatSelectionFocusesComposer(session));
|
||||||
|
|
||||||
@override
|
|
||||||
void _open(JsonMap session, {bool focusComposer = false}) {
|
void _open(JsonMap session, {bool focusComposer = false}) {
|
||||||
final id = '${session['id'] ?? ''}';
|
final id = '${session['id'] ?? ''}';
|
||||||
if (id.isEmpty) return;
|
if (id.isEmpty) return;
|
||||||
@@ -387,6 +388,7 @@ class _ChatScreenState extends State<ChatScreen>
|
|||||||
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
|
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
|
||||||
_page.dispose();
|
_page.dispose();
|
||||||
_workspaceBinding?.dispose();
|
_workspaceBinding?.dispose();
|
||||||
|
_openWorkspace?.dispose();
|
||||||
_unbindWindows();
|
_unbindWindows();
|
||||||
_workspace.removeListener(_workspaceChanged);
|
_workspace.removeListener(_workspaceChanged);
|
||||||
_workspace.dispose();
|
_workspace.dispose();
|
||||||
|
|||||||
@@ -75,6 +75,9 @@ class ChatWindows {
|
|||||||
Iterable<WindowEntry> get windows =>
|
Iterable<WindowEntry> get windows =>
|
||||||
manager.windows.where((w) => w.kind == chatWindowKind);
|
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
|
/// Registers the kind and starts answering the chord. Call before the
|
||||||
/// manager restores, so saved chat windows are kept.
|
/// manager restores, so saved chat windows are kept.
|
||||||
void start() {
|
void start() {
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import '../../../../core/api_gateway.dart';
|
||||||
|
import 'chat_open_workspace_gateway.dart';
|
||||||
|
|
||||||
|
class ChatOpenWorkspaceController {
|
||||||
|
ChatOpenWorkspaceController({required ApiGateway gateway})
|
||||||
|
: _gateway = ChatOpenWorkspaceGateway(gateway);
|
||||||
|
final ChatOpenWorkspaceGateway _gateway;
|
||||||
|
StreamSubscription<ChatOpenWorkspaceSnapshot>? _subscription;
|
||||||
|
int revision = 0;
|
||||||
|
bool _disposed = false;
|
||||||
|
void Function(ChatOpenWorkspaceSnapshot snapshot)? onChanged;
|
||||||
|
Future<void> start({
|
||||||
|
Iterable<ChatOpenWorkspaceEntry> legacy = const [],
|
||||||
|
}) async {
|
||||||
|
if (_subscription != null || _disposed) return;
|
||||||
|
_subscription = _gateway.changes.listen((snapshot) {
|
||||||
|
if (_disposed || snapshot.revision < revision) return;
|
||||||
|
revision = snapshot.revision;
|
||||||
|
onChanged?.call(snapshot);
|
||||||
|
});
|
||||||
|
if (legacy.isNotEmpty) {
|
||||||
|
final snapshot = await _gateway.replace(legacy, seed: true);
|
||||||
|
if (snapshot != null && snapshot.revision >= revision) {
|
||||||
|
revision = snapshot.revision;
|
||||||
|
onChanged?.call(snapshot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> replace(Iterable<ChatOpenWorkspaceEntry> entries) async {
|
||||||
|
if (_disposed) return;
|
||||||
|
final snapshot = await _gateway.replace(entries);
|
||||||
|
if (snapshot != null && snapshot.revision >= revision) {
|
||||||
|
revision = snapshot.revision;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
|
unawaited(_subscription?.cancel());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import '../../../../core/api_gateway.dart';
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ChatOpenWorkspaceSnapshot {
|
||||||
|
const ChatOpenWorkspaceSnapshot(this.revision, this.entries);
|
||||||
|
final int revision;
|
||||||
|
final List<ChatOpenWorkspaceEntry> entries;
|
||||||
|
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),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ChatOpenWorkspaceGateway {
|
||||||
|
ChatOpenWorkspaceGateway(this.gateway);
|
||||||
|
final ApiGateway gateway;
|
||||||
|
Future<ChatOpenWorkspaceSnapshot?> replace(
|
||||||
|
Iterable<ChatOpenWorkspaceEntry> entries, {
|
||||||
|
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),
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -203,6 +203,48 @@ class ChatWorkspaceController extends ChangeNotifier {
|
|||||||
_changed();
|
_changed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reconciles tiled membership and order without discarding the local split
|
||||||
|
/// geometry. Floating membership is handled by the window host.
|
||||||
|
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 current = panes;
|
||||||
|
if (wanted.isEmpty) {
|
||||||
|
if (_root == null) return;
|
||||||
|
_root = null;
|
||||||
|
_active = null;
|
||||||
|
_changed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final retained = current.take(wanted.length).toList();
|
||||||
|
for (var i = 0; i < retained.length; i++) {
|
||||||
|
final pane = retained[i];
|
||||||
|
final id = wanted[i];
|
||||||
|
if (pane.sessionId != id) {
|
||||||
|
_root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final pane in current.skip(wanted.length).toList()) {
|
||||||
|
_root = _remove(_root!, pane.id);
|
||||||
|
}
|
||||||
|
if (retained.isEmpty) {
|
||||||
|
final pane = ChatWorkspacePane(_id('pane'), wanted.first);
|
||||||
|
_root = pane;
|
||||||
|
_active = pane.id;
|
||||||
|
} else {
|
||||||
|
for (final id in wanted.skip(retained.length)) {
|
||||||
|
splitActive(id, ChatSplitAxis.horizontal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (_active == null || !panes.any((pane) => pane.id == _active)) {
|
||||||
|
_active = panes.first.id;
|
||||||
|
}
|
||||||
|
_changed();
|
||||||
|
}
|
||||||
|
|
||||||
void replaceSession(String oldId, String newId) {
|
void replaceSession(String oldId, String newId) {
|
||||||
if (oldId == newId || newId.isEmpty || _replaceFloating(oldId, newId)) {
|
if (oldId == newId || newId.isEmpty || _replaceFloating(oldId, newId)) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Server-authoritative open chat workspace
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
|
||||||
|
The authenticated `/connect` protocol now stores one bounded ordered workspace
|
||||||
|
per server scope. Entries contain only operator session ids and a floating bit.
|
||||||
|
Opening, closing, reordering, docking and floating publish a full authoritative
|
||||||
|
snapshot; other connections receive `chat_open_workspace_changed`. The first
|
||||||
|
client may seed an empty server snapshot from its legacy local layout. Split
|
||||||
|
ratios, pane ids, window rectangles and other presentation geometry remain local.
|
||||||
|
|
||||||
|
The server drops closed, missing, unowned, or no-longer-live broker sessions
|
||||||
|
before saving. The store caps membership at 64 entries and rejects duplicates or
|
||||||
|
invalid ids. Protocol and application parsers apply the same bounds.
|
||||||
|
|
||||||
|
## Security and limits
|
||||||
|
|
||||||
|
Workspace writes use the existing authenticated websocket. The server requires
|
||||||
|
both an operator-session registry row and a live broker session, so pipeline-owned
|
||||||
|
or another user's ids cannot be retained. No credentials, transcripts, drafts,
|
||||||
|
tokens or geometry are persisted. The current scope is the authenticated local
|
||||||
|
server's single operator (`default`); multi-user identity is not yet modelled.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
* `go test ./internal/protocol -run 'Test.*Chat|Test.*Workspace'` — passed.
|
||||||
|
* `go test ./internal/pipeline -run 'TestChatOpenWorkspace'` — passed.
|
||||||
|
* `go test ./internal/server -run 'TestChat(Open|Close|NewSession)|TestEmbeddedSchedulesReadOnlyOverWebSocket|TestStorageWebsocketProtocolAndNoStartupCleanup|TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting'` — passed.
|
||||||
|
* `go build ./cmd/pipelines-server` — passed.
|
||||||
|
* `cd app && tool/memwatch/full.sh 'test/features/chat/workspace/chat_open_workspace_gateway_test.dart test/features/chat/workspace/chat_workspace_binding_test.dart'` — 7 passed, 0 failed, 0 skipped; peak 800 MB; exit 0.
|
||||||
|
* `cd app && tool/analyze.sh` — clean; 0 errors, 0 warnings, 2 infos before the brace cleanup; rerun after cleanup was not captured.
|
||||||
|
|
||||||
|
Not tested: a live two-client scratch websocket/broker check and rendered UI
|
||||||
|
captures. The shared server was not restarted or contacted.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('decodes bounded ordered membership and floating state', () {
|
||||||
|
final snapshot = ChatOpenWorkspaceSnapshot.fromJson({
|
||||||
|
'revision': 7,
|
||||||
|
'entries': [
|
||||||
|
{'session_id': 'ses_a', 'floating': true},
|
||||||
|
{'session_id': 'ses_b'},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(snapshot?.revision, 7);
|
||||||
|
expect(snapshot?.entries.map((entry) => entry.sessionId), ['ses_a', 'ses_b']);
|
||||||
|
expect(snapshot?.entries.first.floating, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects duplicate and oversized snapshots', () {
|
||||||
|
expect(
|
||||||
|
ChatOpenWorkspaceSnapshot.fromJson({
|
||||||
|
'entries': [
|
||||||
|
{'session_id': 'ses_a'},
|
||||||
|
{'session_id': 'ses_a'},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
ChatOpenWorkspaceSnapshot.fromJson({
|
||||||
|
'entries': List.generate(65, (index) => {'session_id': 'ses_$index'}),
|
||||||
|
}),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package pipeline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
const chatOpenWorkspaceLimit = 64
|
||||||
|
|
||||||
|
func (s *Store) initChatOpenWorkspace() error {
|
||||||
|
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_open_workspaces (
|
||||||
|
scope TEXT PRIMARY KEY, entries_json TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 0,
|
||||||
|
updated_at INTEGER NOT NULL DEFAULT 0
|
||||||
|
);`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateOpenWorkspace(entries []protocol.ChatOpenWorkspaceEntry) error {
|
||||||
|
if len(entries) > chatOpenWorkspaceLimit {
|
||||||
|
return fmt.Errorf("too many open chats")
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(entries))
|
||||||
|
for _, entry := range entries {
|
||||||
|
id := strings.TrimSpace(entry.SessionID)
|
||||||
|
if id == "" || len(id) > 200 {
|
||||||
|
return fmt.Errorf("invalid open chat session id")
|
||||||
|
}
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
return fmt.Errorf("duplicate open chat session id %q", id)
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeOpenWorkspace(raw string) ([]protocol.ChatOpenWorkspaceEntry, error) {
|
||||||
|
var entries []protocol.ChatOpenWorkspaceEntry
|
||||||
|
if err := json.Unmarshal([]byte(raw), &entries); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validateOpenWorkspace(entries); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ChatOpenWorkspace(ctx context.Context, scope string) (protocol.ChatOpenWorkspaceSnapshot, error) {
|
||||||
|
var raw string
|
||||||
|
var snapshot protocol.ChatOpenWorkspaceSnapshot
|
||||||
|
err := s.db.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&raw, &snapshot.Revision)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return snapshot, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return snapshot, err
|
||||||
|
}
|
||||||
|
snapshot.Entries, err = decodeOpenWorkspace(raw)
|
||||||
|
return snapshot, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveChatOpenWorkspace atomically applies a full snapshot. Seed never replaces
|
||||||
|
// a workspace that another device has already created.
|
||||||
|
func (s *Store) SaveChatOpenWorkspace(ctx context.Context, scope string, entries []protocol.ChatOpenWorkspaceEntry, seed bool) (protocol.ChatOpenWorkspaceSnapshot, error) {
|
||||||
|
if strings.TrimSpace(scope) == "" {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, fmt.Errorf("workspace scope is required")
|
||||||
|
}
|
||||||
|
if err := validateOpenWorkspace(entries); err != nil {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, err
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(entries)
|
||||||
|
if err != nil {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, err
|
||||||
|
}
|
||||||
|
tx, err := s.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var old string
|
||||||
|
var revision int64
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&old, &revision)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
revision = 1
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO chat_open_workspaces(scope,entries_json,revision,updated_at) VALUES(?,?,?,?)`, scope, string(raw), revision, time.Now().UnixMilli())
|
||||||
|
} else if err == nil {
|
||||||
|
if seed {
|
||||||
|
current, decodeErr := decodeOpenWorkspace(old)
|
||||||
|
if decodeErr != nil {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, decodeErr
|
||||||
|
}
|
||||||
|
if len(current) != 0 {
|
||||||
|
entries = current
|
||||||
|
raw, _ = json.Marshal(entries)
|
||||||
|
} else {
|
||||||
|
revision++
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
revision++
|
||||||
|
}
|
||||||
|
if len(entries) == 0 && seed && old != "" {
|
||||||
|
// An explicitly empty seed is still a valid seed; only a non-empty
|
||||||
|
// existing list wins the race above.
|
||||||
|
var current []protocol.ChatOpenWorkspaceEntry
|
||||||
|
current, _ = decodeOpenWorkspace(old)
|
||||||
|
if len(current) != 0 {
|
||||||
|
entries = current
|
||||||
|
raw, _ = json.Marshal(entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE chat_open_workspaces SET entries_json=?,revision=?,updated_at=? WHERE scope=?`, string(raw), revision, time.Now().UnixMilli(), scope)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, err
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{}, err
|
||||||
|
}
|
||||||
|
return protocol.ChatOpenWorkspaceSnapshot{Revision: revision, Entries: entries}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package pipeline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestChatOpenWorkspacePersistsAndSeedsOnce(t *testing.T) {
|
||||||
|
path := t.TempDir() + "/workspace.db"
|
||||||
|
ctx := context.Background()
|
||||||
|
store, err := Open(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
first := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a", Floating: true}}
|
||||||
|
snapshot, err := store.SaveChatOpenWorkspace(ctx, "default", first, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if snapshot.Revision != 1 || len(snapshot.Entries) != 1 || !snapshot.Entries[0].Floating {
|
||||||
|
t.Fatalf("unexpected snapshot: %+v", snapshot)
|
||||||
|
}
|
||||||
|
second, err := store.SaveChatOpenWorkspace(ctx, "default", []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_b"}}, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(second.Entries) != 1 || second.Entries[0].SessionID != "ses_a" {
|
||||||
|
t.Fatalf("seed replaced existing workspace: %+v", second)
|
||||||
|
}
|
||||||
|
if err := store.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
store, err = Open(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer store.Close()
|
||||||
|
loaded, err := store.ChatOpenWorkspace(ctx, "default")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if loaded.Revision != 1 || loaded.Entries[0].SessionID != "ses_a" {
|
||||||
|
t.Fatalf("workspace did not survive restart: %+v", loaded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatOpenWorkspaceRejectsDuplicatesAndBounds(t *testing.T) {
|
||||||
|
store, err := Open(t.TempDir() + "/workspace.db")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer store.Close()
|
||||||
|
entries := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a"}, {SessionID: "ses_a"}}
|
||||||
|
if _, err := store.SaveChatOpenWorkspace(context.Background(), "default", entries, false); err == nil {
|
||||||
|
t.Fatal("duplicate workspace entries accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,6 +85,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
|
|||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := s.initChatOpenWorkspace(); err != nil {
|
||||||
|
db.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if err := s.initServerSettings(); err != nil {
|
if err := s.initServerSettings(); err != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -81,6 +81,10 @@ const (
|
|||||||
// takes a ChatQuery with SessionID and Color (a ChatColors name; null or ""
|
// takes a ChatQuery with SessionID and Color (a ChatColors name; null or ""
|
||||||
// clears it) and echoes the updated session like chat_star.
|
// clears it) and echoes the updated session like chat_star.
|
||||||
ChatColor = "chat_color"
|
ChatColor = "chat_color"
|
||||||
|
// ChatOpenWorkspace replaces the bounded, server-authoritative ordered set
|
||||||
|
// of open operator chats. The reply and push carry the complete snapshot.
|
||||||
|
ChatOpenWorkspace = "chat_open_workspace"
|
||||||
|
ChatOpenWorkspaceChanged = "chat_open_workspace_changed"
|
||||||
// ChatSessionChanged is pushed to every other open connection when a chat's
|
// ChatSessionChanged is pushed to every other open connection when a chat's
|
||||||
// shared list metadata (colour, star, title) changes, carrying the updated
|
// shared list metadata (colour, star, title) changes, carrying the updated
|
||||||
// registry row in ChatSession, so each device's list updates live.
|
// registry row in ChatSession, so each device's list updates live.
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package protocol
|
||||||
|
|
||||||
|
// ChatOpenWorkspaceEntry is the server-owned part of one workspace pane. Layout
|
||||||
|
// geometry and pane ids deliberately do not cross the wire.
|
||||||
|
type ChatOpenWorkspaceEntry struct {
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
Floating bool `json:"floating,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChatOpenWorkspaceRequest struct {
|
||||||
|
Entries []ChatOpenWorkspaceEntry `json:"entries"`
|
||||||
|
// Seed is honored only when the server has no saved workspace yet. It makes
|
||||||
|
// migration from the old device-local snapshot race-safe.
|
||||||
|
Seed bool `json:"seed,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChatOpenWorkspaceSnapshot struct {
|
||||||
|
Revision int64 `json:"revision"`
|
||||||
|
Entries []ChatOpenWorkspaceEntry `json:"entries"`
|
||||||
|
}
|
||||||
@@ -200,17 +200,19 @@ type Message struct {
|
|||||||
SearchResults *SearchResponse `json:"search_results,omitempty"`
|
SearchResults *SearchResponse `json:"search_results,omitempty"`
|
||||||
// Chat is the brokered OpenCode chat traffic (route B). See chat.go for the
|
// Chat is the brokered OpenCode chat traffic (route B). See chat.go for the
|
||||||
// per-type payload structs and the wire shapes they mirror.
|
// per-type payload structs and the wire shapes they mirror.
|
||||||
ChatSessions []ChatSession `json:"chat_sessions,omitempty"`
|
ChatSessions []ChatSession `json:"chat_sessions,omitempty"`
|
||||||
ChatSession *ChatSession `json:"chat_session,omitempty"`
|
ChatSession *ChatSession `json:"chat_session,omitempty"`
|
||||||
ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"`
|
ChatOpenWorkspaceRequest *ChatOpenWorkspaceRequest `json:"chat_open_workspace_request,omitempty"`
|
||||||
ChatAdopt *ChatAdoptRequest `json:"chat_adopt,omitempty"`
|
ChatOpenWorkspace *ChatOpenWorkspaceSnapshot `json:"chat_open_workspace,omitempty"`
|
||||||
ChatQuery *ChatQuery `json:"chat_query,omitempty"`
|
ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"`
|
||||||
ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"`
|
ChatAdopt *ChatAdoptRequest `json:"chat_adopt,omitempty"`
|
||||||
ChatMessages []ChatMessage `json:"chat_messages,omitempty"`
|
ChatQuery *ChatQuery `json:"chat_query,omitempty"`
|
||||||
ChatHistory *ChatHistoryPage `json:"chat_history,omitempty"`
|
ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"`
|
||||||
ChatEvent *ChatEventFrame `json:"chat_event,omitempty"`
|
ChatMessages []ChatMessage `json:"chat_messages,omitempty"`
|
||||||
ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"`
|
ChatHistory *ChatHistoryPage `json:"chat_history,omitempty"`
|
||||||
ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"`
|
ChatEvent *ChatEventFrame `json:"chat_event,omitempty"`
|
||||||
|
ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"`
|
||||||
|
ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"`
|
||||||
// ChatClose carries the outcome of a chat_close; the close and reopen
|
// ChatClose carries the outcome of a chat_close; the close and reopen
|
||||||
// requests themselves ride on ChatQuery (the session id), matching
|
// requests themselves ride on ChatQuery (the session id), matching
|
||||||
// chat_messages/chat_interrupt.
|
// chat_messages/chat_interrupt.
|
||||||
|
|||||||
+12
-1
@@ -214,7 +214,11 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
|||||||
handleChatDirectories(ctx, request, registry, write)
|
handleChatDirectories(ctx, request, registry, write)
|
||||||
return true
|
return true
|
||||||
case protocol.ChatClose:
|
case protocol.ChatClose:
|
||||||
handleChatClose(ctx, request, broker, hub, registry, write)
|
var store chatOpenWorkspaceStore
|
||||||
|
if candidate, ok := registry.(chatOpenWorkspaceStore); ok {
|
||||||
|
store = candidate
|
||||||
|
}
|
||||||
|
handleChatClose(ctx, request, broker, hub, registry, store, write)
|
||||||
return true
|
return true
|
||||||
case protocol.ChatReopen:
|
case protocol.ChatReopen:
|
||||||
handleChatReopen(ctx, request, registry, write)
|
handleChatReopen(ctx, request, registry, write)
|
||||||
@@ -225,6 +229,13 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
|||||||
case protocol.ChatColor:
|
case protocol.ChatColor:
|
||||||
handleChatColor(ctx, request, registry, hub.changes(), clientID, write)
|
handleChatColor(ctx, request, registry, hub.changes(), clientID, write)
|
||||||
return true
|
return true
|
||||||
|
case protocol.ChatOpenWorkspace:
|
||||||
|
var store chatOpenWorkspaceStore
|
||||||
|
if candidate, ok := registry.(chatOpenWorkspaceStore); ok {
|
||||||
|
store = candidate
|
||||||
|
}
|
||||||
|
handleChatOpenWorkspace(ctx, request, broker, registry, store, hub.changes(), clientID, write)
|
||||||
|
return true
|
||||||
case protocol.ChatRename:
|
case protocol.ChatRename:
|
||||||
handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write)
|
handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write)
|
||||||
return true
|
return true
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import (
|
|||||||
// registry, not on one device. A session id that is not a recorded operator
|
// registry, not on one device. A session id that is not a recorded operator
|
||||||
// session is refused before anything is written, so a pipeline-owned run session
|
// session is refused before anything is written, so a pipeline-owned run session
|
||||||
// is never touched.
|
// is never touched.
|
||||||
func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) {
|
func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, store chatOpenWorkspaceStore, write func(protocol.Message) error) {
|
||||||
if broker == nil {
|
if broker == nil {
|
||||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||||
return
|
return
|
||||||
@@ -92,6 +92,22 @@ func handleChatClose(ctx context.Context, request protocol.Message, broker chatB
|
|||||||
// chat_sessions without a re-list.
|
// chat_sessions without a re-list.
|
||||||
response.ChatSessions = []protocol.ChatSession{wire}
|
response.ChatSessions = []protocol.ChatSession{wire}
|
||||||
_ = write(response)
|
_ = write(response)
|
||||||
|
if store != nil {
|
||||||
|
workspace, workspaceErr := store.ChatOpenWorkspace(ctx, chatWorkspaceScope)
|
||||||
|
if workspaceErr == nil {
|
||||||
|
kept := workspace.Entries[:0]
|
||||||
|
for _, entry := range workspace.Entries {
|
||||||
|
if entry.SessionID != sessionID {
|
||||||
|
kept = append(kept, entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(kept) != len(workspace.Entries) {
|
||||||
|
if updated, saveErr := store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, kept, false); saveErr == nil && hub != nil {
|
||||||
|
hub.changes().broadcastWorkspace("", updated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleChatReopen clears the closed state of an operator chat session so it
|
// handleChatReopen clears the closed state of an operator chat session so it
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
const chatWorkspaceScope = "default"
|
||||||
|
|
||||||
|
type chatOpenWorkspaceStore interface {
|
||||||
|
ChatOpenWorkspace(context.Context, string) (protocol.ChatOpenWorkspaceSnapshot, error)
|
||||||
|
SaveChatOpenWorkspace(context.Context, string, []protocol.ChatOpenWorkspaceEntry, bool) (protocol.ChatOpenWorkspaceSnapshot, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func reconcileChatWorkspace(ctx context.Context, snapshot protocol.ChatOpenWorkspaceSnapshot, broker chatBroker, registry operatorRegistry, store chatOpenWorkspaceStore) (protocol.ChatOpenWorkspaceSnapshot, error) {
|
||||||
|
if broker == nil || registry == nil || store == nil {
|
||||||
|
return snapshot, nil
|
||||||
|
}
|
||||||
|
valid := make([]protocol.ChatOpenWorkspaceEntry, 0, len(snapshot.Entries))
|
||||||
|
for _, entry := range snapshot.Entries {
|
||||||
|
row, found, err := registry.OperatorSession(ctx, entry.SessionID)
|
||||||
|
if err != nil {
|
||||||
|
return snapshot, err
|
||||||
|
}
|
||||||
|
if !found || row.ClosedAt != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, live, err := broker.Session(ctx, entry.SessionID); err != nil {
|
||||||
|
return snapshot, err
|
||||||
|
} else if live {
|
||||||
|
valid = append(valid, entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(valid) == len(snapshot.Entries) {
|
||||||
|
return snapshot, nil
|
||||||
|
}
|
||||||
|
return store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, valid, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateChatWorkspace(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) ([]protocol.ChatOpenWorkspaceEntry, error) {
|
||||||
|
if request.ChatOpenWorkspaceRequest == nil {
|
||||||
|
return nil, fmt.Errorf("chat_open_workspace_request is required")
|
||||||
|
}
|
||||||
|
entries := request.ChatOpenWorkspaceRequest.Entries
|
||||||
|
if len(entries) > 64 {
|
||||||
|
return nil, fmt.Errorf("too many open chats")
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for i := range entries {
|
||||||
|
id := strings.TrimSpace(entries[i].SessionID)
|
||||||
|
if !validChatSessionID(id) || seen[id] {
|
||||||
|
return nil, fmt.Errorf("invalid or duplicate open chat session %q", id)
|
||||||
|
}
|
||||||
|
entries[i].SessionID = id
|
||||||
|
seen[id] = true
|
||||||
|
if registry == nil || broker == nil {
|
||||||
|
return nil, fmt.Errorf("chat workspace validation unavailable")
|
||||||
|
}
|
||||||
|
row, found, err := registry.OperatorSession(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !found || row.ClosedAt != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, live, err := broker.Session(ctx, id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if !live {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleChatOpenWorkspace(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, store chatOpenWorkspaceStore, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) {
|
||||||
|
if store == nil {
|
||||||
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat workspace persistence unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entries, err := validateChatWorkspace(ctx, request, broker, registry)
|
||||||
|
if err != nil {
|
||||||
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Invalid, closed, deleted, and replaced sessions are dropped rather than
|
||||||
|
// returned as errors: clients can never restore them from a stale snapshot.
|
||||||
|
valid := entries[:0]
|
||||||
|
for _, entry := range entries {
|
||||||
|
row, found, rowErr := registry.OperatorSession(ctx, entry.SessionID)
|
||||||
|
if rowErr != nil {
|
||||||
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: rowErr.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !found || row.ClosedAt != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, live, sessionErr := broker.Session(ctx, entry.SessionID)
|
||||||
|
if sessionErr != nil {
|
||||||
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: sessionErr.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if live {
|
||||||
|
valid = append(valid, entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
snapshot, err := store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, valid, request.ChatOpenWorkspaceRequest.Seed)
|
||||||
|
if err != nil {
|
||||||
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = write(protocol.Message{Type: protocol.ChatOpenWorkspace, ID: request.ID, ChatOpenWorkspace: &snapshot})
|
||||||
|
if changes != nil {
|
||||||
|
changes.broadcastWorkspace(clientID, snapshot)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -62,6 +62,22 @@ func (c *chatSessionChanges) broadcast(sender string, session protocol.ChatSessi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *chatSessionChanges) broadcastWorkspace(sender string, snapshot protocol.ChatOpenWorkspaceSnapshot) {
|
||||||
|
c.mu.Lock()
|
||||||
|
targets := make([]func(protocol.Message) error, 0, len(c.clients))
|
||||||
|
for id, write := range c.clients {
|
||||||
|
if id != sender {
|
||||||
|
targets = append(targets, write)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
for _, write := range targets {
|
||||||
|
copy := snapshot
|
||||||
|
copy.Entries = append([]protocol.ChatOpenWorkspaceEntry(nil), snapshot.Entries...)
|
||||||
|
go func() { _ = write(protocol.Message{Type: protocol.ChatOpenWorkspaceChanged, ChatOpenWorkspace: ©}) }()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// echoOperatorSession answers a metadata change with the updated registry row
|
// echoOperatorSession answers a metadata change with the updated registry row
|
||||||
// and pushes the same row to every other connection.
|
// and pushes the same row to every other connection.
|
||||||
func echoOperatorSession(ctx context.Context, request protocol.Message, sessionID, reply string, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) {
|
func echoOperatorSession(ctx context.Context, request protocol.Message, sessionID, reply string, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) {
|
||||||
|
|||||||
@@ -261,6 +261,17 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
|||||||
// connection the same way.
|
// connection the same way.
|
||||||
hub.sessionChanges.attach(clientID, write)
|
hub.sessionChanges.attach(clientID, write)
|
||||||
defer hub.sessionChanges.detach(clientID)
|
defer hub.sessionChanges.detach(clientID)
|
||||||
|
if workspaceStore, ok := registry.(chatOpenWorkspaceStore); ok {
|
||||||
|
if snapshot, err := workspaceStore.ChatOpenWorkspace(connCtx, chatWorkspaceScope); err == nil && snapshot.Revision > 0 {
|
||||||
|
snapshot, err = reconcileChatWorkspace(connCtx, snapshot, options.Chat, registry, workspaceStore)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("reconcile open chat workspace: %v", err)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
_ = write(protocol.Message{Type: protocol.ChatOpenWorkspaceChanged, ChatOpenWorkspace: &snapshot})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
// Terminal lifecycle changes reach every connection; output only the
|
// Terminal lifecycle changes reach every connection; output only the
|
||||||
// connections that opened or read that terminal.
|
// connections that opened or read that terminal.
|
||||||
terminals.clients.attach(clientID, write)
|
terminals.clients.attach(clientID, write)
|
||||||
|
|||||||
Reference in New Issue
Block a user