diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 5eef36ef..8cc84a43 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import '../../../core/api_gateway.dart'; +import '../../../core/servers/server_scope.dart'; import '../../../shell/shell_bar.dart'; import '../data/chat_attachment_images.dart'; import '../data/chat_repository.dart'; @@ -51,6 +52,9 @@ import 'chat_reading_width.dart'; import 'chat_thread_header.dart'; import 'chat_transcript_anchor.dart'; import 'chat_transcript_cache.dart'; +import '../files/files_controller.dart'; +import '../files/files_panel.dart'; +import '../files/files_preferences.dart'; import 'chat_transcript_scroll_view.dart'; import 'chat_permission_card_model.dart'; import 'chat_permission_group.dart'; @@ -212,6 +216,86 @@ class _ChatThreadViewState extends State { int _commandNoticeSeq = 0; final ScrollController _scroll = ScrollController(); + late FilesController _files = _newFilesController(); + bool _filesVisible = false; + bool _filesPrefsLoaded = false; + bool _filesSheetOpen = false; + + FilesController _newFilesController() => FilesController( + gateway: widget.gateway, + initialPath: '${widget.session?['directory'] ?? ''}', + ); + + FilesPreferences get _filesPreferences => + FilesPreferences(serverStorageScope(serverIdentity(widget.gateway))); + + Future _loadFilesPreferences() async { + final prefs = _filesPreferences; + final visible = await prefs.visible(); + final view = await prefs.view(); + final sort = await prefs.sort(); + if (!mounted) return; + _files.view = view; + _files.sort = sort; + setState(() { + _filesVisible = visible; + _filesPrefsLoaded = true; + }); + if (visible && MediaQuery.sizeOf(context).width < 700) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _openFilesSheet(); + }); + } + } + + void _toggleFiles() { + final next = !_filesVisible; + if (!mounted) return; + setState(() => _filesVisible = next); + unawaited(_filesPreferences.setVisible(next)); + if (next && MediaQuery.sizeOf(context).width < 700) _openFilesSheet(); + } + + void _openFilesSheet() { + if (!mounted || + _filesSheetOpen || + !_filesVisible || + MediaQuery.sizeOf(context).width >= 700) { + return; + } + _filesSheetOpen = true; + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final sheet = cupertino + ? showCupertinoModalPopup( + context: context, + builder: (_) => Align( + alignment: Alignment.bottomCenter, + child: SafeArea( + child: CupertinoPopupSurface( + child: SizedBox( + height: MediaQuery.sizeOf(context).height * .85, + child: FilesPanel(controller: _files), + ), + ), + ), + ), + ) + : showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (_) => SizedBox( + height: MediaQuery.sizeOf(context).height * .85, + child: FilesPanel(controller: _files), + ), + ); + sheet.whenComplete(() { + _filesSheetOpen = false; + if (!mounted) return; + setState(() => _filesVisible = false); + unawaited(_filesPreferences.setVisible(false)); + }); + } /// True while the transcript's end is in view. The operator's own upward /// scroll releases it; only returning to the end (or the jump control) arms @@ -466,6 +550,8 @@ class _ChatThreadViewState extends State { @override void initState() { super.initState(); + _files.addListener(_persistFilesPreferences); + unawaited(_loadFilesPreferences()); _savedPosition = widget.scrollPositions?.read(widget.sessionId); _adoptCachedTranscript(); _seedCommandNotice(); @@ -486,6 +572,11 @@ class _ChatThreadViewState extends State { } _controller.dispose(); _composer.dispose(); + _files.removeListener(_persistFilesPreferences); + _files.dispose(); + _files = _newFilesController()..addListener(_persistFilesPreferences); + _filesVisible = false; + unawaited(_loadFilesPreferences()); _closed = false; _controller = _attach(); _composer = _attachComposer(); @@ -549,9 +640,18 @@ class _ChatThreadViewState extends State { _scroll.dispose(); _composer.dispose(); _controller.dispose(); + _files.removeListener(_persistFilesPreferences); + _files.dispose(); super.dispose(); } + void _persistFilesPreferences() { + if (!_filesPrefsLoaded) return; + final prefs = _filesPreferences; + unawaited(prefs.setView(_files.view)); + unawaited(prefs.setSort(_files.sort)); + } + /// The ids of the transcript's messages in view order. Cards are conversation /// state, not messages, so a pending approval does not count as an arrival. List _messageIds() => [ @@ -1146,13 +1246,26 @@ class _ChatThreadViewState extends State { // composer sits below it; the wheel over them scrolls it, as a page // scrolls under fixed bars. final column = VerticalWheelForwarder(controller: _scroll, child: page); - if (!inShellBar) return column; + final wideFiles = + _filesVisible && MediaQuery.sizeOf(context).width >= 700; + final content = wideFiles + ? Row( + children: [ + Expanded(child: column), + SizedBox( + width: filesPanelWidth(MediaQuery.sizeOf(context).width), + child: FilesPanel(controller: _files), + ), + ], + ) + : column; + if (!inShellBar) return content; // The conversation draws its own floating bar; the page shows none. final title = widget.title.trim(); return ShellBar( barless: true, title: title.isEmpty ? null : title, - child: column, + child: content, ); }, ); @@ -1212,6 +1325,15 @@ class _ChatThreadViewState extends State { // would take more than half the pill. A session without a mode draws // no mode control, so no empty pill is ever drawn. controls: [ + ChatBarAction( + label: 'Files', + identifier: 'chat-files-toggle', + onPressed: _toggleFiles, + materialIcon: _filesVisible ? Icons.folder : Icons.folder_outlined, + cupertinoIcon: _filesVisible + ? CupertinoIcons.folder_fill + : CupertinoIcons.folder, + ), ?widget.sidebarControl, ...widget.paneControls, if (hasModel) diff --git a/app/lib/features/chat/data/directory_listing.dart b/app/lib/features/chat/data/directory_listing.dart index fe31a4df..73fa43f8 100644 --- a/app/lib/features/chat/data/directory_listing.dart +++ b/app/lib/features/chat/data/directory_listing.dart @@ -9,6 +9,8 @@ class DirectoryEntry { required this.isDir, required this.isGitRepo, required this.hidden, + this.size, + this.modified, }); factory DirectoryEntry.fromJson(JsonMap json) => DirectoryEntry( @@ -17,6 +19,8 @@ class DirectoryEntry { isDir: json['is_dir'] == true, isGitRepo: json['is_git_repo'] == true, hidden: json['hidden'] == true, + size: json['size'] is num ? (json['size'] as num).toInt() : null, + modified: json['modified'] is String ? json['modified'] as String : null, ); final String name; @@ -24,6 +28,8 @@ class DirectoryEntry { final bool isDir; final bool isGitRepo; final bool hidden; + final int? size; + final String? modified; } /// The server's home-restricted listing of one folder. diff --git a/app/lib/features/chat/files/files_controller.dart b/app/lib/features/chat/files/files_controller.dart new file mode 100644 index 00000000..c4bc614f --- /dev/null +++ b/app/lib/features/chat/files/files_controller.dart @@ -0,0 +1,90 @@ +import 'package:flutter/foundation.dart'; +import '../../../core/api_gateway.dart'; +import '../data/directory_listing.dart'; +import 'files_models.dart'; + +class FilesController extends ChangeNotifier { + FilesController({required this.gateway, required this.initialPath}); + final ApiGateway gateway; + final String initialPath; + DirectoryListing? listing; + String? error; + bool loading = false; + bool showHidden = false; + String filter = ''; + FilesSort sort = const FilesSort(FilesSortKey.name); + FilesViewMode view = FilesViewMode.list; + int _request = 0; + bool _disposed = false; + + bool get missingDirectory => initialPath.trim().isEmpty; + List get entries { + final current = listing; + if (current == null) return const []; + final needle = filter.trim().toLowerCase(); + return sortFileEntries( + current.entries.where( + (entry) => + (showHidden || !entry.hidden) && + (needle.isEmpty || entry.name.toLowerCase().contains(needle)), + ), + sort, + ); + } + + Future start() => open(initialPath); + + Future open(String? path) async { + if (path == null || path.trim().isEmpty) return; + final request = ++_request; + loading = true; + error = null; + _notify(); + try { + final next = await listDirectory(gateway, path); + if (_disposed || request != _request) return; + listing = next; + filter = ''; + } catch (e) { + if (_disposed || request != _request) return; + error = '$e'; + } finally { + if (!_disposed && request == _request) { + loading = false; + _notify(); + } + } + } + + Future retry() => open(listing?.path ?? initialPath); + void toggleHidden(bool value) { + showHidden = value; + _notify(); + } + + void setFilter(String value) { + filter = value; + _notify(); + } + + void setSort(FilesSort value) { + sort = value; + _notify(); + } + + void setView(FilesViewMode value) { + view = value; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _request++; + super.dispose(); + } +} diff --git a/app/lib/features/chat/files/files_icons.dart b/app/lib/features/chat/files/files_icons.dart new file mode 100644 index 00000000..8fb19f8b --- /dev/null +++ b/app/lib/features/chat/files/files_icons.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; +import '../../artifacts/domain/artifact_kind.dart'; +import '../data/directory_listing.dart'; + +/// Chooses the same broad kind glyphs used by the artifact gallery. +IconData fileIcon(DirectoryEntry entry) { + if (entry.isDir) return Icons.folder_outlined; + + switch (artifactKind('', entry.name)) { + case ArtifactKind.image: + return Icons.image_outlined; + case ArtifactKind.video: + return Icons.movie_outlined; + case ArtifactKind.audio: + return Icons.audio_file_outlined; + case ArtifactKind.pdf: + return Icons.picture_as_pdf_outlined; + case ArtifactKind.json: + case ArtifactKind.code: + return Icons.code_outlined; + case ArtifactKind.archive: + return Icons.archive_outlined; + case ArtifactKind.spreadsheet: + return Icons.table_chart_outlined; + case ArtifactKind.log: + case ArtifactKind.document: + return Icons.description_outlined; + case ArtifactKind.other: + return Icons.insert_drive_file_outlined; + } +} diff --git a/app/lib/features/chat/files/files_models.dart b/app/lib/features/chat/files/files_models.dart new file mode 100644 index 00000000..8bbb1bf6 --- /dev/null +++ b/app/lib/features/chat/files/files_models.dart @@ -0,0 +1,56 @@ +import '../data/directory_listing.dart'; +import '../../artifacts/domain/artifact_kind.dart'; + +enum FilesViewMode { list, grid } + +enum FilesSortKey { name, modified, size, kind } + +class FilesSort { + const FilesSort(this.key, {this.ascending = true}); + final FilesSortKey key; + final bool ascending; + + FilesSort reverseOr(FilesSortKey next) => + FilesSort(next, ascending: next == key ? !ascending : true); +} + +List sortFileEntries( + Iterable entries, + FilesSort sort, +) { + final result = entries.toList(); + result.sort((a, b) { + // Keep directories above files regardless of the selected direction. + if (a.isDir != b.isDir) return a.isDir ? -1 : 1; + int compare; + switch (sort.key) { + case FilesSortKey.name: + compare = a.name.toLowerCase().compareTo(b.name.toLowerCase()); + case FilesSortKey.modified: + compare = (a.modified ?? '').compareTo(b.modified ?? ''); + case FilesSortKey.size: + compare = (a.size ?? -1).compareTo(b.size ?? -1); + case FilesSortKey.kind: + compare = fileKind(a).compareTo(fileKind(b)); + } + if (compare == 0) compare = a.name.compareTo(b.name); + return sort.ascending ? compare : -compare; + }); + return result; +} + +String fileKind(DirectoryEntry entry) => + entry.isDir ? 'Folder' : artifactKind('', entry.name).name; + +String fileSizeLabel(int? size) { + if (size == null) return '—'; + if (size < 1024) return '$size B'; + final units = ['KiB', 'MiB', 'GiB', 'TiB']; + var value = size.toDouble(); + var unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return '${value.toStringAsFixed(value >= 10 ? 0 : 1)} ${units[unit]}'; +} diff --git a/app/lib/features/chat/files/files_panel.dart b/app/lib/features/chat/files/files_panel.dart new file mode 100644 index 00000000..9a1d8622 --- /dev/null +++ b/app/lib/features/chat/files/files_panel.dart @@ -0,0 +1,239 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import '../data/directory_listing.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'files_controller.dart'; +import 'files_icons.dart'; +import 'files_models.dart'; + +const double filesPanelMinWidth = 280; +const double filesPanelMaxWidth = 420; +const double filesPanelFraction = .30; + +double filesPanelWidth(double available) => (available * filesPanelFraction) + .clamp(filesPanelMinWidth, filesPanelMaxWidth); + +class FilesPanel extends StatefulWidget { + const FilesPanel({super.key, required this.controller, this.onOpen}); + final FilesController controller; + final ValueChanged? onOpen; + @override + State createState() => _FilesPanelState(); +} + +class _FilesPanelState extends State { + late final TextEditingController _filter = TextEditingController(); + FilesController get controller => widget.controller; + @override + void initState() { + super.initState(); + controller.addListener(_changed); + controller.start(); + } + + void _changed() { + if (mounted) setState(() {}); + } + + @override + void dispose() { + controller.removeListener(_changed); + _filter.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final listing = controller.listing; + if (controller.missingDirectory) { + return const _FilesMessage('This chat has no working directory.'); + } + return Material( + color: Theme.of(context).colorScheme.surface, + child: Column( + children: [ + _header(context, listing), + if (controller.error != null) + ChatErrorNotice( + message: controller.error!, + onRetry: controller.retry, + ), + if (controller.loading && listing == null) + const Expanded(child: ChatLoadingIndicator()) + else if (listing != null && + controller.entries.isEmpty && + !controller.loading) + const Expanded(child: _FilesMessage('This folder is empty.')) + else + Expanded( + child: controller.view == FilesViewMode.grid ? _grid() : _list(), + ), + if (listing?.truncated == true) + const Padding( + padding: EdgeInsets.all(8), + child: Text('Some entries are not shown.'), + ), + ], + ), + ); + } + + Widget _header(BuildContext context, DirectoryListing? listing) => Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 8, 4), + child: Column( + children: [ + Row( + children: [ + if (listing?.parent != null) + IconButton( + tooltip: 'Back', + onPressed: controller.loading + ? null + : () => controller.open(listing!.parent), + icon: const Icon(Icons.arrow_back), + ), + Expanded( + child: Text( + homeRelativeLabel( + listing?.home ?? '', + listing?.path ?? controller.initialPath, + ), + overflow: TextOverflow.ellipsis, + ), + ), + IconButton( + tooltip: 'Refresh', + onPressed: controller.loading ? null : controller.retry, + icon: const Icon(Icons.refresh), + ), + IconButton( + tooltip: controller.view == FilesViewMode.list + ? 'Grid view' + : 'List view', + onPressed: () => controller.setView( + controller.view == FilesViewMode.list + ? FilesViewMode.grid + : FilesViewMode.list, + ), + icon: Icon( + controller.view == FilesViewMode.list + ? Icons.grid_view + : Icons.view_list, + ), + ), + PopupMenuButton( + initialValue: controller.sort.key, + tooltip: 'Sort', + onSelected: (key) => + controller.setSort(controller.sort.reverseOr(key)), + itemBuilder: (_) => [ + for (final key in FilesSortKey.values) + PopupMenuItem(value: key, child: Text(key.name)), + ], + ), + ], + ), + Row( + children: [ + Expanded( + child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoSearchTextField( + controller: _filter, + onChanged: controller.setFilter, + placeholder: 'Filter files', + ) + : TextField( + controller: _filter, + onChanged: controller.setFilter, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + hintText: 'Filter files', + isDense: true, + ), + ), + ), + IconButton( + tooltip: 'Show hidden files', + onPressed: () => controller.toggleHidden(!controller.showHidden), + icon: Icon( + controller.showHidden ? Icons.visibility : Icons.visibility_off, + ), + ), + ], + ), + ], + ), + ); + + Widget _list() => ListView.builder( + itemCount: controller.entries.length, + itemBuilder: (_, index) { + final entry = controller.entries[index]; + return ListTile( + onTap: () => entry.isDir + ? controller.open(entry.path) + : widget.onOpen?.call(entry), + leading: Icon( + fileIcon(entry), + ), + title: Text(entry.name), + subtitle: Text( + entry.isDir + ? 'Folder' + : '${entry.modified ?? 'Unknown'} · ${fileSizeLabel(entry.size)}', + ), + trailing: entry.isDir ? null : Text(fileKind(entry)), + ); + }, + ); + + Widget _grid() => GridView.builder( + padding: const EdgeInsets.all(12), + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 180, + childAspectRatio: 1.25, + ), + itemCount: controller.entries.length, + itemBuilder: (_, index) { + final entry = controller.entries[index]; + return InkWell( + onTap: () => entry.isDir + ? controller.open(entry.path) + : widget.onOpen?.call(entry), + child: Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + fileIcon(entry), + size: 32, + ), + const SizedBox(height: 8), + Text( + entry.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + ], + ), + ), + ), + ); + }, + ); +} + +class _FilesMessage extends StatelessWidget { + const _FilesMessage(this.text); + final String text; + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(text, textAlign: TextAlign.center), + ), + ); +} diff --git a/app/lib/features/chat/files/files_preferences.dart b/app/lib/features/chat/files/files_preferences.dart new file mode 100644 index 00000000..7a195c13 --- /dev/null +++ b/app/lib/features/chat/files/files_preferences.dart @@ -0,0 +1,42 @@ +import 'package:shared_preferences/shared_preferences.dart'; +import 'files_models.dart'; + +class FilesPreferences { + const FilesPreferences(this.serverScope); + final String serverScope; + + String get _prefix => 'pipelines.chat.files.v1.$serverScope'; + + Future _prefs() => SharedPreferences.getInstance(); + + Future visible() async => + (await _prefs()).getBool('$_prefix.visible') ?? false; + Future setVisible(bool value) async => + (await _prefs()).setBool('$_prefix.visible', value); + + Future view() async { + final value = (await _prefs()).getString('$_prefix.view'); + return FilesViewMode.values.firstWhere( + (v) => v.name == value, + orElse: () => FilesViewMode.list, + ); + } + + Future setView(FilesViewMode value) async => + (await _prefs()).setString('$_prefix.view', value.name); + + Future sort() async { + final prefs = await _prefs(); + final key = FilesSortKey.values.firstWhere( + (v) => v.name == prefs.getString('$_prefix.sort'), + orElse: () => FilesSortKey.name, + ); + return FilesSort(key, ascending: prefs.getBool('$_prefix.asc') ?? true); + } + + Future setSort(FilesSort value) async { + final prefs = await _prefs(); + await prefs.setString('$_prefix.sort', value.key.name); + await prefs.setBool('$_prefix.asc', value.ascending); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart index 2a94ce95..f06ecf74 100644 --- a/app/lib/features/chat/ui/sessions/chat_adaptive.dart +++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart @@ -21,12 +21,14 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable { required this.onPressed, required this.materialIcon, required this.cupertinoIcon, + this.identifier, }); final String label; final VoidCallback onPressed; final IconData materialIcon; final IconData cupertinoIcon; + final String? identifier; /// A narrow bar moves it into its More menu, under the bar's host's icon. @override @@ -40,6 +42,7 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable { Widget build(BuildContext context) { if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { return Semantics( + identifier: identifier, label: label, button: true, child: CupertinoButton( @@ -49,10 +52,13 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable { ), ); } - return IconButton( - tooltip: label, - onPressed: onPressed, - icon: Icon(materialIcon), + return Semantics( + identifier: identifier, + child: IconButton( + tooltip: label, + onPressed: onPressed, + icon: Icon(materialIcon), + ), ); } } diff --git a/app/test/features/chat/files/files_models_test.dart b/app/test/features/chat/files/files_models_test.dart new file mode 100644 index 00000000..5693e6c0 --- /dev/null +++ b/app/test/features/chat/files/files_models_test.dart @@ -0,0 +1,46 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/data/directory_listing.dart'; +import 'package:pipelines_app/features/chat/files/files_models.dart'; + +DirectoryEntry entry(String name, {bool dir = false, int? size}) => + DirectoryEntry( + name: name, + path: '/home/$name', + isDir: dir, + isGitRepo: false, + hidden: false, + size: size, + ); + +void main() { + test('reads optional size and modified fields without requiring them', () { + final parsed = DirectoryEntry.fromJson({ + 'name': 'report.md', + 'path': '/home/report.md', + 'is_dir': false, + 'modified': '2026-11-07T00:00:00Z', + 'size': 12, + }); + expect(parsed.size, 12); + expect(parsed.modified, '2026-11-07T00:00:00Z'); + expect(DirectoryEntry.fromJson({'name': 'unknown'}).size, isNull); + }); + + test('sorts folders first and then by selected key', () { + final sorted = sortFileEntries([ + entry('z.txt', size: 2), + entry('apps', dir: true), + entry('a.txt', size: 1), + ], const FilesSort(FilesSortKey.size)); + expect(sorted.map((item) => item.name), ['apps', 'a.txt', 'z.txt']); + }); + + test('keeps folders first when sorting descending', () { + final sorted = sortFileEntries([ + entry('z.txt', size: 2), + entry('apps', dir: true), + entry('a.txt', size: 1), + ], const FilesSort(FilesSortKey.name, ascending: false)); + expect(sorted.map((item) => item.name), ['apps', 'z.txt', 'a.txt']); + }); +} diff --git a/docs/notes/files-panel.md b/docs/notes/files-panel.md new file mode 100644 index 00000000..db1f7639 --- /dev/null +++ b/docs/notes/files-panel.md @@ -0,0 +1,6 @@ +# Files panel + +The chat Files panel lists and navigates the active session's server working +directory, with filtering, hidden files, sorting, and list/grid presentation. +The follow-up slice will add file opening, viewing, downloading, and image +thumbnails.