Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

refactor: improve resource disposal, caching, and exception handling. also update proj to 2.22.4

fatDuckb4a6cb93bd72
diff --git a/.windsurf/workflows/generatechangelog.md b/.devin/workflows/generatechangelog.md
similarity index 100%
rename from .windsurf/workflows/generatechangelog.md
rename to .devin/workflows/generatechangelog.md
diff --git a/.kilocode/rules/rtk-rules.md b/.kilocode/rules/rtk-rules.md
new file mode 100644
index 0000000..53d7645
--- /dev/null
+++ b/.kilocode/rules/rtk-rules.md
@@ -0,0 +1,32 @@
+# RTK - Rust Token Killer (Kilo Code)
+
+**Usage**: Token-optimized CLI proxy for shell commands.
+
+## Rule
+
+Always prefix shell commands with `rtk` to minimize token consumption.
+
+Examples:
+
+```bash
+rtk git status
+rtk cargo test
+rtk ls src/
+rtk grep "pattern" src/
+rtk find "*.rs" .
+rtk docker ps
+rtk gh pr list
+```
+
+## Meta Commands
+
+```bash
+rtk gain # Show token savings
+rtk gain --history # Command history with savings
+rtk discover # Find missed RTK opportunities
+rtk proxy <cmd> # Run raw (no filtering, for debugging)
+```
+
+## Why
+
+RTK filters and compresses command output before it reaches the LLM context, saving 60-90% tokens on common operations. Always use `rtk <cmd>` instead of raw commands.
diff --git a/AGENTS.md b/AGENTS.md
index 17704e4..06474d1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,34 +2,44 @@
## Windows-Only WPF App
- **Windows-only**: Build/run/test only on Windows. Target framework: `net10.0-windows10.0.17763.0` with `UseWPF=true`. `CA1416` (platform compatibility) is silenced — all code is Windows-only.
-- **Runs as admin**: `app.manifest` sets `requireAdministrator` UAC level.
+- **Runs as admin**: `app.manifest` sets `requireAdministrator` UAC level. Tests that modify system settings or registry need admin too.
- **Solution format**: `.slnx` (not `.sln`).
+- **Data directory**: `%LocalAppData%\optimizerDuck\` — holds revert files, resources, downloads, assets.
## Build, Test, Run Commands
- `dotnet restore optimizerDuck.slnx` — restore dependencies.
- `dotnet build optimizerDuck.slnx --configuration Release --no-restore` — CI-aligned build.
- `dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj --configuration Release --no-build` — run all tests.
+- `dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj --configuration Release --no-build --filter "FullyQualifiedName~TestName"` — run a single test.
- `dotnet run --project optimizerDuck/optimizerDuck.csproj` — run locally.
- `publish.bat portable` or `publish.bat single --skip-tests` — create release artifacts.
## Project Structure
-- `optimizerDuck/` — WPF app:
+- `optimizerDuck/` — WPF app (single project, no sub-projects):
- `Domain/` — models, interfaces, attributes (no UI deps)
- - `Services/` — business logic: `Configuration/`, `Customize/`, `Optimization/`, `Revert/`, `System/`
+ - `Services/` — business logic: `Configuration/`, `Customize/`, `Optimization/`, `Revert/`, `System/`, `UI/`
- `UI/` — XAML pages, ViewModels, windows, controls, dialogs, styles
- `Common/` — extensions, helpers, converters
- `Resources/` — images, embedded assets, localization (`Resources/Languages/Translations.resx`)
-- `optimizerDuck.Test/` — xUnit v3 tests
-
-## Optimization & Feature Discovery (Reflection, No Manual Registration)
-- **New optimizations**: Create a **nested class** inside the relevant category class (e.g., `Domain/Optimizations/Categories/Performance.cs`), extend `BaseOptimization`, and decorate with `[Optimization(Id = "guid", Risk = ..., Tags = ...)]`.
-- **New customize settings**: Same nesting pattern inside `Domain/Customize/Categories/`, extend `BaseCustomizeSetting`, decorate with `[CustomizeSetting(Section = ..., Icon = ..., Recommendation = ...)]`.
-- **Category classes**: Must be decorated with `[OptimizationCategory(PageType = typeof(...))]` or `[FeatureCategory(PageType = typeof(...))]`.
-- **Discovery**: `ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` scans all `optimizerDuck.*` assemblies — no DI registration array to update.
+- `optimizerDuck.Test/` — xUnit v3 tests (single test project)
+- Do **not** create top-level directories outside these two project folders.
+
+## Key NuGet Packages
+- `CommunityToolkit.Mvvm` 8.x — MVVM source generators (`[ObservableProperty]`, `[RelayCommand]`)
+- `WPF-UI` + `WPF-UI.DependencyInjection` 4.x — Fluent Design controls + navigation
+- `Microsoft.Extensions.Hosting` 10.x — DI / hosted service wiring
+- `xunit.v3` 3.x — test framework (with global using `Xunit` in test csproj)
+
+## Optimization & Customize Discovery (Reflection, No Manual Registration)
+- **New optimizations**: Create a **nested class** inside the relevant category class (e.g., `Domain/Optimizations/Categories/Performance.cs`), extend `BaseOptimization`, decorate with `[Optimization(Id = "guid", Risk = ..., Tags = ...)]`.
+- **New customize settings**: Same nesting pattern inside `Domain/Customize/Categories/`, extend `BaseCustomizeSetting`, decorate with `[CustomizeSetting(Section = ..., Icon = ..., Recommendation = ...)]`. `Icon` is required (`SymbolRegular` enum). `Section` can be a string or enum value.
+- **Category classes**: Decorate with `[OptimizationCategory(typeof(PageClass))]` or `[CustomizeCategory(PageType = typeof(PageClass))]`.
+- **Discovery**: `ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()` scans assemblies whose name starts with `optimizerDuck` — no DI registration array to update.
- **Static provider services**: `RegistryService`, `ServiceProcessService`, `ScheduledTaskService`, `ShellService` are **static classes** (not DI-registered). They capture revert steps into the ambient `ExecutionScope`.
+- **`CompleteFromScope()`**: Optimizations call `BaseOptimization.CompleteFromScope()` to build the `ApplyResult` from steps recorded in the ambient `ExecutionScope`. Do not manually construct `ApplyResult`.
## Revert System
-- **File-based**: Each applied optimization creates `Shared.RevertDirectory/{optimizationId}.json`. Applied state is inferred from file presence on disk.
+- **File-based**: Each applied optimization creates `%LocalAppData%\optimizerDuck\Revert\{optimizationId}.json`. Applied state is inferred from file presence on disk.
- **Atomic writes**: `RevertManager` writes to `.tmp` then `File.Replace` for crash safety.
- **Step types**: `RegistryRevertStep`, `ServiceRevertStep`, `ScheduledTaskRevertStep`, `ShellRevertStep`, `UsbPowerRevertStep`.
- **`ExecutionScope`**: Uses `AsyncLocal<ExecutionScope?>` for ambient step tracking — no need to pass context through parameters.
@@ -37,195 +47,37 @@
## Coding & Style
- Nullable enabled, file-scoped namespaces, implicit usings.
- Indent: 4 spaces. PascalCase types/members, `_camelCase` private fields, `camelCase` locals/params.
-- **No hardcoded strings** — use `Translations.resx` keys. Access via `Loc.Instance["Key"]` or `Translations.KeyName`.
+- Max line length: 100 characters (enforced by `.editorconfig`).
+- **No hardcoded UI strings** — use `Loc.Instance["Key"]` (C#) or `Translations.KeyName` (XAML bindings). Add new keys to `Resources/Languages/Translations.resx`.
- **Keep comments sparse** — existing code has none; do not add them.
- DI via `Microsoft.Extensions.Hosting` + `CommunityToolkit.Mvvm`. Pages + ViewModels registered as singletons.
-- Prefer `dotnet_diagnostic.CA1416.severity = silent` in `.editorconfig` (already set). Do not add `SupportedOSPlatform` guards.
+- `optimizerDuck.csproj` has `<InternalsVisibleTo Include="optimizerDuck.Test" />` — test project can access internal members.
## Testing (xUnit v3, Integration-Style)
- **No mocking libraries** — all test doubles are hand-written (`FakeOptimization`, `TestOptimization`, etc.) implementing interfaces directly.
- **Real I/O**: Tests use real filesystem (revert JSON files), real registry (`HKCU\Software\TestOptimizerDuck*`), real process execution (CMD/PowerShell).
-- **STA thread**: Tests involving `ContentDialogService` or WPF components must use `RunInStaThreadAsync` helper (STA thread + `TaskCompletionSource`).
+- **STA thread**: Tests involving WPF components must use `RunInStaThreadAsync` helper (STA thread + `TaskCompletionSource`). The test project itself defines this helper — add it if missing.
- **Logging**: Use `NullLogger<T>.Instance` / `NullLoggerFactory.Instance` for DI logging parameters.
- **Test naming**: `{Method}_{Scenario}_{ExpectedResult}` (e.g., `ApplyAsync_Success_PersistsRevertDataFile`).
- **Cleanup**: Use `try/finally` or `IDisposable` for test artifact cleanup (revert files, registry keys).
-- **Coverage**: No coverage gate enforced — prioritize meaningful unit coverage for changed logic.
+- **No coverage gate** — prioritize meaningful unit coverage for changed logic.
+- **CI test command** uses `--blame-hang --blame-hang-timeout 30s` — tests must not hang longer than 30s.
## Commit & PR
- Conventional Commits: `feat:`, `fix:`, `refactor:`, `docs:`, `test:`, `i18n:`, `chore:`.
- Branch from `master`: `feature/<name>` or `fix/<issue-id>`.
-- PRs: clear description, linked issue (`Closes #123`), passing `dotnet build` + `dotnet test`, screenshot for UI changes.
+- PRs: clear description, linked issue (`Closes #123`), passing CI (build + test), screenshot for UI changes.
- Never commit secrets or machine-specific paths.
<!-- rtk-instructions v2 -->
-# RTK (Rust Token Killer) - Token-Optimized Commands
-
-## Golden Rule
+# RTK — Always Prefix Shell Commands with `rtk`
-**Always prefix commands with `rtk`**. If RTK has a dedicated filter, it uses it. If not, it passes through unchanged. This means RTK is always safe to use.
+**Every shell command must be prefixed with `rtk`** (RTK = Rust Token Killer). This filters and compresses output before it reaches the LLM context, saving 60-90% tokens. RTK passes through any command it doesn't recognize.
-**Important**: Even in command chains with `&&`, use `rtk`:
+In a command chain, prefix each command individually:
```bash
-# ❌ Wrong
-git add . && git commit -m "msg" && git push
-
-# ✅ Correct
rtk git add . && rtk git commit -m "msg" && rtk git push
```
-## RTK Commands by Workflow
-
-### Build & Compile (80-90% savings)
-```bash
-rtk cargo build # Cargo build output
-rtk cargo check # Cargo check output
-rtk cargo clippy # Clippy warnings grouped by file (80%)
-rtk tsc # TypeScript errors grouped by file/code (83%)
-rtk lint # ESLint/Biome violations grouped (84%)
-rtk prettier --check # Files needing format only (70%)
-rtk next build # Next.js build with route metrics (87%)
-```
-
-### Test (60-99% savings)
-```bash
-rtk cargo test # Cargo test failures only (90%)
-rtk go test # Go test failures only (90%)
-rtk jest # Jest failures only (99.5%)
-rtk vitest # Vitest failures only (99.5%)
-rtk playwright test # Playwright failures only (94%)
-rtk pytest # Python test failures only (90%)
-rtk rake test # Ruby test failures only (90%)
-rtk rspec # RSpec test failures only (60%)
-rtk test <cmd> # Generic test wrapper - failures only
-```
-
-### Git (59-80% savings)
-```bash
-rtk git status # Compact status
-rtk git log # Compact log (works with all git flags)
-rtk git diff # Compact diff (80%)
-rtk git show # Compact show (80%)
-rtk git add # Ultra-compact confirmations (59%)
-rtk git commit # Ultra-compact confirmations (59%)
-rtk git push # Ultra-compact confirmations
-rtk git pull # Ultra-compact confirmations
-rtk git branch # Compact branch list
-rtk git fetch # Compact fetch
-rtk git stash # Compact stash
-rtk git worktree # Compact worktree
-```
-
-Note: Git passthrough works for ALL subcommands, even those not explicitly listed.
-
-### GitHub (26-87% savings)
-```bash
-rtk gh pr view <num> # Compact PR view (87%)
-rtk gh pr checks # Compact PR checks (79%)
-rtk gh run list # Compact workflow runs (82%)
-rtk gh issue list # Compact issue list (80%)
-rtk gh api # Compact API responses (26%)
-```
-
-### JavaScript/TypeScript Tooling (70-90% savings)
-```bash
-rtk pnpm list # Compact dependency tree (70%)
-rtk pnpm outdated # Compact outdated packages (80%)
-rtk pnpm install # Compact install output (90%)
-rtk npm run <script> # Compact npm script output
-rtk npx <cmd> # Compact npx command output
-rtk prisma # Prisma without ASCII art (88%)
-```
-
-### Files & Search (60-75% savings)
-```bash
-rtk ls <path> # Tree format, compact (65%)
-rtk read <file> # Code reading with filtering (60%)
-rtk grep <pattern> # Search grouped by file (75%)
-rtk find <pattern> # Find grouped by directory (70%)
-```
-
-### Analysis & Debug (70-90% savings)
-```bash
-rtk err <cmd> # Filter errors only from any command
-rtk log <file> # Deduplicated logs with counts
-rtk json <file> # JSON structure without values
-rtk deps # Dependency overview
-rtk env # Environment variables compact
-rtk summary <cmd> # Smart summary of command output
-rtk diff # Ultra-compact diffs
-```
-
-### Infrastructure (85% savings)
-```bash
-rtk docker ps # Compact container list
-rtk docker images # Compact image list
-rtk docker logs <c> # Deduplicated logs
-rtk kubectl get # Compact resource list
-rtk kubectl logs # Deduplicated pod logs
-```
-
-### Network (65-70% savings)
-```bash
-rtk curl <url> # Compact HTTP responses (70%)
-rtk wget <url> # Compact download output (65%)
-```
-
-### Meta Commands
-```bash
-rtk gain # View token savings statistics
-rtk gain --history # View command history with savings
-rtk discover # Analyze Claude Code sessions for missed RTK usage
-rtk proxy <cmd> # Run command without filtering (for debugging)
-rtk init # Add RTK instructions to CLAUDE.md
-rtk init --global # Add RTK to ~/.claude/CLAUDE.md
-```
-
-## Token Savings Overview
-
-| Category | Commands | Typical Savings |
-|----------|----------|-----------------|
-| Tests | vitest, playwright, cargo test | 90-99% |
-| Build | next, tsc, lint, prettier | 70-87% |
-| Git | status, log, diff, add, commit | 59-80% |
-| GitHub | gh pr, gh run, gh issue | 26-87% |
-| Package Managers | pnpm, npm, npx | 70-90% |
-| Files | ls, read, grep, find | 60-75% |
-| Infrastructure | docker, kubectl | 85% |
-| Network | curl, wget | 65-70% |
-
-Overall average: **60-90% token reduction** on common development operations.
+Meta commands: `rtk gain` (savings stats), `rtk discover` (find missed opportunities), `rtk proxy <cmd>` (run raw for debugging).
<!-- /rtk-instructions -->
-
-<!-- CODEGRAPH_START -->
-## CodeGraph
-
-This project has a CodeGraph MCP server (`codegraph_*` tools) configured. CodeGraph is a tree-sitter-parsed knowledge graph of every symbol, edge, and file. Reads are sub-millisecond and return structural information grep cannot.
-
-### When to prefer codegraph over native search
-
-Use codegraph for **structural** questions — what calls what, what would break, where is X defined, what is X's signature. Use native grep/read only for **literal text** queries (string contents, comments, log messages) or after you already have a specific file open.
-
-| Question | Tool |
-|---|---|
-| "Where is X defined?" / "Find symbol named X" | `codegraph_search` |
-| "What calls function Y?" | `codegraph_callers` |
-| "What does Y call?" | `codegraph_callees` |
-| "What would break if I changed Z?" | `codegraph_impact` |
-| "Show me Y's signature / source / docstring" | `codegraph_node` |
-| "Give me focused context for a task/area" | `codegraph_context` |
-| "Survey an unfamiliar module/topic" | `codegraph_explore` |
-| "What files exist under path/" | `codegraph_files` |
-| "Is the index healthy?" | `codegraph_status` |
-
-### Rules of thumb
-
-- **Trust codegraph results.** They come from a full AST parse. Do NOT re-verify them with grep — that's slower, less accurate, and wastes context.
-- **Don't grep first** when looking up a symbol by name. `codegraph_search` is faster and returns kind + location + signature in one call.
-- **Don't chain `codegraph_search` + `codegraph_node`** when you just want context — `codegraph_context` is one call.
-- **`codegraph_explore` is the heavy hitter** for unfamiliar areas — it returns full source from all relevant files in one call, but is token-heavy. If your harness supports parallel subagents (e.g., Claude Code's Task tool), spawn one for explore-class questions to keep main session context clean.
-- **Index lag**: the file watcher debounces ~500ms behind writes; don't re-query immediately after editing a file in the same turn.
-
-### If `.codegraph/` doesn't exist
-
-The MCP server returns "not initialized." Ask the user: *"I notice this project doesn't have CodeGraph initialized. Want me to run `codegraph init -i` to build the index?"*
-<!-- CODEGRAPH_END -->
diff --git a/README.es-ES.md b/README.es-ES.md
index 21a79a6..0a6aca4 100644
--- a/README.es-ES.md
+++ b/README.es-ES.md
@@ -34,6 +34,14 @@ Cada estrella nos motiva a realizar futuras mejoras.
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck Modo Oscuro" title="optimizerDuck Modo Oscuro" width="800"/>
diff --git a/README.fr-FR.md b/README.fr-FR.md
index 2729d2f..acf30f4 100644
--- a/README.fr-FR.md
+++ b/README.fr-FR.md
@@ -34,6 +34,14 @@ Chaque étoile aide à motiver les améliorations futures.
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck Mode sombre" title="optimizerDuck Mode sombre" width="800"/>
diff --git a/README.ja-JP.md b/README.ja-JP.md
index 2394774..b5c14d8 100644
--- a/README.ja-JP.md
+++ b/README.ja-JP.md
@@ -34,6 +34,14 @@ optimizerDuck が PC の改善に役立ったなら、リポジトリに ⭐ を
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck ダークモード" title="optimizerDuck ダークモード" width="800"/>
diff --git a/README.ko-KR.md b/README.ko-KR.md
index ffa60c5..d18bbaa 100644
--- a/README.ko-KR.md
+++ b/README.ko-KR.md
@@ -34,6 +34,14 @@ optimizerDuck이 PC 성능을 개선하는 데 도움이 되었다면, 이 저
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck 다크 모드" title="optimizerDuck 다크 모드" width="800"/>
diff --git a/README.md b/README.md
index cc5a0ed..49a4d98 100644
--- a/README.md
+++ b/README.md
@@ -34,6 +34,14 @@ Every star helps motivate future improvements.
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck Dark Mode" title="optimizerDuck Dark Mode" width="800"/>
diff --git a/README.ru-RU.md b/README.ru-RU.md
index eae2ce3..6cfb0f5 100644
--- a/README.ru-RU.md
+++ b/README.ru-RU.md
@@ -34,6 +34,14 @@
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck Тёмная тема" title="optimizerDuck Тёмная тема" width="800"/>
diff --git a/README.vi.md b/README.vi.md
index 9498004..f723df7 100644
--- a/README.vi.md
+++ b/README.vi.md
@@ -34,6 +34,14 @@ Càng nhiều sao càng có động lực cải thiện công cụ.
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck Chế độ tối" title="optimizerDuck Chế độ tối" width="800"/>
diff --git a/README.zh-CN.md b/README.zh-CN.md
index df35bef..07ad146 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -34,6 +34,14 @@
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck 深色模式" title="optimizerDuck 深色模式" width="800"/>
diff --git a/README.zh-TW.md b/README.zh-TW.md
index a7a4438..886e697 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -34,6 +34,14 @@
</picture>
</a>
+<a href="https://starmapper.bruniaux.com/itsfatduck/optimizerDuck">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck?theme=light" />
+ <img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/itsfatduck/optimizerDuck" />
+ </picture>
+</a>
+
</details>
<img src="./.github/assets/app.png" alt="optimizerDuck 深色模式" title="optimizerDuck 深色模式" width="800"/>
diff --git a/opencode.jsonc b/opencode.jsonc
index 2c2509a..fdd351b 100644
--- a/opencode.jsonc
+++ b/opencode.jsonc
@@ -10,5 +10,8 @@
],
"enabled": true
}
+ },
+ "commit_message": {
+ "prompt": "# Commit Message Instructions\n\n## Format\n\n```\n<type>: <short description>\n\n[optional body]\n\n[optional footer(s)]\n```\n\n## Allowed Types\n\n| Type | Usage |\n|------------|--------------------------------------------|\n| `feat:` | New feature |\n| `fix:` | Bug fix |\n| `refactor:`| Code change that neither fixes nor adds |\n| `docs:` | Documentation only |\n| `test:` | Adding or fixing tests |\n| `i18n:` | Translations / localization |\n| `chore:` | Build, tooling, deps, CI |\n\n## Rules\n\n- Use **lowercase** for type, short description, and scope.\n- Short description: imperative mood, no period, max ~72 chars.\n- Scope: optional noun in parentheses, e.g. `feat(startup): add virtualization`.\n- Body: wrap at 72 chars, explain *what* and *why*, not *how*.\n- Footer: `Closes #123`, `BREAKING CHANGE: <desc>`.\n- Branch naming: `feature/<name>` or `fix/<issue-id>` branching from `master`.\n- PRs: clear description, linked issue, passing `dotnet build` + `dotnet test`.\n- Never commit secrets or machine-specific paths.\n\n## Examples\n\n```\nfeat(startup): add VirtualizingStackPanel with Recycling mode\n\nEnables container reuse when scrolling the startup apps list,\nreducing GC pressure and improving scroll smoothness.\n\nCloses #42\n```\n\n```\nfix(startup): remove CanContentScroll from outer ScrollViewer\n\nStackPanel children don't implement IScrollInfo so logical scrolling\nsilently drops mouse-wheel events, making the page appear stuck.\n```\n\n```\ni18n: add Vietnamese translations for StartupManager page\n```\n\n```\nchore: update WPF UI package to 3.0.4\n```\n"
}
}
diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
index 745eef2..0e1cdd5 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
@@ -136,7 +136,7 @@ public class OptimizationServiceIntegrationTests : IDisposable
_testOptimizationIds.Add(optimization.Id);
var progress = new Progress<ProcessingProgress>();
- var result = await optimizationService.ApplyAsync(optimization, progress);
+ var result = await optimizationService.ApplyAsync(optimization, progress, TestContext.Current.CancellationToken);
Assert.Equal(OptimizationSuccessResult.Success, result.Status);
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
index e493763..a0cfa6c 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
@@ -273,7 +273,7 @@ public class RegistryServiceTests : IDisposable
Assert.True(RegistryService.Write(new RegistryItem(key, "Value", value)));
var read = RegistryService.Read<string>(new RegistryItem(key, "Value"));
Assert.Equal(value, read);
- })
+ }, TestContext.Current.CancellationToken)
);
}
diff --git a/optimizerDuck.Test/Services/RegistryWatcherTests.cs b/optimizerDuck.Test/Services/RegistryWatcherTests.cs
index 7177a1b..0819878 100644
--- a/optimizerDuck.Test/Services/RegistryWatcherTests.cs
+++ b/optimizerDuck.Test/Services/RegistryWatcherTests.cs
@@ -85,7 +85,7 @@ public class RegistryWatcherTests : IDisposable
watcher.Watch(TestRoot);
// Give the watcher thread time to start and block on RegNotifyChangeKeyValue
- await Task.Delay(500);
+ await Task.Delay(500, TestContext.Current.CancellationToken);
// Write a value to trigger the notification
using var key = Registry.CurrentUser.OpenSubKey(TestRootNative, writable: true);
@@ -93,7 +93,7 @@ public class RegistryWatcherTests : IDisposable
key.SetValue("TestValue", 42);
// Wait for the event with a timeout
- var completed = await Task.WhenAny(tcs.Task, Task.Delay(5000));
+ var completed = await Task.WhenAny(tcs.Task, Task.Delay(5000, TestContext.Current.CancellationToken));
Assert.Equal(tcs.Task, completed);
var firedPath = await tcs.Task;
@@ -110,12 +110,12 @@ public class RegistryWatcherTests : IDisposable
watcher.Watch(TestRoot);
// Give the watcher time to attempt opening the key and start its retry loop
- await Task.Delay(300);
+ await Task.Delay(300, TestContext.Current.CancellationToken);
watcher.Unwatch(TestRoot);
// Give cancellation time to interrupt any in-flight delay/operation
- await Task.Delay(500);
+ await Task.Delay(500, TestContext.Current.CancellationToken);
// Create key and write — at this point the watcher should be stopped
using var key = Registry.CurrentUser.CreateSubKey(TestRootNative);
@@ -123,7 +123,7 @@ public class RegistryWatcherTests : IDisposable
key.SetValue("TestValue", 99);
// Extra settle time to ensure no late notification arrives
- await Task.Delay(1500);
+ await Task.Delay(1500, TestContext.Current.CancellationToken);
Assert.Equal(0, fireCount);
}
@@ -160,7 +160,7 @@ public class RegistryWatcherTests : IDisposable
watcher.Watch(pathB);
// Give watcher threads time to block on RegNotifyChangeKeyValue
- await Task.Delay(500);
+ await Task.Delay(500, TestContext.Current.CancellationToken);
// Write to path A
using (var keyA = Registry.CurrentUser.OpenSubKey(pathANative, writable: true))
@@ -176,8 +176,8 @@ public class RegistryWatcherTests : IDisposable
keyB.SetValue("Val", 2);
}
- var completedA = await Task.WhenAny(tcsA.Task, Task.Delay(5000));
- var completedB = await Task.WhenAny(tcsB.Task, Task.Delay(5000));
+ var completedA = await Task.WhenAny(tcsA.Task, Task.Delay(5000, TestContext.Current.CancellationToken));
+ var completedB = await Task.WhenAny(tcsB.Task, Task.Delay(5000, TestContext.Current.CancellationToken));
Assert.Equal(tcsA.Task, completedA);
Assert.Equal(tcsB.Task, completedB);
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index f68c634..f908e68 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -141,8 +141,10 @@ public partial class App : Application
{
base.OnStartup(e);
- // Run initialization in a background task to keep UI responsive if needed,
- // but since we need the MainWindow to show, we'll await the async part.
+ AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
+ TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
+ DispatcherUnhandledException += OnDispatcherUnhandledException;
+
_ = Task.Run(async () =>
{
try
@@ -156,8 +158,60 @@ public partial class App : Application
});
}
+ private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
+ {
+ var ex = e.ExceptionObject as Exception ?? new Exception(e.ExceptionObject?.ToString());
+ LogExceptionToFile("AppDomain.UnhandledException", ex);
+ Log.Logger?.Fatal(ex, "Unhandled AppDomain exception. IsTerminating={IsTerminating}", e.IsTerminating);
+ }
+
+ private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
+ {
+ LogExceptionToFile("UnobservedTaskException", e.Exception);
+ Log.Logger?.Error(e.Exception, "Unobserved task exception");
+ e.SetObserved();
+ }
+
+ private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
+ {
+ LogExceptionToFile("DispatcherUnhandledException", e.Exception);
+ Log.Logger?.Error(e.Exception, "Unhandled UI dispatcher exception");
+ e.Handled = true;
+ }
+
+ private static void LogExceptionToFile(string category, Exception ex)
+ {
+ try
+ {
+ var crashDir = Path.Combine(Shared.RootDirectory, "Crashes");
+ Directory.CreateDirectory(crashDir);
+ var crashFile = Path.Combine(
+ crashDir,
+ $"crash_{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}.log"
+ );
+ File.WriteAllText(
+ crashFile,
+ $"""
+ [{category}] {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}
+ Type: {ex.GetType().FullName}
+ Message: {ex.Message}
+ StackTrace:
+ {ex.StackTrace}
+
+ {(ex.InnerException is not null ? $"Inner: {ex.InnerException}" : "")}
+ """
+ );
+ }
+ catch
+ {
+ // cannot do anything if crash logging itself fails
+ }
+ }
+
private async Task HandleStartupErrorAsync(Exception ex)
{
+ LogExceptionToFile("App.Startup", ex);
+
try
{
Log.Logger?.Fatal(ex, "Fatal error during startup");
@@ -334,24 +388,22 @@ public partial class App : Application
optimizationRegistry.StartPreload();
}
- protected override void OnExit(ExitEventArgs e)
+ protected override async void OnExit(ExitEventArgs e)
{
try
{
if (_host != null)
{
- _host.StopAsync().GetAwaiter().GetResult();
+ await _host.StopAsync();
_host.Dispose();
}
- // Dispose WMI scopes to prevent resource leaks
WmiHelper.DisposeScopes();
-
Log.CloseAndFlush();
}
- catch
+ catch (Exception ex)
{
- // Silently ignore exit errors to prevent blocking shutdown
+ LogExceptionToFile("App.OnExit", ex);
}
base.OnExit(e);
diff --git a/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs b/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs
index e02fab8..b696f3e 100644
--- a/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs
+++ b/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs
@@ -14,8 +14,7 @@ public static class CustomizePageRegistryExtensions
public static void AddAllCustomizeCategoryPages(this IServiceCollection services)
{
var categoryTypes = ReflectionHelper
- .FindImplementationsInLoadedAssemblies<ICustomizeCategory>()
- .ToList();
+ .FindImplementationsInLoadedAssemblies<ICustomizeCategory>();
foreach (var categoryType in categoryTypes)
{
diff --git a/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs b/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs
index ed171c5..ca7bfe0 100644
--- a/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs
+++ b/optimizerDuck/Common/Extensions/OptimizationPageRegistryExtensions.cs
@@ -18,8 +18,7 @@ public static class OptimizationPageRegistryExtensions
public static void AddAllOptimizationPages(this IServiceCollection services)
{
var categoryTypes = ReflectionHelper
- .FindImplementationsInLoadedAssemblies<IOptimizationCategory>()
- .ToList();
+ .FindImplementationsInLoadedAssemblies<IOptimizationCategory>();
foreach (var categoryType in categoryTypes)
{
diff --git a/optimizerDuck/Common/Extensions/StringExtensions.cs b/optimizerDuck/Common/Extensions/StringExtensions.cs
index 826574c..81b67bb 100644
--- a/optimizerDuck/Common/Extensions/StringExtensions.cs
+++ b/optimizerDuck/Common/Extensions/StringExtensions.cs
@@ -28,7 +28,7 @@ public static class TextExtensions
{
IEnumerable<object> list => string.Join(
Environment.NewLine,
- list.Where(_ => true).Select(o => o.ToString()?.Trim() ?? string.Empty)
+ list.Select(o => o.ToString()?.Trim() ?? string.Empty)
),
_ => deserialized?.ToString()?.Trim() ?? string.Empty,
};
diff --git a/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.cs b/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.cs
index a8fbe15..52ed625 100644
--- a/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.cs
+++ b/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.cs
@@ -98,22 +98,23 @@ public static class EmbeddedResourceHelper
/// Gets all available embedded resources in the optimizerDuck.Resources.Embedded namespace.
/// </summary>
/// <returns>Enumerable of resource names with the namespace prefix removed.</returns>
+ private static readonly string[] _cachedResourceNames =
+ Assembly.GetExecutingAssembly().GetManifestResourceNames();
+
+ private static readonly HashSet<string> _cachedResourceSet =
+ new(_cachedResourceNames, StringComparer.Ordinal);
+
public static IEnumerable<string> GetAvailableResources()
{
- var assembly = Assembly.GetExecutingAssembly();
var prefix = $"{ResourceNamespace}.";
- return assembly
- .GetManifestResourceNames()
+ return _cachedResourceNames
.Where(name => name.StartsWith(prefix, StringComparison.Ordinal))
.Select(name => name.Substring(prefix.Length));
}
- /// <summary>
- /// Checks if a specific resource exists in the assembly.
- /// </summary>
private static bool ResourceExists(Assembly assembly, string resourceName)
{
- return assembly.GetManifestResourceNames().Contains(resourceName);
+ return _cachedResourceSet.Contains(resourceName);
}
}
diff --git a/optimizerDuck/Common/Helpers/Shared.cs b/optimizerDuck/Common/Helpers/Shared.cs
index ca2dac3..45120e9 100644
--- a/optimizerDuck/Common/Helpers/Shared.cs
+++ b/optimizerDuck/Common/Helpers/Shared.cs
@@ -41,7 +41,7 @@ public static class Shared
public static readonly HashSet<string> SafeApps = new()
{
- // Bing / MSN
+ // Bing / MSN / News
"Microsoft.BingWeather",
"Microsoft.BingNews",
"Microsoft.BingSearch",
@@ -51,25 +51,30 @@ public static class Shared
"Microsoft.BingHealthAndFitness",
"Microsoft.BingTravel",
"Microsoft.MicrosoftNews",
- // Utilities & Services
+ // Help, Tips & Feedback
"Microsoft.GetHelp",
"Microsoft.GetStarted",
+ "Microsoft.WindowsFeedbackHub",
+ "Microsoft.WindowsTips",
+ "MicrosoftCorporationII.QuickAssist",
+ // Communications (Legacy/Web Wrappers)
"Microsoft.Messaging",
"Microsoft.OneConnect",
"Microsoft.People",
- "Microsoft.WindowsFeedbackHub",
- "Microsoft.WindowsMaps",
"Microsoft.YourPhone",
+ "Microsoft.SkypeApp",
+ "MicrosoftTeams",
+ // Office (Web Wrappers & Legacy)
"Microsoft.OneNote",
"Microsoft.Todos",
"Microsoft.MicrosoftOfficeHub",
"Microsoft.Office.OneNote",
"Microsoft.Office.Sway",
- "Microsoft.SkypeApp",
+ "Microsoft.OutlookForWindows",
+ "Microsoft.MicrosoftJournal",
+ // Social & Wallet
"Microsoft.Wallet",
"Microsoft.MSWallet",
- "Microsoft.RemoteDesktop",
- "Microsoft.OutlookForWindows",
"Microsoft.LinkedInForWindows",
// Mixed Reality & 3D
"Microsoft.Microsoft3DViewer",
@@ -82,10 +87,14 @@ public static class Shared
"Microsoft.ZuneVideo",
"Microsoft.Sway",
"Microsoft.WindowsSoundRecorder",
- // Entertainment & Games
+ "Microsoft.StickyNotes",
+ "Microsoft.MicrosoftStickyNotes",
+ // Entertainment, Games & Widgets
"Microsoft.MicrosoftSolitaireCollection",
"Microsoft.WindowsAlarms",
"Microsoft.549981C3F5F10", // Cortana
+ "Microsoft.Windows.DevHome",
+ "Microsoft.StartExperiencesApp",
// Third-party (often pre-installed by MS)
"SpotifyAB.SpotifyMusic",
"Disney.DisneyPlus",
@@ -95,6 +104,8 @@ public static class Shared
"WindowsPhone",
"CommsPhone",
"Microsoft.DrawboardPDF",
+ // Windows 11 Widgets
+ "MicrosoftWindows.Client.WebExperience",
};
public static readonly HashSet<string> CautionApps = new()
@@ -103,23 +114,25 @@ public static class Shared
"Microsoft.WindowsCalculator",
"Microsoft.WindowsPhotos",
"Microsoft.MSPaint",
+ "Microsoft.Paint",
"Microsoft.WindowsNotepad",
"Microsoft.WindowsCamera",
"Microsoft.ScreenSketch",
+ "Microsoft.WindowsMaps",
// System Tools
"Microsoft.WindowsStore",
"Microsoft.StorePurchaseApp",
"Microsoft.DesktopAppInstaller",
"Microsoft.WindowsTerminal",
"Microsoft.WindowsTerminalPreview",
+ "Microsoft.RemoteDesktop",
"Microsoft.PowerAutomateDesktop",
- // Communication
- "MicrosoftTeams",
+ // Communication & Collaboration
"Microsoft.WindowsCommunicationsApps",
// Security & Family
"MicrosoftCorporationII.MicrosoftFamily",
"MicrosoftCorporationII.MicrosoftSupportDiagnosticTool",
- // Extensions (Essential for files)
+ // Media Extensions (Essential for file format support)
"Microsoft.HEIFImageExtension",
"Microsoft.WebMediaExtensions",
"Microsoft.WebpImageExtension",
diff --git a/optimizerDuck/Domain/Execution/ExecutionScope.cs b/optimizerDuck/Domain/Execution/ExecutionScope.cs
index 986333b..dcf8dab 100644
--- a/optimizerDuck/Domain/Execution/ExecutionScope.cs
+++ b/optimizerDuck/Domain/Execution/ExecutionScope.cs
@@ -94,8 +94,8 @@ public sealed class ExecutionScope : IDisposable
Logger.LogInformation(
"Steps: {Total} ({Success} success, {Failed} failed)",
_executedSteps.Count,
- SuccessfulSteps.Count,
- FailedSteps.Count
+ _executedSteps.Count(s => s.Success),
+ _executedSteps.Count(s => !s.Success)
);
_current.Value = null;
@@ -395,7 +395,7 @@ public sealed class ExecutionScope : IDisposable
if (_executedSteps.Count == 0)
return OptimizationSuccessResult.Failed;
- var failed = FailedSteps.Count;
+ var failed = _executedSteps.Count(s => !s.Success);
var total = ExecutedSteps.Count;
return failed == 0 ? OptimizationSuccessResult.Success
diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
index 0bd57eb..8596203 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
@@ -64,59 +64,62 @@ public class PowerManagement : IOptimizationCategory
)]
public class DisableUSBPowerSaving : BaseOptimization
{
- public override async Task<ApplyResult> ApplyAsync(
+ public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context
)
{
- context.Logger.LogInformation("Saving current USB power state");
- var usbStates = await ShellService.PowerShellAsync(
- """
- $states = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
- Where-Object { $_.InstanceName -match 'USB\\ROOT' } |
- Select-Object InstanceName, Enable
+ return Task.Run(async () =>
+ {
+ context.Logger.LogInformation("Saving current USB power state");
+ var usbStates = await ShellService.PowerShellAsync(
+ """
+ $states = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
+ Where-Object { $_.InstanceName -match 'USB\\ROOT' } |
+ Select-Object InstanceName, Enable
- $states | ConvertTo-Json -Compress
- """
- );
+ $states | ConvertTo-Json -Compress
+ """
+ );
- if (string.IsNullOrWhiteSpace(usbStates.Stdout))
- {
- context.Logger.LogInformation("No USB devices found, skipping");
- return CompleteFromScope();
- }
+ if (string.IsNullOrWhiteSpace(usbStates.Stdout))
+ {
+ context.Logger.LogInformation("No USB devices found, skipping");
+ return CompleteFromScope();
+ }
- var capturedStates = ParseUsbPowerStates(usbStates.Stdout);
- if (capturedStates.Count == 0)
- {
- context.Logger.LogInformation("No USB device states parsed, skipping");
- return CompleteFromScope();
- }
+ var capturedStates = ParseUsbPowerStates(usbStates.Stdout);
+ if (capturedStates.Count == 0)
+ {
+ context.Logger.LogInformation("No USB device states parsed, skipping");
+ return CompleteFromScope();
+ }
- context.Logger.LogInformation("Disabling USB power saving");
- var disableResult = await ShellService.PowerShellAsync(
- """
- $devices = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
- Where-Object { $_.InstanceName -match 'USB\\ROOT' }
+ context.Logger.LogInformation("Disabling USB power saving");
+ var disableResult = await ShellService.PowerShellAsync(
+ """
+ $devices = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
+ Where-Object { $_.InstanceName -match 'USB\\ROOT' }
- foreach ($d in $devices) {
- if ($d.Enable -ne $false) {
- Set-CimInstance -CimInstance $d -Property @{ Enable = $false } | Out-Null
+ foreach ($d in $devices) {
+ if ($d.Enable -ne $false) {
+ Set-CimInstance -CimInstance $d -Property @{ Enable = $false } | Out-Null
+ }
}
- }
- """
- );
+ """
+ );
- var revertStep = new UsbPowerRevertStep { States = capturedStates };
- ExecutionScope.RecordStep(
- Translations.Service_Shell_Name,
- Name,
- disableResult.ExitCode == 0,
- disableResult.ExitCode == 0 ? revertStep : null,
- disableResult.ExitCode == 0 ? null : disableResult.Stderr
- );
+ var revertStep = new UsbPowerRevertStep { States = capturedStates };
+ ExecutionScope.RecordStep(
+ Translations.Service_Shell_Name,
+ Name,
+ disableResult.ExitCode == 0,
+ disableResult.ExitCode == 0 ? revertStep : null,
+ disableResult.ExitCode == 0 ? null : disableResult.Stderr
+ );
- return CompleteFromScope();
+ return CompleteFromScope();
+ });
}
private static List<UsbPowerRevertStep.DeviceState> ParseUsbPowerStates(string stdout)
@@ -138,6 +141,11 @@ public class PowerManagement : IOptimizationCategory
}
}
+ private static readonly Regex _activePlanGuidRegex = new(
+ @".*:\s*([a-fA-F0-9\-]{36})",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled
+ );
+
[Optimization(
Id = "EE71E993-EE41-4449-8856-84B09B2B0C46",
Risk = OptimizationRisk.Safe,
@@ -151,11 +159,7 @@ public class PowerManagement : IOptimizationCategory
)
{
var activeQuery = await ShellService.CMDAsync("powercfg /getactivescheme");
- var match = Regex.Match(
- activeQuery.Stdout,
- @".*:\s*([a-fA-F0-9\-]{36})",
- RegexOptions.IgnoreCase
- );
+ var match = _activePlanGuidRegex.Match(activeQuery.Stdout);
if (!match.Success)
{
@@ -237,19 +241,20 @@ public class PowerManagement : IOptimizationCategory
IProgress<ProcessingProgress> progress,
OptimizationContext context
)
- {
- RegistryService.Write(
- new RegistryItem(
- @"HKLM\SYSTEM\CurrentControlSet\Control\USB\AutomaticSurpriseRemoval",
- "AttemptRecoveryFromUsbPowerDrain",
- 0
- ),
- new RegistryItem(
- @"HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerThrottling",
- "PowerThrottlingOff",
- 1
- )
- );
+ {
+ RegistryService.Write(
+ new RegistryItem(
+ @"HKLM\SYSTEM\CurrentControlSet\Control\USB\AutomaticSurpriseRemoval",
+ "AttemptRecoveryFromUsbPowerDrain",
+ 0
+ ),
+ new RegistryItem(
+ @"HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerThrottling",
+ "PowerThrottlingOff",
+ 1
+ )
+ );
+
context.Logger.LogInformation("Disabled power saving features");
return Task.FromResult(CompleteFromScope());
}
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 0ff3891..592230e 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -10,7 +10,6 @@ using optimizerDuck.Domain.UI;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Managers;
using optimizerDuck.Services.Optimization.Providers;
-using optimizerDuck.UI.Controls;
using optimizerDuck.UI.Dialogs;
using optimizerDuck.UI.ViewModels.Dialogs;
using Wpf.Ui;
@@ -31,15 +30,18 @@ public class OptimizationService(
public bool WasRequestedRestorePoint { get; set; } = false;
+ private static readonly Regex _restorePointDisabledRegex = new(
+ @"\b(is\s+disabled|system\s+restore\s+is\s+disabled|disabled\s+by\s+group\s+policy|disableconfig|disablesr|protection\s+is\s+off)\b",
+ RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled
+ );
+
public async Task<RestorePointResult> CreateRestorePointAsync()
{
var dialogViewModel = new ProcessingViewModel();
- var dialogContent = new ProcessingDialog { DataContext = dialogViewModel };
-
var dialog = new ContentDialog
{
Title = Translations.RestorePoint_Title,
- Content = dialogContent,
+ Content = new ProcessingDialog { DataContext = dialogViewModel },
IsFooterVisible = false,
};
@@ -61,33 +63,25 @@ public class OptimizationService(
$"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"
);
- if (
- result.Stderr.Contains(
- "already been created within the past",
- StringComparison.OrdinalIgnoreCase
- )
- )
+ if (IsFrequencyLimited(result.Stderr))
{
_logger.LogWarning("Restore point creation skipped: frequency limit reached.");
return RestorePointResult.FrequencyLimitReached;
}
if (result.ExitCode == 0)
+ {
+ _logger.LogInformation("Restore point created successfully.");
return RestorePointResult.Success;
+ }
- if (
- !Regex.IsMatch(
- result.Stderr,
- @"\b(is\s+disabled|system\s+restore\s+is\s+disabled|disabled\s+by\s+group\s+policy|disableconfig|disablesr|protection\s+is\s+off)\b",
- RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
- )
- )
+ if (!_restorePointDisabledRegex.IsMatch(result.Stderr))
{
_logger.LogError("Failed to create restore point: {Message}", result.Stderr);
return RestorePointResult.Failed;
}
- _logger.LogInformation("Enabling System Protection...");
+ _logger.LogInformation("System Protection is disabled. Enabling...");
dialogViewModel.ProgressReporter.Report(
new ProcessingProgress
{
@@ -99,6 +93,7 @@ public class OptimizationService(
var enableResult = await ShellService.PowerShellAsync(
"Enable-ComputerRestore -Drive \"$env:SystemDrive\""
);
+
if (enableResult.ExitCode != 0)
{
_logger.LogError(
@@ -120,12 +115,7 @@ public class OptimizationService(
$"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"
);
- if (
- result.Stderr.Contains(
- "already been created within the past",
- StringComparison.OrdinalIgnoreCase
- )
- )
+ if (IsFrequencyLimited(result.Stderr))
return RestorePointResult.FrequencyLimitReached;
return result.ExitCode == 0 ? RestorePointResult.Success : RestorePointResult.Failed;
@@ -136,6 +126,14 @@ public class OptimizationService(
}
}
+ private static bool IsFrequencyLimited(string? stderr)
+ {
+ return stderr?.Contains(
+ "already been created within the past",
+ StringComparison.OrdinalIgnoreCase
+ ) == true;
+ }
+
public async Task<OptimizationResult> ApplyAsync(
IOptimization optimization,
IProgress<ProcessingProgress> progress,
diff --git a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
index dd41a1d..387e1b0 100644
--- a/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ScheduledTaskService.cs
@@ -465,9 +465,16 @@ public static class ScheduledTaskService
var triggers = def.Triggers;
var actions = def.Actions;
- var triggerDescriptions = triggers
- .Select(t => t.ToString() ?? t.TriggerType.ToString())
- .ToList();
+ var triggerDescriptions = new List<string>();
+ var hasLogon = false;
+ var hasBoot = false;
+
+ foreach (var t in triggers)
+ {
+ triggerDescriptions.Add(t.ToString() ?? t.TriggerType.ToString());
+ if (t.TriggerType == TaskTriggerType.Logon) hasLogon = true;
+ if (t.TriggerType == TaskTriggerType.Boot) hasBoot = true;
+ }
var actionSummary = string.Empty;
if (actions.Count > 0 && actions[0] is ExecAction exec)
@@ -475,9 +482,6 @@ public static class ScheduledTaskService
? exec.Path ?? string.Empty
: $"{exec.Path} {exec.Arguments}";
- var hasLogon = triggers.Any(t => t.TriggerType == TaskTriggerType.Logon);
- var hasBoot = triggers.Any(t => t.TriggerType == TaskTriggerType.Boot);
-
return new ScheduledTaskModel
{
Name = task.Name,
diff --git a/optimizerDuck/Services/System/StreamService.cs b/optimizerDuck/Services/System/StreamService.cs
index 3514de9..fb68551 100644
--- a/optimizerDuck/Services/System/StreamService.cs
+++ b/optimizerDuck/Services/System/StreamService.cs
@@ -5,7 +5,7 @@ using optimizerDuck.Common.Helpers;
namespace optimizerDuck.Services;
-public class StreamService(ILogger<StreamService> logger)
+public class StreamService(ILogger<StreamService> logger) : IDisposable
{
private HttpClient? _client;
@@ -67,4 +67,9 @@ public class StreamService(ILogger<StreamService> logger)
return (false, null);
}
}
+
+ public void Dispose()
+ {
+ _client?.Dispose();
+ }
}
diff --git a/optimizerDuck/Services/System/SystemInfoService.cs b/optimizerDuck/Services/System/SystemInfoService.cs
index c8f7006..74f6c9b 100644
--- a/optimizerDuck/Services/System/SystemInfoService.cs
+++ b/optimizerDuck/Services/System/SystemInfoService.cs
@@ -560,7 +560,8 @@ internal static class WmiHelper
{
var scope = GetScope(namespacePath);
using var searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query));
- return searcher.Get().Cast<ManagementObject>().ToArray();
+ using var results = searcher.Get();
+ return results.Cast<ManagementObject>().ToArray();
}
catch
{
@@ -636,7 +637,17 @@ internal static class WmiHelper
public static ManagementObject? GetFirst(string query, string namespacePath = @"root\cimv2")
{
- return Query(query, namespacePath).FirstOrDefault();
+ try
+ {
+ var scope = GetScope(namespacePath);
+ using var searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query));
+ using var results = searcher.Get();
+ return results.Cast<ManagementObject>().FirstOrDefault();
+ }
+ catch
+ {
+ return null;
+ }
}
}
@@ -1529,10 +1540,31 @@ internal static class GpuProvider
if (gpus.Count == 1)
return gpus[0];
- return gpus.OrderByDescending(g => g.MemoryMB ?? 0)
- .ThenByDescending(g => g.Vendor == GpuVendor.NVIDIA)
- .ThenByDescending(g => g.Vendor == GpuVendor.AMD)
- .First();
+ GpuInfo? best = null;
+ foreach (var g in gpus)
+ {
+ if (best is null)
+ {
+ best = g;
+ continue;
+ }
+
+ var memG = g.MemoryMB ?? 0;
+ var memBest = best.MemoryMB ?? 0;
+ if (memG != memBest)
+ {
+ if (memG > memBest) best = g;
+ continue;
+ }
+
+ var gScore = g.Vendor == GpuVendor.NVIDIA ? 2
+ : g.Vendor == GpuVendor.AMD ? 1 : 0;
+ var bestScore = best.Vendor == GpuVendor.NVIDIA ? 2
+ : best.Vendor == GpuVendor.AMD ? 1 : 0;
+ if (gScore > bestScore) best = g;
+ }
+
+ return best;
}
// ── DXGI path ──────────────────────────────────────────────────────────
@@ -1990,7 +2022,7 @@ internal static class BiosProvider
// MAIN SERVICE (Public API)
// ============================================================================
-public sealed class SystemInfoService
+public sealed class SystemInfoService : IDisposable
{
private readonly ILogger<SystemInfoService> _logger;
private readonly SemaphoreSlim _semaphore = new(1, 1);
@@ -2193,4 +2225,9 @@ public sealed class SystemInfoService
_logger.LogInformation("Total GPUs : {GpuCount}", gpuCount);
}
}
+
+ public void Dispose()
+ {
+ _semaphore.Dispose();
+ }
}
diff --git a/optimizerDuck/Services/System/UpdaterService.cs b/optimizerDuck/Services/System/UpdaterService.cs
index a0f071b..e4b3683 100644
--- a/optimizerDuck/Services/System/UpdaterService.cs
+++ b/optimizerDuck/Services/System/UpdaterService.cs
@@ -6,7 +6,7 @@ using optimizerDuck.Common.Helpers;
namespace optimizerDuck.Services;
-public class UpdaterService
+public class UpdaterService : IDisposable
{
private const string Owner = "itsfatduck";
private const string Repo = "optimizerDuck";
@@ -100,6 +100,10 @@ public class UpdaterService
return (false, null);
}
}
+ public void Dispose()
+ {
+ _httpClient.Dispose();
+ }
}
// Helper classes for deserializing GitHub API response
diff --git a/optimizerDuck/Services/UI/BloatwareService.cs b/optimizerDuck/Services/UI/BloatwareService.cs
index 467decf..d270dd1 100644
--- a/optimizerDuck/Services/UI/BloatwareService.cs
+++ b/optimizerDuck/Services/UI/BloatwareService.cs
@@ -84,9 +84,9 @@ public class BloatwareService(
};
var apps = JsonSerializer
- .Deserialize<List<AppXPackage>>(result.Stdout, options)!
- .OrderBy(a => a.Name)
- .ToList();
+ .Deserialize<List<AppXPackage>>(result.Stdout, options)!;
+
+ apps.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
foreach (var app in apps)
{
@@ -342,7 +342,7 @@ public class BloatwareService(
var baseNameWithoutQualifiers = StripKnownQualifiers(baseResourceName);
var preferredLogicalSize = GuessLogicalBaseSize(baseNameWithoutQualifiers);
- var files = Directory
+ return Directory
.EnumerateFiles(candidateDirectory, "*.*", SearchOption.TopDirectoryOnly)
.Where(path =>
SupportedImageExtensions.Contains(
@@ -360,10 +360,8 @@ public class BloatwareService(
);
})
.Select(path => new LogoVariant(path, preferredLogicalSize, includeThemeSpecific))
- .OrderByDescending(v => v.SortScore)
- .ToList();
-
- return files.FirstOrDefault()?.Path;
+ .MaxBy(v => v.SortScore)
+ ?.Path;
}
private static string StripKnownQualifiers(string fileNameWithoutExtension)
diff --git a/optimizerDuck/UI/Pages/DiskCleanupPage.xaml b/optimizerDuck/UI/Pages/DiskCleanupPage.xaml
index d848d5b..3c98e91 100644
--- a/optimizerDuck/UI/Pages/DiskCleanupPage.xaml
+++ b/optimizerDuck/UI/Pages/DiskCleanupPage.xaml
@@ -192,7 +192,18 @@
Grid.Column="0"
Margin="0,0,12,0"
VerticalAlignment="Center"
- IsChecked="{Binding IsSelected, Mode=TwoWay}" />
+ IsChecked="{Binding IsSelected, Mode=TwoWay}">
+ <CheckBox.Style>
+ <Style BasedOn="{StaticResource DefaultCheckBoxStyle}" TargetType="CheckBox">
+ <Setter Property="IsEnabled" Value="True" />
+ <Style.Triggers>
+ <DataTrigger Binding="{Binding SizeBytes}" Value="0">
+ <Setter Property="IsEnabled" Value="False" />
+ </DataTrigger>
+ </Style.Triggers>
+ </Style>
+ </CheckBox.Style>
+ </CheckBox>
<!-- Icon -->
<Border
@@ -355,6 +366,12 @@
<ui:SplitButton.Flyout>
<ContextMenu>
+ <MenuItem
+ Command="{Binding DataContext.ViewModel.RefreshItemCommand, Source={x:Reference ThisPage}}"
+ CommandParameter="{Binding}"
+ Cursor="Hand"
+ Header="{ext:Loc StartupManager.Menu.Refresh}"
+ Icon="{ui:SymbolIcon ArrowClockwise24}" />
<MenuItem
Command="{Binding DataContext.ViewModel.OpenFolderCommand, Source={x:Reference ThisPage}}"
CommandParameter="{Binding}"
diff --git a/optimizerDuck/UI/Pages/ScheduledTasksPage.xaml b/optimizerDuck/UI/Pages/ScheduledTasksPage.xaml
index 953ed0e..5de188a 100644
--- a/optimizerDuck/UI/Pages/ScheduledTasksPage.xaml
+++ b/optimizerDuck/UI/Pages/ScheduledTasksPage.xaml
@@ -198,7 +198,7 @@
Visibility="{Binding ViewModel.Tasks.Count, Converter={StaticResource GreaterThanZeroToVisibilityConverter}}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
- <ScrollViewer CanContentScroll="True" HorizontalScrollBarVisibility="Disabled">
+ <ScrollViewer CanContentScroll="False" HorizontalScrollBarVisibility="Disabled">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index 4808bc0..71e4c29 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -788,7 +788,6 @@ public partial class OptimizationCategoryViewModel : ViewModel
switch (resultState)
{
case RestorePointResult.Success:
- // if setting show snackbar after applied successfully was off, so show it and applied snackbar wont conflict this
if (!_appOptionsMonitor.CurrentValue.Optimize.ShowCompletionNotification)
{
_snackbarService.Show(
@@ -805,8 +804,8 @@ public partial class OptimizationCategoryViewModel : ViewModel
},
TimeSpan.FromSeconds(5)
);
- break;
}
+
_logger.LogInformation("Successfully created restore point");
return (true, true);
diff --git a/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs
index abaca0c..8c80dcf 100644
--- a/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs
@@ -64,8 +64,10 @@ public partial class BloatwareViewModel : ViewModel
public ObservableCollection<AppXPackage> AppxPackages { get; } = [];
- public bool HasSelectedItems => AppxPackages.Any(x => x.IsSelected);
- public int SelectedCount => AppxPackages.Count(x => x.IsSelected);
+ private int _selectedCount;
+
+ public bool HasSelectedItems => _selectedCount > 0;
+ public int SelectedCount => _selectedCount;
public bool HasData => _allPackages.Count > 0;
public bool HasSafePackages => AppxPackages.Any(x => x.Risk == AppRisk.Safe);
@@ -141,6 +143,13 @@ public partial class BloatwareViewModel : ViewModel
AppxPackages.Clear();
foreach (var package in filtered)
AppxPackages.Add(package);
+
+ _selectedCount = 0;
+ foreach (var p in filtered)
+ {
+ if (p.IsSelected)
+ _selectedCount++;
+ }
}
#region Property Changed
@@ -149,6 +158,9 @@ public partial class BloatwareViewModel : ViewModel
{
if (e.PropertyName == nameof(AppXPackage.IsSelected))
{
+ if (sender is AppXPackage pkg)
+ _selectedCount += pkg.IsSelected ? 1 : -1;
+
UpdateProperties();
RemoveSelectedCommand.NotifyCanExecuteChanged();
}
diff --git a/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs
index 2d9ca83..4153c86 100644
--- a/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs
@@ -139,8 +139,8 @@ public partial class CustomizeCategoryViewModel : ViewModel
var sortedSettings = SelectedSortByIndex switch
{
- 1 => filtered.OrderByDescending(f => f.IsEnabled).ThenBy(f => f.Name).ToList(),
- _ => filtered.OrderBy(f => f.Name).ToList(),
+ 1 => filtered.OrderByDescending(f => f.IsEnabled).ThenBy(f => f.Name),
+ _ => filtered.OrderBy(f => f.Name),
};
var grouped = sortedSettings
diff --git a/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs
index 896e215..03463cb 100644
--- a/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs
@@ -235,6 +235,21 @@ public partial class DiskCleanupViewModel(
}
}
+ [RelayCommand]
+ private async Task RefreshItemAsync(CleanupItem item)
+ {
+ if (item is null)
+ return;
+
+ await diskCleanupService.ScanAsync(item);
+
+ if (item.SizeBytes == 0)
+ item.IsSelected = false;
+
+ UpdateProperties();
+ ApplySort();
+ }
+
[RelayCommand]
private void OpenFolder(CleanupItem item)
{
diff --git a/optimizerDuck/optimizerDuck.csproj b/optimizerDuck/optimizerDuck.csproj
index 7bdbf2d..8405501 100644
--- a/optimizerDuck/optimizerDuck.csproj
+++ b/optimizerDuck/optimizerDuck.csproj
@@ -9,8 +9,8 @@
<Authors>fatDuck</Authors>
<ApplicationIcon>Logo.ico</ApplicationIcon>
<Company>fatDuck</Company>
- <FileVersion>2.21.1</FileVersion>
- <Version>2.21.1</Version>
+ <FileVersion>2.22.4</FileVersion>
+ <Version>2.22.4</Version>
<Product>optimizerDuck</Product>
<Copyright>Copyright fatDuck 2026</Copyright>
<AssemblyTitle>optimizerDuck</AssemblyTitle>