Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): speed up Windows diagnostics and editor discovery #3911

ClosedSivanTechDev(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/3911/headopened View on GitHub

What Changed

  • Replace the Windows process-diagnostics N+1 CIM query with two bulk queries joined by process ID.
  • Use a five-second diagnostics timeout on Windows while retaining the existing one-second POSIX timeout.
  • Bound non-Windows editor discovery to four concurrent probes and a five-second config fallback.
  • Use the existing Windows executable resolver for editor discovery instead of repeatedly scanning the full PATH for every editor.
  • Add focused coverage for the bulk Windows query and exact editor results.

Why

Fixes #3610.

On the affected Windows machine, process diagnostics and optional editor discovery delayed server.getConfig long enough for the client to treat the local environment as disconnected. Project history and provider configuration then failed to load.

Windows diagnostics previously queried performance data once per process. Reading both CIM classes once and joining them by process ID reduced the measured query to about 866 ms, so this change gives Windows a five-second budget without changing the POSIX timeout.

The first editor-discovery fallback used 500 ms, but that hid installed editors. A trace on the affected machine showed that its 37-entry PATH still took more than five seconds when scanned separately for every editor, even with four concurrent probes. Windows now reuses the existing executable resolver, which restores VS Code and File Manager discovery without introducing another PATH/PATHEXT implementation.

The Windows resolver uses synchronous filesystem checks, so the surrounding Effect timeout cannot preempt a filesystem call while the event loop is blocked. This PR keeps that existing tradeoff to remain a focused fix; a fully interruptible batch resolver would be broader shell infrastructure work.

Validation

  • Manually verified with pnpm dev:desktop that VS Code and File Manager are discovered on the affected machine.
  • Typecheck passed.
  • Formatting passed.
  • apps/server/src/process/externalLauncher.test.ts passed.
  • The changed test-file run passed 111 tests and reported two Windows-environment failures: an existing POSIX-specific diagnostics test that does not pin the platform, and a server test that could not create a symlink (EPERM).
  • Confirmed that config loading completes and the local environment connects.

Checklist

  • This PR is small and focused.
  • I explained what changed and why.
  • No UI changes; screenshots are not applicable.
  • No animation or interaction changes; video is not applicable.

Note

Speed up Windows process diagnostics and editor discovery

  • Windows process diagnostics now fetches perf data once via a single Get-CimInstance Win32_PerfFormattedData_PerfProc_Process call and uses a dictionary lookup per process, replacing per-process -Filter CIM queries.
  • Windows editor discovery uses SpawnExecutableResolution instead of async PATH scans; non-Windows discovery runs probes with bounded concurrency (4).
  • Editor discovery in the WebSocket server config snapshot is capped at a 5-second timeout, returning an empty availableEditors list on timeout instead of blocking.
  • Separate timeout constants are introduced: POSIX_PROCESS_QUERY_TIMEOUT_MS (1s) and WINDOWS_PROCESS_QUERY_TIMEOUT_MS (5s), replacing a single shared constant.
Macroscope summarized ff0764b.

Summary by CodeRabbit

  • New Features

    • Server configuration now remains responsive even when editor discovery is delayed or unavailable.
    • Editor availability checks run more efficiently, including faster discovery on Windows.
  • Bug Fixes

    • Added a timeout and safe fallback for editor discovery, preventing configuration requests from hanging.
    • Improved Windows process diagnostics by gathering performance data more efficiently.
    • Platform-specific diagnostic timeouts improve reliability across Windows and POSIX systems.

Note

Medium Risk Changes server config snapshot timing and Windows diagnostics/editor probing paths; mitigated by timeouts and empty-editor fallback, but slow or sync Windows FS resolution can still affect discovery.

Overview Fixes slow Windows server.getConfig / local disconnect by speeding up process diagnostics and bounding editor discovery.

Windows process diagnostics no longer runs a per-process Get-CimInstance with -Filter for perf data. It loads Win32_PerfFormattedData_PerfProc_Process once into $perfById, then joins by ProcessId when enumerating Win32_Process. Query timeouts are split: 5s on Windows, 1s on POSIX (passed through runProcess).

Editor discovery on Windows uses SpawnExecutableResolution instead of repeated full PATH scans per editor. On other platforms, availability probes run with concurrency 4. WebSocket server config wraps resolveAvailableEditors() in withEditorDiscoveryTimeout (5s default) and returns [] on timeout so config snapshots are not blocked.

Tests cover the bulk PowerShell script shape, non-blocking editor timeout behavior, and Windows editor discovery via the resolver mock.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ff0764b5053dba11e273df7c861177852d65d057. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Review Change Stack

      📝 Walkthrough

      Walkthrough

      Process diagnostics now use platform-specific timeouts and batched Windows performance queries. Editor discovery uses concurrent command resolution, while server configuration applies a timeout and empty fallback for stalled discovery. Tests cover Windows querying, resolver behavior, and non-blocking configuration.

      Changes

      Diagnostics and editor discovery

      Layer / File(s)Summary
      Platform-specific process querying
      apps/server/src/diagnostics/ProcessDiagnostics.ts, apps/server/src/diagnostics/ProcessDiagnostics.test.ts
      Process execution accepts POSIX or Windows timeout values, and Windows performance data is indexed once by process ID instead of queried per process. Tests verify the generated PowerShell command.
      Concurrent editor discovery
      apps/server/src/process/externalLauncher.ts, apps/server/src/process/externalLauncher.test.ts
      Windows discovery uses executable resolution, while other platforms probe editors concurrently with a limit of four. Tests mock executable resolution directly.
      Timed server configuration loading
      apps/server/src/ws.ts, apps/server/src/server.test.ts
      Editor discovery in server configuration is bounded by a timeout and falls back to an empty list; websocket tests cover stalled discovery and path assertions.

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Sequence Diagram(s)

      sequenceDiagram
        participant Client
        participant ServerGetConfig
        participant EditorDiscovery
        participant ExecutableResolver
        Client->>ServerGetConfig: request configuration
        ServerGetConfig->>EditorDiscovery: resolve available editors
        EditorDiscovery->>ExecutableResolver: probe editor commands
        ExecutableResolver-->>EditorDiscovery: resolved commands
        EditorDiscovery-->>ServerGetConfig: editor IDs or timeout
        ServerGetConfig-->>Client: configuration with availableEditors

      Poem

      I’m a rabbit with a tidy queue, PowerShell hops through processes two by two. Editors race, but timeout gates the way, Config still returns before the hay. Tests nudge each path with paws of cheer.

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedThe changes address #3610 by fixing Windows diagnostics latency, editor discovery blocking, and config fallback behavior.
      Out of Scope Changes check✅ PassedThe diff stays focused on Windows diagnostics, editor discovery, and related tests without clear unrelated additions.
      Title check✅ PassedThe title clearly summarizes the main server-side speedups for Windows diagnostics and editor discovery.
      Description check✅ PassedThe description includes What Changed, Why, validation, and a completed checklist, with no UI changes to document.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      ✅ Action performed

      Review finished.

      Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

    4. 🧹 Nitpick comments (2)
      apps/server/src/diagnostics/ProcessDiagnostics.test.ts (1)

      223-257: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Test coverage is solid for the bulk query optimization.

      The assertions verify each CIM class is queried exactly once, the $perfById join expression is present, and -Filter (which would indicate per-process queries) is absent. Consider also asserting the -ErrorAction SilentlyContinue flag is present on the perf query, since silent error handling is the degradation mechanism for environments where Win32_PerfFormattedData_PerfProc_Process is unavailable.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/diagnostics/ProcessDiagnostics.test.ts` around lines 223 -
      257, Extend the “queries each Windows CIM class once” test around
      ProcessDiagnostics.readProcessRows to assert that the generated PowerShell
      script applies “-ErrorAction SilentlyContinue” to the
      Win32_PerfFormattedData_PerfProc_Process query. Keep the existing query-count,
      join-expression, and -Filter assertions unchanged.
      apps/server/src/server.test.ts (1)

      3723-3741: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

      Test correctly validates non-blocking behavior, but runs for ~5 seconds.

      Using Effect.never with TestClock.withLive means the test waits the full 5-second EDITOR_DISCOVERY_TIMEOUT in real time before the timeout fires and the fallback applies. This is functionally correct but adds ~5s to the test suite. If this becomes a concern, consider using a virtual TestClock with a shorter timeout override, or testing the timeout fallback at the loadServerConfig unit level rather than through the full WebSocket RPC.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@apps/server/src/server.test.ts` around lines 3723 - 3741, Shorten this test’s
      runtime while preserving validation that server.getConfig is not blocked by
      editor discovery. Replace the real-time five-second wait in the test around
      buildAppUnderTest and the WebSocket RPC with a virtual TestClock and a shorter
      editor-discovery timeout override, or move the timeout-fallback assertion to the
      loadServerConfig unit path rather than the full RPC flow.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Nitpick comments:
      In `@apps/server/src/diagnostics/ProcessDiagnostics.test.ts`:
      - Around line 223-257: Extend the “queries each Windows CIM class once” test
      around ProcessDiagnostics.readProcessRows to assert that the generated
      PowerShell script applies “-ErrorAction SilentlyContinue” to the
      Win32_PerfFormattedData_PerfProc_Process query. Keep the existing query-count,
      join-expression, and -Filter assertions unchanged.
      
      In `@apps/server/src/server.test.ts`:
      - Around line 3723-3741: Shorten this test’s runtime while preserving validation
      that server.getConfig is not blocked by editor discovery. Replace the real-time
      five-second wait in the test around buildAppUnderTest and the WebSocket RPC with
      a virtual TestClock and a shorter editor-discovery timeout override, or move the
      timeout-fallback assertion to the loadServerConfig unit path rather than the
      full RPC flow.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: d9466a82-f659-433c-9e74-3d47afb862ab

      📥 Commits

      Reviewing files that changed from the base of the PR and between c1ec1915fc16f3dc1ec5d47d9a97f6210a574526 and 9526c33f60f26f641c1082947ec119b208b4609b.

      📒 Files selected for processing (6)
      • apps/server/src/diagnostics/ProcessDiagnostics.test.ts
      • apps/server/src/diagnostics/ProcessDiagnostics.ts
      • apps/server/src/process/externalLauncher.test.ts
      • apps/server/src/process/externalLauncher.ts
      • apps/server/src/server.test.ts
      • apps/server/src/ws.ts
    5. Approvability

      Verdict: Approved

      Performance optimization for Windows diagnostics and editor discovery. Changes batch CIM queries, add concurrency, and include timeout fallbacks for resilience. Well-tested and self-contained with no new functionality.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Tested on Windows; see my comment on #3610 — #3911 helps but wasn’t enough until editor discovery was skipped.

    7. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ff0764b5053dba11e273df7c861177852d65d057. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -117,3 +117,14 @@
      117117 const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
      118118
      119119 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
      120+const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);
      121+const EDITOR_DISCOVERY_FALLBACK = [] as const;
      122+
      123+export const withEditorDiscoveryTimeout = <A, E, R>(
      124+ discovery: Effect.Effect<ReadonlyArray<A>, E, R>,
      125+ timeout: Duration.Input = EDITOR_DISCOVERY_TIMEOUT,
      126+) =>
      127+ discovery.pipe(
      128+ Effect.timeoutOption(timeout),
      129+ Effect.map(Option.getOrElse(() => EDITOR_DISCOVERY_FALLBACK)),
      130+ );
      cursor[bot](GitHub profile, opens in a new tab)commented

      Empty editors stick after timeout

      Medium Severity

      withEditorDiscoveryTimeout falls back to an empty availableEditors list on timeout, but subscribeServerConfig never emits a later editors update—live events only cover keybindings, providers, and settings. A one-time slow discovery therefore leaves Open-in-Editor empty for the rest of the session.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ff0764b5053dba11e273df7c861177852d65d057. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -270,12 +272,9 @@
      270- if (editor.commands === null) {
      271- const command = fileManagerCommandForPlatform(platform);
      272- if (yield* isCommandAvailable(command, { env })) {
      273- available.push(editor.id);
      274- }
      275- continue;
      276- }
      277-
      278- const command = yield* resolveAvailableCommand(editor.commands, env);
      279- if (Option.isSome(command)) {
      280- available.push(editor.id);
      281- }
      272+ if (platform === "win32") {
      273+ // Use the existing fast resolver: repeated asynchronous PATH scans exceeded five seconds on the reported machine.
      274+ const resolveExecutable = yield* SpawnExecutableResolution;
      275+ return EDITORS.flatMap((editor) => {
      276+ const commands = editor.commands ?? [fileManagerCommandForPlatform(platform)];
      277+ return commands.some((command) => resolveExecutable(command, platform, env) !== undefined)
      278+ ? [editor.id]
      279+ : [];
      280+ });
      cursor[bot](GitHub profile, opens in a new tab)commented

      Windows timeout cannot interrupt discovery

      Medium Severity

      Windows buildAvailableEditors resolves every editor with synchronous SpawnExecutableResolution PATH/statSync work inside a single flatMap, with no Effect yield points. withEditorDiscoveryTimeout therefore cannot fire while that work runs, so server.getConfig can still block past five seconds on the platform #3610 targets.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ff0764b5053dba11e273df7c861177852d65d057. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. SivanTechDev(GitHub profile, opens in a new tab)commented

      @juliusmarminge Thanks for updating the branch and taking the time to view this PR.

      The new findings are valid and match #3610 and some reports in #3746. The current Windows resolver improves editor detection, but its synchronous filesystem checks cannot be interrupted by the timeout. The empty fallback also remains for the config subscription.

      This PR should alleviate the connection problem, but it will not completely solve it. A full solution requires a broader asynchronous or deferred editor-discovery design.

      A simpler option is to keep only the original fix(server): bound editor discovery and optimize Windows diagnostics commit and omit the follow-up fix(server): discover external editors reliably commit. That version keeps the checks interruptible and the application working, but accepts that some weaker Windows PCs may discover no editors. This trades optional editor detection for a reliable and faster connection path.

    9. Closing as superseded by the focused fixes in #4291 for editor discovery and #2679 for Windows process diagnostics: https://github.com/pingdotgg/t3code/pull/4291 and https://github.com/pingdotgg/t3code/pull/2679

Sign in to join this conversation.