Remember the last Files folder per chat

Persist each chat session's last navigated Files folder, restore it with bounded parent fallback, and forget it when the session closes. Add persistence coverage and capture-fixture support for the reviewed behavior.
This commit is contained in:
2026-11-12 22:56:52 +00:00
parent d19a14b9f9
commit 1928cfe51b
7 changed files with 277 additions and 4 deletions
@@ -270,6 +270,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
FilesController _newFilesController() => FilesController(
gateway: widget.gateway,
initialPath: '${widget.session?['directory'] ?? ''}',
sessionId: widget.sessionId,
folderPreferences: _filesPreferences,
);
FilesPreferences get _filesPreferences =>
@@ -509,6 +511,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
void _sessionClosed() {
_closed = true;
unawaited(_filesPreferences.forgetFolder(widget.sessionId));
widget.transcripts?.remove(widget.sessionId);
widget.onSessionClosed?.call();
}
@@ -7,10 +7,18 @@ import '../domain/chat_attachment_picker.dart';
import 'files_models.dart';
import 'files_mutations.dart';
import 'files_upload.dart';
import 'files_preferences.dart';
class FilesController extends ChangeNotifier {
FilesController({required this.gateway, required this.initialPath});
FilesController({
required this.gateway,
required this.initialPath,
this.sessionId,
this.folderPreferences,
});
final ApiGateway gateway;
final String? sessionId;
final FilesPreferences? folderPreferences;
String initialPath;
bool _started = false;
DirectoryListing? listing;
@@ -55,7 +63,73 @@ class FilesController extends ChangeNotifier {
Future<void> start() {
_started = true;
return open(initialPath);
return _openRemembered();
}
Future<void> _openRemembered() async {
final remembered = sessionId == null || folderPreferences == null
? null
: await folderPreferences!.rememberedFolder(sessionId!);
if (_disposed) return;
final candidate = remembered != null && _isWithinRoot(remembered)
? remembered
: _rootPath;
await _openWithFallback(candidate);
}
Future<void> _openWithFallback(String candidate) async {
var path = _isWithinRoot(candidate) ? _normal(candidate) : _rootPath;
while (path.trim().isNotEmpty) {
final request = ++_request;
loading = true;
error = null;
_notify();
try {
final next = await listDirectory(gateway, path);
if (_disposed || request != _request) return;
listing = next;
filter = '';
await _remember(next.path);
loading = false;
_notify();
return;
} catch (_) {
if (_disposed || request != _request) return;
final parent = _parentWithinRoot(path);
if (parent == null) {
error = "Couldn't load this folder.";
loading = false;
_notify();
return;
}
path = parent;
}
}
}
String? _parentWithinRoot(String path) {
if (path == _rootPath) return null;
final slash = path.lastIndexOf('/');
if (slash < 0) return null;
final parent = slash == 0 ? '/' : path.substring(0, slash);
return _isWithinRoot(parent) ? parent : null;
}
String get _rootPath => _normal(initialPath);
String _normal(String path) {
final value = path.trim();
return value.length > 1 && value.endsWith('/')
? value.replaceFirst(RegExp(r'/+$'), '')
: value;
}
bool _isWithinRoot(String path) => isInsideHome(_rootPath, _normal(path));
Future<void> _remember(String path) async {
if (sessionId != null && folderPreferences != null) {
await folderPreferences!.setRememberedFolder(sessionId!, path);
}
}
/// Session metadata can arrive after the retained conversation is mounted.
@@ -66,7 +140,7 @@ class FilesController extends ChangeNotifier {
initialPath = path;
if (_started && (listing == null || listing!.path == previous)) {
listing = null;
await open(path);
await _openRemembered();
} else {
_notify();
}
@@ -83,6 +157,7 @@ class FilesController extends ChangeNotifier {
if (_disposed || request != _request) return;
listing = next;
filter = '';
await _remember(next.path);
} catch (e) {
if (_disposed || request != _request) return;
error = "Couldn't load this folder.";
@@ -1,4 +1,5 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'files_models.dart';
class FilesPreferences {
@@ -39,4 +40,55 @@ class FilesPreferences {
await prefs.setString('$_prefix.sort', value.key.name);
await prefs.setBool('$_prefix.asc', value.ascending);
}
/// The last folder for each chat. This is deliberately one bounded record,
/// rather than one preference key per chat, so old chats can be evicted.
Future<String?> rememberedFolder(String sessionId) async {
final records = await _records();
final record = records[sessionId];
return record is Map ? '${record['path'] ?? ''}'.trim() : null;
}
Future<void> setRememberedFolder(String sessionId, String path) async {
if (sessionId.trim().isEmpty || path.trim().isEmpty) return;
final records = await _records();
records[sessionId] = {
'path': path.trim(),
'used': DateTime.now().microsecondsSinceEpoch,
};
final ordered = records.entries.toList()
..sort(
(a, b) => (a.value['used'] as int).compareTo(b.value['used'] as int),
);
final kept = <String, dynamic>{
for (final entry in ordered.skip(
ordered.length > 200 ? ordered.length - 200 : 0,
))
entry.key: entry.value,
};
await (await _prefs()).setString('$_prefix.folders', jsonEncode(kept));
}
Future<void> forgetFolder(String sessionId) async {
final records = await _records();
if (records.remove(sessionId) != null) {
await (await _prefs()).setString('$_prefix.folders', jsonEncode(records));
}
}
Future<Map<String, dynamic>> _records() async {
final raw = (await _prefs()).getString('$_prefix.folders');
if (raw == null) return {};
try {
final decoded = jsonDecode(raw);
if (decoded is! Map) return {};
return {
for (final entry in decoded.entries)
if (entry.key is String && entry.value is Map)
entry.key as String: Map<String, dynamic>.from(entry.value as Map),
};
} catch (_) {
return {};
}
}
}
+13
View File
@@ -0,0 +1,13 @@
# Files remembers the last folder
Implemented per-server/per-chat Files folder persistence with a bounded 200-entry SharedPreferences record. Successful directory navigation updates the record; startup restores it, validates it against the chat directory, and walks parent folders using `list_directory` when the saved folder is gone. Closing a chat removes its record. File previews and filters remain transient.
## Checks
- `tool/memwatch/full.sh 'test/features/chat/files/files_controller_persistence_test.dart test/features/chat/files/files_panel_test.dart test/features/chat/files/files_models_test.dart'`: 20 passed.
- `tool/analyze.sh`: clean.
- Browser/device captures were not run in this implementation stage.
The browser fixture supports `filesMissing=1` alongside `files=1`: after
seeding a remembered `assets` folder, reload with that flag to show the folder
request failing and the panel reopening at `/workspace/demo`.
@@ -0,0 +1,116 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/files/files_controller.dart';
import 'package:pipelines_app/features/chat/files/files_preferences.dart';
class _Gateway extends PipelinesClient {
@override
Uri get endpoint => Uri.parse('ws://example.test/connect');
@override
Stream<JsonMap> get frames => const Stream.empty();
final Set<String> missing;
final requested = <String>[];
_Gateway([this.missing = const {}]);
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
final path = '${(fields['list_directory'] as Map?)?['path'] ?? ''}';
requested.add(path);
if (missing.contains(path)) throw StateError('missing');
return {
'directory_listing': {
'path': path,
'home': '/home/chat',
'entries': const [],
},
};
}
}
void main() {
const server = FilesPreferences('example');
setUp(() => SharedPreferences.setMockInitialValues({}));
test('restores a folder after a new controller is created', () async {
final first = FilesController(
gateway: _Gateway(),
initialPath: '/home/chat',
sessionId: 'one',
folderPreferences: server,
);
await first.start();
await first.open('/home/chat/src');
first.dispose();
final gateway = _Gateway();
final second = FilesController(
gateway: gateway,
initialPath: '/home/chat',
sessionId: 'one',
folderPreferences: server,
);
await second.start();
expect(second.listing?.path, '/home/chat/src');
expect(gateway.requested, ['/home/chat/src']);
second.dispose();
});
test(
'falls back one parent at a time and never leaves the chat root',
() async {
await server.setRememberedFolder('one', '/home/chat/removed/deep');
final gateway = _Gateway({
'/home/chat/removed/deep',
'/home/chat/removed',
});
final controller = FilesController(
gateway: gateway,
initialPath: '/home/chat',
sessionId: 'one',
folderPreferences: server,
);
await controller.start();
expect(controller.listing?.path, '/home/chat');
expect(gateway.requested, [
'/home/chat/removed/deep',
'/home/chat/removed',
'/home/chat',
]);
controller.dispose();
},
);
test('rejects a remembered path outside the chat root', () async {
await server.setRememberedFolder('one', '/home/other');
final gateway = _Gateway();
final controller = FilesController(
gateway: gateway,
initialPath: '/home/chat',
sessionId: 'one',
folderPreferences: server,
);
await controller.start();
expect(controller.listing?.path, '/home/chat');
expect(gateway.requested, ['/home/chat']);
controller.dispose();
});
test('keeps folders separate and forgets a closed chat', () async {
await server.setRememberedFolder('one', '/home/chat/src');
await server.setRememberedFolder('two', '/home/chat/docs');
expect(await server.rememberedFolder('one'), '/home/chat/src');
expect(await server.rememberedFolder('two'), '/home/chat/docs');
await server.forgetFolder('one');
expect(await server.rememberedFolder('one'), isNull);
expect(await server.rememberedFolder('two'), '/home/chat/docs');
});
}
+11
View File
@@ -2,10 +2,21 @@ import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/files/files_urls.dart';
/// A static, two-level explorer fixture. Its files live in capture/fixtures/files.
/// Set [probeMissingRememberedFolder] to make the nested folder disappear so
/// browser captures can exercise the controller's parent fallback.
bool probeMissingRememberedFolder = false;
JsonMap probeFilesReply(JsonMap request) {
final fields = request['list_directory'] as Map?;
final path = '${fields?['path'] ?? '/srv/probe/release'}';
final nested = path.endsWith('/assets');
if (probeMissingRememberedFolder && nested) {
return {
'id': request['id'],
'type': 'error',
'error': 'directory does not exist: $path',
};
}
final entries = nested
? <(String, int)>[('design.png', 18432), ('icon.jpg', 23000)]
: <(String, int)>[
+4 -1
View File
@@ -806,7 +806,10 @@ Future<void> main() async {
return;
}
configurePerfFixture(params);
if (params['files'] == '1') installFilesFixture();
if (params['files'] == '1') {
probeMissingRememberedFolder = params['filesMissing'] == '1';
installFilesFixture();
}
// `?font=inter` chooses a font as Settings would; otherwise the stored one.
final font = params['font'];
unawaited(