From c4776657c8f7e74ce8db5b7b59f000ebae61b640 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 6 Nov 2026 19:10:20 +0000 Subject: [PATCH] Persist validated device-local chat workspace layouts --- .../workspace/chat_workspace_controller.dart | 83 ++++-- .../chat/workspace/chat_workspace_nodes.dart | 24 ++ .../workspace/chat_workspace_snapshot.dart | 177 ++++++++++++ .../chat/workspace/chat_workspace_store.dart | 42 +++ app/notes/chat-workspace-persistence.md | 23 ++ .../chat_workspace_persistence_test.dart | 268 ++++++++++++++++++ 6 files changed, 586 insertions(+), 31 deletions(-) create mode 100644 app/lib/features/chat/workspace/chat_workspace_nodes.dart create mode 100644 app/lib/features/chat/workspace/chat_workspace_snapshot.dart create mode 100644 app/lib/features/chat/workspace/chat_workspace_store.dart create mode 100644 app/notes/chat-workspace-persistence.md create mode 100644 app/test/features/chat/workspace/chat_workspace_persistence_test.dart diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index 5ed65efc..467e36cc 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -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 = {}; + 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( diff --git a/app/lib/features/chat/workspace/chat_workspace_nodes.dart b/app/lib/features/chat/workspace/chat_workspace_nodes.dart new file mode 100644 index 00000000..bce7d994 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_nodes.dart @@ -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; +} diff --git a/app/lib/features/chat/workspace/chat_workspace_snapshot.dart b/app/lib/features/chat/workspace/chat_workspace_snapshot.dart new file mode 100644 index 00000000..ec210797 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_snapshot.dart @@ -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 = {}; + final _sessions = {}; + final paneIds = {}; + + 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 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; +} diff --git a/app/lib/features/chat/workspace/chat_workspace_store.dart b/app/lib/features/chat/workspace/chat_workspace_store.dart new file mode 100644 index 00000000..88ef11e8 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_store.dart @@ -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 read(); + Future 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 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 write(ChatWorkspaceSnapshot snapshot) async { + try { + final preferences = await SharedPreferences.getInstance(); + return await preferences.setString(key, snapshot.encode()); + } on Object { + return false; + } + } +} diff --git a/app/notes/chat-workspace-persistence.md b/app/notes/chat-workspace-persistence.md new file mode 100644 index 00000000..78dd61ad --- /dev/null +++ b/app/notes/chat-workspace-persistence.md @@ -0,0 +1,23 @@ +# Local chat workspace persistence + +`ChatWorkspaceSnapshot` encodes the split tree, stable pane IDs, chat session IDs, +axes, divider ratios, active pane, and sidebar mode. It contains no message bodies, +drafts, authentication, or server-side session operations. The SharedPreferences +store scopes its key by the supplied logical server storage identity; browser and +mobile preferences remain local to their installation. + +The screen owns loading and saving. Capture `controller.revision` before an async +read and supply it as `expectedRevision` to `restoreLayout` so opening, splitting, +resizing, or activating chats during loading takes precedence over stored state. +Explicit initial routes can select their chat after a successful restore. Save +mutations and sidebar changes with debounce/serialized writes. A validated empty +snapshot records deliberate closure rather than resurrecting an older workspace. + +Version 1 validates IDs, uniqueness, active membership, axes and finite ratios, +with a maximum 128 KiB representation, 127 nodes and depth 32. Invalid or unknown +versions return null; unknown ordinary fields remain compatible. The store also +returns null for unavailable/corrupt preferences and false for failed writes. +Session availability is a screen/provider concern: the codec preserves identities +without contacting or reopening sessions on the server. + +Focused validation: `tool/memwatch/full.sh 'test/features/chat/workspace --no-pub'`. diff --git a/app/test/features/chat/workspace/chat_workspace_persistence_test.dart b/app/test/features/chat/workspace/chat_workspace_persistence_test.dart new file mode 100644 index 00000000..81084325 --- /dev/null +++ b/app/test/features/chat/workspace/chat_workspace_persistence_test.dart @@ -0,0 +1,268 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_snapshot.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; + +ChatWorkspaceController _layout() { + final controller = ChatWorkspaceController()..open('session-a'); + controller.splitActive('session-b', ChatSplitAxis.horizontal); + final horizontal = controller.root as ChatWorkspaceSplit; + controller.resize(horizontal.id, .37); + controller.splitActive('session-c', ChatSplitAxis.vertical); + final vertical = + (controller.root as ChatWorkspaceSplit).second as ChatWorkspaceSplit; + controller.resize(vertical.id, .64); + controller.activate(controller.panes.first.id); + return controller; +} + +Map _pane(String id, String session) => { + 'kind': 'pane', + 'id': id, + 'session_id': session, +}; +Map _split(Object? first, Object? second) => { + 'kind': 'split', + 'id': 'split', + 'axis': 'horizontal', + 'ratio': .5, + 'first': first, + 'second': second, +}; +String _json( + Object? root, { + Object? active = 'a', + Object? sidebar = 'expanded', +}) => jsonEncode({ + 'version': 1, + 'root': root, + 'active_pane': active, + 'sidebar_mode': sidebar, +}); + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test( + 'cold store/controller restores nested axes, exact ratios, active pane and sidebar', + () async { + final original = _layout(); + addTearDown(original.dispose); + final snapshot = original.snapshot(sidebarMode: 'hidden')!; + const store = SharedPreferencesChatWorkspaceStore( + serverScope: 'server-a', + ); + expect(await store.write(snapshot), isTrue); + final restored = await const SharedPreferencesChatWorkspaceStore( + serverScope: 'server-a', + ).read(); + expect(restored, isNotNull); + expect(restored!.encode(), snapshot.encode()); + final fresh = ChatWorkspaceController(); + addTearDown(fresh.dispose); + expect(fresh.restoreLayout(restored, expectedRevision: 0), isTrue); + expect(fresh.panes.map((p) => p.sessionId), [ + 'session-a', + 'session-b', + 'session-c', + ]); + expect(fresh.panes.map((p) => p.id), original.panes.map((p) => p.id)); + expect(fresh.activePane!.sessionId, 'session-a'); + final root = fresh.root as ChatWorkspaceSplit; + expect(root.axis, ChatSplitAxis.horizontal); + expect(root.ratio, .37); + expect((root.second as ChatWorkspaceSplit).axis, ChatSplitAxis.vertical); + expect((root.second as ChatWorkspaceSplit).ratio, .64); + expect(restored.sidebarMode, 'hidden'); + fresh.splitActive('session-d', ChatSplitAxis.vertical); + final ids = []; + void collect(ChatWorkspaceNode node) { + ids.add(node.id); + if (node is ChatWorkspaceSplit) { + collect(node.first); + collect(node.second); + } + } + + collect(fresh.root!); + expect( + ids.toSet().length, + ids.length, + reason: 'new IDs must not collide after restore', + ); + }, + ); + + test( + 'per-server keys isolate layouts, legacy key remains independent, no draft data saved', + () async { + final controller = _layout(); + addTearDown(controller.dispose); + const a = SharedPreferencesChatWorkspaceStore(serverScope: 'a'); + const b = SharedPreferencesChatWorkspaceStore(serverScope: 'b'); + const legacy = SharedPreferencesChatWorkspaceStore(serverScope: ''); + expect( + await a.write(controller.snapshot(sidebarMode: 'compact')!), + isTrue, + ); + expect(await b.read(), isNull); + expect(await legacy.read(), isNull); + final preferences = await SharedPreferences.getInstance(); + expect(preferences.getKeys(), {a.key}); + final stored = preferences.getString(a.key)!; + expect(stored, isNot(contains('draft'))); + expect((await a.read())!.sidebarMode, 'compact'); + // A second mocked device/browser has its own preferences. + SharedPreferences.setMockInitialValues({}); + expect(await a.read(), isNull); + }, + ); + + test( + 'late restore cannot replace mutations made while preferences load', + () async { + final saved = _layout(); + addTearDown(saved.dispose); + final controller = ChatWorkspaceController()..open('initial'); + addTearDown(controller.dispose); + final expected = controller.revision; + final pending = Future.value(saved.snapshot()!); + controller.open('user-chosen'); + expect( + controller.restoreLayout(await pending, expectedRevision: expected), + isFalse, + ); + expect(controller.activePane!.sessionId, 'user-chosen'); + expect(controller.paneCount, 1); + final before = controller.revision; + expect( + controller.restoreLayout(saved.snapshot()!, expectedRevision: before), + isTrue, + ); + expect(controller.revision, before + 1); + }, + ); + + test( + 'empty layout records deliberate closure instead of resurrecting old panes', + () async { + const store = SharedPreferencesChatWorkspaceStore(serverScope: 'a'); + final controller = _layout(); + addTearDown(controller.dispose); + await store.write(controller.snapshot()!); + for (final pane in controller.panes.toList()) { + controller.close(pane.id); + } + expect( + await store.write(controller.snapshot(sidebarMode: 'compact')!), + isTrue, + ); + final stored = (await store.read())!; + expect(stored.root, isNull); + expect(stored.activePaneId, isNull); + expect(stored.sidebarMode, 'compact'); + }, + ); + + test( + 'corrupt, unsupported, duplicate, missing and nonfinite values are ignored', + () { + final a = _pane('a', 'session-a'); + final cases = [ + '', + '[]', + '{', + '{"version":1}', + '{"version":2,"root":null}', + _json(a, active: 'unknown'), + _json(a, active: 7), + _json(a, sidebar: 'unknown'), + _json({'kind': 'pane', 'id': '', 'session_id': 's'}), + _json(_split(a, _pane('a', 'session-b'))), + _json(_split(a, _pane('b', 'session-a'))), + _json({..._split(a, _pane('b', 'session-b')), 'axis': 'diagonal'}), + _json({..._split(a, _pane('b', 'session-b')), 'ratio': 0}), + _json({..._split(a, _pane('b', 'session-b')), 'ratio': 1.1}), + _json({..._split(a, _pane('b', 'session-b')), 'second': null}), + _json({'kind': 'future', 'id': 'a'}), + _json(_pane('a', 'session with space')), + '{"version":1,"root":{"kind":"split","id":"s","axis":"horizontal","ratio":1e999}}', + ]; + for (final source in cases) { + expect(ChatWorkspaceSnapshot.decode(source), isNull, reason: source); + } + expect( + ChatWorkspaceSnapshot.fromLayout( + ChatWorkspaceSplit( + 's', + ChatSplitAxis.horizontal, + const ChatWorkspacePane('a', 'a'), + const ChatWorkspacePane('b', 'b'), + ratio: double.nan, + ), + 'a', + ), + isNull, + ); + }, + ); + + test( + 'unknown ordinary fields are forward compatible but nesting and size are bounded', + () { + final data = + jsonDecode(_json(_pane('a', 'session-a'))) as Map; + data['future'] = {'name': 'quoted braces: "{[\\'}; + expect(ChatWorkspaceSnapshot.decode(jsonEncode(data)), isNotNull); + expect( + ChatWorkspaceSnapshot.decode( + ' ' * (chatWorkspaceSnapshotMaxLength + 1), + ), + isNull, + ); + final deeplyNested = "${'[' * 1000}0${']' * 1000}"; + expect(ChatWorkspaceSnapshot.decode(deeplyNested), isNull); + ChatWorkspaceNode deep = const ChatWorkspacePane('p0', 'session0'); + for (var i = 1; i <= chatWorkspaceSnapshotMaxDepth; i++) { + deep = ChatWorkspaceSplit( + 's$i', + ChatSplitAxis.vertical, + deep, + ChatWorkspacePane('p$i', 'session$i'), + ); + } + expect(ChatWorkspaceSnapshot.fromLayout(deep, 'p0'), isNull); + var serial = 0; + ChatWorkspaceNode balanced(int levels) { + if (levels == 0) { + final n = serial++; + return ChatWorkspacePane('p$n', 'session$n'); + } + final id = 's${serial++}'; + return ChatWorkspaceSplit( + id, + ChatSplitAxis.horizontal, + balanced(levels - 1), + balanced(levels - 1), + ); + } + + final tooMany = balanced(7); + expect(ChatWorkspaceSnapshot.fromLayout(tooMany, 'p7'), isNull); + }, + ); + + test( + 'bad preference type or malformed stored blob is not treated as a valid empty workspace', + () async { + const store = SharedPreferencesChatWorkspaceStore(serverScope: 'a'); + SharedPreferences.setMockInitialValues({store.key: 12}); + expect(await store.read(), isNull); + SharedPreferences.setMockInitialValues({store.key: '{"version":1}'}); + expect(await store.read(), isNull); + }, + ); +}