From 0f0d048b04a93debed469e49c90aad3e36943573 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Mon, 12 Oct 2026 15:44:08 +0300 Subject: [PATCH 1/2] Guard against invalid-item dialog for placeholder items Co-Authored-By: Codex Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../investigations/invalid-item-dialog.md | 52 +++++++++++++++++++ .../FileSystem/OpenFileLocationAction.cs | 10 ++-- .../Helpers/Navigation/NavigationItemGuard.cs | 47 +++++++++++++++++ .../NavigationToolbarViewModel.cs | 10 ++-- src/Files.App/Views/Layouts/BaseLayoutPage.cs | 8 ++- 5 files changed, 115 insertions(+), 12 deletions(-) create mode 100644 docs/linux-port/investigations/invalid-item-dialog.md create mode 100644 src/Files.App/Helpers/Navigation/NavigationItemGuard.cs diff --git a/docs/linux-port/investigations/invalid-item-dialog.md b/docs/linux-port/investigations/invalid-item-dialog.md new file mode 100644 index 000000000000..10100a9e055c --- /dev/null +++ b/docs/linux-port/investigations/invalid-item-dialog.md @@ -0,0 +1,52 @@ +# Invalid item dialog after session restore + +## Status + +Investigated by source inspection; the reported first-right-click failure was not reproduced. The fix is defensive. A loading/state race is plausible, but there is no proven right-click-to-dialog chain. Uno desktop build and UI execution were unavailable in this sandbox. + +## Text and all producers + +`Strings/en-US/Resources.resw` defines `InvalidItemDialogTitle` as “Invalid item” and `InvalidItemDialogContent` as “The item referenced is either invalid or inaccessible.{0}Error message:{0}{1}”. Other locales have the same resource keys. `{0}` is a newline and `{1}` is `FileSystemStatusCode.ToString()`, hence “Generic”. This is separate from the invalid-item-name rename resource. + +Repository-wide searches for `Invalid item`, `InvalidItemDialog`, `ShowInvalidItem`, and `DynamicDialog` found these four original dialog call sites (now routed through `NavigationItemGuard.ShowInvalidItemAsync`): + +| Producer | Conditions | +| --- | --- | +| `NavigationToolbarViewModel.HandleItemNavigationAsync` | Omnibar path submission fails folder lookup/access check, file lookup, command launch, and URI launch (false or URI/argument exception). Displays the **folder** lookup error, not the final launcher error. | +| `NavigationToolbarViewModel.CheckPathInputAsync`, URI-false branch | Legacy toolbar query submission follows the same lookup/command fallbacks, then URI launch returns false. | +| `NavigationToolbarViewModel.CheckPathInputAsync`, exception branch | Same legacy path, but URI parsing/launch throws `UriFormatException` or `ArgumentException`. | +| `OpenFileLocationAction.ExecuteAsync` | Selected shortcut has a nonblank target, but its containing-folder lookup fails with an error other than `NotFound`. A null containing directory explicitly creates a `Generic` result. `NotFound` uses a different dialog; blank targets return silently. | + +`DialogDisplayHelper.ShowDialogAsync(title, message)` constructs a `DynamicDialog` / `DynamicDialogViewModel` and awaits `ShowAsync`. `DynamicDialogFactory` has no additional producer of this particular dialog. No pre-existing `ShowInvalidItem` method was found. + +`FilesystemTasks.GetErrorCode` maps otherwise unclassified exceptions to `Generic`. In the Linux legacy storage bridge (`StorageFileExtensions.Linux.cs`), resolver statuses outside the explicitly supported success/not-found/unauthorized/type-mismatch cases throw `NotSupportedException`, which becomes `Generic`. The label alone does not identify a race or a missing file. + +## Restore, incomplete items, and right-click + +- `MainPageViewModel.RestoreSessionTabsAsync` deserializes saved `TabBarItemParameter` values, opens the previously selected tab first, adds other tabs without selecting them, and then restores tab ordering. Parameters may be a string, pane arguments, or null. This path calls `NavigationHelpers.AddNewTabByParamAsync`, not either toolbar path validator. +- Saved missing/inaccessible locations pass through shell enumeration and its location-unavailable UI (`ShowLocationInaccessibleOrMissing` / `ShowLocationUnavailable`), not this dialog. A later explicit toolbar submission of a bad saved location can reach the toolbar producers above. +- Toolbar validators already ignore empty/whitespace normalized input and an unchanged path. Empty path text therefore does **not** independently prove this dialog's origin. They perform several awaits; the modern validator re-reads `ContentPageContext.ShellPage` after lookups, so failure completion can outlive the original pane context. +- `ListedItem.ItemPath` and `ItemNameRaw` are nullable. Linux enumeration normally assigns both before publishing items; icon/metadata completion can legitimately happen later. `ItemPropertiesInitialized` is not a reliable test for identity readiness and is deliberately not used by the guard. The local filesystem root name already falls back to its path. +- `BaseLayoutPage.FileListItem_RightTapped` selects an item. Item flyout opening can also select the flyout target as a workaround, then uses the selection to build commands. Background flyout opening uses `CurrentFolder`. Neither handler directly emits “Invalid item”. Previously there was no identity/loading guard, and a missing `CurrentFolder` threw an exception. +- `EnsurePageIsCurrentAsync` waits up to 500 ms for pane activation and then another 10 ms; it does not wait for folder enumeration. `ShellViewModel.IsLoadingItems` is set around enumeration, and the focused restored tab is intentionally available while other tabs load. This gives a real window for interaction with loading/stale folder state. +- Omnibar `LostFocus` only updates focus state. Query submission occurs on Enter or suggestion click; ordinary right-click focus loss does not submit a path. “Open file location” requires command execution, not merely menu opening. + +The most plausible race candidate is interaction during restored-pane activation/enumeration, with menu work or an earlier asynchronous navigation failure completing against changing context. The direct evidence supports that timing window, **not** a confirmed causal connection to the exact dialog. An already pending toolbar failure becoming visible on first interaction remains possible. Blank shortcut identity/target data and unsupported legacy lookup results are alternate candidates. + +## Guarded change + +`NavigationItemGuard` checks that the source shell exists, is the current instance/pane, and is not loading. Its item overload additionally requires a nonempty `ItemPath` and `ItemNameRaw`; it accepts whitespace names (legal Linux filenames) and does not wait for icons or metadata. + +Item and background context menus stop before command construction when their inputs are loading/incomplete. A missing current folder is ignored rather than thrown. Open-file-location checks identity before lookup and retains the source item/shell across the await. All four invalid-item producers now check source-shell readiness immediately before displaying; the modern toolbar validator captures its original shell rather than using the later replacement context for this check. Valid, ready-pane failures retain their existing localized dialog/error code. + +Existing `PerformanceTrace` supplies opt-in `FILES_TRACE=1` logging. `operation=navigation-item-guard` has outcomes `no-shell`, `inactive-pane`, `loading`, or `placeholder`; `operation=invalid-item-dialog` records the error code for failures that reach display. No paths, filenames, session data, or typed input are logged. Menus are not automatically reopened; retry after loading completes. This does not cancel existing lookups or establish a navigation-generation token, so a transition that finishes before the final check can still require investigation. + +## Verification and follow-up + +- Reference searches covered all resource producers and callers, session restoration, Omnibar submission/focus, Linux enumeration, and item/background context menus. +- `git diff --check` passed; existing modified-file BOM/newline conventions were preserved. +- Single-node platform build initially failed because sandbox networking blocked NuGet vulnerability feeds (`NU1900`). Retried with invocation-only `-p:NuGetAudit=false`; build passed with zero warnings/errors. No project/dependency configuration changed. +- The standard single-node `dotnet test --project ... --no-build` command could not start its test host: named-pipe/socket creation was denied by the sandbox. Direct test-assembly execution (`dotnet tests/Files.Platform.Tests/bin/Debug/net10.0/Files.Platform.Tests.dll --no-ansi --progress off --output Minimal`) ran 1,262 tests: 1,208 passed, 41 skipped, 13 failed. Failures included denied X11/DBus/socket binding, bubblewrap sandbox setup, and three trusted-native-directory assertions; the latter were not diagnosed in this UI-focused task. This is not a clean full-suite pass. +- The platform project does not compile the changed Uno UI files. Desktop compilation and runtime behavior remain unverified. + +On a capable machine, use `FILES_TRACE=1 scripts/linux/headless-run.sh` with the script's private display/throwaway home. Restore multiple tabs and immediately right-click both background and an item; retry after enumeration, switch panes during pending navigation, submit a genuinely invalid path once ready, and execute Open file location for invalid shortcuts. Check for suppression records during loading and error-code records only for ready-pane failures. Include root, archive, trash, and a whitespace-only filename to check identity handling. Do not collect real session paths in trace logs. diff --git a/src/Files.App/Actions/FileSystem/OpenFileLocationAction.cs b/src/Files.App/Actions/FileSystem/OpenFileLocationAction.cs index b243679958f8..ee55dc71e943 100644 --- a/src/Files.App/Actions/FileSystem/OpenFileLocationAction.cs +++ b/src/Files.App/Actions/FileSystem/OpenFileLocationAction.cs @@ -36,10 +36,13 @@ public OpenFileLocationAction() public async Task ExecuteAsync(object? parameter = null) { - if (context.ShellPage?.ShellViewModel is not { } shellViewModel) + var sourceShellPage = context.ShellPage; + var sourceItem = context.SelectedItem; + if (NavigationItemGuard.ShouldSuppress(sourceShellPage, sourceItem) || + sourceShellPage?.ShellViewModel is not { } shellViewModel) return; - var item = context.SelectedItem as IShortcutItem; + var item = sourceItem as IShortcutItem; if (string.IsNullOrWhiteSpace(item?.TargetPath)) return; @@ -68,8 +71,7 @@ public async Task ExecuteAsync(object? parameter = null) } else { - await DialogDisplayHelper.ShowDialogAsync(Strings.InvalidItemDialogTitle.GetLocalizedResource(), - string.Format(Strings.InvalidItemDialogContent.GetLocalizedResource(), Environment.NewLine, destFolder.ErrorCode.ToString())); + await NavigationItemGuard.ShowInvalidItemAsync(sourceShellPage, destFolder.ErrorCode, sourceItem); } } diff --git a/src/Files.App/Helpers/Navigation/NavigationItemGuard.cs b/src/Files.App/Helpers/Navigation/NavigationItemGuard.cs new file mode 100644 index 000000000000..e179e3979593 --- /dev/null +++ b/src/Files.App/Helpers/Navigation/NavigationItemGuard.cs @@ -0,0 +1,47 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Abstractions.Diagnostics; + +namespace Files.App.Helpers +{ + internal static class NavigationItemGuard + { + public static bool ShouldSuppress(IShellPage? shellPage) + { + var reason = shellPage?.ShellViewModel is not { } viewModel ? "no-shell" + : !shellPage.IsCurrentInstance || !shellPage.IsCurrentPane ? "inactive-pane" + : viewModel.IsLoadingItems ? "loading" : null; + return TraceSuppression(reason); + } + + public static bool ShouldSuppress(IShellPage? shellPage, ListedItem? item) + { + if (ShouldSuppress(shellPage)) + return true; + + // Icon/metadata initialization can lag behind a usable item; only identity is required. + return TraceSuppression(item is null || string.IsNullOrEmpty(item.ItemPath) || + string.IsNullOrEmpty(item.ItemNameRaw) ? "placeholder" : null); + } + + private static bool TraceSuppression(string? reason) + { + if (reason is null) + return false; + + PerformanceTrace.Begin("navigation-item-guard").Complete(reason); + return true; + } + + public static async Task ShowInvalidItemAsync(IShellPage? shellPage, FileSystemStatusCode errorCode, ListedItem? item = null) + { + if (item is null ? ShouldSuppress(shellPage) : ShouldSuppress(shellPage, item)) + return; + + PerformanceTrace.Begin("invalid-item-dialog").Complete(errorCode.ToString()); + await DialogDisplayHelper.ShowDialogAsync(Strings.InvalidItemDialogTitle.GetLocalizedResource(), + string.Format(Strings.InvalidItemDialogContent.GetLocalizedResource(), Environment.NewLine, errorCode.ToString())); + } + } +} diff --git a/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs b/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs index 8d719bf9e456..0ad34d388353 100644 --- a/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs @@ -600,6 +600,7 @@ public async Task HandleItemNavigationAsync(string path) var shellViewModel = shellPage.ShellViewModel ?? throw new InvalidOperationException("The current shell page does not have a view model."); + var sourceShellPage = shellPage; var currentPath = PathComponents.LastOrDefault()?.Path; var isFtp = FtpHelpers.IsFtpPath(path); var normalizedInput = NormalizePathInput(path, isFtp); @@ -704,8 +705,7 @@ public async Task HandleItemNavigationAsync(string path) if (!isValid) { - await DialogDisplayHelper.ShowDialogAsync(Strings.InvalidItemDialogTitle.GetLocalizedResource(), - string.Format(Strings.InvalidItemDialogContent.GetLocalizedResource(), Environment.NewLine, resFolder.ErrorCode.ToString())); + await NavigationItemGuard.ShowInvalidItemAsync(sourceShellPage, resFolder.ErrorCode); return false; } } @@ -1007,13 +1007,11 @@ await DialogDisplayHelper.ShowDialogAsync(Strings.CommandNotExecutable.GetLocali try { if (!await Windows.System.Launcher.LaunchUriAsync(new Uri(currentInput))) - await DialogDisplayHelper.ShowDialogAsync(Strings.InvalidItemDialogTitle.GetLocalizedResource(), - string.Format(Strings.InvalidItemDialogContent.GetLocalizedResource(), Environment.NewLine, resFolder.ErrorCode.ToString())); + await NavigationItemGuard.ShowInvalidItemAsync(shellPage, resFolder.ErrorCode); } catch (Exception ex) when (ex is UriFormatException || ex is ArgumentException) { - await DialogDisplayHelper.ShowDialogAsync(Strings.InvalidItemDialogTitle.GetLocalizedResource(), - string.Format(Strings.InvalidItemDialogContent.GetLocalizedResource(), Environment.NewLine, resFolder.ErrorCode.ToString())); + await NavigationItemGuard.ShowInvalidItemAsync(shellPage, resFolder.ErrorCode); } } } diff --git a/src/Files.App/Views/Layouts/BaseLayoutPage.cs b/src/Files.App/Views/Layouts/BaseLayoutPage.cs index 98c568da515b..837ab373a245 100644 --- a/src/Files.App/Views/Layouts/BaseLayoutPage.cs +++ b/src/Files.App/Views/Layouts/BaseLayoutPage.cs @@ -759,6 +759,9 @@ private async void ItemContextFlyout_Opening(object? sender, object e) if (selectedItems is null or { Count: 0 }) return; + if (selectedItems.Any(item => NavigationItemGuard.ShouldSuppress(parentShellPage, item))) + return; + shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); SelectedItemsPropertiesViewModel.CheckAllFileExtensions(selectedItems.Select(x => x.FileExtension).ToList()); @@ -1038,8 +1041,9 @@ private async void BaseContextFlyout_Opening(object? sender, object e) ItemManipulationModel.ClearSelection(); shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); - var currentFolder = shellViewModel.CurrentFolder - ?? throw new InvalidOperationException("The current folder is not available."); + var currentFolder = shellViewModel.CurrentFolder; + if (NavigationItemGuard.ShouldSuppress(parentShellPage, currentFolder) || currentFolder is null) + return; List contextItems = [currentFolder]; token = RenewShellMenuToken(); var buildVersion = contextMenuVersion; From c1a378b8607863690a374a20541e69c481173fd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Mon, 12 Oct 2026 18:27:53 +0300 Subject: [PATCH 2/2] Address review findings Co-Authored-By: Codex Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../Helpers/MenuFlyout/FastContextFlyout.cs | 19 +++++++++++++++++++ src/Files.App/Views/Layouts/BaseLayoutPage.cs | 16 ++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs b/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs index 6bd26e752999..44107c1cf15d 100644 --- a/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs +++ b/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs @@ -61,11 +61,14 @@ public FastContextFlyout() Flyout.Closed += Flyout_Closed; } + private bool openingSuppressed; + /// /// Clears the menu and the per-open placement state. Call at the start of each invocation. /// public void Reset() { + openingSuppressed = false; invocationScreenY = double.NaN; preserveOpenPlacement = false; Flyout.Items.Clear(); @@ -78,6 +81,16 @@ public void Reset() invocationPosition = null; } + /// + /// Clears retained commands and closes even if Opening fires before the popup becomes visible. + /// + public void SuppressOpening() + { + Reset(); + openingSuppressed = true; + Hide(); + } + /// /// Builds the given models into the menu: the primary commands as an icon-button row on top, the rest as /// regular menu items. The overflow placeholder models ("ItemOverflow"/"OverflowSeparator") are markers @@ -524,6 +537,12 @@ public void CorrectRebuiltPlacement() [DynamicWindowsRuntimeCast(typeof(FrameworkElement))] private void Flyout_Opened(object? sender, object e) { + if (openingSuppressed) + { + Hide(); + return; + } + try { if (Flyout.XamlRoot is null) diff --git a/src/Files.App/Views/Layouts/BaseLayoutPage.cs b/src/Files.App/Views/Layouts/BaseLayoutPage.cs index 837ab373a245..6bd0f8d0346b 100644 --- a/src/Files.App/Views/Layouts/BaseLayoutPage.cs +++ b/src/Files.App/Views/Layouts/BaseLayoutPage.cs @@ -739,6 +739,7 @@ private async void ItemContextFlyout_Opening(object? sender, object e) { using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-build", DispatcherQueue.HasThreadAccess); var token = RenewShellMenuToken(); + ItemContextFlyoutHost.Reset(); try { var parentShellPage = await EnsurePageIsCurrentAsync(); @@ -753,21 +754,29 @@ private async void ItemContextFlyout_Opening(object? sender, object e) ItemManipulationModel.SetSelectedItem(li); if (!IsItemSelected) + { + ItemContextFlyoutHost.SuppressOpening(); return; + } var selectedItems = SelectedItems?.ToList(); if (selectedItems is null or { Count: 0 }) + { + ItemContextFlyoutHost.SuppressOpening(); return; + } if (selectedItems.Any(item => NavigationItemGuard.ShouldSuppress(parentShellPage, item))) + { + ItemContextFlyoutHost.SuppressOpening(); return; + } shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); SelectedItemsPropertiesViewModel.CheckAllFileExtensions(selectedItems.Select(x => x.FileExtension).ToList()); token = RenewShellMenuToken(); var buildVersion = contextMenuVersion; - ItemContextFlyoutHost.Reset(); ItemContextFlyoutHost.Items.Add(new MenuFlyoutItem { Text = Strings.Loading.GetLocalizedResource(), IsEnabled = false }); var items = await ContentPageContextFlyoutFactory.GetItemContextCommandsWithoutShellItemsAsync(currentInstanceViewModel: instanceViewModel, selectedItems: selectedItems, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: commandsViewModel, shiftPressed: shiftPressed, itemViewModel: null, cancellationToken: token); token.ThrowIfCancellationRequested(); @@ -1030,6 +1039,7 @@ private async void BaseContextFlyout_Opening(object? sender, object e) { using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-build", DispatcherQueue.HasThreadAccess); var token = RenewShellMenuToken(); + BaseContextFlyoutHost.Reset(); try { var parentShellPage = await EnsurePageIsCurrentAsync(); @@ -1043,11 +1053,13 @@ private async void BaseContextFlyout_Opening(object? sender, object e) shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); var currentFolder = shellViewModel.CurrentFolder; if (NavigationItemGuard.ShouldSuppress(parentShellPage, currentFolder) || currentFolder is null) + { + BaseContextFlyoutHost.SuppressOpening(); return; + } List contextItems = [currentFolder]; token = RenewShellMenuToken(); var buildVersion = contextMenuVersion; - BaseContextFlyoutHost.Reset(); BaseContextFlyoutHost.Items.Add(new MenuFlyoutItem { Text = Strings.Loading.GetLocalizedResource(), IsEnabled = false }); var items = await ContentPageContextFlyoutFactory.GetItemContextCommandsWithoutShellItemsAsync(currentInstanceViewModel: instanceViewModel, selectedItems: contextItems, commandsViewModel: commandsViewModel, shiftPressed: shiftPressed, itemViewModel: shellViewModel, selectedItemsPropertiesViewModel: null, cancellationToken: token); token.ThrowIfCancellationRequested();