From eed3806efb73d905f34c5435fd6cf49543f5c496 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 1 Nov 2026 21:51:48 +0000 Subject: [PATCH] Add a home-restricted folder picker to the new-chat dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Server: list_directory returns a directory_listing (path, home, parent, entries with is_dir/is_git_repo/hidden, truncated) confined to the server user's home subtree after cleaning and resolving symlinks, refusing pseudo filesystems and capping entries at 2000. Documented in docs/cli.md. App: "Choose folder…" in the create dialog opens a picker (full-screen page on phones, large dialog on wide windows, Material and Cupertino) with breadcrumbs, filter, Show hidden, git badges, dimmed files, recent folders, inline errors and "Start chat here". The probe app gains a folder fixture for captures. --- .../features/chat/data/directory_listing.dart | 112 ++++++++ .../folder_picker_controller.dart | 138 +++++++++ .../ui/folder_picker/folder_picker_list.dart | 194 +++++++++++++ .../ui/folder_picker/folder_picker_page.dart | 152 ++++++++++ .../ui/folder_picker/folder_picker_parts.dart | 268 ++++++++++++++++++ .../ui/folder_picker/folder_picker_route.dart | 70 +++++ .../folder_picker/folder_picker_status.dart | 164 +++++++++++ .../chat/ui/sessions/chat_create_fields.dart | 50 +++- .../chat/ui/sessions/create_chat_dialog.dart | 43 ++- app/notes/chat-folder-picker.md | 18 ++ .../chat/data/directory_listing_test.dart | 52 ++++ .../folder_picker/fake_directory_gateway.dart | 84 ++++++ .../ui/folder_picker/folder_picker_test.dart | 237 ++++++++++++++++ .../chat_create_folder_picker_test.dart | 88 ++++++ app/tool/probe_folder_fixture.dart | 103 +++++++ app/tool/search_selection_probe_entry.dart | 5 +- docs/cli.md | 17 ++ internal/protocol/directories.go | 45 +++ internal/protocol/message.go | 4 + internal/server/directory_fs_darwin.go | 26 ++ internal/server/directory_fs_linux.go | 31 ++ internal/server/directory_fs_other.go | 6 + internal/server/directory_listing.go | 200 +++++++++++++ internal/server/directory_listing_test.go | 232 +++++++++++++++ internal/server/websocket.go | 3 + 25 files changed, 2333 insertions(+), 9 deletions(-) create mode 100644 app/lib/features/chat/data/directory_listing.dart create mode 100644 app/lib/features/chat/ui/folder_picker/folder_picker_controller.dart create mode 100644 app/lib/features/chat/ui/folder_picker/folder_picker_list.dart create mode 100644 app/lib/features/chat/ui/folder_picker/folder_picker_page.dart create mode 100644 app/lib/features/chat/ui/folder_picker/folder_picker_parts.dart create mode 100644 app/lib/features/chat/ui/folder_picker/folder_picker_route.dart create mode 100644 app/lib/features/chat/ui/folder_picker/folder_picker_status.dart create mode 100644 app/notes/chat-folder-picker.md create mode 100644 app/test/features/chat/data/directory_listing_test.dart create mode 100644 app/test/features/chat/ui/folder_picker/fake_directory_gateway.dart create mode 100644 app/test/features/chat/ui/folder_picker/folder_picker_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_create_folder_picker_test.dart create mode 100644 app/tool/probe_folder_fixture.dart create mode 100644 internal/protocol/directories.go create mode 100644 internal/server/directory_fs_darwin.go create mode 100644 internal/server/directory_fs_linux.go create mode 100644 internal/server/directory_fs_other.go create mode 100644 internal/server/directory_listing.go create mode 100644 internal/server/directory_listing_test.go diff --git a/app/lib/features/chat/data/directory_listing.dart b/app/lib/features/chat/data/directory_listing.dart new file mode 100644 index 00000000..fe31a4df --- /dev/null +++ b/app/lib/features/chat/data/directory_listing.dart @@ -0,0 +1,112 @@ +import '../../../core/api_gateway.dart'; + +/// One name in a `directory_listing` reply. Only directories are selectable; +/// files are listed for context. +class DirectoryEntry { + const DirectoryEntry({ + required this.name, + required this.path, + required this.isDir, + required this.isGitRepo, + required this.hidden, + }); + + factory DirectoryEntry.fromJson(JsonMap json) => DirectoryEntry( + name: '${json['name'] ?? ''}', + path: '${json['path'] ?? ''}', + isDir: json['is_dir'] == true, + isGitRepo: json['is_git_repo'] == true, + hidden: json['hidden'] == true, + ); + + final String name; + final String path; + final bool isDir; + final bool isGitRepo; + final bool hidden; +} + +/// The server's home-restricted listing of one folder. +class DirectoryListing { + const DirectoryListing({ + required this.path, + required this.home, + required this.parent, + required this.entries, + this.truncated = false, + }); + + /// Reads the `directory_listing` body; a reply without one is a protocol + /// error, never an empty folder. + factory DirectoryListing.fromReply(JsonMap reply) { + final body = reply['directory_listing']; + if (body is! Map || body['path'] is! String || body['home'] is! String) { + throw StateError('Server did not return a directory listing.'); + } + final entries = body['entries']; + return DirectoryListing( + path: body['path'] as String, + home: body['home'] as String, + parent: body['parent'] is String ? body['parent'] as String : null, + entries: [ + if (entries is List) + for (final entry in entries) + if (entry is Map) DirectoryEntry.fromJson(entry.cast()), + ], + truncated: body['truncated'] == true, + ); + } + + final String path; + final String home; + final String? parent; + final List entries; + final bool truncated; +} + +/// One breadcrumb: its visible label and the folder it opens. +typedef FolderCrumb = ({String label, String path}); + +/// The crumbs from home (`~`) down to [path]. A path outside [home] yields +/// home alone, because the picker never lists outside it. +List folderCrumbs(String home, String path) { + final crumbs = [(label: '~', path: home)]; + if (!isInsideHome(home, path) || path == home) return crumbs; + final base = home.endsWith('/') ? home : '$home/'; + var current = home; + for (final part in path.substring(base.length).split('/')) { + if (part.isEmpty) continue; + current = current.endsWith('/') ? '$current$part' : '$current/$part'; + crumbs.add((label: part, path: current)); + } + return crumbs; +} + +/// Whether [path] is [home] or a folder below it, compared lexically. +bool isInsideHome(String home, String path) { + if (home.isEmpty) return false; + if (path == home) return true; + final base = home.endsWith('/') ? home : '$home/'; + return path.startsWith(base); +} + +/// [path] shown relative to home (`~/src/app`), or as sent when outside it. +String homeRelativeLabel(String home, String path) { + if (path == home) return '~'; + if (!isInsideHome(home, path)) return path; + final base = home.endsWith('/') ? home : '$home/'; + return '~/${path.substring(base.length)}'; +} + +/// Sends `list_directory`; an omitted [path] lists the server user's home. +Future listDirectory( + ApiGateway gateway, [ + String? path, +]) async { + final reply = await gateway.call('list_directory', { + 'list_directory': { + if (path != null && path.trim().isNotEmpty) 'path': path.trim(), + }, + }); + return DirectoryListing.fromReply(reply); +} diff --git a/app/lib/features/chat/ui/folder_picker/folder_picker_controller.dart b/app/lib/features/chat/ui/folder_picker/folder_picker_controller.dart new file mode 100644 index 00000000..2af343b4 --- /dev/null +++ b/app/lib/features/chat/ui/folder_picker/folder_picker_controller.dart @@ -0,0 +1,138 @@ +import 'package:flutter/foundation.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/directory_listing.dart'; + +/// The folder picker's state: the last listing, the folder being loaded, an +/// inline error, the hidden toggle and the filter. Listing goes through the +/// server's home-restricted `list_directory`; nothing is guessed locally. +class FolderPickerController extends ChangeNotifier { + FolderPickerController({ + required this.gateway, + this.initialPath, + this.recentFolders = const [], + }); + + final ApiGateway gateway; + final String? initialPath; + + /// Every recent chat folder the server reported; [recents] filters them. + final List recentFolders; + + DirectoryListing? _listing; + String? _error; + String? _failedPath; + bool _loading = false; + bool _showHidden = false; + String _filter = ''; + int _request = 0; + bool _disposed = false; + + DirectoryListing? get listing => _listing; + String? get error => _error; + bool get loading => _loading; + bool get showHidden => _showHidden; + String get filter => _filter; + + /// The home directory once any listing has arrived. + String? get home => _listing?.home; + + /// The folder "Start chat here" would use: only a successfully listed one. + String? get selectable => _loading || _error != null ? null : _listing?.path; + + bool get atHome => _listing != null && _listing!.parent == null; + + /// Recent chat folders inside home, offered only at the home level. + List get recents { + final listing = _listing; + if (listing == null || listing.parent != null || _error != null) { + return const []; + } + return [ + for (final path in recentFolders) + if (path != listing.home && isInsideHome(listing.home, path)) path, + ]; + } + + /// The visible entries: hidden names only when toggled on, then the filter + /// (case-insensitive substring). Folders stay ahead of files as sent. + List get entries { + final listing = _listing; + if (listing == null) return const []; + final needle = _filter.trim().toLowerCase(); + return [ + for (final entry in listing.entries) + if ((_showHidden || !entry.hidden) && + (needle.isEmpty || entry.name.toLowerCase().contains(needle))) + entry, + ]; + } + + /// How many hidden names the toggle currently conceals. + int get hiddenCount => + _showHidden ? 0 : (_listing?.entries.where((e) => e.hidden).length ?? 0); + + Future start() => open(initialPath); + + /// Lists [path] (home when null). A failure keeps the previous listing for + /// the breadcrumbs and Back, and shows the server's words inline. + Future open(String? path) async { + final request = ++_request; + _loading = true; + _error = null; + _failedPath = path; + _notify(); + try { + final next = await listDirectory(gateway, path); + if (_disposed || request != _request) return; + _listing = next; + _filter = ''; + _failedPath = null; + } catch (error) { + if (_disposed || request != _request) return; + _error = '$error'; + } finally { + if (!_disposed && request == _request) { + _loading = false; + _notify(); + } + } + } + + Future retry() => open(_failedPath ?? _listing?.path ?? initialPath); + + /// Back: dismiss an error first, then go up one folder. Returns false at + /// home, where Back leaves the picker. + bool up() { + if (_error != null && _listing != null) { + _error = null; + _failedPath = null; + _notify(); + return true; + } + final parent = _listing?.parent; + if (parent == null) return false; + open(parent); + return true; + } + + void setShowHidden(bool value) { + _showHidden = value; + _notify(); + } + + void setFilter(String value) { + _filter = value; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/chat/ui/folder_picker/folder_picker_list.dart b/app/lib/features/chat/ui/folder_picker/folder_picker_list.dart new file mode 100644 index 00000000..d76f30b6 --- /dev/null +++ b/app/lib/features/chat/ui/folder_picker/folder_picker_list.dart @@ -0,0 +1,194 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../data/directory_listing.dart'; +import 'folder_picker_controller.dart'; +import 'folder_picker_status.dart'; + +/// The body: loading, the inline error, or recent folders (home level only) +/// followed by the current folder's folders and its dimmed, unselectable files. +class FolderPickerList extends StatelessWidget { + const FolderPickerList({ + super.key, + required this.cupertino, + required this.controller, + }); + + final bool cupertino; + final FolderPickerController controller; + + @override + Widget build(BuildContext context) { + final listing = controller.listing; + if (controller.error != null) { + return FolderPickerError(cupertino: cupertino, controller: controller); + } + if (listing == null) { + return FolderPickerLoading(cupertino: cupertino); + } + final entries = controller.entries; + final recents = controller.filter.trim().isEmpty + ? controller.recents + : const []; + final rows = [ + if (controller.loading) FolderPickerLoadingBar(cupertino: cupertino), + if (recents.isNotEmpty) ...[ + FolderSectionHeader(cupertino: cupertino, text: 'Recent folders'), + for (final path in recents) + _RecentRow( + cupertino: cupertino, + label: homeRelativeLabel(listing.home, path), + onTap: () => controller.open(path), + ), + FolderSectionHeader( + cupertino: cupertino, + text: 'In ${homeRelativeLabel(listing.home, listing.path)}', + ), + ], + for (final entry in entries) + _EntryRow( + cupertino: cupertino, + entry: entry, + onTap: entry.isDir ? () => controller.open(entry.path) : null, + ), + if (entries.isEmpty) + FolderPickerNote( + cupertino: cupertino, + text: controller.filter.trim().isNotEmpty + ? 'Nothing here matches “${controller.filter.trim()}”.' + : controller.hiddenCount > 0 + ? 'Only hidden items here. Turn on Show hidden to see them.' + : 'This folder is empty.', + ), + if (listing.truncated) + FolderPickerNote( + cupertino: cupertino, + text: + 'This folder is large; only the first entries are shown. ' + 'Use the filter or type the path instead.', + ), + ]; + return ListView( + key: ValueKey('folder-list-${listing.path}'), + children: rows, + ); + } +} + +class _RecentRow extends StatelessWidget { + const _RecentRow({ + required this.cupertino, + required this.label, + required this.onTap, + }); + + final bool cupertino; + final String label; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + if (cupertino) { + return CupertinoListTile( + leading: const Icon(CupertinoIcons.clock), + title: Text(label), + trailing: const CupertinoListTileChevron(), + onTap: onTap, + ); + } + return ListTile( + leading: const Icon(Icons.history), + title: Text(label), + trailing: const Icon(Icons.chevron_right), + onTap: onTap, + ); + } +} + +class _EntryRow extends StatelessWidget { + const _EntryRow({ + required this.cupertino, + required this.entry, + required this.onTap, + }); + + final bool cupertino; + final DirectoryEntry entry; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final folder = entry.isDir; + final trailing = folder + ? Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (entry.isGitRepo) FolderGitBadge(cupertino: cupertino), + const SizedBox(width: 4), + cupertino + ? const CupertinoListTileChevron() + : const Icon(Icons.chevron_right), + ], + ) + : null; + if (cupertino) { + final dim = CupertinoColors.tertiaryLabel.resolveFrom(context); + return CupertinoListTile( + key: ValueKey('folder-entry-${entry.path}'), + leading: Icon( + folder ? CupertinoIcons.folder_fill : CupertinoIcons.doc, + color: folder ? null : dim, + ), + title: Text(entry.name, style: folder ? null : TextStyle(color: dim)), + trailing: trailing, + onTap: onTap, + ); + } + return ListTile( + key: ValueKey('folder-entry-${entry.path}'), + enabled: folder, + leading: Icon( + folder ? Icons.folder : Icons.insert_drive_file_outlined, + color: folder ? Theme.of(context).colorScheme.primary : null, + ), + title: Text(entry.name), + trailing: trailing, + onTap: onTap, + ); + } +} + +/// The small "git" mark on a repository folder. +class FolderGitBadge extends StatelessWidget { + const FolderGitBadge({super.key, required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) { + if (!cupertino) { + final scheme = Theme.of(context).colorScheme; + return Badge( + label: const Text('git'), + backgroundColor: scheme.secondaryContainer, + textColor: scheme.onSecondaryContainer, + ); + } + return DecoratedBox( + decoration: BoxDecoration( + color: CupertinoColors.systemGrey5.resolveFrom(context), + borderRadius: BorderRadius.circular(6), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + child: Text( + 'git', + style: TextStyle( + fontSize: 12, + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/folder_picker/folder_picker_page.dart b/app/lib/features/chat/ui/folder_picker/folder_picker_page.dart new file mode 100644 index 00000000..dbf50736 --- /dev/null +++ b/app/lib/features/chat/ui/folder_picker/folder_picker_page.dart @@ -0,0 +1,152 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/directory_listing.dart'; +import '../sessions/chat_adaptive.dart'; +import 'folder_picker_controller.dart'; +import 'folder_picker_list.dart'; +import 'folder_picker_parts.dart'; + +const String folderPickerTitle = 'Choose folder'; +const String folderPickerStartLabel = 'Start chat here'; + +/// The folder picker: breadcrumbs, a filter and hidden toggle, the current +/// folder's entries and a prominent "Start chat here". It pops with the chosen +/// absolute path; Back climbs one folder and leaves only at home. +class FolderPickerPage extends StatefulWidget { + const FolderPickerPage({ + super.key, + required this.gateway, + this.initialPath, + this.recents = const [], + }); + + final ApiGateway gateway; + final String? initialPath; + final List recents; + + @override + State createState() => _FolderPickerPageState(); +} + +class _FolderPickerPageState extends State { + late final FolderPickerController _controller = FolderPickerController( + gateway: widget.gateway, + initialPath: widget.initialPath, + recentFolders: widget.recents, + ); + final _filter = TextEditingController(); + String? _shownPath; + + @override + void initState() { + super.initState(); + _controller.addListener(_changed); + _controller.start(); + } + + void _changed() { + final path = _controller.listing?.path; + if (path != _shownPath) { + _shownPath = path; + _filter.clear(); + } + setState(() {}); + } + + @override + void dispose() { + _controller.removeListener(_changed); + _controller.dispose(); + _filter.dispose(); + super.dispose(); + } + + void _back() { + if (!_controller.up()) Navigator.pop(context); + } + + void _start() { + final path = _controller.selectable; + if (path != null) Navigator.pop(context, path); + } + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final body = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + FolderBreadcrumbs(cupertino: cupertino, controller: _controller), + FolderPickerToolbar( + cupertino: cupertino, + controller: _controller, + filter: _filter, + ), + Expanded( + child: FolderPickerList( + cupertino: cupertino, + controller: _controller, + ), + ), + FolderStartBar( + cupertino: cupertino, + path: _controller.selectable, + home: _controller.home, + onStart: _start, + ), + ], + ); + return PopScope( + canPop: _controller.atHome && _controller.error == null, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _back(); + }, + child: cupertino ? _cupertino(context, body) : _material(body), + ); + } + + Widget _material(Widget body) { + return Scaffold( + appBar: AppBar( + leading: BackButton(onPressed: _back), + title: const Text(folderPickerTitle), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ), + body: SafeArea(top: false, child: body), + ); + } + + Widget _cupertino(BuildContext context, Widget body) { + final parent = _controller.listing?.parent; + final home = _controller.home; + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + automaticallyImplyLeading: false, + leading: CupertinoNavigationBarBackButton( + onPressed: _back, + previousPageTitle: parent == null || home == null + ? 'Back' + : folderCrumbs(home, parent).last.label, + ), + middle: const Text(folderPickerTitle), + trailing: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + child: DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: SafeArea(child: body), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/folder_picker/folder_picker_parts.dart b/app/lib/features/chat/ui/folder_picker/folder_picker_parts.dart new file mode 100644 index 00000000..d8a51571 --- /dev/null +++ b/app/lib/features/chat/ui/folder_picker/folder_picker_parts.dart @@ -0,0 +1,268 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../data/directory_listing.dart'; +import 'folder_picker_controller.dart'; + +/// The path from `~` to the current folder; every crumb but the last opens +/// that folder. It scrolls so the current folder stays visible. +class FolderBreadcrumbs extends StatelessWidget { + const FolderBreadcrumbs({ + super.key, + required this.cupertino, + required this.controller, + }); + + final bool cupertino; + final FolderPickerController controller; + + @override + Widget build(BuildContext context) { + final listing = controller.listing; + if (listing == null) return const SizedBox.shrink(); + final crumbs = folderCrumbs(listing.home, listing.path); + final children = []; + for (var i = 0; i < crumbs.length; i++) { + final crumb = crumbs[i]; + final last = i == crumbs.length - 1; + if (i > 0) { + children.add( + Icon( + cupertino ? CupertinoIcons.chevron_right : Icons.chevron_right, + size: 16, + ), + ); + } + children.add( + Semantics( + label: last ? 'Current folder ${crumb.label}' : 'Open ${crumb.label}', + button: !last, + excludeSemantics: true, + child: _crumb(context, crumb, last), + ), + ); + } + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + // Reversed so a deep path keeps the current folder in view; the + // viewport-wide minimum keeps a short path aligned to the start. + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + scrollDirection: Axis.horizontal, + reverse: true, + child: ConstrainedBox( + constraints: BoxConstraints(minWidth: constraints.maxWidth), + child: Row(children: children), + ), + ), + ), + ); + } + + Widget _crumb(BuildContext context, FolderCrumb crumb, bool last) { + final text = Text( + crumb.label, + style: last ? const TextStyle(fontWeight: FontWeight.w600) : null, + ); + final home = crumb.label == '~' && crumb.path == controller.home; + final label = home + ? Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(cupertino ? CupertinoIcons.house : Icons.home_outlined), + const SizedBox(width: 4), + text, + ], + ) + : text; + final onPressed = last ? null : () => controller.open(crumb.path); + if (cupertino) { + return CupertinoButton( + key: ValueKey('folder-crumb-${crumb.path}'), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8), + onPressed: onPressed, + disabledColor: CupertinoColors.transparent, + child: last + ? DefaultTextStyle.merge( + style: TextStyle( + color: CupertinoColors.label.resolveFrom(context), + ), + child: label, + ) + : label, + ); + } + return TextButton( + key: ValueKey('folder-crumb-${crumb.path}'), + onPressed: onPressed, + style: last + ? TextButton.styleFrom( + disabledForegroundColor: Theme.of(context).colorScheme.onSurface, + ) + : null, + child: label, + ); + } +} + +/// The filter field for the current folder and the "Show hidden" toggle. +class FolderPickerToolbar extends StatelessWidget { + const FolderPickerToolbar({ + super.key, + required this.cupertino, + required this.controller, + required this.filter, + }); + + final bool cupertino; + final FolderPickerController controller; + final TextEditingController filter; + + @override + Widget build(BuildContext context) { + final hiddenLabel = controller.hiddenCount > 0 + ? 'Show hidden (${controller.hiddenCount})' + : 'Show hidden'; + final field = cupertino + ? CupertinoSearchTextField( + key: const Key('folder-picker-filter'), + controller: filter, + placeholder: 'Filter this folder', + onChanged: controller.setFilter, + ) + : TextField( + key: const Key('folder-picker-filter'), + controller: filter, + onChanged: controller.setFilter, + decoration: InputDecoration( + isDense: true, + prefixIcon: const Icon(Icons.search), + hintText: 'Filter this folder', + border: const OutlineInputBorder(), + suffixIcon: filter.text.isEmpty + ? null + : IconButton( + tooltip: 'Clear filter', + icon: const Icon(Icons.clear), + onPressed: () { + filter.clear(); + controller.setFilter(''); + }, + ), + ), + ); + final toggle = cupertino + ? Semantics( + label: 'Show hidden', + toggled: controller.showHidden, + excludeSemantics: true, + child: GestureDetector( + onTap: () => controller.setShowHidden(!controller.showHidden), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(hiddenLabel), + const SizedBox(width: 6), + CupertinoSwitch( + key: const Key('folder-picker-hidden'), + value: controller.showHidden, + onChanged: controller.setShowHidden, + ), + ], + ), + ), + ) + : FilterChip( + key: const Key('folder-picker-hidden'), + label: Text(hiddenLabel), + selected: controller.showHidden, + onSelected: controller.setShowHidden, + ); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), + child: Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: field, + ), + toggle, + ], + ), + ); + } +} + +/// The prominent confirm: names the folder and starts the chat there. It is +/// disabled until a folder is listed (never while loading or after an error). +class FolderStartBar extends StatelessWidget { + const FolderStartBar({ + super.key, + required this.cupertino, + required this.path, + required this.home, + required this.onStart, + }); + + final bool cupertino; + final String? path; + final String? home; + final VoidCallback onStart; + + @override + Widget build(BuildContext context) { + final where = path == null || home == null + ? 'No folder selected' + : 'Start in ${homeRelativeLabel(home!, path!)}'; + final onPressed = path == null ? null : onStart; + final button = cupertino + ? CupertinoButton.filled( + key: const Key('folder-picker-start'), + onPressed: onPressed, + child: const Text('Start chat here'), + ) + : FilledButton.icon( + key: const Key('folder-picker-start'), + onPressed: onPressed, + icon: const Icon(Icons.chat_bubble_outline), + label: const Text('Start chat here'), + ); + final content = Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + where, + key: const Key('folder-picker-where'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + button, + ], + ), + ); + if (cupertino) { + return DecoratedBox( + decoration: BoxDecoration( + border: Border( + top: BorderSide( + color: CupertinoColors.separator.resolveFrom(context), + width: 0, + ), + ), + ), + child: content, + ); + } + return Material( + color: Theme.of(context).colorScheme.surfaceContainer, + child: content, + ); + } +} diff --git a/app/lib/features/chat/ui/folder_picker/folder_picker_route.dart b/app/lib/features/chat/ui/folder_picker/folder_picker_route.dart new file mode 100644 index 00000000..1584b4df --- /dev/null +++ b/app/lib/features/chat/ui/folder_picker/folder_picker_route.dart @@ -0,0 +1,70 @@ +import 'dart:math' as math; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../sessions/chat_adaptive.dart'; +import 'folder_picker_page.dart'; + +/// At or above this window width the picker is a large dialog over the create +/// dialog; below it, a full-screen page. +const double folderPickerDialogBreakpoint = 720; + +/// The wide dialog's bounds, kept here so the page itself stays content-sized. +const double _dialogMaxWidth = 760; +const double _dialogMaxHeight = 900; + +/// Opens the folder picker and resolves to the chosen absolute folder, or +/// null when the operator cancels. [initialPath] opens there when the server +/// can list it; [recents] are offered as quick picks at the home level. +Future showFolderPicker( + BuildContext context, { + required ApiGateway gateway, + String? initialPath, + List recents = const [], +}) { + final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final size = MediaQuery.sizeOf(context); + final wide = size.width >= folderPickerDialogBreakpoint; + final navigator = Navigator.of(context, rootNavigator: true); + Widget page(BuildContext _) => FolderPickerPage( + gateway: gateway, + initialPath: initialPath, + recents: recents, + ); + if (!wide) { + return navigator.push( + cupertino + ? CupertinoPageRoute(fullscreenDialog: true, builder: page) + : MaterialPageRoute(fullscreenDialog: true, builder: page), + ); + } + Widget bounded(BuildContext context) { + final window = MediaQuery.sizeOf(context); + return SizedBox( + width: math.min(_dialogMaxWidth, window.width - 64), + height: math.min(_dialogMaxHeight, window.height * 0.85), + child: page(context), + ); + } + + if (cupertino) { + return showCupertinoDialog( + context: context, + useRootNavigator: true, + builder: (context) => Center( + child: ClipRRect( + borderRadius: BorderRadius.circular(14), + child: bounded(context), + ), + ), + ); + } + return showDialog( + context: context, + useRootNavigator: true, + builder: (context) => + Dialog(clipBehavior: Clip.antiAlias, child: bounded(context)), + ); +} diff --git a/app/lib/features/chat/ui/folder_picker/folder_picker_status.dart b/app/lib/features/chat/ui/folder_picker/folder_picker_status.dart new file mode 100644 index 00000000..0d0eda1c --- /dev/null +++ b/app/lib/features/chat/ui/folder_picker/folder_picker_status.dart @@ -0,0 +1,164 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../data/directory_listing.dart'; +import 'folder_picker_controller.dart'; + +/// First load: a centred native activity indicator. +class FolderPickerLoading extends StatelessWidget { + const FolderPickerLoading({super.key, required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) { + return Center( + child: Semantics( + label: 'Loading folder', + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), + ); + } +} + +/// A later load keeps the previous listing on screen under a thin indicator. +class FolderPickerLoadingBar extends StatelessWidget { + const FolderPickerLoadingBar({super.key, required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) { + return Semantics( + label: 'Loading folder', + child: cupertino + ? const Padding( + padding: EdgeInsets.all(8), + child: CupertinoActivityIndicator(), + ) + : const LinearProgressIndicator(), + ); + } +} + +/// The server's refusal shown in place (outside home, permission denied, +/// missing folder), with Retry, Back to the last good folder, and Home. +class FolderPickerError extends StatelessWidget { + const FolderPickerError({ + super.key, + required this.cupertino, + required this.controller, + }); + + final bool cupertino; + final FolderPickerController controller; + + @override + Widget build(BuildContext context) { + final color = cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + final listing = controller.listing; + final actions = <(String, VoidCallback)>[ + ('Retry', controller.retry), + if (listing != null) + ( + 'Back to ${homeRelativeLabel(listing.home, listing.path)}', + controller.up, + ), + if (!controller.atHome || listing == null) + ('Go to home', () => controller.open(null)), + ]; + return SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Icon( + cupertino + ? CupertinoIcons.exclamationmark_triangle + : Icons.error_outline, + color: color, + ), + const SizedBox(height: 8), + Text( + "Can't open this folder", + style: const TextStyle(fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + ), + const SizedBox(height: 4), + Text( + controller.error ?? '', + key: const Key('folder-picker-error'), + textAlign: TextAlign.center, + style: TextStyle(color: color), + ), + const SizedBox(height: 12), + Wrap( + spacing: 8, + alignment: WrapAlignment.center, + children: [ + for (final (label, onPressed) in actions) + cupertino + ? CupertinoButton(onPressed: onPressed, child: Text(label)) + : TextButton(onPressed: onPressed, child: Text(label)), + ], + ), + ], + ), + ); + } +} + +/// A section label above recent folders and the folder's own entries. +class FolderSectionHeader extends StatelessWidget { + const FolderSectionHeader({ + super.key, + required this.cupertino, + required this.text, + }); + + final bool cupertino; + final String text; + + @override + Widget build(BuildContext context) { + final style = cupertino + ? TextStyle( + fontSize: 13, + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : Theme.of(context).textTheme.labelLarge?.copyWith( + color: Theme.of(context).colorScheme.primary, + ); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text(text, style: style), + ); + } +} + +/// A quiet explanatory line (empty folder, no matches, truncated listing). +class FolderPickerNote extends StatelessWidget { + const FolderPickerNote({ + super.key, + required this.cupertino, + required this.text, + }); + + final bool cupertino; + final String text; + + @override + Widget build(BuildContext context) { + final color = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + return Padding( + padding: const EdgeInsets.all(16), + child: Text(text, style: TextStyle(color: color)), + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_create_fields.dart b/app/lib/features/chat/ui/sessions/chat_create_fields.dart index 6fe84873..338119e7 100644 --- a/app/lib/features/chat/ui/sessions/chat_create_fields.dart +++ b/app/lib/features/chat/ui/sessions/chat_create_fields.dart @@ -6,6 +6,9 @@ import 'chat_adaptive.dart'; /// The web's directory prompt, also the directory picker's label. const String chatCreatePrompt = 'Where should this chat live?'; +/// Opens the folder picker from the create dialog. +const String chatChooseFolderLabel = 'Choose folder…'; + /// The home choice: shown as `Home (~)` and sent as the `~` the server /// documents. const String chatHomeDirectory = '~'; @@ -49,6 +52,7 @@ class ChatCatalogFields extends StatelessWidget { required this.onDirectory, required this.onBackend, required this.onRetry, + this.onBrowse, }); final bool loading; @@ -61,6 +65,9 @@ class ChatCatalogFields extends StatelessWidget { final ValueChanged onBackend; final VoidCallback onRetry; + /// Opens the folder picker; null hides the "Choose folder" action. + final VoidCallback? onBrowse; + @override Widget build(BuildContext context) { final cupertino = @@ -85,13 +92,42 @@ class ChatCatalogFields extends StatelessWidget { onSelected: onDirectory, ) else - MaterialPickerField( - fieldKey: const Key('chat-create-server-directory'), - label: chatCreatePrompt, - value: directory, - values: choices, - labelOf: directoryLabel, - onSelected: onDirectory, + // Keyed by the value so a folder chosen in the picker replaces the + // dropdown's retained initial value. + KeyedSubtree( + key: ValueKey('chat-create-directory-$directory'), + child: MaterialPickerField( + fieldKey: const Key('chat-create-server-directory'), + label: chatCreatePrompt, + value: directory, + values: choices, + labelOf: directoryLabel, + onSelected: onDirectory, + ), + ), + if (onBrowse != null) + Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + key: const Key('chat-create-choose-folder'), + padding: const EdgeInsets.symmetric(vertical: 4), + onPressed: onBrowse, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(CupertinoIcons.folder), + SizedBox(width: 6), + Flexible(child: Text(chatChooseFolderLabel)), + ], + ), + ) + : TextButton.icon( + key: const Key('chat-create-choose-folder'), + onPressed: onBrowse, + icon: const Icon(Icons.folder_open), + label: const Text(chatChooseFolderLabel), + ), ), if (backends.length > 1) if (cupertino) diff --git a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart index d653809e..c704136e 100644 --- a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart +++ b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart @@ -7,7 +7,9 @@ import '../../../../core/api_gateway.dart'; import '../../../../core/servers/server_scope.dart'; import '../../data/chat_create_prompt_store.dart'; import '../../data/chat_repository.dart'; +import '../../data/directory_listing.dart'; import '../../domain/chat_commands.dart'; +import '../folder_picker/folder_picker_route.dart'; import 'chat_adaptive.dart'; import 'chat_create_dialog_frame.dart'; import 'chat_create_fields.dart'; @@ -17,7 +19,8 @@ import 'chat_prompt_chooser.dart'; const String chatCreateInstructionsHelper = "Preloaded as this chat's session instructions. The agent still reads the " "repository's AGENTS.md and skills."; -const String chatCreateModelNote = "New chats start with the server's default model."; +const String chatCreateModelNote = + "New chats start with the server's default model."; class ChatDraft { const ChatDraft({ @@ -211,6 +214,43 @@ class _CreateChatDialogState extends State { }); } + /// Opens the folder picker at the current folder when it is inside home, + /// with the server's recent chat folders as quick picks, and makes the + /// chosen folder this chat's directory. + Future _browse() async { + final home = _directories.isEmpty ? null : _directories.first; + final current = _directory; + final initial = + home != null && + current != null && + current != chatHomeDirectory && + isInsideHome(home, current) + ? current + : null; + final chosen = await showFolderPicker( + context, + gateway: widget.repository.gateway, + initialPath: initial, + recents: _directories.skip(1).toList(), + ); + if (!mounted || chosen == null || _submitting) return; + setState(() { + if (chosen == home) { + _directory = chatHomeDirectory; + } else { + if (!_directories.contains(chosen)) { + _directories = [ + ..._directories.take(1), + chosen, + ..._directories.skip(1), + ]; + } + _directory = chosen; + } + }); + _choiceChanged(); + } + Future _submit() async { if (!_catalogReady || _submitting) return; if (!_promptReady) { @@ -284,6 +324,7 @@ class _CreateChatDialogState extends State { _choiceChanged(); }, onRetry: _loadCatalog, + onBrowse: _submitting ? null : _browse, ), const SizedBox(height: 12), const Text('Name'), diff --git a/app/notes/chat-folder-picker.md b/app/notes/chat-folder-picker.md new file mode 100644 index 00000000..d1aec271 --- /dev/null +++ b/app/notes/chat-folder-picker.md @@ -0,0 +1,18 @@ +# New-chat folder picker + +The create dialog has a "Choose folder…" action under the directory dropdown. It +opens `lib/features/chat/ui/folder_picker/`: a full-screen page below 720 px, a +large dialog above it (Material and Cupertino). The picker opens at `~`, or at +the dialog's current folder when that folder is inside home. Recent chat folders +from `chat_directories` show as quick picks at the home level. The page has a +breadcrumb from `~`, a filter field, a "Show hidden" toggle, folders with a git +badge, and dimmed files. Back climbs one folder. Server refusals (outside home, +permission denied) show inline with Retry, Back and Go to home. "Start chat +here" fills the directory and returns to the dialog. The dropdown is still there +as the other way to choose. + +Server: `list_directory` / `directory_listing` (docs/cli.md, Chat sessions). + +Evidence: `/tmp/folder-picker-evidence/{material,cupertino}-{560,880}x1000/`, +made with the capture kit over the probe app (fixture in `tool/probe_folder_fixture.dart`) +and the script `/tmp/folder-picker-evidence/flow.json`. diff --git a/app/test/features/chat/data/directory_listing_test.dart b/app/test/features/chat/data/directory_listing_test.dart new file mode 100644 index 00000000..7fa61745 --- /dev/null +++ b/app/test/features/chat/data/directory_listing_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/data/directory_listing.dart'; + +void main() { + test('parses the directory_listing reply, null parent at home', () { + final listing = DirectoryListing.fromReply({ + 'type': 'directory_listing', + 'directory_listing': { + 'path': '/home/op', + 'home': '/home/op', + 'parent': null, + 'entries': [ + { + 'name': 'src', + 'path': '/home/op/src', + 'is_dir': true, + 'is_git_repo': true, + 'hidden': false, + }, + {'name': '.zshrc', 'path': '/home/op/.zshrc', 'hidden': true}, + ], + 'truncated': true, + }, + }); + expect(listing.parent, isNull); + expect(listing.truncated, isTrue); + expect(listing.entries.first.isGitRepo, isTrue); + expect(listing.entries.last.isDir, isFalse); + expect(listing.entries.last.hidden, isTrue); + }); + + test('a reply without a listing is an error, not an empty folder', () { + expect( + () => DirectoryListing.fromReply({'type': 'pong'}), + throwsStateError, + ); + }); + + test('crumbs run from ~ to the folder', () { + expect(folderCrumbs('/home/op', '/home/op/a/b'), [ + (label: '~', path: '/home/op'), + (label: 'a', path: '/home/op/a'), + (label: 'b', path: '/home/op/a/b'), + ]); + expect(folderCrumbs('/home/op', '/home/opal'), [ + (label: '~', path: '/home/op'), + ]); + expect(isInsideHome('/home/op', '/home/opal'), isFalse); + expect(homeRelativeLabel('/home/op', '/home/op/a'), '~/a'); + expect(homeRelativeLabel('/home/op', '/srv'), '/srv'); + }); +} diff --git a/app/test/features/chat/ui/folder_picker/fake_directory_gateway.dart b/app/test/features/chat/ui/folder_picker/fake_directory_gateway.dart new file mode 100644 index 00000000..0a50cc5b --- /dev/null +++ b/app/test/features/chat/ui/folder_picker/fake_directory_gateway.dart @@ -0,0 +1,84 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; + +const fakeHome = '/home/op'; + +JsonMap _entry( + String parent, + String name, { + bool dir = true, + bool git = false, +}) => { + 'name': name, + 'path': '$parent/$name', + 'is_dir': dir, + 'is_git_repo': git, + 'hidden': name.startsWith('.'), +}; + +/// A server-shaped home tree for `list_directory`; anything else is refused +/// with the server's words, like the real handler. +final Map> fakeTree = { + fakeHome: [ + _entry(fakeHome, '.config'), + _entry(fakeHome, 'projects'), + _entry(fakeHome, 'src', git: true), + _entry(fakeHome, '.zshrc', dir: false), + _entry(fakeHome, 'notes.txt', dir: false), + ], + '$fakeHome/projects': [ + _entry('$fakeHome/projects', 'app', git: true), + _entry('$fakeHome/projects', 'web'), + _entry('$fakeHome/projects', 'README.md', dir: false), + ], + '$fakeHome/projects/app': [_entry('$fakeHome/projects/app', 'lib')], + '$fakeHome/projects/web': const [], + '$fakeHome/src': const [], +}; + +String? _parent(String path) { + if (path == fakeHome) return null; + return path.substring(0, path.lastIndexOf('/')); +} + +/// Answers `list_directory` from [fakeTree] and records requested paths. +class FakeDirectoryGateway implements ApiGateway { + final requests = []; + + /// Paths that are refused like the server refuses a locked folder. + final denied = {'$fakeHome/locked'}; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'list_directory') { + throw ProtocolError('Fake does not implement $type'); + } + final body = fields['list_directory'] as Map? ?? const {}; + final requested = body['path'] as String?; + requests.add(requested); + final path = requested == null || requested == '~' ? fakeHome : requested; + if (denied.contains(path)) throw ProtocolError('permission denied: $path'); + if (path != fakeHome && !path.startsWith('$fakeHome/')) { + throw ProtocolError( + 'path $path is outside the home directory $fakeHome; only folders ' + 'inside home can be listed', + ); + } + final entries = fakeTree[path]; + if (entries == null) throw ProtocolError('$path does not exist'); + return { + 'type': 'directory_listing', + 'directory_listing': { + 'path': path, + 'home': fakeHome, + 'parent': _parent(path), + 'entries': entries, + }, + }; + } +} diff --git a/app/test/features/chat/ui/folder_picker/folder_picker_test.dart b/app/test/features/chat/ui/folder_picker/folder_picker_test.dart new file mode 100644 index 00000000..4fd52a23 --- /dev/null +++ b/app/test/features/chat/ui/folder_picker/folder_picker_test.dart @@ -0,0 +1,237 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/ui/folder_picker/folder_picker_route.dart'; + +import 'fake_directory_gateway.dart'; + +/// Hosts a button that opens the picker and records what it returns. +class _Launcher extends StatelessWidget { + const _Launcher({ + required this.gateway, + required this.onResult, + this.initialPath, + this.recents = const [], + }); + + final FakeDirectoryGateway gateway; + final ValueChanged onResult; + final String? initialPath; + final List recents; + + @override + Widget build(BuildContext context) { + return Center( + child: CupertinoButton( + child: const Text('Open picker'), + onPressed: () async => onResult( + await showFolderPicker( + context, + gateway: gateway, + initialPath: initialPath, + recents: recents, + ), + ), + ), + ); + } +} + +enum _Host { material, cupertino } + +Future _pump( + WidgetTester tester, + _Host host, + Widget launcher, { + Size size = const Size(420, 900), +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + host == _Host.material + ? MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: launcher), + ) + : CupertinoApp(home: CupertinoPageScaffold(child: launcher)), + ); + await tester.tap(find.text('Open picker')); + await tester.pumpAndSettle(); +} + +Finder _crumb(String path) => find.byKey(ValueKey('folder-crumb-$path')); + +void main() { + for (final host in _Host.values) { + testWidgets('${host.name}: opens at home, navigates, jumps up and returns ' + 'the folder', (tester) async { + final gateway = FakeDirectoryGateway(); + String? result = 'unset'; + await _pump( + tester, + host, + _Launcher(gateway: gateway, onResult: (value) => result = value), + ); + expect(gateway.requests, [null]); + expect(find.text('Choose folder'), findsOneWidget); + expect(find.text('projects'), findsOneWidget); + expect(find.text('src'), findsOneWidget); + expect(find.text('git'), findsOneWidget); + expect(find.text('notes.txt'), findsOneWidget); + expect(find.text('Start in ~'), findsOneWidget); + + await tester.tap(find.text('projects')); + await tester.pumpAndSettle(); + expect(gateway.requests.last, '$fakeHome/projects'); + expect(find.text('app'), findsOneWidget); + expect(find.text('README.md'), findsOneWidget); + expect(find.text('Start in ~/projects'), findsOneWidget); + + await tester.tap(find.text('app')); + await tester.pumpAndSettle(); + expect(find.text('lib'), findsOneWidget); + // The home crumb jumps straight back up two levels. + await tester.tap(_crumb(fakeHome)); + await tester.pumpAndSettle(); + expect(gateway.requests.last, fakeHome); + expect(find.text('Start in ~'), findsOneWidget); + + // Back climbs one folder instead of leaving the picker. + await tester.tap(find.text('projects')); + await tester.pumpAndSettle(); + await tester.tap(find.text('web')); + await tester.pumpAndSettle(); + expect(find.text('This folder is empty.'), findsOneWidget); + await tester.tap( + host == _Host.material + ? find.byType(BackButton) + : find.byType(CupertinoNavigationBarBackButton), + ); + await tester.pumpAndSettle(); + expect(find.text('Start in ~/projects'), findsOneWidget); + expect(result, 'unset'); + + await tester.tap(find.byKey(const Key('folder-picker-start'))); + await tester.pumpAndSettle(); + expect(result, '$fakeHome/projects'); + expect(find.text('Choose folder'), findsNothing); + }); + + testWidgets('${host.name}: hidden toggle and filter', (tester) async { + final gateway = FakeDirectoryGateway(); + await _pump(tester, host, _Launcher(gateway: gateway, onResult: (_) {})); + expect(find.text('.config'), findsNothing); + expect(find.text('.zshrc'), findsNothing); + expect(find.text('Show hidden (2)'), findsOneWidget); + await tester.tap(find.byKey(const Key('folder-picker-hidden'))); + await tester.pumpAndSettle(); + expect(find.text('.config'), findsOneWidget); + expect(find.text('.zshrc'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('folder-picker-filter')), + 'PRO', + ); + await tester.pumpAndSettle(); + expect(find.text('projects'), findsOneWidget); + expect(find.text('src'), findsNothing); + await tester.enterText( + find.byKey(const Key('folder-picker-filter')), + 'zzz', + ); + await tester.pumpAndSettle(); + expect(find.textContaining('Nothing here matches'), findsOneWidget); + }); + + testWidgets('${host.name}: a refused folder is shown inline and home ' + 'recovers', (tester) async { + final gateway = FakeDirectoryGateway(); + String? result = 'unset'; + await _pump( + tester, + host, + _Launcher( + gateway: gateway, + initialPath: '/etc', + onResult: (value) => result = value, + ), + ); + expect(find.textContaining('outside the home directory'), findsOneWidget); + expect(find.text('No folder selected'), findsOneWidget); + await tester.tap(find.byKey(const Key('folder-picker-start'))); + await tester.pumpAndSettle(); + expect(result, 'unset'); + + await tester.tap(find.text('Go to home')); + await tester.pumpAndSettle(); + expect(find.text('projects'), findsOneWidget); + + gateway.denied.add('$fakeHome/projects'); + await tester.tap(find.text('projects')); + await tester.pumpAndSettle(); + expect( + find.text('permission denied: $fakeHome/projects'), + findsOneWidget, + ); + await tester.tap(find.text('Back to ~')); + await tester.pumpAndSettle(); + expect(find.text('projects'), findsOneWidget); + expect(find.text('Start in ~'), findsOneWidget); + }); + } + + testWidgets('opens at an initial folder and offers recents at home', ( + tester, + ) async { + final gateway = FakeDirectoryGateway(); + await _pump( + tester, + _Host.material, + _Launcher( + gateway: gateway, + initialPath: '$fakeHome/projects', + recents: const ['$fakeHome/projects/app', '/elsewhere'], + onResult: (_) {}, + ), + ); + expect(gateway.requests, ['$fakeHome/projects']); + expect(find.text('Recent folders'), findsNothing); + await tester.tap(_crumb(fakeHome)); + await tester.pumpAndSettle(); + expect(find.text('Recent folders'), findsOneWidget); + expect(find.text('~/projects/app'), findsOneWidget); + expect(find.text('/elsewhere'), findsNothing); + await tester.tap(find.text('~/projects/app')); + await tester.pumpAndSettle(); + expect(find.text('lib'), findsOneWidget); + }); + + for (final host in _Host.values) { + testWidgets('${host.name}: wide windows get a dialog, phones a page', ( + tester, + ) async { + final gateway = FakeDirectoryGateway(); + await _pump( + tester, + host, + _Launcher(gateway: gateway, onResult: (_) {}), + size: const Size(1000, 900), + ); + final page = tester.getSize(find.text('Choose folder')); + expect(page.width, greaterThan(0)); + final scaffoldType = host == _Host.material + ? Scaffold + : CupertinoPageScaffold; + final picker = find.ancestor( + of: find.text('Choose folder'), + matching: find.byType(scaffoldType), + ); + expect(tester.getSize(picker.first).width, lessThan(1000)); + expect( + host == _Host.material ? find.byType(Dialog) : find.byType(ClipRRect), + findsWidgets, + ); + }); + } +} diff --git a/app/test/features/chat/ui/sessions/chat_create_folder_picker_test.dart b/app/test/features/chat/ui/sessions/chat_create_folder_picker_test.dart new file mode 100644 index 00000000..1a730364 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_create_folder_picker_test.dart @@ -0,0 +1,88 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; + +import '../folder_picker/fake_directory_gateway.dart'; +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// A chat gateway whose `list_directory` answers come from the fake home tree. +FakeChatGateway _gateway(FakeDirectoryGateway directories) { + final gateway = FakeChatGateway(); + gateway.directoriesHandler = () async => { + 'chat_directories': [fakeHome, '$fakeHome/projects/app', '/srv/other'], + }; + gateway.actionHandler = (type, fields) => directories.call(type, fields); + return gateway; +} + +void main() { + final hosts = Function(WidgetTester, FakeChatGateway)>{ + 'material': (tester, gateway) => pumpMaterialChat(tester, gateway), + 'cupertino': (tester, gateway) => pumpCupertinoChat(tester, gateway), + 'ios material': (tester, gateway) => pumpIosMaterialChat(tester, gateway), + }; + for (final MapEntry(key: name, value: pump) in hosts.entries) { + testWidgets('$name: Choose folder fills the directory and creates there', ( + tester, + ) async { + usePhoneSurface(tester); + final directories = FakeDirectoryGateway(); + final gateway = _gateway(directories); + await pump(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-create-choose-folder'))); + await tester.pumpAndSettle(); + // Opened at home (the dialog's current choice is ~) with the recent + // folder inside home offered first. + expect(directories.requests, [null]); + expect(find.text('Recent folders'), findsOneWidget); + expect(find.text('~/projects/app'), findsOneWidget); + expect(find.text('/srv/other'), findsNothing); + + await tester.tap(find.text('projects')); + await tester.pumpAndSettle(); + await tester.tap(find.text('web')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('folder-picker-start'))); + await tester.pumpAndSettle(); + + expect(find.text('Choose folder'), findsNothing); + expect(find.text('Start in $fakeHome/projects/web'), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-create-confirm'))); + await tester.pumpAndSettle(); + final fields = + gateway.lastFields('chat_create')!['chat_create']! as JsonMap; + expect(fields['directory'], '$fakeHome/projects/web'); + expect(fields['title'], 'Web OpenCode'); + }); + } + + testWidgets('the picker reopens at the chosen folder; cancel keeps it', ( + tester, + ) async { + usePhoneSurface(tester); + final directories = FakeDirectoryGateway(); + final gateway = _gateway(directories); + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-create-choose-folder'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('src')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('folder-picker-start'))); + await tester.pumpAndSettle(); + expect(find.text('Start in $fakeHome/src'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-create-choose-folder'))); + await tester.pumpAndSettle(); + expect(directories.requests.last, '$fakeHome/src'); + await tester.tap(find.text('Cancel').last); + await tester.pumpAndSettle(); + expect(find.text('Start in $fakeHome/src'), findsOneWidget); + }); +} diff --git a/app/tool/probe_folder_fixture.dart b/app/tool/probe_folder_fixture.dart new file mode 100644 index 00000000..f47a353c --- /dev/null +++ b/app/tool/probe_folder_fixture.dart @@ -0,0 +1,103 @@ +// Fixture replies for the new-chat folder picker in the capture probe app +// (`search_selection_probe_entry.dart`). They answer `chat_sessions`, +// `chat_directories`, `chat_backends` and `list_directory` with server-shaped +// bodies over an invented home tree, so `/chat` → New chat → Choose folder can +// be rendered and captured without any server. +import 'package:pipelines_app/core/api_gateway.dart'; + +const probeHome = '/home/operator'; + +JsonMap _entry( + String parent, + String name, { + bool dir = true, + bool git = false, +}) => { + 'name': name, + 'path': '$parent/$name', + 'is_dir': dir, + 'is_git_repo': git, + 'hidden': name.startsWith('.'), +}; + +final Map> _tree = { + probeHome: [ + for (final name in ['.cache', '.config', '.ssh']) _entry(probeHome, name), + _entry(probeHome, 'Desktop'), + _entry(probeHome, 'Documents'), + _entry(probeHome, 'Downloads'), + _entry(probeHome, 'notes', git: true), + _entry(probeHome, 'Private'), + _entry(probeHome, 'repos'), + _entry(probeHome, '.zshrc', dir: false), + _entry(probeHome, 'todo.md', dir: false), + ], + '$probeHome/repos': [ + _entry('$probeHome/repos', 'dotfiles', git: true), + _entry('$probeHome/repos', 'pipelines', git: true), + _entry('$probeHome/repos', 'scratch'), + _entry('$probeHome/repos', 'website', git: true), + _entry('$probeHome/repos', 'README.txt', dir: false), + ], + '$probeHome/repos/pipelines': [ + for (final name in ['.git', '.github']) + _entry('$probeHome/repos/pipelines', name), + for (final name in ['app', 'cmd', 'docs', 'internal', 'web']) + _entry('$probeHome/repos/pipelines', name), + for (final name in ['AGENTS.md', 'go.mod', 'README.md']) + _entry('$probeHome/repos/pipelines', name, dir: false), + ], +}; + +/// The reply for a folder-picker request, or null when [request] is not one. +JsonMap? probeFolderReply(JsonMap request) { + final id = request['id']; + switch ('${request['type']}') { + case 'chat_sessions': + return {'id': id, 'type': 'chat_sessions', 'chat_sessions': const []}; + case 'chat_directories': + return { + 'id': id, + 'type': 'chat_directories', + 'chat_directories': [probeHome, '$probeHome/repos/pipelines'], + }; + case 'chat_backends': + return { + 'id': id, + 'type': 'chat_backends', + 'chat_backends': ['opencode', 'claude', 'codex'], + }; + case 'list_directory': + final body = request['list_directory']; + final requested = body is Map ? body['path'] as String? : null; + final path = requested == null || requested == '~' + ? probeHome + : requested; + final entries = _tree[path]; + if (path == '$probeHome/Private') { + return {'id': id, 'type': 'error', 'error': 'permission denied: $path'}; + } + if (path != probeHome && !path.startsWith('$probeHome/')) { + return { + 'id': id, + 'type': 'error', + 'error': + 'path $path is outside the home directory $probeHome; only ' + 'folders inside home can be listed', + }; + } + return { + 'id': id, + 'type': 'directory_listing', + 'directory_listing': { + 'path': path, + 'home': probeHome, + 'parent': path == probeHome + ? null + : path.substring(0, path.lastIndexOf('/')), + 'entries': entries ?? const [], + }, + }; + } + return null; +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index b8813a86..b786b9aa 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -27,6 +27,8 @@ import 'package:flutter/widgets.dart'; import 'package:web/web.dart' as web; import 'package:web_socket_channel/web_socket_channel.dart'; +import 'probe_folder_fixture.dart'; + /// The run every run-scoped hit names. Its recorded sequences are deliberately /// not its row indexes (plan 5, build 2, plan 1), exactly like the unit /// fixture, so a selection has to resolve the recorded sequence. @@ -395,7 +397,8 @@ JsonMap? probeReply(JsonMap request) { }, }; default: - return error('Fixture does not implement $type'); + return probeFolderReply(request) ?? + error('Fixture does not implement $type'); } } diff --git a/docs/cli.md b/docs/cli.md index c5e3f0df..b54b6516 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -482,6 +482,23 @@ sessions pipeline runs create. The protocol types are: (currently 8). It is a dedicated request so the create dialog can load the choices without first listing sessions; `chat_sessions` stays a pure session list. +- `list_directory` backs the app's "Choose folder" picker. The request body is + `list_directory: {"path": "..."}`; `path` is optional, absolute or starting + with `~` (`~` or `~/sub`), and defaults to the server user's home. The reply + is `directory_listing: {"path", "home", "parent", "entries", "truncated"}`: + `path` is the absolute, cleaned directory (expressed under `home`), `parent` is + `null` at the home root, and each entry is + `{"name", "path", "is_dir", "is_git_repo", "hidden"}` — directories first, + then files, each group sorted case-insensitively. Files are names only (never + contents) and are not selectable; `is_git_repo` marks a directory containing + `.git`; `hidden` marks a dot-name. Listing is confined to the home subtree: + the path is cleaned and its symlinks resolved first, so `..`, an absolute path + outside home, or a symlink that escapes home is refused with an `error` frame + ("... is outside the home directory ..."); a symlink entry that escapes home is + listed only as a plain name. Kernel pseudo filesystems (proc, sysfs, devfs and + similar) are refused, permission problems are reported as + `permission denied: `, and a reply carries at most 2000 entries with + `truncated: true` when more exist. - `chat_adopt` takes a `session_id` that already exists on the configured endpoint and records it in the operator session registry, using the endpoint's own directory and title (never a guess or the server's working directory). The diff --git a/internal/protocol/directories.go b/internal/protocol/directories.go new file mode 100644 index 00000000..24e9a43e --- /dev/null +++ b/internal/protocol/directories.go @@ -0,0 +1,45 @@ +package protocol + +// Directory browsing for the chat folder picker. A client sends +// Message{Type: ListDirectory, ID: , ListDirectory: &DirectoryListRequest{Path: ...}} +// and the server echoes the ID on a DirectoryListing reply. Listing is +// restricted to the server user's home directory subtree, returns names and +// kinds only (never file contents) and is bounded by DirectoryListingMaxEntries. +const ( + ListDirectory = "list_directory" + DirectoryListing = "directory_listing" +) + +// DirectoryListingMaxEntries caps the entries one directory_listing returns; +// a larger directory sets Truncated. +const DirectoryListingMaxEntries = 2000 + +// DirectoryListRequest is the list_directory body. Path is absolute or starts +// with "~" ("~" or "~/sub"); an omitted or empty path lists the home directory. +type DirectoryListRequest struct { + Path string `json:"path,omitempty"` +} + +// DirectoryListingResult is the directory_listing reply. Path is the absolute, +// cleaned directory listed (expressed under Home), Parent is null at the home +// root, and Entries are directories first, then files, each group sorted +// case-insensitively. Files are listed by name only so a picker can show +// context; they are not selectable. +type DirectoryListingResult struct { + Path string `json:"path"` + Home string `json:"home"` + Parent *string `json:"parent"` + Entries []DirectoryEntry `json:"entries"` + Truncated bool `json:"truncated,omitempty"` +} + +// DirectoryEntry is one listed name. IsDir is true only for a directory (or a +// symlink to one) that stays inside the home subtree; IsGitRepo marks a +// directory containing .git; Hidden marks a dot-name. +type DirectoryEntry struct { + Name string `json:"name"` + Path string `json:"path"` + IsDir bool `json:"is_dir"` + IsGitRepo bool `json:"is_git_repo"` + Hidden bool `json:"hidden"` +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 942fd650..05499a36 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -234,6 +234,10 @@ type Message struct { ChatShellOutputQuery *ChatShellOutputQuery `json:"chat_shell_output_query,omitempty"` ChatShells []ChatShell `json:"chat_shells,omitempty"` ChatShellOutput *ChatShellOutputPage `json:"chat_shell_output,omitempty"` + // ListDirectory is the list_directory body and DirectoryListing its reply: + // the home-restricted folder picker listing (see directories.go). + ListDirectory *DirectoryListRequest `json:"list_directory,omitempty"` + DirectoryListing *DirectoryListingResult `json:"directory_listing,omitempty"` // ChatAttachmentImageRequest is the chat_attachment_image body and // ChatAttachmentImage its reply. ChatAttachmentImageRequest *ChatAttachmentImageRequest `json:"chat_attachment_image_request,omitempty"` diff --git a/internal/server/directory_fs_darwin.go b/internal/server/directory_fs_darwin.go new file mode 100644 index 00000000..a440f767 --- /dev/null +++ b/internal/server/directory_fs_darwin.go @@ -0,0 +1,26 @@ +//go:build darwin + +package server + +import "syscall" + +// specialFilesystem reports whether path lives on a pseudo filesystem (devfs, +// autofs, fdesc) that a folder picker must never list. +func specialFilesystem(path string) bool { + var stat syscall.Statfs_t + if err := syscall.Statfs(path, &stat); err != nil { + return false + } + name := make([]byte, 0, len(stat.Fstypename)) + for _, c := range stat.Fstypename { + if c == 0 { + break + } + name = append(name, byte(c)) + } + switch string(name) { + case "devfs", "autofs", "fdesc": + return true + } + return false +} diff --git a/internal/server/directory_fs_linux.go b/internal/server/directory_fs_linux.go new file mode 100644 index 00000000..fe0f0c79 --- /dev/null +++ b/internal/server/directory_fs_linux.go @@ -0,0 +1,31 @@ +//go:build linux + +package server + +import "syscall" + +// Filesystem magic numbers (linux/magic.h) for kernel pseudo filesystems that +// a folder picker must never list. +var specialFilesystemMagic = map[int64]struct{}{ + 0x9fa0: {}, // proc + 0x62656572: {}, // sysfs + 0x1cd1: {}, // devpts + 0x64626720: {}, // debugfs + 0x74726163: {}, // tracefs + 0x27e0eb: {}, // cgroup + 0x63677270: {}, // cgroup2 + 0xf97cff8c: {}, // selinuxfs + 0x73636673: {}, // securityfs + 0xcafe4a11: {}, // bpf + 0x65735546: {}, // fuse control +} + +// specialFilesystem reports whether path lives on a kernel pseudo filesystem. +func specialFilesystem(path string) bool { + var stat syscall.Statfs_t + if err := syscall.Statfs(path, &stat); err != nil { + return false + } + _, ok := specialFilesystemMagic[int64(stat.Type)] + return ok +} diff --git a/internal/server/directory_fs_other.go b/internal/server/directory_fs_other.go new file mode 100644 index 00000000..e1223592 --- /dev/null +++ b/internal/server/directory_fs_other.go @@ -0,0 +1,6 @@ +//go:build !linux && !darwin + +package server + +// specialFilesystem has no pseudo-filesystem probe on this platform. +func specialFilesystem(string) bool { return false } diff --git a/internal/server/directory_listing.go b/internal/server/directory_listing.go new file mode 100644 index 00000000..6b8af91c --- /dev/null +++ b/internal/server/directory_listing.go @@ -0,0 +1,200 @@ +package server + +import ( + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// directoryListingScanLimit bounds how many names one list_directory reads +// before sorting, so a huge directory cannot make the server read without end. +// The reply itself is capped at protocol.DirectoryListingMaxEntries. +const directoryListingScanLimit = 5 * protocol.DirectoryListingMaxEntries + +// handleDirectoryListing answers list_directory. It returns true when the +// request was a list_directory and has been answered. +func handleDirectoryListing(request protocol.Message, write func(protocol.Message) error) bool { + if request.Type != protocol.ListDirectory { + return false + } + path := "" + if request.ListDirectory != nil { + path = request.ListDirectory.Path + } + home, err := OperatorHomeDirectory() + if err == nil { + var listing protocol.DirectoryListingResult + listing, err = listHomeDirectory(home, path, protocol.DirectoryListingMaxEntries) + if err == nil { + _ = write(protocol.Message{Type: protocol.DirectoryListing, ID: request.ID, DirectoryListing: &listing}) + return true + } + } + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return true +} + +// listHomeDirectory lists one directory inside home. The requested path is +// cleaned and its symlinks resolved before the containment check, so neither +// ".." nor a symlink can escape home. The listed path is reported under home +// (as the operator sees it) even when home itself is reached through a link. +func listHomeDirectory(home, requested string, maxEntries int) (protocol.DirectoryListingResult, error) { + home = filepath.Clean(home) + realHome, err := filepath.EvalSymlinks(home) + if err != nil { + return protocol.DirectoryListingResult{}, errors.New("resolve home directory: " + err.Error()) + } + target, err := expandHomePath(home, requested) + if err != nil { + return protocol.DirectoryListingResult{}, err + } + rel, realTarget, err := resolveInsideHome(realHome, target) + if err != nil { + return protocol.DirectoryListingResult{}, err + } + shown := filepath.Join(home, rel) + info, err := os.Stat(realTarget) + if err != nil { + return protocol.DirectoryListingResult{}, describePathError(shown, err) + } + if !info.IsDir() { + return protocol.DirectoryListingResult{}, errors.New(shown + " is not a directory") + } + if specialFilesystem(realTarget) { + return protocol.DirectoryListingResult{}, errors.New(shown + " is on a special filesystem and cannot be listed") + } + entries, truncated, err := readDirectoryEntries(realHome, realTarget, shown, maxEntries) + if err != nil { + return protocol.DirectoryListingResult{}, err + } + result := protocol.DirectoryListingResult{Path: shown, Home: home, Entries: entries, Truncated: truncated} + if rel != "." { + parent := filepath.Dir(shown) + result.Parent = &parent + } + return result, nil +} + +// expandHomePath turns "", "~" and "~/sub" into paths under home and requires +// anything else to be absolute. "~user" forms are refused. +func expandHomePath(home, requested string) (string, error) { + requested = strings.TrimSpace(requested) + switch { + case requested == "" || requested == "~": + return home, nil + case strings.HasPrefix(requested, "~/"): + return filepath.Join(home, requested[2:]), nil + case strings.HasPrefix(requested, "~"): + return "", errors.New("path " + requested + " must be absolute or start with ~/") + case !filepath.IsAbs(requested): + return "", errors.New("path " + requested + " must be absolute or start with ~") + } + return filepath.Clean(requested), nil +} + +// resolveInsideHome resolves every symlink in target and returns its path +// relative to realHome, refusing anything outside the home subtree. +func resolveInsideHome(realHome, target string) (string, string, error) { + realTarget, err := filepath.EvalSymlinks(target) + if err != nil { + return "", "", describePathError(target, err) + } + rel, ok := relInside(realHome, realTarget) + if !ok { + return "", "", errors.New("path " + target + " is outside the home directory " + realHome + "; only folders inside home can be listed") + } + return rel, realTarget, nil +} + +func relInside(root, path string) (string, bool) { + rel, err := filepath.Rel(root, path) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return "", false + } + return rel, true +} + +func describePathError(path string, err error) error { + switch { + case errors.Is(err, fs.ErrPermission): + return errors.New("permission denied: " + path) + case errors.Is(err, fs.ErrNotExist): + return errors.New(path + " does not exist") + } + return errors.New(path + " is not available: " + err.Error()) +} + +// readDirectoryEntries reads at most directoryListingScanLimit names, sorts +// directories first then case-insensitively, and caps the result. Only names +// and kinds are read; no file is opened. +func readDirectoryEntries(realHome, realDir, shown string, maxEntries int) ([]protocol.DirectoryEntry, bool, error) { + dir, err := os.Open(realDir) + if err != nil { + return nil, false, describePathError(shown, err) + } + defer dir.Close() + items, err := dir.ReadDir(directoryListingScanLimit + 1) + if err != nil && !errors.Is(err, io.EOF) { + return nil, false, describePathError(shown, err) + } + truncated := len(items) > directoryListingScanLimit + if truncated { + items = items[:directoryListingScanLimit] + } + entries := make([]protocol.DirectoryEntry, 0, len(items)) + for _, item := range items { + entries = append(entries, describeEntry(realHome, realDir, shown, item)) + } + sort.SliceStable(entries, func(i, j int) bool { + a, b := entries[i], entries[j] + if a.IsDir != b.IsDir { + return a.IsDir + } + la, lb := strings.ToLower(a.Name), strings.ToLower(b.Name) + if la != lb { + return la < lb + } + return a.Name < b.Name + }) + if len(entries) > maxEntries { + entries = entries[:maxEntries] + truncated = true + } + return entries, truncated, nil +} + +// describeEntry classifies one name. A symlink counts as a directory only when +// it resolves to a directory still inside home; one that escapes is shown as a +// plain, non-selectable name. Devices, sockets and pipes are plain names too. +func describeEntry(realHome, realDir, shown string, item fs.DirEntry) protocol.DirectoryEntry { + name := item.Name() + entry := protocol.DirectoryEntry{Name: name, Path: filepath.Join(shown, name), Hidden: strings.HasPrefix(name, ".")} + full := filepath.Join(realDir, name) + switch { + case item.IsDir(): + entry.IsDir = true + case item.Type()&fs.ModeSymlink != 0: + resolved, err := filepath.EvalSymlinks(full) + if err != nil { + break + } + if _, ok := relInside(realHome, resolved); !ok { + break + } + if info, err := os.Stat(resolved); err == nil && info.IsDir() { + entry.IsDir = true + } + } + if entry.IsDir { + if _, err := os.Lstat(filepath.Join(full, ".git")); err == nil { + entry.IsGitRepo = true + } + } + return entry +} diff --git a/internal/server/directory_listing_test.go b/internal/server/directory_listing_test.go new file mode 100644 index 00000000..ccaf183b --- /dev/null +++ b/internal/server/directory_listing_test.go @@ -0,0 +1,232 @@ +package server + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "github.com/coder/websocket/wsjson" +) + +// newListingHome builds a scratch home: folders of mixed case, a hidden folder, +// a git repository, files, and an outside directory next to (not inside) home. +func newListingHome(t *testing.T) (home, outside string) { + t.Helper() + root := t.TempDir() + home = filepath.Join(root, "home") + outside = filepath.Join(root, "outside") + for _, dir := range []string{"zeta", "Alpha", "beta", ".config", "repo/.git", "repo/src"} { + mustMkdir(t, filepath.Join(home, dir)) + } + mustMkdir(t, outside) + for _, file := range []string{"Notes.txt", "a.md", ".profile", "repo/README.md"} { + if err := os.WriteFile(filepath.Join(home, file), []byte("secret contents"), 0o644); err != nil { + t.Fatal(err) + } + } + return home, outside +} + +func mustMkdir(t *testing.T, path string) { + t.Helper() + if err := os.MkdirAll(path, 0o755); err != nil { + t.Fatal(err) + } +} + +func entryNames(entries []protocol.DirectoryEntry) []string { + names := make([]string, 0, len(entries)) + for _, entry := range entries { + names = append(names, entry.Name) + } + return names +} + +func TestListDirectoryHomeSortsDirectoriesFirstAndMarksHiddenAndRepos(t *testing.T) { + home, _ := newListingHome(t) + for _, requested := range []string{"", "~", home, home + "/"} { + listing, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries) + if err != nil { + t.Fatalf("%q: %v", requested, err) + } + if listing.Path != home || listing.Home != home || listing.Parent != nil || listing.Truncated { + t.Fatalf("%q: header = %+v", requested, listing) + } + got := strings.Join(entryNames(listing.Entries), ",") + if want := ".config,Alpha,beta,repo,zeta,.profile,a.md,Notes.txt"; got != want { + t.Fatalf("%q: order = %s, want %s", requested, got, want) + } + } + listing, _ := listHomeDirectory(home, "~", protocol.DirectoryListingMaxEntries) + byName := map[string]protocol.DirectoryEntry{} + for _, entry := range listing.Entries { + byName[entry.Name] = entry + } + if e := byName[".config"]; !e.Hidden || !e.IsDir || e.IsGitRepo { + t.Fatalf(".config = %+v", e) + } + if e := byName["repo"]; !e.IsDir || !e.IsGitRepo || e.Hidden || e.Path != filepath.Join(home, "repo") { + t.Fatalf("repo = %+v", e) + } + if e := byName["Notes.txt"]; e.IsDir || e.Hidden { + t.Fatalf("Notes.txt = %+v", e) + } + if e := byName[".profile"]; e.IsDir || !e.Hidden { + t.Fatalf(".profile = %+v", e) + } +} + +func TestListDirectorySubdirectoryHasParent(t *testing.T) { + home, _ := newListingHome(t) + for _, requested := range []string{"~/repo", filepath.Join(home, "repo"), filepath.Join(home, "beta", "..", "repo")} { + listing, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries) + if err != nil { + t.Fatalf("%q: %v", requested, err) + } + if listing.Path != filepath.Join(home, "repo") || listing.Parent == nil || *listing.Parent != home { + t.Fatalf("%q: header = %+v", requested, listing) + } + if got := strings.Join(entryNames(listing.Entries), ","); got != ".git,src,README.md" { + t.Fatalf("%q: entries = %s", requested, got) + } + } +} + +func TestListDirectoryRefusesPathsOutsideHome(t *testing.T) { + home, outside := newListingHome(t) + if err := os.Symlink(outside, filepath.Join(home, "escape")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(home, "repo"), filepath.Join(home, "inside")); err != nil { + t.Fatal(err) + } + for _, requested := range []string{ + outside, + filepath.Join(home, ".."), + filepath.Join(home, "..", "outside"), + "~/..", + "~/../outside", + "~/escape", + filepath.Join(home, "escape"), + "/", + } { + _, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries) + if err == nil || !strings.Contains(err.Error(), "outside the home directory") { + t.Fatalf("%q: err = %v, want outside-home refusal", requested, err) + } + } + for _, requested := range []string{"relative/path", "~root", "~/missing"} { + if _, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries); err == nil { + t.Fatalf("%q listed, want an error", requested) + } + } + if _, err := listHomeDirectory(home, "~/Notes.txt", protocol.DirectoryListingMaxEntries); err == nil || !strings.Contains(err.Error(), "not a directory") { + t.Fatalf("file listed: %v", err) + } + // An escaping link is listed only as a non-selectable name; a link that + // stays inside home is a directory and lists under its home-relative path. + listing, err := listHomeDirectory(home, "~", protocol.DirectoryListingMaxEntries) + if err != nil { + t.Fatal(err) + } + for _, entry := range listing.Entries { + if entry.Name == "escape" && entry.IsDir { + t.Fatalf("escaping link marked as a directory: %+v", entry) + } + if entry.Name == "inside" && (!entry.IsDir || !entry.IsGitRepo) { + t.Fatalf("inside link = %+v", entry) + } + } + inside, err := listHomeDirectory(home, "~/inside", protocol.DirectoryListingMaxEntries) + if err != nil || inside.Path != filepath.Join(home, "repo") { + t.Fatalf("inside link listing = %+v, %v", inside, err) + } +} + +func TestListDirectoryPermissionDenied(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + home, _ := newListingHome(t) + locked := filepath.Join(home, "locked") + mustMkdir(t, locked) + if err := os.Chmod(locked, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + _, err := listHomeDirectory(home, "~/locked", protocol.DirectoryListingMaxEntries) + if err == nil || !strings.Contains(err.Error(), "permission denied") { + t.Fatalf("err = %v, want permission denied", err) + } +} + +func TestListDirectoryTruncatesAtTheCap(t *testing.T) { + home, _ := newListingHome(t) + big := filepath.Join(home, "big") + for i := 0; i < 6; i++ { + mustMkdir(t, filepath.Join(big, fmt.Sprintf("d%d", i))) + if err := os.WriteFile(filepath.Join(big, fmt.Sprintf("f%d", i)), nil, 0o644); err != nil { + t.Fatal(err) + } + } + listing, err := listHomeDirectory(home, "~/big", 4) + if err != nil { + t.Fatal(err) + } + if !listing.Truncated || strings.Join(entryNames(listing.Entries), ",") != "d0,d1,d2,d3" { + t.Fatalf("listing = %+v", listing) + } + full, err := listHomeDirectory(home, "~/big", 12) + if err != nil || full.Truncated || len(full.Entries) != 12 { + t.Fatalf("exact-cap listing = %+v, %v", full, err) + } +} + +// TestListDirectoryOverWebsocket pins the wire: list_directory replies with a +// directory_listing echoing the request id, and a refusal is an error frame. +func TestListDirectoryOverWebsocket(t *testing.T) { + home, outside := newListingHome(t) + t.Setenv("HOME", home) + ctx, _, conn := dialChatOptions(t, Options{}) + request := protocol.Message{Type: protocol.ListDirectory, ID: "l1", ListDirectory: &protocol.DirectoryListRequest{Path: "~/repo"}} + if err := wsjson.Write(ctx, conn, request); err != nil { + t.Fatal(err) + } + var reply protocol.Message + if err := wsjson.Read(ctx, conn, &reply); err != nil { + t.Fatal(err) + } + if reply.Type != protocol.DirectoryListing || reply.ID != "l1" || reply.DirectoryListing == nil { + t.Fatalf("reply = %+v", reply) + } + if got := reply.DirectoryListing; got.Path != filepath.Join(home, "repo") || got.Home != home || got.Parent == nil || *got.Parent != home { + t.Fatalf("listing = %+v", got) + } + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ListDirectory, ID: "l2"}); err != nil { + t.Fatal(err) + } + var raw map[string]any + if err := wsjson.Read(ctx, conn, &raw); err != nil { + t.Fatal(err) + } + body, _ := raw["directory_listing"].(map[string]any) + if raw["id"] != "l2" || body == nil || body["path"] != home { + t.Fatalf("home reply = %+v", raw) + } + if parent, present := body["parent"]; !present || parent != nil { + t.Fatalf("home parent must be an explicit null: %+v", body) + } + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ListDirectory, ID: "l3", ListDirectory: &protocol.DirectoryListRequest{Path: outside}}); err != nil { + t.Fatal(err) + } + var refusal protocol.Message + if err := wsjson.Read(ctx, conn, &refusal); err != nil { + t.Fatal(err) + } + if refusal.Type != protocol.Error || refusal.ID != "l3" || !strings.Contains(refusal.Error, "outside the home directory") { + t.Fatalf("refusal = %+v", refusal) + } +} diff --git a/internal/server/websocket.go b/internal/server/websocket.go index db5765b9..4d368653 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -221,6 +221,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin if handleChat(connCtx, request, options.Chat, hub, registry, clientID, write) { continue } + if handleDirectoryListing(request, write) { + continue + } if handleNotificationSettings(ctx, request, settingsStore, write) { continue }