From 41e21ae2506fd5410379a141d526aff70dbdc62e Mon Sep 17 00:00:00 2001 From: Inspire Queue Development Date: Fri, 27 Nov 2026 22:28:41 -0800 Subject: [PATCH 1/2] LS-91: resolve pasted and approximate file paths Co-authored-by: multica-agent --- scripts/test_queue_dart.py | 20 +- serverbox/lib/data/model/file/path_query.dart | 193 +++++++ .../lib/data/model/file/path_resolver.dart | 463 ++++++++++++++++ .../test/unit/file/path_resolver_test.dart | 512 ++++++++++++++++++ 4 files changed, 1184 insertions(+), 4 deletions(-) create mode 100644 serverbox/lib/data/model/file/path_query.dart create mode 100644 serverbox/lib/data/model/file/path_resolver.dart create mode 100644 serverbox/test/unit/file/path_resolver_test.dart diff --git a/scripts/test_queue_dart.py b/scripts/test_queue_dart.py index 7cdea71..78cea2c 100644 --- a/scripts/test_queue_dart.py +++ b/scripts/test_queue_dart.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Run production queue tests without unrelated app native build hooks.""" +"""Run production queue and file search tests without app native build hooks.""" import argparse import json from pathlib import Path @@ -23,22 +23,34 @@ def main(): ui = ' material_ui: 1.5.0\n cupertino_ui: 1.1.1\n url_launcher: 6.3.2\n clock: ^1.1.3\n' if args.widgets else '' if args.ssh_bundle: ui += f' archive: ^4.3.0\n crypto: ^3.0.0\n pointycastle: ^4.0.0\n pinenacl: ^0.6.0\n dartssh2:\n path: "{ROOT / "serverbox/packages/dartssh2"}"\n' - (harness/'pubspec.yaml').write_text("name: queue_protocol_checks\nenvironment:\n sdk: '>=3.11.0 <4.0.0'\ndependencies:\n flutter:\n sdk: flutter\n"+ui+"dev_dependencies:\n flutter_test:\n sdk: flutter\nflutter:\n uses-material-design: true\n") + (harness/'pubspec.yaml').write_text("name: queue_protocol_checks\nenvironment:\n sdk: '>=3.11.0 <4.0.0'\ndependencies:\n flutter:\n sdk: flutter\n logging: ^1.3.0\n"+ui+"dev_dependencies:\n flutter_test:\n sdk: flutter\nflutter:\n uses-material-design: true\n") names = ['queue_protocol_test.dart', 'queue_session_test.dart', 'queue_presentation_test.dart', 'mac_update_release_test.dart', 'mac_update_bridge_test.dart', 'local_calendar_test.dart', 'result_preview_test.dart'] if args.widgets: names += ['queue_resource_widget_test.dart', 'queue_workspace_widget_test.dart', 'feishu_task_widget_test.dart', 'overview_layout_test.dart'] for name in names: source = (ROOT/'serverbox/test/unit/app'/name).read_text() (harness/'test'/name).write_text(source) + name = 'path_resolver_test.dart' + (harness/'test'/name).write_text((ROOT/'serverbox/test/unit/file'/name).read_text()) if args.ssh_bundle: (harness/'test/client_bundle_test.dart').write_text((ROOT/'serverbox/test/unit/ssh/client_bundle_test.dart').read_text()) (harness/'test/device_login_test.dart').write_text((ROOT/'serverbox/test/unit/ssh/device_login_test.dart').read_text()) subprocess.run([args.flutter, 'pub', 'get', *(['--offline'] if args.offline else [])], cwd=harness, check=True) - # Resolve the real production library; no copies, mocks, or native app - # hooks. Only the small declared dependency graph is built by this harness. + # The real FileBackend imports fl_lib for its logger. Its full package + # builds a Rust theme store, so expose only the logger used here. + logger_lib = harness/'test_support/lib' + logger_lib.mkdir(parents=True) + (logger_lib/'fl_lib.dart').write_text( + "import 'package:logging/logging.dart';\n\n" + "abstract final class Loggers {\n" + " static final app = Logger('App');\n" + "}\n" + ) + # Exercise the real server_box sources through the minimal package graph. config = harness/'.dart_tool/package_config.json' packages = json.loads(config.read_text()) packages['packages'].append({'name': 'server_box', 'rootUri': (ROOT/'serverbox').as_uri(), 'packageUri': 'lib/', 'languageVersion': '3.11'}) + packages['packages'].append({'name': 'fl_lib', 'rootUri': logger_lib.parent.as_uri(), 'packageUri': 'lib/', 'languageVersion': '3.11'}) config.write_text(json.dumps(packages)) subprocess.run([args.flutter, 'test', '--no-pub'], cwd=harness, check=True) diff --git a/serverbox/lib/data/model/file/path_query.dart b/serverbox/lib/data/model/file/path_query.dart new file mode 100644 index 0000000..358d2b6 --- /dev/null +++ b/serverbox/lib/data/model/file/path_query.dart @@ -0,0 +1,193 @@ +import 'package:server_box/data/model/file/browse_path.dart'; + +/// A pasted search query, with a backend path only when it can be resolved +/// within the browser root. Paths use forward slashes on every backend. +final class ParsedPathQuery { + const ParsedPathQuery._({ + required this.cleanedPath, + required this.root, + required this.targetPath, + required this.basePath, + required this.isPathLike, + required this.isRelative, + required this.isOutOfBounds, + required this.line, + }); + + /// Input after removing paste artifacts, before expanding home or resolving. + final String cleanedPath; + final String root; + final String? targetPath; + + /// The already selected directory for relative and home paths. + final String? basePath; + final bool isPathLike; + + /// Eligible for rebasing against recently visited directories. + final bool isRelative; + final bool isOutOfBounds; + final int? line; + + static ParsedPathQuery parse( + String raw, { + required String currentDir, + required String root, + String? homePath, + }) { + var path = _unwrap(raw); + final suffix = _lineSuffix.firstMatch(path); + final line = int.tryParse(suffix?.group(1) ?? suffix?.group(2) ?? ''); + if (suffix != null) path = _unwrap(path.substring(0, suffix.start)); + + final isFileUri = path.toLowerCase().startsWith('file://'); + if (isFileUri) { + path = path.substring('file://'.length); + if (path.toLowerCase().startsWith('localhost/')) { + path = path.substring('localhost'.length); + } + try { + path = Uri.decodeComponent(path); + } on ArgumentError { + // Keep malformed escapes literal. + } on FormatException { + // The escapes can also decode to invalid UTF-8. + } + } + path = path.replaceAll(r'\', '/'); + if (isFileUri && + path.startsWith('/') && + _drivePath.hasMatch(path.substring(1))) { + path = path.substring(1); + } + + final scp = isFileUri ? null : _scpPrefix.firstMatch(path); + if (scp != null) path = path.substring(scp.end); + + final isPathLike = + isFileUri || + scp != null || + path.contains('/') || + path.startsWith('~') || + path.startsWith('.'); + final usesHome = path == '~' || path.startsWith('~/'); + final isAbsolute = path.startsWith('/') || _drivePath.hasMatch(path); + final isRelative = + path.isNotEmpty && + !usesHome && + !isAbsolute && + !isFileUri && + scp == null && + !path.startsWith('~'); + final browser = BrowsePath(root: root); + final normalizedRoot = _withDriveRootSlash(browser.root); + + String? requestedPath; + String? basePath; + if (usesHome && homePath != null && homePath.isNotEmpty) { + final home = homePath.replaceAll(r'\', '/'); + basePath = _resolveWithin(browser, home); + requestedPath = path == '~' + ? home + : BrowsePath.join(home, path.substring(2)); + } else if (isAbsolute) { + requestedPath = path; + } else if (isRelative) { + basePath = _resolveWithin(browser, currentDir); + if (basePath != null) requestedPath = BrowsePath.join(basePath, path); + } + + final target = requestedPath == null + ? null + : _resolveWithin(browser, requestedPath); + final missingHome = usesHome && (homePath == null || homePath.isEmpty); + return ParsedPathQuery._( + cleanedPath: path, + root: normalizedRoot, + targetPath: target, + basePath: basePath, + isPathLike: isPathLike, + isRelative: isRelative, + isOutOfBounds: + target == null && + !missingHome && + (isAbsolute || isRelative || usesHome), + line: line, + ); + } + + /// Resolves a trusted browser location such as a history directory against + /// this query's root, rejecting traversal at the root boundary. + String? resolveDirectory(String directory) => + _resolveWithin(BrowsePath(root: root), directory); + + /// Validates one untrusted listing component before it is joined to a path. + bool isSafeEntryName(String name) => + name.isNotEmpty && + name != '.' && + name != '..' && + !name.contains('/') && + !name.contains(r'\') && + !name.contains('\x00') && + (root.startsWith('/') || _isWindowsFileName(name)); + + static bool _isWindowsFileName(String name) => + !name.contains(':') && !name.endsWith('.') && !name.endsWith(' '); + + static final _lineSuffix = RegExp( + r':([0-9]+)(?::[0-9]+)?$|#L([0-9]+)(?:-L[0-9]+)?$', + ); + static final _scpPrefix = RegExp( + r'^([^/\s:]{2,}|\[[0-9A-Fa-f:]+\]):(?=/|~/)', + ); + static final _drivePath = RegExp(r'^[A-Za-z]:/'); + static final _driveRoot = RegExp(r'^[A-Za-z]:$'); + + static String _unwrap(String input) { + var text = input.trim(); + while (text.length >= 2) { + final first = text[0]; + final end = first == '<' ? '>' : first; + if (!const {'<', "'", '"', '`'}.contains(first) || !text.endsWith(end)) + break; + text = text.substring(1, text.length - 1).trim(); + } + return text; + } + + static String? _resolveWithin(BrowsePath browser, String rawPath) { + final path = rawPath.replaceAll(r'\', '/'); + final windows = _driveRoot.hasMatch(browser.root.split('/').first); + if (path.contains('\x00') || + (windows && !_drivePath.hasMatch(path) && !_driveRoot.hasMatch(path)) || + (!windows && !path.startsWith('/'))) { + return null; + } + final rootDepth = browser.root + .split('/') + .where((part) => part.isNotEmpty) + .length; + var depth = 0; + for (final part in path.split('/')) { + if (part.isEmpty || part == '.') continue; + // Reject traversal at the browser root before BrowsePath normalizes it. + if (part == '..') { + if (depth <= rootDepth) return null; + depth--; + continue; + } + // Win32 can reinterpret trailing spaces, trailing dots and stream + // specifiers before accessing a component. + if (windows && depth > 0 && !_isWindowsFileName(part)) { + return null; + } + depth++; + } + + final resolved = browser.resolve(path); + return resolved == null ? null : _withDriveRootSlash(resolved); + } + + // A bare drive letter and colon would be drive-relative on Windows. + static String _withDriveRootSlash(String path) => + _driveRoot.hasMatch(path) ? '$path/' : path; +} diff --git a/serverbox/lib/data/model/file/path_resolver.dart b/serverbox/lib/data/model/file/path_resolver.dart new file mode 100644 index 0000000..f166941 --- /dev/null +++ b/serverbox/lib/data/model/file/path_resolver.dart @@ -0,0 +1,463 @@ +import 'dart:math' as math; + +import 'package:server_box/data/model/file/browse_path.dart'; +import 'package:server_box/data/model/file/file_backend.dart'; +import 'package:server_box/data/model/file/path_query.dart'; + +enum PathMatchKind { exactFile, exactDir, fuzzyFile, fuzzyDir, nearestDir } + +final class PathMatchCandidate { + const PathMatchCandidate({ + required this.fullPath, + required this.parentDir, + required this.entry, + required this.matchKind, + required this.score, + }); + + final String fullPath; + final String parentDir; + final FileEntry entry; + final PathMatchKind matchKind; + + /// 100 for exact paths, 0 for the nearest ancestor, and 1–99 otherwise. + final int score; +} + +final class PathResolveResult { + PathResolveResult._({ + Iterable candidates = const [], + this.nearestExistingDir, + this.truncated = false, + this.budgetExhausted = false, + this.cancelled = false, + }) : candidates = List.unmodifiable(candidates); + + final List candidates; + final String? nearestExistingDir; + + /// The search skipped work due to a depth, branch, or backend call limit. + final bool truncated; + + /// The search attempted to exceed a backend call limit. + final bool budgetExhausted; + final bool cancelled; +} + +/// Searches through the browser's backend using per-request limits and state. +final class PathResolver { + PathResolver( + this.backend, { + this.maxListCalls = 8, + this.maxBranch = 3, + this.maxDepth = 3, + this.maxStatCalls = 32, + this.directoryCache, + }) { + if (maxListCalls < 0 || maxBranch < 1 || maxDepth < 0 || maxStatCalls < 0) { + throw ArgumentError('Invalid path search limits'); + } + } + + final FileBackend backend; + final int maxListCalls; + final int maxBranch; + final int maxDepth; + final int maxStatCalls; + + /// Optional writable cache of successful listings, owned by the caller. + /// Scope it to one backend and invalidate it when directory contents change. + final Map>? directoryCache; + + Future resolve( + ParsedPathQuery query, { + bool showHiddenFiles = false, + Iterable historyDirs = const [], + bool Function()? isCancelled, + }) async { + final search = _PathSearch(this, query, showHiddenFiles, isCancelled); + try { + search.checkCancellation(); + final target = query.targetPath; + if (target == null) return PathResolveResult._(); + return await search.resolve(target, historyDirs); + } on _SearchCancelled { + return PathResolveResult._(cancelled: true); + } + } +} + +typedef _Branch = ({String dir, int offset, int points, bool usedGap}); + +final class _PathSearch { + _PathSearch(this.options, this.query, this.showHiddenFiles, this.isCancelled); + + final PathResolver options; + final ParsedPathQuery query; + final bool showHiddenFiles; + final bool Function()? isCancelled; + + final _listings = ?>{}; + final _directories = {}; + final _candidates = {}; + var _listCalls = 0; + var _statCalls = 0; + var _budgetExhausted = false; + var _truncated = false; + + Future resolve( + String target, + Iterable historyDirs, + ) async { + final parent = _parentOf(target); + String? nearest; + if (target == query.root) { + if (await _list(target) != null || + await _existsAfterListFailure(target)) { + _add(_directoryCandidate(target, PathMatchKind.exactDir, 100)); + } + } else { + var dir = parent; + while (true) { + final entries = await _list(dir); + checkCancellation(); + if (entries != null) { + nearest = dir; + await _expand(dir, target, entries); + break; + } + if (await _existsAfterListFailure(dir)) { + nearest = dir; + break; + } + if (dir == query.root) break; + dir = _parentOf(dir); + } + } + + var exact = _candidates[target]?.score == 100; + if (!exact && query.isRelative) { + exact = await _searchHistory(target, historyDirs); + } + checkCancellation(); + if (exact) nearest = null; + if (nearest != null && !_candidates.containsKey(nearest)) { + _add(_directoryCandidate(nearest, PathMatchKind.nearestDir, 0)); + } + final ranked = _candidates.values.toList() + ..sort((a, b) { + final score = b.score.compareTo(a.score); + return score == 0 ? a.fullPath.compareTo(b.fullPath) : score; + }); + return PathResolveResult._( + candidates: ranked, + nearestExistingDir: nearest, + truncated: _truncated || _budgetExhausted, + budgetExhausted: _budgetExhausted, + ); + } + + /// Walks the literal suffix one component at a time. If a component has no + /// match, try one omitted, visible directory on a lower-scoring branch. + Future _expand( + String ancestor, + String target, + List initialEntries, + ) async { + final base = query.basePath; + if (base != null && ancestor != base) { + final prefix = BrowsePath.join(base, ''); + if (target.startsWith(prefix) && !ancestor.startsWith(prefix)) return; + } + final prefixLength = ancestor.length + (ancestor.endsWith('/') ? 0 : 1); + final segments = target.substring(prefixLength).split('/'); + var layer = <_Branch>[ + (dir: ancestor, offset: 0, points: 0, usedGap: false), + ]; + for (var depth = 0; layer.isNotEmpty; depth++) { + final next = <_Branch>[]; + for (final branch in layer) { + final entries = depth == 0 ? initialEntries : await _list(branch.dir); + checkCancellation(); + if (entries == null) continue; + final segment = segments[branch.offset]; + final isLeaf = branch.offset == segments.length - 1; + var matched = false; + for (final entry in entries) { + if (!entry.isDir && (!isLeaf || entry.kind != FileKind.file)) + continue; + if (!_visible(entry.name, segment)) continue; + + final score = _score(segment, entry.name); + if (score == 0) continue; + matched = true; + final path = BrowsePath.join(branch.dir, entry.name); + final points = branch.points + score; + if (isLeaf) { + final matchesTarget = path == target; + _add( + _candidate( + path, + entry, + exact: matchesTarget, + score: points ~/ (segments.length + (branch.usedGap ? 1 : 0)), + ), + ); + } else { + next.add(( + dir: path, + offset: branch.offset + 1, + points: points, + usedGap: branch.usedGap, + )); + } + } + + if (!matched && !branch.usedGap) { + for (final entry in entries) { + // The user supplied no component which could opt into a dot dir. + if (!entry.isDir || !_visible(entry.name, '')) continue; + next.add(( + dir: BrowsePath.join(branch.dir, entry.name), + offset: branch.offset, + points: branch.points + 20, + usedGap: true, + )); + } + } + } + if (next.isEmpty) break; + if (depth == options.maxDepth) { + _truncated = true; + break; + } + next.sort((a, b) { + final score = b.points.compareTo(a.points); + return score == 0 ? a.dir.compareTo(b.dir) : score; + }); + if (next.length > options.maxBranch) _truncated = true; + layer = next.take(options.maxBranch).toList(); + } + } + + Future _searchHistory( + String target, + Iterable historyDirs, + ) async { + final searchedTargets = {target}; + for (final previous in historyDirs) { + checkCancellation(); + final dir = query.resolveDirectory(previous); + if (dir == null) continue; + final rebased = query.resolveDirectory( + BrowsePath.join(dir, query.cleanedPath), + ); + if (rebased == null || !searchedTargets.add(rebased)) continue; + if (rebased == query.root) { + if (await _list(rebased) != null || + await _existsAfterListFailure(rebased)) { + _add(_directoryCandidate(rebased, PathMatchKind.exactDir, 100)); + return true; + } + } else { + final name = _basename(rebased); + final entries = await _list(_parentOf(rebased)); + for (final entry in entries ?? const []) { + if (entry.name == name && + (entry.isDir || entry.kind == FileKind.file)) { + _add(_candidate(rebased, entry, exact: true, score: 100)); + return true; + } + } + } + if (searchedTargets.length == 4) break; + } + return false; + } + + Future?> _list(String dir) async { + checkCancellation(); + if (_listings.containsKey(dir)) return _listings[dir]; + final shared = options.directoryCache?[dir]; + if (shared == null && _listCalls >= options.maxListCalls) { + _budgetExhausted = true; + return null; + } + if (options.backend.traits.symlinks && !await _confirmDirectory(dir)) { + _listings[dir] = null; + return null; + } + checkCancellation(); + if (shared != null) { + return _listings[dir] = _safeEntries(shared); + } + + _listCalls++; + final entries = await _request(() => options.backend.list(dir)); + if (entries == null) { + _listings[dir] = null; + return null; + } + + checkCancellation(); + final safe = _safeEntries(entries); + _directories[dir] = true; + options.directoryCache?.putIfAbsent(dir, () => safe); + return _listings[dir] = safe; + } + + /// On link-capable backends, a listing can follow intermediate symlinks. + /// Check components below the caller's root from top to bottom first. + Future _confirmDirectory(String dir) async { + final unverified = []; + var ancestor = dir; + while (ancestor != query.root && !_directories.containsKey(ancestor)) { + unverified.add(ancestor); + ancestor = _parentOf(ancestor); + } + + var exists = ancestor == query.root || _directories[ancestor] == true; + for (final path in unverified.reversed) { + exists = exists && await _statDirectory(path); + _directories[path] = exists; + } + return exists; + } + + Future _existsAfterListFailure(String dir) async { + if (!_listings.containsKey(dir)) return false; + return _directories[dir] ??= await _statDirectory(dir); + } + + Future _statDirectory(String dir) async { + checkCancellation(); + if (_statCalls >= options.maxStatCalls) { + _budgetExhausted = true; + return false; + } + _statCalls++; + final entry = await _request(() => options.backend.stat(dir)); + return entry?.isDir ?? false; + } + + Future _request(Future Function() request) async { + checkCancellation(); + try { + return await request(); + } on Exception { + // Backends can report absent and unreadable directories as list errors. + // Stat can verify an existing ancestor before it is offered as a result. + return null; + } finally { + checkCancellation(); + } + } + + void checkCancellation() { + if (isCancelled?.call() == true) throw const _SearchCancelled(); + } + + bool _visible(String name, String segment) => + showHiddenFiles || !name.startsWith('.') || segment.startsWith('.'); + + String _parentOf(String path) { + if (path == query.root) return path; + final slash = path.lastIndexOf('/'); + final bareParent = slash <= 0 ? '/' : path.substring(0, slash); + return query.root == '$bareParent/' ? query.root : bareParent; + } + + String _basename(String path) { + if (path == '/') return path; + final end = path.endsWith('/') ? path.length - 1 : path.length; + return path.substring(path.lastIndexOf('/', end - 1) + 1, end); + } + + PathMatchCandidate _candidate( + String path, + FileEntry entry, { + required bool exact, + required int score, + }) => PathMatchCandidate( + fullPath: path, + parentDir: _parentOf(path), + entry: entry, + matchKind: entry.isDir + ? (exact ? PathMatchKind.exactDir : PathMatchKind.fuzzyDir) + : (exact ? PathMatchKind.exactFile : PathMatchKind.fuzzyFile), + score: exact ? 100 : math.min(score, 99), + ); + + PathMatchCandidate _directoryCandidate( + String dir, + PathMatchKind kind, + int score, + ) => PathMatchCandidate( + fullPath: dir, + parentDir: _parentOf(dir), + entry: FileEntry(name: _basename(dir), kind: FileKind.dir), + matchKind: kind, + score: score, + ); + + void _add(PathMatchCandidate candidate) { + final previous = _candidates[candidate.fullPath]; + if (previous == null || candidate.score > previous.score) { + _candidates[candidate.fullPath] = candidate; + } + } + + List _safeEntries(List entries) => List.unmodifiable( + entries.where((entry) => query.isSafeEntryName(entry.name)), + ); +} + +final class _SearchCancelled implements Exception { + const _SearchCancelled(); +} + +int _score(String query, String name) { + if (query == name) return 100; + final needle = query.toLowerCase(); + final haystack = name.toLowerCase(); + if (needle == haystack) return 90; + if (haystack.startsWith(needle)) return 78; + if (haystack.contains(needle)) return 66; + if (needle.length >= 3 && _isSubsequence(needle, haystack)) return 50; + + if (needle.length < 3 || needle.length > 64 || haystack.length > 64) return 0; + final limit = needle.length <= 5 ? 1 : 2; + final edits = _editDistance(needle, haystack, limit); + return edits <= limit ? 40 - edits * 4 : 0; +} + +bool _isSubsequence(String needle, String haystack) { + var matched = 0; + for (var i = 0; i < haystack.length; i++) { + if (haystack.codeUnitAt(i) == needle.codeUnitAt(matched)) { + if (++matched == needle.length) return true; + } + } + return false; +} + +int _editDistance(String a, String b, int limit) { + if ((a.length - b.length).abs() > limit) return limit + 1; + var row = List.generate(b.length + 1, (i) => i); + var next = List.filled(row.length, 0); + for (var i = 1; i <= a.length; i++) { + next[0] = i; + var best = i; + for (var j = 1; j <= b.length; j++) { + final cost = a.codeUnitAt(i - 1) == b.codeUnitAt(j - 1) ? 0 : 1; + next[j] = math.min( + row[j - 1] + cost, + math.min(next[j - 1] + 1, row[j] + 1), + ); + best = math.min(best, next[j]); + } + if (best > limit) return limit + 1; + (row, next) = (next, row); + } + return row.last; +} diff --git a/serverbox/test/unit/file/path_resolver_test.dart b/serverbox/test/unit/file/path_resolver_test.dart new file mode 100644 index 0000000..0120173 --- /dev/null +++ b/serverbox/test/unit/file/path_resolver_test.dart @@ -0,0 +1,512 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/data/model/file/file_backend.dart'; +import 'package:server_box/data/model/file/path_query.dart'; +import 'package:server_box/data/model/file/path_resolver.dart'; + +const _root = '/fixtures'; + +ParsedPathQuery _parse( + String input, { + String current = _root, + String root = _root, + String? home, +}) => ParsedPathQuery.parse( + input, + currentDir: current, + root: root, + homePath: home, +); + +FileEntry _file(String name) => FileEntry(name: name, kind: FileKind.file); +FileEntry _dir(String name) => FileEntry(name: name, kind: FileKind.dir); + +class _Backend implements FileBackend { + _Backend(this.tree, {bool symlinks = false}) + : traits = FileBackendTraits(symlinks: symlinks); + + final Map> tree; + final listed = []; + final checked = []; + Future> Function(String)? onList; + Future Function(String)? onStat; + + @override + final FileBackendTraits traits; + + @override + Future> list(String path) async { + listed.add(path); + final hook = onList; + if (hook != null) return hook(path); + return tree[path] ?? (throw Exception('Directory unavailable')); + } + + @override + Future stat(String path) async { + checked.add(path); + final hook = onStat; + if (hook != null) return hook(path); + final slash = path.lastIndexOf('/'); + final parent = slash <= 0 ? '/' : path.substring(0, slash); + final name = path.substring(slash + 1); + for (final entry in tree[parent] ?? const []) { + if (entry.name == name) return entry; + } + return tree.containsKey(path) ? _dir(name) : null; + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + group('pasted paths', () { + test('unwraps clipboard text and recognizes all line suffix forms', () { + for (final (input, line) in [ + (' "\n/fixtures/code.py:42\n" ', 42), + (" '/fixtures/code.py':42:10 ", 42), + (' `/fixtures/code.py#L42` ', 42), + (' ', 42), + (' /fixtures/code.py:notes ', null), + ]) { + final query = _parse(input); + expect( + query.targetPath, + line == null ? '/fixtures/code.py:notes' : '/fixtures/code.py', + reason: input, + ); + expect(query.line, line, reason: input); + expect(query.isPathLike, isTrue, reason: input); + } + }); + + test( + 'decodes file URIs and retains invalid percent encoding literally', + () { + expect( + _parse('file:///fixtures/code%20sample.py#L9').targetPath, + '/fixtures/code sample.py', + ); + for (final name in ['bad%ZZ.py', 'bad%FF.py', 'bad%.py']) { + expect( + _parse('file:///fixtures/$name').targetPath, + '/fixtures/$name', + ); + } + final escapedName = _parse('file://localhost/fixtures/report%3A42'); + expect(escapedName.targetPath, '/fixtures/report:42'); + expect(escapedName.line, isNull); + }, + ); + + test('handles SCP, Windows drive letters, and slash normalization', () { + expect( + _parse(r'person@compute.example:/fixtures\logs\output:42').targetPath, + '/fixtures/logs/output', + ); + expect( + _parse('compute.example:~/logs', home: '/fixtures/home').targetPath, + '/fixtures/home/logs', + ); + expect( + _parse( + r'C:\Fixtures\logs\output:42', + root: 'C:/Fixtures', + current: 'C:/Fixtures', + ).targetPath, + 'C:/Fixtures/logs/output', + ); + expect( + _parse('file:///C:/', root: 'C:/', current: 'C:/').targetPath, + 'C:/', + ); + }); + + test('distinguishes names, relative paths, and unexpanded home', () { + expect(_parse('output.log').isPathLike, isFalse); + expect(_parse('.env').isPathLike, isTrue); + final relative = _parse(r'..\src\cfg.yml', current: '/fixtures/sub'); + expect(relative.isRelative, isTrue); + expect(relative.targetPath, '/fixtures/src/cfg.yml'); + expect(_parse('~', home: '/fixtures/home').targetPath, '/fixtures/home'); + expect( + _parse('~/src', home: '/fixtures/home').targetPath, + '/fixtures/home/src', + ); + expect(_parse('~/fixtures/src', home: '/').targetPath, '/fixtures/src'); + final unresolved = _parse('~/src'); + expect(unresolved.cleanedPath, '~/src'); + expect(unresolved.targetPath, isNull); + expect(unresolved.isOutOfBounds, isFalse); + }); + }); + + test( + 'one listing finds an exact file, exact dir, and ranks siblings', + () async { + final backend = _Backend({ + _root: [ + _file('train.py.bak'), + _file('train_v2.py'), + _file('xtrain.py'), + _file('TRAIN.PY'), + _file('train.py'), + _dir('TrainFiles'), + ], + }); + final resolver = PathResolver(backend); + final files = await resolver.resolve(_parse('/fixtures/train.py')); + expect(files.candidates.map((item) => item.entry.name), [ + 'train.py', + 'TRAIN.PY', + 'train.py.bak', + 'xtrain.py', + 'train_v2.py', + ]); + final exact = files.candidates.first; + expect(exact.fullPath, '/fixtures/train.py'); + expect(exact.parentDir, _root); + expect(exact.matchKind, PathMatchKind.exactFile); + expect(exact.score, 100); + expect(files.nearestExistingDir, isNull); + expect(backend.listed, [_root]); + + final directory = await resolver.resolve(_parse('/fixtures/TrainFiles')); + expect(directory.candidates.first.matchKind, PathMatchKind.exactDir); + final root = await resolver.resolve(_parse('/fixtures/')); + expect(root.candidates.single.matchKind, PathMatchKind.exactDir); + expect(root.candidates.single.parentDir, _root); + }, + ); + + test('matches misspellings, missing letters and subsequences', () async { + final resolver = PathResolver( + _Backend({ + _root: [ + _file('train.py'), + _file('train_config.yml'), + _dir('sample-dir'), + ], + }), + ); + for (final (query, name, kind) in [ + ('trzin.py', 'train.py', PathMatchKind.fuzzyFile), + ('tran.py', 'train.py', PathMatchKind.fuzzyFile), + ('trn_cnf.yml', 'train_config.yml', PathMatchKind.fuzzyFile), + ('sampl-di', 'sample-dir', PathMatchKind.fuzzyDir), + ]) { + final result = await resolver.resolve(_parse(query)); + expect(result.candidates.first.entry.name, name, reason: query); + expect(result.candidates.first.matchKind, kind, reason: query); + } + }); + + test( + 'probes a missing parent, then ranks paths from the nearest ancestor', + () async { + final backend = _Backend({ + '/fixtures/exp': [_dir('run_02'), _dir('run_010')], + '/fixtures/exp/run_02': [_file('train_v2.py')], + '/fixtures/exp/run_010': [_file('train.py')], + }); + final result = await PathResolver(backend) + .resolve(_parse('/fixtures/exp/run_01/train.py')); + + expect(backend.listed.take(2), ['/fixtures/exp/run_01', '/fixtures/exp']); + expect(result.nearestExistingDir, '/fixtures/exp'); + expect(result.candidates.map((item) => item.fullPath), [ + '/fixtures/exp/run_010/train.py', + '/fixtures/exp/run_02/train_v2.py', + '/fixtures/exp', + ]); + expect(result.candidates.last.matchKind, PathMatchKind.nearestDir); + }, + ); + + test('can locate a target under one omitted directory', () async { + final backend = _Backend({ + _root: [_dir('outputs')], + '/fixtures/outputs': [_dir('generated')], + '/fixtures/outputs/generated': [_file('report.json')], + }); + final result = await PathResolver(backend) + .resolve(_parse('outputs/report.json')); + expect( + result.candidates.first.fullPath, + '/fixtures/outputs/generated/report.json', + ); + expect(result.candidates.first.matchKind, PathMatchKind.fuzzyFile); + }); + + test( + 'reports the deepest confirmed ancestor and tolerates list errors', + () async { + final backend = _Backend({ + _root: [_dir('reports')], + '/fixtures/reports': [], + }); + backend.onList = (path) async => throw Exception('Directory unavailable'); + final result = await PathResolver(backend) + .resolve(_parse('/fixtures/reports/missing/deep/private.txt')); + expect(result.nearestExistingDir, '/fixtures/reports'); + expect(result.candidates.single.entry.name, 'reports'); + expect(backend.listed, [ + '/fixtures/reports/missing/deep', + '/fixtures/reports/missing', + '/fixtures/reports', + ]); + }, + ); + + test('prefers the current directory, then tries up to three distinct history dirs', () async { + final backend = _Backend({ + _root: [], + '/fixtures/current': [_dir('src')], + '/fixtures/current/src': [_file('here.yml')], + '/fixtures/store3/src': [_file('config.yml')], + '/fixtures/store4/src': [_file('absent.yml')], + }); + final resolver = PathResolver(backend); + const history = [ + '/unrelated', + '/fixtures/current', + '/fixtures/store1', + '/fixtures/./store1/', + '/fixtures/store2', + '/fixtures/store3', + '/fixtures/store4', + ]; + final exact = await resolver.resolve( + _parse('src/here.yml', current: '/fixtures/current'), + historyDirs: history, + ); + expect(exact.candidates.first.fullPath, '/fixtures/current/src/here.yml'); + expect(backend.listed, ['/fixtures/current/src']); + + backend.listed.clear(); + final rebased = await resolver.resolve( + _parse('src/config.yml', current: '/fixtures/current'), + historyDirs: history, + ); + expect( + rebased.candidates.first.fullPath, + '/fixtures/store3/src/config.yml', + ); + expect(rebased.candidates.first.matchKind, PathMatchKind.exactFile); + expect(rebased.nearestExistingDir, isNull); + expect(backend.listed, [ + '/fixtures/current/src', + '/fixtures/store1/src', + '/fixtures/store2/src', + '/fixtures/store3/src', + ]); + + backend.listed.clear(); + await resolver.resolve( + _parse('src/absent.yml', current: '/fixtures/current'), + historyDirs: history, + ); + expect(backend.listed, isNot(contains('/fixtures/store4/src'))); + }); + + test('rejects root escapes before any backend request', () async { + final backend = _Backend({}, symlinks: true); + final resolver = PathResolver(backend); + for (final query in [ + _parse('/../../etc/passwd', root: '/', current: '/'), + _parse('/fixtures/../../etc/passwd'), + _parse('/fixtures/../fixtures/report'), + _parse('/fixtures-copy/report'), + _parse('../report'), + _parse('file:///fixtures/%2e%2e/report'), + _parse('~/report', home: '/outside'), + _parse('report', current: '/outside'), + _parse('C:/../C:/report', root: 'C:/', current: 'C:/'), + _parse( + 'C:/Fixtures/.. /report', + root: 'C:/Fixtures', + current: 'C:/Fixtures', + ), + ]) { + expect(query.isOutOfBounds, isTrue, reason: query.cleanedPath); + final result = await resolver.resolve(query, historyDirs: [_root]); + expect(result.candidates, isEmpty); + } + await resolver.resolve(_parse('~/report')); + expect(backend.listed, isEmpty); + expect(backend.checked, isEmpty); + }); + + test('preserves the absolute form of a Windows drive root', () async { + final backend = _Backend({'C:/': []}); + final result = await PathResolver(backend) + .resolve(_parse('C:/', root: 'C:/', current: 'C:/')); + expect(result.candidates.single.fullPath, 'C:/'); + expect(backend.listed, ['C:/']); + }); + + test('filters untrusted entry names and applies hidden visibility after cache reads', () async { + final backend = _Backend({}); + final resolver = PathResolver( + backend, + directoryCache: { + _root: [ + _file(''), + _dir('.'), + _dir('..'), + _file('../outside'), + _file(r'..\outside'), + _file('.env'), + _dir('.config'), + _file('env.txt'), + ], + '/fixtures/.config': [_file('app.ini')], + }, + ); + final visible = await resolver.resolve(_parse('env')); + expect(visible.candidates.map((item) => item.entry.name), [ + 'env.txt', + 'fixtures', + ]); + final hidden = await resolver.resolve(_parse('env'), showHiddenFiles: true); + expect(hidden.candidates.map((item) => item.entry.name), contains('.env')); + + final exact = await resolver.resolve(_parse('.env')); + expect(exact.candidates.first.fullPath, '/fixtures/.env'); + final nested = await resolver.resolve(_parse('.config/app.ini')); + expect(nested.candidates.first.fullPath, '/fixtures/.config/app.ini'); + final omitted = await resolver.resolve(_parse('app.ini')); + expect(omitted.candidates.map((item) => item.entry.name), ['fixtures']); + + final bogus = await resolver.resolve( + _parse('outside'), + showHiddenFiles: true, + ); + expect(bogus.candidates.map((item) => item.entry.name), ['fixtures']); + expect(backend.listed, isEmpty); + }); + + test('cache keys are normalized and successful results are reused', () async { + final backend = _Backend({ + '/fixtures/src': [_file('config.yml'), _file('../config.yml')], + }); + final cache = >{}; + final resolver = PathResolver(backend, directoryCache: cache); + final first = await resolver.resolve(_parse('src//./config.yml')); + final second = await resolver.resolve(_parse('/fixtures/src/config.yml')); + expect(first.candidates.single.fullPath, second.candidates.single.fullPath); + expect(cache.keys, ['/fixtures/src']); + expect(cache['/fixtures/src']!.map((entry) => entry.name), ['config.yml']); + expect(backend.listed, ['/fixtures/src']); + }); + + test('never descends into links in a direct path or fuzzy branch', () async { + final backend = _Backend({ + _root: [const FileEntry(name: 'linked', kind: FileKind.link)], + '/fixtures/linked/sub': [_file('private.txt')], + }, symlinks: true); + final resolver = PathResolver(backend); + final result = await resolver.resolve(_parse('linked/sub/private.txt')); + expect(result.nearestExistingDir, _root); + expect(result.candidates.single.matchKind, PathMatchKind.nearestDir); + expect(backend.checked, ['/fixtures/linked']); + expect(backend.listed, [_root]); + final direct = await resolver.resolve(_parse('linked')); + expect(direct.candidates.single.matchKind, PathMatchKind.nearestDir); + }); + + test('enforces list, depth, and branch limits independently', () async { + final backend = _Backend({ + _root: [ + _dir('run_00a'), + _dir('run_00b'), + _dir('run_00c'), + _dir('run_00d'), + ], + '/fixtures/run_00a': [_dir('result')], + '/fixtures/run_00b': [_dir('result')], + }); + const input = 'run_00/result/train.py'; + final bounded = await PathResolver( + backend, + maxListCalls: 4, + ).resolve(_parse(input)); + expect(backend.listed.length, 4); + expect(bounded.truncated, isTrue); + expect(bounded.budgetExhausted, isTrue); + expect(bounded.nearestExistingDir, _root); + + backend.listed.clear(); + final narrow = await PathResolver( + backend, + maxBranch: 1, + maxDepth: 0, + ).resolve(_parse(input)); + expect(backend.listed, [ + '/fixtures/run_00/result', + '/fixtures/run_00', + _root, + ]); + expect(narrow.truncated, isTrue); + expect(narrow.budgetExhausted, isFalse); + + backend.listed.clear(); + await PathResolver( + backend, + maxBranch: 1, + maxDepth: 1, + ).resolve(_parse(input)); + expect(backend.listed.last, '/fixtures/run_00a'); + expect(backend.listed, isNot(contains('/fixtures/run_00b'))); + }); + + test( + 'cancellation before or during a list stops requests and cache writes', + () async { + final backend = _Backend({}); + final cache = >{}; + final resolver = PathResolver(backend, directoryCache: cache); + final query = _parse('src/train.py'); + final alreadyCancelled = await resolver.resolve( + query, + isCancelled: () => true, + ); + expect(alreadyCancelled.cancelled, isTrue); + expect(backend.listed, isEmpty); + + final request = Completer>(); + final started = Completer(); + backend.onList = (_) { + started.complete(); + return request.future; + }; + var cancel = false; + final future = resolver.resolve(query, isCancelled: () => cancel); + await started.future; + cancel = true; + request.complete([_file('train.py')]); + final cancelled = await future; + expect(cancelled.cancelled, isTrue); + expect(cancelled.candidates, isEmpty); + expect(cache, isEmpty); + expect(backend.listed, ['/fixtures/src']); + expect(backend.checked, isEmpty); + }, + ); + + test('cancellation after a stat prevents subsequent I/O', () async { + var cancel = false; + final backend = _Backend({}, symlinks: true); + backend.onStat = (_) async { + cancel = true; + return _dir('src'); + }; + final result = await PathResolver(backend) + .resolve(_parse('src/build/train.py'), isCancelled: () => cancel); + expect(result.cancelled, isTrue); + expect(backend.checked, ['/fixtures/src']); + expect(backend.listed, isEmpty); + }); +} From b98532f97e5f924aadabe545010d0e5d74b7e194 Mon Sep 17 00:00:00 2001 From: Inspire Queue Development Date: Mon, 30 Nov 2026 04:40:16 -0800 Subject: [PATCH 2/2] LS-91: recover from backend status failures and list from root Co-authored-by: multica-agent --- .../lib/data/model/file/path_resolver.dart | 21 ++-- .../test/unit/file/path_resolver_test.dart | 108 +++++++++++++++--- 2 files changed, 107 insertions(+), 22 deletions(-) diff --git a/serverbox/lib/data/model/file/path_resolver.dart b/serverbox/lib/data/model/file/path_resolver.dart index f166941..ea9c997 100644 --- a/serverbox/lib/data/model/file/path_resolver.dart +++ b/serverbox/lib/data/model/file/path_resolver.dart @@ -283,7 +283,11 @@ final class _PathSearch { _budgetExhausted = true; return null; } - if (options.backend.traits.symlinks && !await _confirmDirectory(dir)) { + // At /, the backend controls which paths it serves. A readable directory + // can have an inaccessible or symlinked ancestor. + if (query.root != '/' && + options.backend.traits.symlinks && + !await _confirmDirectory(dir)) { _listings[dir] = null; return null; } @@ -342,15 +346,16 @@ final class _PathSearch { Future _request(Future Function() request) async { checkCancellation(); + T? result; try { - return await request(); - } on Exception { - // Backends can report absent and unreadable directories as list errors. - // Stat can verify an existing ancestor before it is offered as a result. - return null; - } finally { - checkCancellation(); + result = await request(); + } on Object catch (error) { + if (error is Error || error is _SearchCancelled) rethrow; + // Backend status objects can report absent or unreadable paths. + // The caller can continue with another probe. } + checkCancellation(); + return result; } void checkCancellation() { diff --git a/serverbox/test/unit/file/path_resolver_test.dart b/serverbox/test/unit/file/path_resolver_test.dart index 0120173..08dd7e9 100644 --- a/serverbox/test/unit/file/path_resolver_test.dart +++ b/serverbox/test/unit/file/path_resolver_test.dart @@ -1,6 +1,8 @@ import 'dart:async'; +import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/core/utils/local_file_backend.dart'; import 'package:server_box/data/model/file/file_backend.dart'; import 'package:server_box/data/model/file/path_query.dart'; import 'package:server_box/data/model/file/path_resolver.dart'; @@ -22,6 +24,8 @@ ParsedPathQuery _parse( FileEntry _file(String name) => FileEntry(name: name, kind: FileKind.file); FileEntry _dir(String name) => FileEntry(name: name, kind: FileKind.dir); +enum _BackendFailure { missing, forbidden } + class _Backend implements FileBackend { _Backend(this.tree, {bool symlinks = false}) : traits = FileBackendTraits(symlinks: symlinks); @@ -260,6 +264,39 @@ void main() { }, ); + test('falls back after list and stat throw backend status objects', () async { + const parent = '/fixtures/reports'; + const missing = '$parent/missing'; + final backend = _Backend({}); + backend.onList = (path) async { + if (path == missing) throw _BackendFailure.missing; + expect(path, parent); + return []; + }; + backend.onStat = (path) async { + expect(path, missing); + throw _BackendFailure.missing; + }; + + final result = await PathResolver(backend) + .resolve(_parse('$missing/summary.txt')); + expect(result.nearestExistingDir, parent); + expect(result.candidates.single.matchKind, PathMatchKind.nearestDir); + expect(backend.listed, [missing, parent]); + expect(backend.checked, [missing]); + }); + + test('propagates Dart errors from a backend operation', () async { + final error = StateError('Invalid backend state'); + final backend = _Backend({})..onList = (_) async => throw error; + await expectLater( + PathResolver(backend).resolve(_parse('reports/summary.txt')), + throwsA(same(error)), + ); + expect(backend.listed, ['/fixtures/reports']); + expect(backend.checked, isEmpty); + }); + test('prefers the current directory, then tries up to three distinct history dirs', () async { final backend = _Backend({ _root: [], @@ -402,20 +439,63 @@ void main() { expect(backend.listed, ['/fixtures/src']); }); - test('never descends into links in a direct path or fuzzy branch', () async { - final backend = _Backend({ - _root: [const FileEntry(name: 'linked', kind: FileKind.link)], - '/fixtures/linked/sub': [_file('private.txt')], - }, symlinks: true); - final resolver = PathResolver(backend); - final result = await resolver.resolve(_parse('linked/sub/private.txt')); - expect(result.nearestExistingDir, _root); - expect(result.candidates.single.matchKind, PathMatchKind.nearestDir); - expect(backend.checked, ['/fixtures/linked']); - expect(backend.listed, [_root]); - final direct = await resolver.resolve(_parse('linked')); - expect(direct.candidates.single.matchKind, PathMatchKind.nearestDir); - }); + test( + 'lists and caches accessible paths under a restricted ancestor at /', + () async { + const dir = '/fixtures/restricted/reports'; + final backend = _Backend({ + dir: [_file('summary.txt')], + }, symlinks: true)..onStat = (_) async => throw _BackendFailure.forbidden; + final resolver = PathResolver(backend, directoryCache: {}); + final query = _parse('$dir/summary.txt', root: '/', current: '/'); + + for (var attempt = 0; attempt < 2; attempt++) { + final result = await resolver.resolve(query); + expect(result.candidates.single.fullPath, '$dir/summary.txt'); + expect(result.candidates.single.matchKind, PathMatchKind.exactFile); + } + expect(backend.listed, [dir]); + expect(backend.checked, isEmpty); + }, + ); + + test('resolves a local file through an explicit symlink at /', () async { + final sandbox = await Directory.systemTemp.createTemp('path-resolver-'); + addTearDown(() => sandbox.delete(recursive: true)); + final target = await Directory('${sandbox.path}/target').create(); + await File('${target.path}/summary.txt').writeAsString('fixture'); + final alias = await Link('${sandbox.path}/alias').create(target.path); + final path = '${alias.path}/summary.txt'; + + final result = await PathResolver(const LocalFileBackend()) + .resolve(_parse(path, root: '/', current: '/')); + expect(result.candidates.single.fullPath, path); + expect(result.candidates.single.matchKind, PathMatchKind.exactFile); + expect(result.nearestExistingDir, isNull); + }, skip: Platform.isWindows); + + test( + 'never descends into links under a confined root, including cache hits', + () async { + final backend = _Backend({ + _root: [const FileEntry(name: 'linked', kind: FileKind.link)], + '/fixtures/linked/sub': [_file('private.txt')], + }, symlinks: true); + final resolver = PathResolver( + backend, + directoryCache: { + '/fixtures/linked/sub': [_file('private.txt')], + }, + ); + final result = await resolver.resolve(_parse('linked/sub/private.txt')); + expect(result.nearestExistingDir, _root); + expect(result.candidates.single.matchKind, PathMatchKind.nearestDir); + expect(backend.checked, ['/fixtures/linked']); + expect(backend.listed, [_root]); + final direct = await resolver.resolve(_parse('linked')); + expect(direct.candidates.single.matchKind, PathMatchKind.nearestDir); + }, + ); test('enforces list, depth, and branch limits independently', () async { final backend = _Backend({