@@ -19,7 +19,8 @@ import 'dart:async';
1919import 'dart:convert' ;
2020import 'dart:typed_data' ;
2121
22- import 'package:flutter/foundation.dart' show ValueListenable, immutable;
22+ import 'package:flutter/foundation.dart'
23+ show ValueChanged, ValueListenable, immutable;
2324import 'package:flutter_riverpod/flutter_riverpod.dart' ;
2425
2526import 'package:pyble/app/providers.dart' ;
@@ -68,12 +69,136 @@ enum FileErrorKind {
6869 generic,
6970}
7071
72+ /// The terminal truth reported by one visible-file delete batch.
73+ enum FileDeleteBatchOutcome { complete, failed, partial }
74+
75+ /// Item-level progress emitted immediately before each delete attempt.
76+ @immutable
77+ class FileDeleteBatchProgress {
78+ const FileDeleteBatchProgress ({
79+ required this .completed,
80+ required this .total,
81+ required this .currentPath,
82+ });
83+
84+ /// The number of paths already deleted successfully.
85+ final int completed;
86+
87+ /// The number of unique selected paths in the displayed batch order.
88+ final int total;
89+
90+ /// The absolute board path about to be attempted.
91+ final String currentPath;
92+ }
93+
94+ /// The immutable, non-transactional result of one delete batch.
95+ @immutable
96+ class FileDeleteBatchResult {
97+ FileDeleteBatchResult ({
98+ required this .outcome,
99+ required List <String > succeededPaths,
100+ this .failedPath,
101+ required List <String > unattemptedPaths,
102+ this .failure,
103+ }) : succeededPaths = List <String >.unmodifiable (succeededPaths),
104+ unattemptedPaths = List <String >.unmodifiable (unattemptedPaths);
105+
106+ final FileDeleteBatchOutcome outcome;
107+ final List <String > succeededPaths;
108+ final String ? failedPath;
109+ final List <String > unattemptedPaths;
110+ final FileErrorKind ? failure;
111+ }
112+
113+ /// Whether [name] is one editable direct child of [cwd] in [fsRoot] .
114+ ///
115+ /// This pure predicate mirrors the case-sensitive PBLE/1 workspace jail for
116+ /// Files presentation and batch preflight. It additionally rejects malformed
117+ /// direct leaves and paths beyond PBLE/1's 128-byte UTF-8 wire ceiling.
118+ bool isEditableBoardEntry ({
119+ required String fsRoot,
120+ required String cwd,
121+ required String name,
122+ }) => _boardEntryEditFailure (fsRoot: fsRoot, cwd: cwd, name: name) == null ;
123+
124+ FileErrorKind ? _boardEntryEditFailure ({
125+ required String fsRoot,
126+ required String cwd,
127+ required String name,
128+ }) {
129+ if (! _isCanonicalAbsoluteDirectory (fsRoot) ||
130+ ! _isCanonicalAbsoluteDirectory (cwd) ||
131+ ! _isWithinBoardRoot (fsRoot: fsRoot, path: cwd) ||
132+ ! _isSafeDirectLeaf (name)) {
133+ return FileErrorKind .badRequest;
134+ }
135+
136+ final String path = cwd == '/' ? '/$name ' : '$cwd /$name ' ;
137+ if (utf8.encode (path).length > 128 ) return FileErrorKind .range;
138+
139+ final String relativeDirectory;
140+ if (cwd == fsRoot) {
141+ relativeDirectory = '' ;
142+ } else if (fsRoot == '/' ) {
143+ relativeDirectory = cwd.substring (1 );
144+ } else {
145+ relativeDirectory = cwd.substring (fsRoot.length + 1 );
146+ }
147+ final List <String > relativeComponents = < String > [
148+ if (relativeDirectory.isNotEmpty) ...relativeDirectory.split ('/' ),
149+ name,
150+ ];
151+ if (relativeComponents.any (
152+ (String component) => component.endsWith ('.pbltmp' ),
153+ )) {
154+ return FileErrorKind .permission;
155+ }
156+
157+ final String topLevel = relativeComponents.first;
158+ if (topLevel.startsWith ('pyble' ) ||
159+ topLevel.startsWith ('pble' ) ||
160+ topLevel == 'boot.py' ||
161+ topLevel == '_boot.py' ) {
162+ return FileErrorKind .permission;
163+ }
164+ return null ;
165+ }
166+
167+ bool _isCanonicalAbsoluteDirectory (String path) {
168+ if (path == '/' ) return true ;
169+ if (! path.startsWith ('/' ) || path.endsWith ('/' ) || path.contains (r'\' )) {
170+ return false ;
171+ }
172+ if (_hasControlCharacter (path)) return false ;
173+ return path
174+ .split ('/' )
175+ .skip (1 )
176+ .every (
177+ (String component) =>
178+ component.isNotEmpty && component != '.' && component != '..' ,
179+ );
180+ }
181+
182+ bool _isWithinBoardRoot ({required String fsRoot, required String path}) =>
183+ fsRoot == '/' || path == fsRoot || path.startsWith ('$fsRoot /' );
184+
185+ bool _isSafeDirectLeaf (String name) =>
186+ name.isNotEmpty &&
187+ name != '.' &&
188+ name != '..' &&
189+ ! name.contains ('/' ) &&
190+ ! name.contains (r'\' ) &&
191+ ! _hasControlCharacter (name);
192+
193+ bool _hasControlCharacter (String value) =>
194+ value.runes.any ((int rune) => rune < 0x20 || rune == 0x7f );
195+
71196/// The immutable snapshot the [FileExplorerController] publishes.
72197@immutable
73198class FileExplorerState {
74199 const FileExplorerState ({
75- required this .fsRoot,
76- required this .hasReportedFsRoot,
200+ this .fsRoot = '/' ,
201+ this .hasReportedFsRoot = false ,
77202 required this .cwd,
78203 required this .entries,
79204 required this .loading,
@@ -156,6 +281,10 @@ class FileExplorerController extends Notifier<FileExplorerState> {
156281 /// or a competing preview flow.
157282 bool _blocksDownloadInFlight = false ;
158283
284+ /// PBLE/1 has one serialized mutation stream; a second local delete batch is
285+ /// refused before it can send a board verb.
286+ bool _deleteBatchInFlight = false ;
287+
159288 @override
160289 FileExplorerState build () {
161290 // The Connection facade is STABLE (ADR-0009) — its identity never changes
@@ -386,6 +515,191 @@ class FileExplorerController extends Notifier<FileExplorerState> {
386515 }
387516 }
388517
518+ /// Deletes eligible shown regular files sequentially in displayed order.
519+ ///
520+ /// One invocation is bound to its captured folder and opaque connection
521+ /// session. It stops on the first failure or context replacement, never
522+ /// rolls back, and performs at most one same-session reconciliation listing.
523+ Future <FileDeleteBatchResult > deleteMany (
524+ Iterable <String > names, {
525+ String ? expectedCwd,
526+ Object ? expectedSessionStamp,
527+ ValueChanged <FileDeleteBatchProgress >? onProgress,
528+ }) async {
529+ final Connection connection = _conn;
530+ final Object capturedStamp = connectionSessionStampOf (connection);
531+ final String capturedCwd = state.cwd;
532+ final String capturedRoot = state.fsRoot;
533+ final List <RemoteEntry > displayed = List <RemoteEntry >.of (state.entries);
534+ final List <String > requestedNames = List <String >.of (names);
535+
536+ if (requestedNames.isEmpty) {
537+ return _preflightDeleteFailure (FileErrorKind .badRequest);
538+ }
539+
540+ final Set <String > selectedNames = < String > {};
541+ for (final String name in requestedNames) {
542+ if (! selectedNames.add (name)) {
543+ return _preflightDeleteFailure (FileErrorKind .badRequest);
544+ }
545+ }
546+
547+ final Map <String , RemoteEntry > displayedByName = < String , RemoteEntry > {
548+ for (final RemoteEntry entry in displayed) entry.name: entry,
549+ };
550+ for (final String name in selectedNames) {
551+ final FileErrorKind ? editFailure = _boardEntryEditFailure (
552+ fsRoot: capturedRoot,
553+ cwd: capturedCwd,
554+ name: name,
555+ );
556+ if (editFailure != null ) {
557+ return _preflightDeleteFailure (editFailure);
558+ }
559+ final RemoteEntry ? entry = displayedByName[name];
560+ if (entry == null || entry.isDir) {
561+ return _preflightDeleteFailure (FileErrorKind .badRequest);
562+ }
563+ }
564+
565+ final List <String > orderedPaths = < String > [
566+ for (final RemoteEntry entry in displayed)
567+ if (selectedNames.contains (entry.name)) _join (capturedCwd, entry.name),
568+ ];
569+ if (orderedPaths.length != selectedNames.length) {
570+ return _preflightDeleteFailure (FileErrorKind .badRequest);
571+ }
572+
573+ if (expectedCwd != null && expectedCwd != capturedCwd) {
574+ return _preflightDeleteFailure (FileErrorKind .badRequest);
575+ }
576+ if (expectedSessionStamp != null &&
577+ ! identical (expectedSessionStamp, capturedStamp)) {
578+ return _preflightDeleteFailure (
579+ FileErrorKind .notConnected,
580+ unattemptedPaths: orderedPaths,
581+ );
582+ }
583+ if (_deleteBatchInFlight) {
584+ return _preflightDeleteFailure (
585+ FileErrorKind .busy,
586+ unattemptedPaths: orderedPaths,
587+ );
588+ }
589+ _deleteBatchInFlight = true ;
590+
591+ try {
592+ FileErrorKind ? failure = _capturedContextFailure (
593+ connection: connection,
594+ stamp: capturedStamp,
595+ cwd: capturedCwd,
596+ );
597+ if (failure != null ) {
598+ return _preflightDeleteFailure (failure, unattemptedPaths: orderedPaths);
599+ }
600+
601+ state = state.copyWith (clearError: true );
602+ final List <String > succeeded = < String > [];
603+ String ? failedPath;
604+ int attempted = 0 ;
605+ int currentIndex = 0 ;
606+
607+ for (; currentIndex < orderedPaths.length; currentIndex += 1 ) {
608+ final String path = orderedPaths[currentIndex];
609+ failure = _capturedContextFailure (
610+ connection: connection,
611+ stamp: capturedStamp,
612+ cwd: capturedCwd,
613+ );
614+ if (failure != null ) {
615+ failedPath = path;
616+ break ;
617+ }
618+
619+ onProgress? .call (
620+ FileDeleteBatchProgress (
621+ completed: succeeded.length,
622+ total: orderedPaths.length,
623+ currentPath: path,
624+ ),
625+ );
626+ attempted += 1 ;
627+ try {
628+ await connection.delete (path);
629+ succeeded.add (path);
630+ } on PbleException catch (error) {
631+ failure = _kindOf (error);
632+ failedPath = path;
633+ break ;
634+ }
635+ }
636+
637+ PbleException ? reconciliationError;
638+ List <RemoteEntry >? reconciledEntries;
639+ if (attempted > 0 &&
640+ _isCapturedSessionCurrent (
641+ connection: connection,
642+ stamp: capturedStamp,
643+ )) {
644+ try {
645+ reconciledEntries = await connection.listDir (capturedCwd);
646+ reconciledEntries.sort (_entryOrder);
647+ } on PbleException catch (error) {
648+ reconciliationError = error;
649+ }
650+ }
651+
652+ final bool sameSession = _isCapturedSessionCurrent (
653+ connection: connection,
654+ stamp: capturedStamp,
655+ );
656+ if (sameSession) {
657+ FileExplorerState next = state;
658+ if (reconciledEntries != null && state.cwd == capturedCwd) {
659+ next = next.copyWith (entries: reconciledEntries, loading: false );
660+ }
661+ if (failure != null && failedPath != null ) {
662+ next = next.copyWith (
663+ clearProgress: true ,
664+ error: failure,
665+ errorPath: failedPath,
666+ );
667+ } else if (reconciliationError != null ) {
668+ next = next.copyWith (
669+ clearProgress: true ,
670+ error: _kindOf (reconciliationError),
671+ errorPath: capturedCwd,
672+ );
673+ } else {
674+ next = next.copyWith (clearProgress: true , clearError: true );
675+ }
676+ state = next;
677+ }
678+
679+ if (failure == null ) {
680+ return FileDeleteBatchResult (
681+ outcome: FileDeleteBatchOutcome .complete,
682+ succeededPaths: succeeded,
683+ unattemptedPaths: const < String > [],
684+ );
685+ }
686+
687+ return FileDeleteBatchResult (
688+ outcome: succeeded.isEmpty
689+ ? FileDeleteBatchOutcome .failed
690+ : FileDeleteBatchOutcome .partial,
691+ succeededPaths: succeeded,
692+ failedPath: failedPath,
693+ unattemptedPaths: failedPath == null
694+ ? orderedPaths.sublist (currentIndex)
695+ : orderedPaths.sublist (currentIndex + 1 ),
696+ failure: failure,
697+ );
698+ } finally {
699+ _deleteBatchInFlight = false ;
700+ }
701+ }
702+
389703 /// Renames the entry [from] to [to] , both within the current directory.
390704 Future <void > rename (String from, String to) async {
391705 final String src = _join (state.cwd, from);
@@ -400,6 +714,36 @@ class FileExplorerController extends Notifier<FileExplorerState> {
400714
401715 // --- helpers ---------------------------------------------------------------
402716
717+ FileDeleteBatchResult _preflightDeleteFailure (
718+ FileErrorKind failure, {
719+ List <String > unattemptedPaths = const < String > [],
720+ }) => FileDeleteBatchResult (
721+ outcome: FileDeleteBatchOutcome .failed,
722+ succeededPaths: const < String > [],
723+ unattemptedPaths: unattemptedPaths,
724+ failure: failure,
725+ );
726+
727+ FileErrorKind ? _capturedContextFailure ({
728+ required Connection connection,
729+ required Object stamp,
730+ required String cwd,
731+ }) {
732+ if (! _isCapturedSessionCurrent (connection: connection, stamp: stamp)) {
733+ return FileErrorKind .notConnected;
734+ }
735+ return state.cwd == cwd ? null : FileErrorKind .badRequest;
736+ }
737+
738+ bool _isCapturedSessionCurrent ({
739+ required Connection connection,
740+ required Object stamp,
741+ }) {
742+ final Connection current = _conn;
743+ return identical (current, connection) &&
744+ identical (connectionSessionStampOf (current), stamp);
745+ }
746+
403747 /// Wall-clock for the transfer in flight; restarted per transfer.
404748 Stopwatch ? _txClock;
405749 int _lastSent = 0 ;
0 commit comments