Extract a per-user background host so indexing can later run outside the window.

Keep the GUI as the index writer for now; mutex, named pipe, and opt-in logon autostart prepare Explorer.Host.exe without two SQLite writers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-24 17:10:49 +02:00
parent 9efb306979
commit 7c23bc2474
40 changed files with 1586 additions and 140 deletions

View File

@@ -0,0 +1,73 @@
using Explorer.Application;
using Explorer.Domain;
using Explorer.Windows;
namespace Explorer.Application.Tests;
public class RemovableAutoIndexPlannerTests
{
[Fact]
public void Does_nothing_when_disabled()
{
var sources = new[] { Removable(1, indexed: false) };
Assert.Empty(RemovableAutoIndexPlanner.SourceIdsToScan(sources, autoIndexRemovable: false));
}
[Fact]
public void Queues_online_unindexed_removable_only()
{
var sources = new[]
{
Removable(1, indexed: false),
Removable(2, indexed: true),
Removable(3, indexed: false, status: SourceStatus.Offline),
Cloud(4),
Local(5)
};
Assert.Equal(new[] { 1L }, RemovableAutoIndexPlanner.SourceIdsToScan(sources, autoIndexRemovable: true));
}
private static Source Removable(long id, bool indexed, SourceStatus status = SourceStatus.Online)
=> new()
{
Id = id,
StableKey = id.ToString(),
Kind = SourceKind.Removable,
DisplayName = "USB",
LastRootPath = @"E:\",
Status = status,
LastIndexedUtc = indexed ? DateTimeOffset.UtcNow : null
};
private static Source Cloud(long id)
=> new()
{
Id = id,
StableKey = "cloud",
Kind = SourceKind.Cloud,
DisplayName = "Cloud",
LastRootPath = @"C:\Users\me\OneDrive",
Status = SourceStatus.Online
};
private static Source Local(long id)
=> new()
{
Id = id,
StableKey = "local",
Kind = SourceKind.NtfsLocal,
DisplayName = "Local",
LastRootPath = @"C:\",
Status = SourceStatus.Online
};
}
public class ElevatedScanServiceTests
{
[Fact]
public void Never_requests_elevation()
{
IElevatedScanService service = new WindowsElevatedScanService();
Assert.False(service.CanRequestElevation);
}
}

View File

@@ -43,6 +43,18 @@ public class UiPreferencesStoreTests
Assert.Equal(@"C:\Program Files\Git\cmd\git.exe", prefs.GitPath);
}
[Fact]
public void Parse_reads_host_and_removable_index_flags()
{
var prefs = UiPreferencesStore.Parse(
[
"auto-index-removable=true",
"background-host-at-logon=true"
]);
Assert.True(prefs.AutoIndexRemovable);
Assert.True(prefs.BackgroundHostAtLogon);
}
[Fact]
public void Parse_defaults_missing_keys()
{
@@ -54,6 +66,8 @@ public class UiPreferencesStoreTests
Assert.True(prefs.ShowHiddenFiles);
Assert.False(prefs.ShowProtectedSystemLocations);
Assert.False(prefs.AutoClearQueueWhenDone);
Assert.False(prefs.AutoIndexRemovable);
Assert.False(prefs.BackgroundHostAtLogon);
Assert.Null(prefs.SevenZipPath);
Assert.Null(prefs.GitPath);
}
@@ -95,6 +109,8 @@ public class UiPreferencesStoreTests
Assert.True(loaded.ShowHiddenFiles);
Assert.False(loaded.ShowProtectedSystemLocations);
Assert.True(loaded.AutoClearQueueWhenDone);
Assert.False(loaded.AutoIndexRemovable);
Assert.False(loaded.BackgroundHostAtLogon);
Assert.Equal(1100, loaded.WindowWidth);
Assert.Equal(720, loaded.WindowHeight);
Assert.Equal(300, loaded.TreeWidth);

View File

@@ -0,0 +1,60 @@
using Explorer.Application;
using Explorer.Contracts;
using Explorer.Domain;
namespace Explorer.Application.Tests;
public class WorkbenchHostTests
{
[Fact]
public void Forwards_indexing_and_transfer_sessions()
{
var indexing = new FakeIndexing();
var transfers = new FakeTransfers();
IWorkbenchHost host = new WorkbenchHost(indexing, transfers);
Assert.Same(indexing, host.Indexing);
Assert.Same(transfers, host.Transfers);
host.Indexing.EnqueueFullScan(7);
host.Transfers.PauseAll();
Assert.Equal(7, indexing.FullScanId);
Assert.True(transfers.PausedAll);
}
private sealed class FakeIndexing : IIndexingHost
{
public long FullScanId { get; private set; }
public event EventHandler<ScanProgress>? ProgressChanged;
public void EnqueueFullScan(long sourceId) => FullScanId = sourceId;
public void EnqueueFolderScan(long sourceId, string pathRel) { }
public void EnqueueReconcile(long sourceId, string pathRel) { }
public void Cancel(long sourceId) { }
public void Raise() => ProgressChanged?.Invoke(this, new ScanProgress
{
SourceId = 1,
CurrentPath = "",
Status = ScanJobStatus.Running
});
}
private sealed class FakeTransfers : ITransferHost
{
public bool PausedAll { get; private set; }
public event EventHandler? Changed = delegate { };
public event EventHandler<TransferJob>? JobFinished = delegate { };
public bool IsPaused => PausedAll;
public IReadOnlyList<TransferJob> Snapshot() => [];
public void PauseAll() => PausedAll = true;
public void ResumeAll() => PausedAll = false;
public void Pause(long jobId) { }
public void Resume(long jobId) { }
public void Retry(long jobId) { }
public void Cancel(long jobId) { }
public void Dismiss(long jobId) { }
public void ClearFinished() { }
public bool MoveUp(long jobId) => false;
public bool MoveDown(long jobId) => false;
}
}

View File

@@ -0,0 +1,48 @@
using Explorer.Contracts;
using Explorer.Domain;
using Explorer.Domain.Abstractions;
using Explorer.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Explorer.Hosting.Tests;
public class CoreRegistrationTests
{
[Fact]
public async Task AddExplorerCore_registers_workbench_without_clipboard()
{
var dir = Path.Combine(Path.GetTempPath(), "ew-hosting", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton<IAppEnvironment>(new TempEnv(dir));
services.AddExplorerCore();
await using var sp = services.BuildServiceProvider();
Assert.NotNull(sp.GetService<IWorkbenchHost>());
Assert.NotNull(sp.GetService<IIndexingHost>());
Assert.NotNull(sp.GetService<ITransferHost>());
Assert.Null(sp.GetService<IOsClipboard>());
}
finally
{
try { Directory.Delete(dir, true); } catch { /* ignore */ }
}
}
private sealed class TempEnv : IAppEnvironment
{
public TempEnv(string dir)
{
DataDirectory = dir;
DatabasePath = Path.Combine(dir, "index.db");
LogDirectory = Path.Combine(dir, "logs");
Directory.CreateDirectory(LogDirectory);
}
public string DataDirectory { get; }
public string DatabasePath { get; }
public string LogDirectory { get; }
}
}

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Explorer.Application\Explorer.Application.csproj" />
<ProjectReference Include="..\..\src\Explorer.Contracts\Explorer.Contracts.csproj" />
<ProjectReference Include="..\..\src\Explorer.Domain\Explorer.Domain.csproj" />
<ProjectReference Include="..\..\src\Explorer.Hosting\Explorer.Hosting.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,19 @@
using Explorer.Hosting;
namespace Explorer.Hosting.Tests;
public class HostLogonAutostartTests
{
[Fact]
public void Create_args_are_per_user_logon_not_system_service()
{
var args = HostLogonAutostart.CreateTaskArgs(@"C:\Tools\Explorer.Host.exe");
Assert.Contains("/SC", args);
Assert.Contains("ONLOGON", args);
Assert.Contains("/RL", args);
Assert.Contains("LIMITED", args);
Assert.Contains(HostLogonAutostart.TaskName, args);
Assert.DoesNotContain("ONSTART", args);
Assert.DoesNotContain("/RU", args);
}
}

View File

@@ -0,0 +1,76 @@
using Explorer.Application;
using Explorer.Contracts;
using Explorer.Domain;
using Explorer.Hosting.Ipc;
using Microsoft.Extensions.Logging.Abstractions;
namespace Explorer.Hosting.Tests;
public class WorkbenchPipeTests
{
[Fact]
public void Handle_forwards_indexing_and_transfer_calls()
{
var indexing = new FakeIndexing();
var transfers = new FakeTransfers();
var server = new WorkbenchPipeServer(
new WorkbenchHost(indexing, transfers),
new WorkbenchIpcOptions { PipeName = "ew-test" },
NullLogger<WorkbenchPipeServer>.Instance);
var ping = server.Handle(new IpcEnvelope { V = WorkbenchIpc.ProtocolVersion, Op = "Ping" });
Assert.True(ping.Ok);
var scan = server.Handle(new IpcEnvelope { V = WorkbenchIpc.ProtocolVersion, Op = "Indexing.EnqueueFullScan", N = 42 });
Assert.True(scan.Ok);
Assert.Equal(42, indexing.FullScanId);
var pause = server.Handle(new IpcEnvelope { V = WorkbenchIpc.ProtocolVersion, Op = "Transfers.PauseAll" });
Assert.True(pause.Ok);
Assert.True(transfers.PausedAll);
var paused = server.Handle(new IpcEnvelope { V = WorkbenchIpc.ProtocolVersion, Op = "Transfers.IsPaused" });
Assert.True(paused.Paused);
}
[Fact]
public void Handle_rejects_other_protocol_versions()
{
var server = new WorkbenchPipeServer(
new WorkbenchHost(new FakeIndexing(), new FakeTransfers()),
new WorkbenchIpcOptions(),
NullLogger<WorkbenchPipeServer>.Instance);
var reply = server.Handle(new IpcEnvelope { V = 99, Op = "Ping" });
Assert.False(reply.Ok);
Assert.Contains("99", reply.Error);
}
private sealed class FakeIndexing : IIndexingHost
{
public long FullScanId { get; private set; }
public event EventHandler<ScanProgress>? ProgressChanged = delegate { };
public void EnqueueFullScan(long sourceId) => FullScanId = sourceId;
public void EnqueueFolderScan(long sourceId, string pathRel) { }
public void EnqueueReconcile(long sourceId, string pathRel) { }
public void Cancel(long sourceId) { }
}
private sealed class FakeTransfers : ITransferHost
{
public bool PausedAll { get; private set; }
public event EventHandler? Changed = delegate { };
public event EventHandler<TransferJob>? JobFinished = delegate { };
public bool IsPaused => PausedAll;
public IReadOnlyList<TransferJob> Snapshot() => [];
public void PauseAll() => PausedAll = true;
public void ResumeAll() => PausedAll = false;
public void Pause(long jobId) { }
public void Resume(long jobId) { }
public void Retry(long jobId) { }
public void Cancel(long jobId) { }
public void Dismiss(long jobId) { }
public void ClearFinished() { }
public bool MoveUp(long jobId) => false;
public bool MoveDown(long jobId) => false;
}
}

View File

@@ -427,3 +427,28 @@ public class FileRelationTests
Assert.Empty(await store.OperationProfiles.ListAsync());
}
}
public class IndexStoreLockTests
{
[Fact]
public async Task Second_writer_on_same_path_is_rejected()
{
var path = Path.Combine(Path.GetTempPath(), "ew-tests", Guid.NewGuid().ToString("N"), "index.db");
await using var first = new SqliteIndexStore(path, NullLogger<SqliteIndexStore>.Instance);
await first.OpenAsync();
var second = new SqliteIndexStore(path, NullLogger<SqliteIndexStore>.Instance);
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => second.OpenAsync());
Assert.Contains("already in use", ex.Message, StringComparison.OrdinalIgnoreCase);
await first.DisposeAsync();
await second.OpenAsync();
await second.DisposeAsync();
}
[Fact]
public void Mutex_name_is_stable_for_the_same_path()
{
var path = @"C:\Users\me\AppData\Local\ExplorerWorkbench\index.db";
Assert.Equal(IndexStoreLock.MutexNameFor(path), IndexStoreLock.MutexNameFor(path));
Assert.StartsWith(@"Local\ExplorerWorkbench-Index-", IndexStoreLock.MutexNameFor(path));
}
}