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 {};
}
}
}