Skip to content

Add 'devproxy system-proxy reset' and restore previous system proxy settings - #2100

Open
waldekmastykarz wants to merge 31 commits into
dotnet:mainfrom
waldekmastykarz:issue-2060-add-a-command-to-restore-system-proxy-se-ffa2f5
Open

waldekmastykarz wants to merge 31 commits into
dotnet:mainfrom
waldekmastykarz:issue-2060-add-a-command-to-restore-system-proxy-se-ffa2f5

Conversation

@waldekmastykarz

Copy link
Copy Markdown
Collaborator

Resolves #2060

Problem

A graceful shutdown turns the system proxy off, but a killed or crashed Dev Proxy leaves the OS pointing at a dead port. Even a graceful shutdown only flipped ProxyEnable/proxy state off and left Dev Proxy's ProxyServer value behind, and it turned off any proxy the user had configured before (e.g. a corporate proxy). Crash recovery only existed for detached instances (via state files); a killed foreground instance left nothing to recover from.

Changes

  • Snapshot before taking over. SystemProxyManager.Enable records the current OS proxy settings plus the owning PID in system-proxy-backup.json in the Dev Proxy config folder:
    • Windows: previous ProxyEnable / ProxyServer registry values (including "value didn't exist").
    • macOS: per network service web/secure web proxy server, port, and enabled state (networksetup -get[secure]webproxy).
    • An existing snapshot is kept, so a re-enable after a crash doesn't overwrite the original settings with Dev Proxy's.
  • Restore instead of just disabling. Disable puts the snapshot back (Windows: set/delete registry values + WinINET refresh; macOS: toggle-proxy.sh off, then networksetup to restore previous servers/states). Without a snapshot it behaves as before. If restoring fails, the snapshot is kept so it can be retried.
  • New command: devproxy system-proxy reset [--force]. Restores the settings Dev Proxy changed and removes stale instance records. Refuses (exit 1) when a live Dev Proxy owns the system proxy unless --force is passed. On Linux, where Dev Proxy doesn't change the system proxy, it's a no-op.
  • Automatic recovery on startup. Startup reconciliation now also runs for foreground starts (previously only --detach) and treats a snapshot whose PID is dead as a stale registration, so killed foreground instances are recovered too. It never touches settings owned by a live instance.

Notes / decisions

  • Command name: the issue suggested devproxy proxy reset (name TBD). I went with devproxy system-proxy reset since devproxy proxy is ambiguous with Dev Proxy itself. Happy to rename.
  • Startup cleanup is automatic in all sessions rather than prompting in interactive ones, consistent with the existing detached-mode reconciliation and to avoid blocking startup on input.
  • Linux: Dev Proxy doesn't configure gsettings today (it only logs a hint), so there's nothing to snapshot/restore there.
  • Docs: the troubleshooting page (No internet connection after using the proxy) lives in the docs repo and should mention devproxy system-proxy reset once this ships.

Testing

  • Unit tests for networksetup output parsing, restore command generation, and snapshot store round-trip/corrupt-file handling.
  • dotnet build + full DevProxy.Tests pass. Verified devproxy system-proxy reset --help and detached start/stop with --as-system-proxy false. I didn't run the restore against this machine's real system proxy settings.

…ettings

Dev Proxy now records the OS proxy settings it is about to replace (Windows
ProxyEnable/ProxyServer, macOS networksetup web/secure web proxies) together
with the owning PID, and restores them when it stops instead of just turning
the system proxy off.

Because the snapshot outlives the process, a killed or crashed instance
(foreground or detached) can be recovered:
- 'devproxy system-proxy reset' restores the settings on demand
- Dev Proxy restores a stale registration automatically on startup

Closes dotnet#2060

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@waldekmastykarz
waldekmastykarz requested a review from a team as a code owner November 5, 2026 10:47
Copilot AI balanced review requested due to automatic review settings November 5, 2026 10:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Proxy recovery can silently fail and delete its backup, while forced resets can disable a restored corporate proxy and configuration errors can block recovery entirely.

5 open issues
What changed in this PR

Adds system-proxy recovery to Dev Proxy, preserving previous OS settings so they can be restored after shutdown or a crash.

Changes:

  • Saves Windows and macOS proxy settings before Dev Proxy takes over.
  • Adds devproxy system-proxy reset [--force] and extends automatic recovery to foreground starts.
  • Adds tests for snapshot persistence and macOS parsing and restore commands.
File Description
DevProxy/​State/​StateManager.cs Exposes process-liveness checks for recovery.
DevProxy/​Proxy/​SystemProxySnapshot.cs Adds snapshot storage and macOS settings helpers.
DevProxy/​Proxy/​SystemProxyManager.cs Captures and restores settings; tracks live and orphaned owners.
DevProxy/​Program.cs Runs recovery before foreground startup.
DevProxy/​Commands/​SystemProxyCommand.cs Implements the reset command and force option.
DevProxy/​Commands/​StopCommand.cs Adapts stop reporting to the revised recovery results.
DevProxy/​Commands/​DevProxyCommand.cs Registers the system-proxy command.
DevProxy.Tests/​SystemProxyManagerTests.cs Tests snapshot persistence and macOS helpers.
DevProxy.Abstractions/​Proxy/​ISystemProxyManager.cs Documents restoration behavior for cleanup.

Review effort: Balanced

Comment thread DevProxy/Commands/DevProxyCommand.cs Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
- Run 'system-proxy reset' before loading config/plugins
- Don't let an instance's shutdown undo a forced reset or another owner
- Treat networksetup timeouts/nonzero exits and toggle-proxy.sh failures as
  restore failures so the snapshot is kept
- Skip disabled macOS services in toggle-proxy.sh and propagate failures
- Report the Linux no-op before checking proxy ownership

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/toggle-proxy.sh Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
- Clear system-proxy ownership on live instances after a forced reset
- Report failed orphan restores distinctly and keep records for retry
- Continue restoring remaining macOS services after a failure
- Fail toggle-proxy.sh when listing network services fails
- Parse standalone reset args with System.CommandLine

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A partial proxy-disable failure can skip snapshot restoration, leaving affected network services without their previous corporate proxy settings even after retries.

No open issues 🎉

4 previously missed issues

In code that hasn't changed since last review

High severity Restore proxy snapshots even when disabling a service fails

DevProxy/​Proxy/​SystemProxyManager.cs:154

If toggle-proxy.sh off fails for one network service, it can still successfully disable the proxies on the other services. This condition then skips RestoreMacOS entirely, leaving those working services without their previous corporate proxy; retrying repeats the same problem while the failing service remains. Please attempt snapshot restoration even when the disable pass fails, and combine both results so the backup is still retained on either failure.

Medium severity Recognize recovery commands with global options in any position

DevProxy/​Commands/​DevProxyCommand.cs:148

The standalone recovery path is still bypassed when a recursive global option appears between the commands. For example, devproxy system-proxy --no-color reset is valid for the registered command tree, but this positional check returns false. It then builds the application host, where an empty plugins configuration throws before recovery runs. Please recognize the parsed command path independently of global-option placement so these valid invocations also work with broken configurations.

Medium severity Enforce enum validation for standalone options

DevProxy/​Commands/​SystemProxyCommand.cs:56

The registered command validates --output and --log-level as enums, but the standalone path accepts arbitrary strings here. For example, devproxy system-proxy reset --force --log-level typo changes the OS proxy settings instead of rejecting the invalid option before any side effects. Please retain the enum option types in this parser as well.

Medium severity Validate process start time to prevent stale PID ownership

DevProxy/​Proxy/​SystemProxySnapshot.cs:20

After a crash or reboot, the OS can reuse the saved PID for an unrelated process, causing startup recovery to skip restoration and an unforced reset to refuse it. Persist the owner's process start time alongside its PID, refresh both on takeover, and validate both in the ownership and orphan checks. The snapshot's existing CreatedAt cannot identify the current owner because it is preserved across takeovers.

6 resolved since last review

Review effort: Balanced

…ne reset parsing

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@waldekmastykarz

Copy link
Copy Markdown
Collaborator Author

Addressing the previously missed issues from the latest review, fixed in d14a489:

  • Restore snapshots even when disabling fails: fixed. RestoreMacOS now always runs when a snapshot exists, and either failure keeps the snapshot.
  • Global options in any position: fixed. IsSystemProxyResetCommand skips --output/--log-level (and their values) and --no-color before matching the command path.
  • Enum validation in the standalone parser: fixed. It now uses Option<OutputFormat?> and Option<LogLevel?>, so --log-level typo is rejected before any OS change.
  • PID start-time validation: not changing this here. The existing instance state (StateManager.IsProcessRunning, GetOrphanedSystemProxyStatesAsync, stop, status) identifies instances by PID only. The snapshot follows the same model on purpose, so ownership checks stay consistent across the code. If a PID is reused, the worst case is that automatic cleanup is skipped and reset asks for --force, which the error message explains. Validating start time for every PID-based check is a broader change that belongs in a separate issue.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Attached option values cause valid system-proxy reset commands to bypass the standalone recovery path, allowing broken configuration to block the reset.

1 open issue

Review effort: Balanced

Comment thread DevProxy/Commands/DevProxyCommand.cs Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A help flag in a response file is ignored, causing system-proxy reset --force --help to reset the system proxy instead of displaying help.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human review is needed to assess interacting recovery, ownership, and command-routing risks that could lose recovery records or unexpectedly alter system proxy settings.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Resolve conflict in SystemProxyManager.ReconcileOrphanedSystemProxiesAsync:
keep the PR's snapshot-aware restore, and delete orphaned state records via
main's state-matching DeleteStateAsync(ProxyInstanceState) for PID-reuse safety.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because critical restoration and cleanup failure paths can report success while losing recovery state, leaving proxies pointed at dead ports, or overwriting restored settings.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional test results

  • PR: #2100
  • Tested commit: 6c4f16b49192c950d91b5694ee32eb6d60d12e6a
  • Base comparison: b2a9cbfef9bd434ee3b10d761814aa25d83aba20
  • Environment: macOS, .NET SDK 10.0.103, source builds. Isolated HOME and CFFIXED_USER_HOME, pre-created Library/Application Support, unique certificate paths, CI=1. Every runtime launch used --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run; dotnet run also used --no-build --no-restore --no-launch-profile.
  • Main functional matrix: 42 assertions passed. One additional detached-command regression failed and was compared against the base.
Scenario or test command Expected Actual Result
Source build, head and base Compile with warnings treated as errors Initial head build lacked restored assets; locked restore resolved this. Both solution builds succeeded with zero warnings/errors PASS
CI for tested SHA Automated checks successful Build, smoke, C# analysis, Ubuntu/Windows/macOS tests, CodeQL and CLA succeeded. Automated tests were not rerun locally PASS
Detached runtime readiness and local HTTP requests Owned live process; authenticated API 200; PID-scoped status available; exact upstream response/header Four ready instances used random ports; exact {"upstream":"pr2100","ok":true} body and X-PR2100: local-upstream header PASS
Prior --no-mocks mocks from-http-responses response.txt --mocks-file generated.json, without --detach Generate correct mocks without recovery Exit 0, exact {"ok":true} body, byte-identical snapshot and orphan record retained, zero OS adapter calls. The command without leading --no-mocks also passed PASS
Leading output, plugin, multi-value URL/environment options before PID-scoped status; response-file status Read-only operation All six cases preserved the snapshot and made zero OS adapter calls PASS
Reset help, including response file; four invalid argument cases with broken config Usage only or exit 2, without recovery/config failure Correct help; invalid output/log-level/Boolean/unknown option rejected before mutation PASS
Live snapshot owner, including --force false and -c broken.json Refuse with exit 1 and ownership guidance Correct PID guidance; snapshot retained; zero adapter calls PASS
Ownership retirement failure, then retry Exit 1 and retain snapshot until ownership can be retired Read-only owned state directory prevented the write: exit 1, error surfaced, snapshot and live ownership retained. After restoring permissions, forced reset exited 0, cleared ownership and removed snapshot PASS
-c and --config-file with malformed/missing config; JSON reset output Recovery independent of config loading Short and long config options accepted; reset succeeded and emitted JSON result PASS
Dead authoritative snapshot over older live record; reused snapshot PID Recover dead identity and retain newer management identity No force required; superseded ownership cleared. Reused PID case preserved the newer live state byte-for-byte PASS
Failed reset and orphan stop --pid, then retry; read-only orphan status Preserve retryable recovery state; retry removes it Adapter failures exited 1 and retained snapshot/orphan. Retries succeeded with systemProxyRestored; orphan status retained state PASS
Stop dead record while live snapshot owns proxy Remove only dead record Exit 0, snapshot retained, zero adapter calls, staleRecordRemoved result PASS
Startup recovery using --output=json, --output:json, response-file output Recovery plus startup results are valid JSON Lines All three recovered the empty snapshot, emitted a recovery event and passed runtime readiness PASS
PATH-mocked toggle on/off and partial failure Preserve service-name arguments; skip disabled services; propagate failure while continuing Correct calls for Wi-Fi and a name containing spaces; disabled service excluded; partial failure exited 1 and continued remaining calls PASS
Same plugin management command with leading --detach No recovery/state mutation, or safe usage rejection Head generated correct mocks and exited 0, but printed recovery and deleted the snapshot. Identical base invocation generated the same body and preserved the snapshot FAIL
Native OS capture/restoration, nonempty recorded-service restore and authenticated-proxy warning Restore original platform settings and display required authentication guidance BLOCKED: shared-host policy prohibits real proxy mutation. Recorded endpoint restoration uses absolute /usr/sbin/networksetup, so PATH mocking cannot safely exercise that production path. Empty snapshots and mocked fallback tests do not establish native integration correctness BLOCKED
Cleanup Stop only owned processes; remove owned fixtures/state/certificates/logs and base checkout; restore original checkout All 12 observed owned PIDs exited; four ready instances stopped gracefully; local upstream stopped; owned state directories had no instance records; fixtures and temporary base worktree removed; original branch restored; Git status clean PASS

Requested changes

Detached plugin management command still triggers recovery

  • Requested change: Guard the detached parent's reconciliation with the actual parsed start action too, or reject --detach on management commands before attempting recovery.

  • Expected: Generating mocks must not delete a system-proxy snapshot or attempt system-proxy recovery.

  • Actual: The detached parent prints Recovered system proxy left by a crashed Dev Proxy instance (PID: 2147483647). and deletes the snapshot before its child generates the correct mocks.

  • Reproduction: Configure MockResponsePlugin; create response.txt containing an HTTP 200 response with Content-Type: application/json and body {"ok":true}. Seed isolated application data with {"pid":2147483647,"processStartTime":"1970-01-01T00:00:00Z","macOS":[]} as system-proxy-backup.json. From the fixture directory, invoke the source-built CLI:

    devproxy --detach --as-system-proxy false --port 0 --api-port 0 \
      --install-cert false --no-first-run --config-file config.json \
      --no-mocks mocks from-http-responses response.txt --mocks-file generated.json

    Tested head: exit 0, correct generated body, snapshot removed and recovery message. Captured base: exit 0, same generated body, snapshot retained, no recovery message. Both also print Dev Proxy failed to start on stderr; that diagnostic is pre-existing and is not the reported PR regression. The empty macOS snapshot made zero adapter calls.

  • Inline comment: Added current-head and base-comparison evidence to the existing plugin-command parsing thread instead of creating a duplicate: #2100 (comment)

Outcome

Request changes for reproduced unintended recovery in the detached management-command path. The original non-detached reproduction is fixed; retirement failure retention/retry, config-independent reset, ownership decisions and JSON recovery passed. Native restoration and authenticated-endpoint warning remain blocked, not passing. This report is functional testing, not a separate code review. No source fixes, pushes or merges were made. Cleanup and clean checkout restoration are verified.

Resolve conflict in DevProxyCommand.cs by keeping both IsSystemProxyResetCommand and IsValidateInvocation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 10:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Blocking restore, cleanup, and macOS takeover defects can falsely report success, discard recovery state, or leave system proxy settings pointing at a terminated instance.

4 open issues

Review effort: Balanced

Comment thread DevProxy/Commands/StopCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Proxy/SystemProxySnapshot.cs Resolved

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional test results

  • PR: #2100
  • Tested commit: 09fad99edb21f289cf1d98b387425befa5d12630
  • Base commit: 61346d968d73f38c94d3bcb7130f22c29f91171a
  • Environment: macOS; .NET SDK 10.0.103; source builds.
  • Results: 34 assertions passed; 2 failed. Both failures show the same defect.

The tests used separate HOME and CFFIXED_USER_HOME directories. I created Library/Application Support before startup. Each build used a separate certificate path.

All proxy starts used --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run. I set CI=1 to prevent token output.

Scenario or test command Expected Actual Result
Source builds for head and base Both builds succeed Both solution builds succeeded with zero warnings and errors PASS
CI checks for the tested commit All required checks succeed Build, smoke, C# analysis, Ubuntu/Windows/macOS tests, CodeQL and CLA succeeded. I did not repeat automated tests locally PASS
Four detached proxy starts The process runs; the API returns 200; the proxy returns the exact local response Each process passed authenticated API access and PID-specific status. Each returned {"ok":true,"source":"local"} and header X-Test: pr2100 PASS
Mock generation without --detach, with and without --no-mocks The command creates the correct file and keeps the snapshot Both commands returned 0, created body {"ok":true}, kept the snapshot unchanged and made zero OS adapter calls PASS
Mock generation with --detach, with and without --no-mocks The command does not start recovery or delete the snapshot Both commands returned 0 and created the correct file. Both printed recovery output and deleted the snapshot FAIL
The same detached command on the current base The snapshot remains unchanged The base returned 0, created the same body, kept the snapshot unchanged and made zero OS adapter calls PASS
Status after output, plugin, URL and environment options; response-file status The command does not start recovery All six cases returned 0 and kept the snapshot. The five direct cases made zero OS adapter calls PASS
Reset help and response-file help The command shows help without recovery Both commands returned 0 and kept the snapshot PASS
Four incorrect reset arguments with broken configuration The command returns 2 before recovery Incorrect output, log level, Boolean and unknown option cases returned 2 and kept the snapshot PASS
Reset with a live snapshot owner and --force false The command returns 1 and keeps the snapshot The command named the correct PID, returned 1 and kept the snapshot PASS
Failure to write a live ownership record The command returns 1 and keeps the recovery information A read-only test directory caused a logged error. The command returned 1 and kept the snapshot and ownership record PASS
Reset after write permission was restored The command clears ownership and removes the snapshot Reset with --config-file broken.json returned 0, cleared ownership, removed the snapshot and produced JSON output PASS
Dead snapshot owner with an older live record The command does not require force Reset returned 0, removed the snapshot and cleared the older ownership PASS
Old snapshot identity with a newer process at the same PID The command keeps the newer management record Reset returned 0 and kept the newer record unchanged PASS
OS adapter failure during reset and stop --pid Both commands return 1 and keep the recovery files Both commands retained the snapshot and dead-process record. Reset removed both files after adapter recovery PASS
Startup recovery with --output=json, --output:json and response-file output Each output line contains JSON; recovery removes the snapshot All three cases produced valid JSON Lines, removed the snapshot and passed API and proxy checks PASS
Native capture/restoration and authenticated-proxy warning Restore the original OS settings and show necessary instructions BLOCKED: real proxy changes are prohibited on this shared Mac. Absolute /usr/sbin/networksetup prevents safe PATH substitution for recorded endpoints BLOCKED
Cleanup Stop only test processes and remove test files All seven recorded PIDs stopped. Four running proxies stopped through stop --pid. The local server stopped. Test state, certificates, logs and the base checkout were removed. The original branch was restored; Git status was clean PASS
ASD-STE100 language check Check the prose against Issue 9 and its dictionary INCOMPLETE: the official site requires a copy request. The full dictionary was unavailable. I checked sentence lengths and clear instructions without claiming verified conformance BLOCKED

Requested changes

Detached mock generation still starts recovery

  • Requested change: Restrict recovery in the detached parent to a parsed start command. Alternatively, reject --detach for management commands before recovery.

  • Expected: Mock generation creates the file without deleting system-proxy-backup.json or starting system-proxy recovery.

  • Actual: The command returns 0 and creates the file, but first deletes the snapshot and prints a recovery message.

  • Reproduction: Enable MockResponsePlugin. Create response.txt with an HTTP 200 response, Content-Type: application/json, and body {"ok":true}. Create this snapshot in the separate application-data directory:

    {"pid":2147483647,"processStartTime":"1970-01-01T00:00:00Z","macOS":[]}

    Run the source-built CLI from the test directory:

    devproxy --detach --as-system-proxy false --port 0 --api-port 0 \
      --install-cert false --no-first-run --config-file config.json \
      --no-mocks mocks from-http-responses response.txt --mocks-file generated.json

    The tested head prints this evidence and deletes the snapshot:

    Recovered system proxy left by a crashed Dev Proxy instance (PID: 2147483647).
    

    The current base keeps the snapshot unchanged and creates the same body. Removing --detach passes on the tested head.

    Both revisions print Dev Proxy failed to start. on stderr. That diagnostic is not a new defect from this PR.

  • Inline comment: I added new evidence to the existing thread: #2100 (comment)

Outcome

Request changes. The detached command still starts recovery before the full command parse. The current update merges main; it does not change that path.

The original command without --detach passes. Related ownership, reset, status and JSON startup cases pass. Native restoration remains blocked, not passed.

This report covers functional testing, not a separate code review. I made no source fixes, pushes or merges. All test processes and files were removed.

…rvices on takeover

- stop --force no longer terminates an instance or deletes its record when restoring the system proxy fails
- Restore reports failure when the snapshot or orphaned state records can't be removed
- Taking over an existing snapshot records services added since it was captured

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 11:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because unreadable or duplicate-PID state records can survive a reported successful restore, allowing later recovery to disable the restored corporate proxy.

No open issues 🎉

4 resolved since last review

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional test results

  • PR: #2100
  • Tested commit: be593245d7d2fb690e52832cffc26673c42c70b8
  • Base commit: 61346d968d73f38c94d3bcb7130f22c29f91171a
  • Environment: macOS; .NET SDK 10.0.103; source build.
  • Final results: 29 assertions passed; 2 failed. Both failures show the same detached-command defect.

The tests used separate HOME and CFFIXED_USER_HOME directories. I created Library/Application Support before startup. DEV_PROXY_CERT_PATH identified a test-only certificate.

All proxy starts used --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run. I set CI=1 to prevent token output.

Scenario or test command Expected Actual Result
dotnet build DevProxy.sln --no-restore --verbosity quiet The source build succeeds Build succeeded with zero warnings and errors PASS
CI checks for the tested commit All required checks succeed Build, smoke, C# analysis, Ubuntu/Windows/macOS tests, CodeQL and CLA succeeded. I did not repeat automated tests locally PASS
Detached proxy starts The process runs; authenticated API access returns 200; the proxy returns the exact local response All starts passed. The body was {"ok":true,"source":"local"}; header X-Test was pr2100. PID-specific status identified each process PASS
Mock generation without --detach, with and without --no-mocks The command creates the file without recovery Both commands returned 0, created body {"ok":true}, kept the snapshot unchanged and made zero adapter calls PASS
Mock generation with --detach, with and without --no-mocks The command creates the file without recovery or snapshot deletion Both commands returned 0 and created the correct body. Both printed recovery output and deleted the snapshot FAIL
Status after output, plugin, URL and environment options; response-file status The command keeps the snapshot unchanged All six cases passed. The direct cases made zero adapter calls PASS
Reset help and incorrect output argument with broken configuration Return 0 for help or 2 for incorrect input, before recovery Both cases returned the expected code and kept the snapshot PASS
Reset with a live owner and --force false Return 1 and keep the snapshot The command returned 1, named the owner and kept the snapshot PASS
Reset with an immutable snapshot Return 1, log the deletion failure and keep the snapshot With macOS file flag UF_IMMUTABLE, reset returned 1 and kept the snapshot unchanged. The log gave cleanup instructions PASS
Reset after unlocking the snapshot Return 0 and remove the snapshot Reset succeeded and removed the snapshot PASS
Reset with an immutable orphan record Return 1 and keep both recovery files Reset returned 1, logged the record-deletion failure and kept both files PASS
Reset after unlocking the orphan record Return 0 and remove both recovery files Reset succeeded and removed both files PASS
stop --force --pid <owned-pid> when the mocked adapter fails Return 1 before termination; keep the process, snapshot and record The command returned 1. The owned process remained alive. Both recovery files remained. JSON status was failed with recovery guidance PASS
Force-stop with an immutable snapshot Return 1 before termination and keep recovery information The process, management record and snapshot remained PASS
Force-stop after recovery Return 0, stop the owned process and remove recovery files All required results occurred PASS
Startup recovery with --output=json, --output:json and response-file output Each output line contains JSON; recovery removes the snapshot All three cases passed JSON parsing, authenticated API access, the exact proxy response and graceful shutdown PASS
Native new-service capture, takeover, endpoint restoration and authenticated-proxy warning Preserve and restore the original OS settings BLOCKED: real proxy changes are prohibited on this shared Mac. Absolute /usr/sbin/networksetup prevents safe PATH substitution for that production path BLOCKED
Cleanup Stop only test processes and remove test files All 12 recorded PIDs stopped across two runs. Owned force-stop and graceful-stop operations succeeded. Both local servers stopped. State, certificates, logs and fixtures were removed. The original branch was restored; Git status was clean PASS
ASD-STE100 language check Check the prose against Issue 9 and its dictionary INCOMPLETE: the full dictionary was unavailable. Sentence length and clear instructions were checked without claiming verified conformance BLOCKED

An initial assertion searched raw JSON for an apostrophe. JSON output encoded that character as \u0027, so the assertion incorrectly failed. I changed the test harness to inspect the decoded message. The repeated force-stop test passed. This was a test-harness error, not a product defect.

Requested changes

Detached mock generation still starts recovery

  • Requested change: Restrict recovery in the detached parent to a parsed start command. Alternatively, reject --detach for management commands before recovery.
  • Expected: The command creates the mock file without deleting the snapshot or starting system-proxy recovery.
  • Actual: Both detached commands delete the snapshot before creating the correct file. The commands without --detach keep the snapshot unchanged.
  • Reproduction:
  1. Enable MockResponsePlugin in config.json.
  2. Create response.txt with an HTTP 200 response, Content-Type: application/json, and body {"ok":true}.
  3. Create system-proxy-backup.json in the separate application-data directory with this content:
{"pid":2147483647,"processStartTime":"1970-01-01T00:00:00Z","macOS":[]}
  1. Run the source-built CLI from the test directory:
devproxy --detach --as-system-proxy false --port 0 --api-port 0 \
  --install-cert false --no-first-run --config-file config.json \
  --no-mocks mocks from-http-responses response.txt --mocks-file generated.json

The command returns 0 and creates body {"ok":true}. It deletes the snapshot and prints:

Recovered system proxy left by a crashed Dev Proxy instance (PID: 2147483647).

Removing only --no-mocks gives the same result. Removing --detach passes with or without --no-mocks.

The base remains 61346d968d73f38c94d3bcb7130f22c29f91171a. The previous base test kept the snapshot unchanged and generated the same body. I did not repeat the base test in this run. The new commit does not change the detached dispatch path.

The detached commands also print Dev Proxy failed to start. on stderr. The base test had the same diagnostic; it is not a new defect.

  • Inline comment: I added current-head evidence to the existing thread: #2100 (comment)

Outcome

Request changes for the repeated detached-command defect. The new locked-file and force-stop failure behavior passes the tests.

Native takeover and restoration remain blocked, not passed. This report covers functional testing, not a separate code review. I made no source fixes, pushes or merges.

All test processes stopped. All test files were removed. The original checkout is clean.

… orphans

A detached parent ran startup recovery before the command line was resolved,
so detached plugin management commands (e.g. 'mocks from-http-responses')
restored the system proxy and deleted the snapshot. The daemon now recovers in
the root command's action, like a foreground start, and the parent echoes the
outcome from the daemon's log.

Orphaned system-proxy records are now deduplicated by PID and process start
time, so a legacy and a per-PID record for different processes that shared a
PID are both retired after a restore.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 12:15
@waldekmastykarz

Copy link
Copy Markdown
Collaborator Author

Re: the Copilot review overview, "unreadable or duplicate-PID state records can survive a reported successful restore":

  • Duplicate PID: real, fixed in 203d185. GetOrphanedSystemProxyStatesAsync deduped by PID only. A legacy state.json and a per-PID record for different dead processes that shared a PID collapsed into one entry, so retirement removed one record and left the other. That record then triggered another restore later. Orphans are now deduped by PID and process start time. OrphanedSystemProxyStateTests covers this; it fails without the fix.
  • Unreadable records: not changing this. An unreadable record (invalid JSON or an I/O error) reads as null everywhere. That includes GetOrphanedSystemProxyStatesAsync, so later recovery never treats it as an orphan and it can't trigger a restore or disable. Deleting files we can't parse during recovery could remove something we don't own, for a record that has no effect anyway.

waldekmastykarz and others added 2 commits November 27, 2026 13:16
Restore CRLF line endings in DevProxyCommand.cs (lost in the previous merge) and use an ordinal StartsWith to satisfy CA1307 on net11.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ore-system-proxy-se-ffa2f5' into fix-conflicts-pr-2100

# Conflicts:
#	DevProxy/Commands/DevProxyCommand.cs

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The marker-only filter hides recovery authentication warnings during detached starts, leaving proxy authentication disabled without surfacing re-enablement instructions to the caller.

1 open issue

Review effort: Balanced

Comment thread DevProxy/Program.cs Resolved
Copilot AI balanced review requested due to automatic review settings November 27, 2026 12:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Blocking issues can leave the requested live instance running after a successful stop report, suppress required proxy-authentication recovery instructions, and omit JSON reset results.

3 open issues

Review effort: Balanced

Comment thread DevProxy/Commands/StopCommand.cs Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Announce startup recovery before its first message and have the detached parent forward every record between the first and last recovery message, so warnings like macOS proxy credentials that need re-entering reach the caller in text and JSON output.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 12:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because unpublished critical findings identify recovery and ownership failures that can alter a live instance’s proxy settings or report success without restoring the saved configuration.

2 open issues
1 resolved since last review

Review effort: Balanced

- stop --pid: after removing a dead legacy state.json record, keep going
  and stop a live instance whose per-PID record has the same PID instead
  of returning success early.
- system-proxy reset --output json: keep the logging pipeline at
  Information so the structured result survives --log-level Warning/None;
  the JSON formatter still filters diagnostics at the requested level.
- Extract the detached-start recovery echo into SystemProxyRecoveryEcho
  and cover it with tests (text and JSON, incl. the macOS proxy
  authentication warning). Warnings now go to stderr, matching the
  foreground console logger.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 13:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because critical recovery and instance-ownership edge cases can disable active proxy settings, discard recovery data, or suppress authentication-restoration warnings.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-enhancement Product features, behavior fixes, and usability or compatibility improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a command to restore system proxy settings after Dev Proxy was killed or crashed

3 participants