Persist validated device-local chat workspace layouts

This commit is contained in:
2026-11-06 19:10:20 +00:00
parent 7aec6738bd
commit c4776657c8
6 changed files with 586 additions and 31 deletions
@@ -1,35 +1,17 @@
import 'package:flutter/foundation.dart';
enum ChatSplitAxis { horizontal, vertical }
import 'chat_workspace_nodes.dart';
import 'chat_workspace_snapshot.dart';
sealed class ChatWorkspaceNode {
const ChatWorkspaceNode(this.id);
final String id;
}
export 'chat_workspace_nodes.dart';
class ChatWorkspacePane extends ChatWorkspaceNode {
const ChatWorkspacePane(super.id, this.sessionId);
final String sessionId;
}
class ChatWorkspaceSplit extends ChatWorkspaceNode {
const ChatWorkspaceSplit(
super.id,
this.axis,
this.first,
this.second, {
this.ratio = .5,
});
final ChatSplitAxis axis;
final ChatWorkspaceNode first, second;
final double ratio;
}
/// Visit-local layout. Pane identities survive nested splits and resizing.
/// Pane identities survive nested splits, resizing and validated restoration.
class ChatWorkspaceController extends ChangeNotifier {
ChatWorkspaceNode? _root;
String? _active;
int _serial = 0;
int _revision = 0;
int get revision => _revision;
ChatWorkspaceNode? get root => _root;
String? get activePaneId => _active;
int get paneCount => panes.length;
@@ -45,7 +27,46 @@ class ChatWorkspaceController extends ChangeNotifier {
}
}
String _id(String kind) => 'chat-$kind-${++_serial}';
String _id(String kind) {
final ids = <String>{};
void collect(ChatWorkspaceNode? node) {
if (node == null) return;
ids.add(node.id);
if (node is ChatWorkspaceSplit) {
collect(node.first);
collect(node.second);
}
}
collect(_root);
String id;
do {
id = 'chat-$kind-${++_serial}';
} while (ids.contains(id));
return id;
}
/// A late preference read may restore only while the visit is unchanged.
bool restoreLayout(ChatWorkspaceSnapshot snapshot, {int? expectedRevision}) {
if (expectedRevision != null && expectedRevision != _revision) return false;
_root = snapshot.root;
_active = snapshot.activePaneId;
_serial = 0;
_changed();
return true;
}
ChatWorkspaceSnapshot? snapshot({String sidebarMode = 'expanded'}) =>
ChatWorkspaceSnapshot.fromLayout(
_root,
_active,
sidebarMode: sidebarMode,
);
void _changed() {
_revision++;
notifyListeners();
}
/// Ordinary opening replaces the active pane; an already-open chat is focused.
void open(String sessionId) {
@@ -68,7 +89,7 @@ class ChatWorkspaceController extends ChangeNotifier {
);
_active = target.id;
}
notifyListeners();
_changed();
}
void splitActive(String sessionId, ChatSplitAxis axis) {
@@ -90,19 +111,19 @@ class ChatWorkspaceController extends ChangeNotifier {
ChatWorkspaceSplit(_id('split'), axis, target, added),
);
_active = added.id;
notifyListeners();
_changed();
}
void activate(String paneId) {
if (_active == paneId || !panes.any((p) => p.id == paneId)) return;
_active = paneId;
notifyListeners();
_changed();
}
void resize(String splitId, double ratio) {
if (_root == null || !ratio.isFinite) return;
_root = _resize(_root!, splitId, ratio.clamp(.01, .99));
notifyListeners();
_changed();
}
void close(String paneId) {
@@ -116,7 +137,7 @@ class ChatWorkspaceController extends ChangeNotifier {
? null
: after[index.clamp(0, after.length - 1)].id;
}
notifyListeners();
_changed();
}
void replaceSession(String oldId, String newId) {
@@ -130,7 +151,7 @@ class ChatWorkspaceController extends ChangeNotifier {
return;
}
_root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, newId));
notifyListeners();
_changed();
}
ChatWorkspaceNode _replace(
@@ -0,0 +1,24 @@
enum ChatSplitAxis { horizontal, vertical }
sealed class ChatWorkspaceNode {
const ChatWorkspaceNode(this.id);
final String id;
}
class ChatWorkspacePane extends ChatWorkspaceNode {
const ChatWorkspacePane(super.id, this.sessionId);
final String sessionId;
}
class ChatWorkspaceSplit extends ChatWorkspaceNode {
const ChatWorkspaceSplit(
super.id,
this.axis,
this.first,
this.second, {
this.ratio = .5,
});
final ChatSplitAxis axis;
final ChatWorkspaceNode first, second;
final double ratio;
}
@@ -0,0 +1,177 @@
import 'dart:convert';
import 'chat_workspace_nodes.dart';
const chatWorkspaceSnapshotMaxLength = 128 * 1024;
const chatWorkspaceSnapshotMaxNodes = 127;
const chatWorkspaceSnapshotMaxDepth = 32;
const chatWorkspaceSidebarModes = {'expanded', 'compact', 'hidden'};
/// Validated local presentation state. It contains identities and geometry only,
/// never credentials, messages, drafts, or commands to create/reopen a session.
class ChatWorkspaceSnapshot {
const ChatWorkspaceSnapshot._(this.root, this.activePaneId, this.sidebarMode);
final ChatWorkspaceNode? root;
final String? activePaneId;
final String sidebarMode;
static ChatWorkspaceSnapshot? fromLayout(
ChatWorkspaceNode? root,
String? activePaneId, {
String sidebarMode = 'expanded',
}) {
try {
final codec = _NodeCodec();
if (root != null) codec.write(root, 1);
if (!chatWorkspaceSidebarModes.contains(sidebarMode) ||
(root == null
? activePaneId != null
: !codec.paneIds.contains(activePaneId))) {
return null;
}
final snapshot = ChatWorkspaceSnapshot._(root, activePaneId, sidebarMode);
return snapshot.encode().length <= chatWorkspaceSnapshotMaxLength
? snapshot
: null;
} on Object {
return null;
}
}
String encode() => jsonEncode({
'version': 1,
'root': root == null ? null : _NodeCodec().write(root!, 1),
'active_pane': activePaneId,
'sidebar_mode': sidebarMode,
});
static ChatWorkspaceSnapshot? decode(String source) {
if (source.length > chatWorkspaceSnapshotMaxLength ||
!_boundedJson(source)) {
return null;
}
try {
final data = jsonDecode(source);
if (data is! Map || data['version'] != 1 || !data.containsKey('root')) {
return null;
}
final codec = _NodeCodec();
final root = data['root'] == null ? null : codec.read(data['root'], 1);
final active = data['active_pane'];
final sidebar = data['sidebar_mode'] ?? 'expanded';
if (active != null && active is! String || sidebar is! String) {
return null;
}
return fromLayout(root, active as String?, sidebarMode: sidebar);
} on Object {
return null;
}
}
}
class _NodeCodec {
final _ids = <String>{};
final _sessions = <String>{};
final paneIds = <String>{};
String _id(Object? value, int depth) {
if (depth > chatWorkspaceSnapshotMaxDepth ||
_ids.length >= chatWorkspaceSnapshotMaxNodes ||
!_identity(value, 256) ||
!_ids.add(value as String)) {
throw const FormatException('Invalid workspace node');
}
return value;
}
double _ratio(Object? value) {
if (value is! num || !value.isFinite || value <= 0 || value >= 1) {
throw const FormatException('Invalid workspace ratio');
}
return value.toDouble();
}
String _session(Object? value, String paneId) {
if (!_identity(value, 512) || !_sessions.add(value as String)) {
throw const FormatException('Invalid workspace session');
}
paneIds.add(paneId);
return value;
}
Map<String, Object?> write(ChatWorkspaceNode node, int depth) {
final id = _id(node.id, depth);
if (node is ChatWorkspacePane) {
return {
'kind': 'pane',
'id': id,
'session_id': _session(node.sessionId, id),
};
}
final split = node as ChatWorkspaceSplit;
return {
'kind': 'split',
'id': id,
'axis': split.axis.name,
'ratio': _ratio(split.ratio),
'first': write(split.first, depth + 1),
'second': write(split.second, depth + 1),
};
}
ChatWorkspaceNode read(Object? data, int depth) {
if (data is! Map) throw const FormatException('Invalid workspace node');
final id = _id(data['id'], depth);
if (data['kind'] == 'pane') {
return ChatWorkspacePane(id, _session(data['session_id'], id));
}
final axis = switch (data['axis']) {
'horizontal' => ChatSplitAxis.horizontal,
'vertical' => ChatSplitAxis.vertical,
_ => null,
};
if (data['kind'] != 'split' || axis == null) {
throw const FormatException('Invalid workspace split');
}
return ChatWorkspaceSplit(
id,
axis,
read(data['first'], depth + 1),
read(data['second'], depth + 1),
ratio: _ratio(data['ratio']),
);
}
}
bool _identity(Object? value, int limit) =>
value is String &&
value.isNotEmpty &&
value.length <= limit &&
value.trim() == value &&
!value.contains(RegExp(r'[\x00-\x20\x7f]'));
/// Bound nesting before jsonDecode, including hostile unknown-field payloads.
bool _boundedJson(String text) {
var depth = 0;
var quoted = false;
var escaped = false;
for (final unit in text.codeUnits) {
if (quoted) {
if (escaped) {
escaped = false;
} else if (unit == 92) {
escaped = true;
} else if (unit == 34) {
quoted = false;
}
} else if (unit == 34) {
quoted = true;
} else if (unit == 123 || unit == 91) {
if (++depth > chatWorkspaceSnapshotMaxDepth + 2) return false;
} else if (unit == 125 || unit == 93) {
if (--depth < 0) return false;
}
}
return depth == 0 && !quoted;
}
@@ -0,0 +1,42 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/servers/server_scope.dart';
import 'chat_workspace_snapshot.dart';
const chatWorkspacePreferenceKey = 'pipelines.next.chatWorkspace.v1';
abstract interface class ChatWorkspaceStore {
Future<ChatWorkspaceSnapshot?> read();
Future<bool> write(ChatWorkspaceSnapshot snapshot);
}
/// Preferences are local to this device/browser, then scoped to logical server
/// identity like chat drafts. Server aliases can share a layout without saving
/// authentication values or sending presentation state to any server.
class SharedPreferencesChatWorkspaceStore implements ChatWorkspaceStore {
const SharedPreferencesChatWorkspaceStore({required this.serverScope});
final String serverScope;
String get key => scopedServerKey(chatWorkspacePreferenceKey, serverScope);
@override
Future<ChatWorkspaceSnapshot?> read() async {
try {
final preferences = await SharedPreferences.getInstance();
final source = preferences.getString(key);
return source == null ? null : ChatWorkspaceSnapshot.decode(source);
} on Object {
return null;
}
}
@override
Future<bool> write(ChatWorkspaceSnapshot snapshot) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(key, snapshot.encode());
} on Object {
return false;
}
}
}