plugins-workspace icon indicating copy to clipboard operation
plugins-workspace copied to clipboard

single-instance: Windows secondary should grant foreground rights to the primary before notifying it

Open PathGao opened this issue 3 months ago • 9 comments

Summary

On Windows, the secondary instance hands argv/cwd to the primary and exits without granting it the right to set the foreground window. The primary's SetForegroundWindow is therefore refused, and applications fall back on the toolkit's focus hack — which synthesizes keyboard input — to come to the front.

One call to AllowSetForegroundWindow in the secondary, before the WM_COPYDATA, removes the need for that fallback and restores the OS's own handling of "the user changed their mind".

Current behaviour (2.4.3)

src/platform_impl/windows.rs, secondary branch:

let hwnd = FindWindowW(class_name.as_ptr(), window_name.as_ptr());   // L74
if !hwnd.is_null() {
    // … pack cwd|argv into COPYDATASTRUCT …
    SendMessageW(hwnd, WM_COPYDATA, 0, &cds as *const _ as _);       // L91
    app.cleanup_before_exit();
    std::process::exit(0);                                           // L94
}

The launching shell transfers foreground rights to the secondary, since that is the process it started. The process that has to raise a window is the primary, which has usually been in the background for some time. Measured against the primary, none of the documented conditions for SetForegroundWindow hold — it is not the foreground process, it was not started by the foreground process, and it did not receive the last input event. The call is refused, and per the same page Windows flashes the taskbar button instead.

What that costs applications

The natural thing for a callback to do is window.set_focus(). In tao 0.35.3 that reaches force_window_active, which calls SetForegroundWindow and, when the OS refuses, synthesizes an Alt keypress through SendInput to fake recent user input, then retries. tao's own comment scopes the hack to window creation — "We only call this function in the window creation, so it should be fine" — but the single-instance path invokes it much later, from a process that has been idle.

Two consequences:

  1. The synthesized Alt is delivered to whatever window is currently foreground, which is the user's, not the application's. A lone Alt press activates the menu bar in most Windows applications.
  2. It activates unconditionally. If the user double-clicked a file and then switched away while the handoff was still in flight, the application takes focus back regardless.

Proposed change

In the secondary branch, between FindWindowW and SendMessageW:

let mut pid = 0u32;
GetWindowThreadProcessId(hwnd, &mut pid);
if pid != 0 {
    AllowSetForegroundWindow(pid);
}

Both symbols live in Win32::UI::WindowsAndMessaging, already enabled in the crate's windows-sys features — no new dependency and no new feature flag.

Why this does not add a focus-stealing vector

AllowSetForegroundWindow grants a right the OS revokes on its own:

The process specified by the dwProcessId parameter loses the ability to set the foreground window the next time that either the user generates input, unless the input is directed at that process […]

That fixes consequence (2) for free: if the user moves on during the handoff, the grant lapses, the primary's SetForegroundWindow fails, and Windows flashes the taskbar button — which is what the user's action now implies. The plugin does not have to make that judgement itself, and callback policy is unchanged: an application that calls set_focus() makes the same call, it simply succeeds through the documented path when it should and fails when it should.

Prior art

  • Chromium, chrome/browser/win/chrome_process_finder.cc, inside AttemptToNotifyRunningChrome, immediately before the WM_COPYDATA send: ::AllowSetForegroundWindow(process_id);, commented "Allow the current running browser window to make itself the foreground window (otherwise it will just flash in the taskbar)."
  • VS Code, src/vs/code/electron-main/main.ts, windowsAllowSetForegroundWindow(), called from claimInstance before the second instance exits. Electron does not do this on an application's behalf, so VS Code ships a native module (windows-foreground-love) for this single call.

Scope

  • Windows only. macOS lets any application activate itself, and the X11/Wayland path is timestamp-based; neither has a right that disappears when the notifying process exits.
  • No change to the public callback signature, or to what an application decides to do on notification.
  • Independent of #3495 and #3542, which concern ownership and delivery races. This concerns what the secondary owes the primary once delivery is happening at all, and applies to whichever branch ends up sending the notification.

Willing to submit a PR

Happy to open one against plugins/single-instance with the change above, if the direction is agreeable.

Environment

  • tauri-plugin-single-instance 2.4.3
  • tao 0.35.3, for the fallback behaviour described above
  • Windows

PathGao avatar Aug 22 '26 15:08 PathGao

I'm not sure I get what you mean, could you explain it without the LLM?

Legend-Master avatar Sep 17 '26 08:09 Legend-Master

Sorry, that was too long. Here's the plain version.

Setup: the app is already running. The user double-clicks a file, so Windows starts a second instance.

Explorer (foreground)
   | launches
   v
second instance --WM_COPYDATA--> first instance (in background for a while)
   | gets the right to come to front     | callback calls set_focus()
   | then exits                          v
   x the right dies with it          SetForegroundWindow -> refused by Windows
                                         |
                                         v
                              tao fallback: fake an Alt key press, retry

Windows only lets the foreground process (or one it allows) bring a window to the front. The second instance has that right, but it exits without passing it on. The first instance doesn't have it, so it gets refused.

tao's fallback fakes an Alt key press. Two problems with that:

  1. The Alt goes to whatever window the user is in, and can open that window's menu bar.
  2. If the user already switched to another app after double-clicking, the app still steals focus back.

Fix: before sending WM_COPYDATA, the second instance calls AllowSetForegroundWindow(pid of the first instance). One line. It passes the right to the first instance. If the user clicks or types somewhere else in the meantime, Windows takes the right back on its own, so there's no new way to steal focus.

Chromium does exactly this in chrome_process_finder.cc, and VS Code does it too (windowsAllowSetForegroundWindow in main.ts).

PathGao avatar Sep 17 '26 09:09 PathGao

I still don't get what you really mean, instead of talking about SetForegroundWindow, could you just explain what you're trying to do, and what behavior is different from your expectations?

Legend-Master avatar Sep 17 '26 09:09 Legend-Master

Fair. What I expect as a user:

Markpad is already open. I double-click a .md file, then immediately switch to another app. I expect Markpad to flash in the taskbar, not jump in front of the app I switched to.

From reading the code, it will jump in front anyway, because tao's set_focus forces it.

PathGao avatar Sep 17 '26 09:09 PathGao

I think it really just depends on what you're doing when your first instance gets the signal from the second instance no?

Legend-Master avatar Sep 17 '26 09:09 Legend-Master

Yes, the plugin doesn't focus anything, the callback does. The problem is that on Windows the callback only has two options, and neither is right:

  1. Call set_focus(): the window always comes to front, even if the user already switched away (tao forces it).
  2. Don't force it: Windows refuses, so the window only flashes in the taskbar, even when the user is waiting for it.

Chrome and VS Code get the behavior in between: come to front if the user is still waiting, flash if they moved on. For that, the second instance has to hand over the right before it exits. Only the plugin runs in the second instance, so the app can't do this from the callback.

PathGao avatar Sep 17 '26 09:09 PathGao

Same thing as a table:

User still waiting for the window User already switched away
Callback calls set_focus() Comes to front ✅ Comes to front anyway ❌ (tao forces it)
Callback doesn't force it Only flashes in taskbar ❌ Only flashes in taskbar ✅
Chrome / VS Code Comes to front ✅ Only flashes in taskbar ✅

PathGao avatar Sep 17 '26 09:09 PathGao

I think I get it now, thanks for explaining, feel free to open a PR for this.

Legend-Master avatar Sep 17 '26 09:09 Legend-Master

PR is opened。thanks

PathGao avatar Sep 17 '26 09:09 PathGao