gui: a WebView2 that doesn't come up waits for the old profile lock, then starts again (@ljlwlcz on X)

0.1.3688 on Windows 11: after a restart by a script, "timed out after 1m0s
waiting for the WebView2 controller" and the window never came back. Wails
waits 60s in Embed for a controller, then exits the process (ErrorHandler
runs, then os.Exit). The cause is a start that meets the previous magpie's
msedgewebview2 still holding the profile folder (EBWebView\lockfile, opened
without sharing).

- Before the first window, the start waits (30s at most) until the profile
  folder's lockfile can be opened, i.e. the old WebView2 has let go. The
  folder is the one passed to Wails, else Wails' %AppData%\<exe name>.
- ErrorHandler now logs the error with the WebView2 runtime version, the
  folder and whether another process holds it.
- On a WebView2 failure the process starts itself again (update.Respawn,
  MAGPIE_REPLACES set so the new one waits for this one to exit), backing
  off 2s, 4s; after 3 starts a box says what failed and what to do.

Run: gofmt; go vet darwin, GOOS=windows, GOOS=linux with and without
nogui; go test of the WebView2 tests on mote; the same on xiaomi-gpu via
win-run, where TestWebView2FreeSeesTheHeldLockfile holds a real
non-shared file and goes red when webView2Free is forced true (broken by
hand). Full gui/update/proc packages on mote.
Not tried: a real WebView2 timeout and the restart (the controller
timeout can't be forced here without the live app); Wails still exits
the process after the handler, so the tray does not stay up through a
failed start, it is started again instead.
This commit is contained in:
yetone
2026-11-11 22:58:27 +08:00
parent 5a475f90c3
commit fb6b4de0a9
7 changed files with 263 additions and 2 deletions
+2 -1
View File
@@ -422,6 +422,7 @@ func Run(version string, showMain bool, link string) error {
// a quiet start joins the Dock once started (below): Wails activates
// an app that starts in it
policy := dockPolicy(settings.Load().Dock && !quiet)
webView2Prepare()
h.app = application.New(application.Options{
// Windows and Linux start a new process for a magpie:// link (or a
// second launch); it hands its arguments to the running one and quits.
@@ -472,7 +473,7 @@ func Run(version string, showMain bool, link string) error {
updates.install(false)
},
// Wails exits on some webview errors; say why before it does.
ErrorHandler: func(err error) { log.Println("magpie:", err) },
ErrorHandler: func(err error) { webView2Failed(h.app, err) },
})
// Windows without the WebView2 runtime can make no window: Wails would
// exit on the first, with nothing on screen to say why (#1806). The
+80
View File
@@ -2,8 +2,11 @@ package gui
import (
"fmt"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
)
// magpie's windows are WebView2 on Windows, a runtime Windows 10 doesn't
@@ -127,3 +130,80 @@ func splitArgs(s string) []string {
}
return out
}
// WebView2 that does not come up. A magpie started while the one before it
// is still going down finds the profile folder held by the old
// msedgewebview2, and Wails waits a minute for a controller that never
// arrives, then exits (@ljlwlcz on X, 0.1.3688: a restart by a script left
// no window). Two things answer it: the start waits for the folder to be
// free, and a start that still fails is tried again, a few times.
// webView2TryEnv counts the starts that ended in a WebView2 failure; each
// relaunch passes it on.
const webView2TryEnv = "MAGPIE_WV2_TRY"
// webView2Tries is how many starts are made before the failure is shown.
const webView2Tries = 3
// webView2Folder is the folder WebView2 keeps its profile in: the one magpie
// passes Wails (webViewUserDataPath), else Wails' own default,
// %AppData%\<exe name>.
func webView2Folder(userDataPath, appData, exe string) string {
if userDataPath != "" {
return userDataPath
}
if appData == "" || exe == "" {
return ""
}
return filepath.Join(appData, filepath.Base(exe))
}
// webView2Failure says whether err is the webview not coming up, the
// errors Wails' Embed reports: the controller timeout and the loader's.
func webView2Failure(err error) bool {
if err == nil {
return false
}
m := strings.ToLower(err.Error())
return strings.Contains(m, "webview2")
}
// webView2Try is the number of starts already made, from the env value.
func webView2Try(v string) int {
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
return 0
}
return n
}
// webView2Backoff is how long a start waits before the n-th try (n >= 1).
func webView2Backoff(n int) time.Duration {
return time.Duration(n) * 2 * time.Second
}
// awaitWebView2Folder polls free until it says so or max passes, and says
// whether it was free. sleep is a var for tests.
func awaitWebView2Folder(free func() bool, max, step time.Duration, sleep func(time.Duration)) bool {
for waited := time.Duration(0); ; waited += step {
if free() {
return true
}
if waited >= max {
return false
}
sleep(step)
}
}
// webView2FailedNotice is the box shown when the webview would not start
// after every try: what failed and what to do, in lang (English where it
// has none of its own).
func webView2FailedNotice(lang, reason, version string) (title, body string) {
if strings.HasPrefix(lang, "zh") {
return "magpie 的窗口没能打开",
fmt.Sprintf("WebView2 在 %d 次启动里都没有就绪(运行时 %s)。\r\n\r\n%s\r\n\r\n请结束残留的 msedgewebview2.exe 后重新打开 magpie;也可以用 \"magpie web\" 在浏览器里打开。详情见 magpie 的日志。", webView2Tries, version, reason)
}
return "magpie's window didn't open",
fmt.Sprintf("WebView2 was not ready in %d starts (runtime %s).\r\n\r\n%s\r\n\r\nEnd any leftover msedgewebview2.exe and open magpie again, or use \"magpie web\" in your browser. The details are in magpie's log.", webView2Tries, version, reason)
}
@@ -0,0 +1,35 @@
//go:build windows && !nogui
package gui
import (
"os"
"path/filepath"
"testing"
"golang.org/x/sys/windows"
)
// Chromium holds EBWebView\lockfile without sharing while its browser
// process runs; the start waits on it (@ljlwlcz on X).
func TestWebView2FreeSeesTheHeldLockfile(t *testing.T) {
dir := t.TempDir()
if !webView2Free(dir) {
t.Fatal("no lockfile is free")
}
lock := filepath.Join(dir, "EBWebView", "lockfile")
if err := os.MkdirAll(filepath.Dir(lock), 0o755); err != nil {
t.Fatal(err)
}
h, err := windows.CreateFile(windows.StringToUTF16Ptr(lock), windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
t.Fatal(err)
}
if webView2Free(dir) {
t.Fatal("a lockfile held without sharing is free")
}
windows.CloseHandle(h)
if !webView2Free(dir) {
t.Fatal("a released lockfile is held")
}
}
+11 -1
View File
@@ -2,7 +2,17 @@
package gui
import "github.com/wailsapp/wails/v3/pkg/application"
import (
"log"
"github.com/wailsapp/wails/v3/pkg/application"
)
// webView2Check: only Windows' windows are WebView2.
func webView2Check(*application.App) bool { return true }
// webView2Prepare: only Windows' windows are WebView2.
func webView2Prepare() {}
// webView2Failed: Wails exits after this on every OS; say why.
func webView2Failed(_ *application.App, err error) { log.Println("magpie:", err) }
+45
View File
@@ -1,8 +1,10 @@
package gui
import (
"errors"
"strings"
"testing"
"time"
)
// #1806 (ufec): Wails' "WebView2" is "" when its lookup fails, the version
@@ -55,3 +57,46 @@ func TestWebView2Notice(t *testing.T) {
t.Errorf("pt: %q, want English", title)
}
}
func TestWebView2Folder(t *testing.T) {
if got := webView2Folder(`D:\p\webview2`, `C:\A`, `C:\x\magpie.exe`); got != `D:\p\webview2` {
t.Fatal(got)
}
if got := webView2Folder("", "", "magpie.exe"); got != "" {
t.Fatal(got)
}
}
func TestWebView2Failure(t *testing.T) {
for err, want := range map[error]bool{
errors.New("timed out after 1m0s waiting for the WebView2 controller; x"): true,
errors.New("error calling Webview2Loader: boom"): true,
errors.New("something else"): false,
nil: false,
} {
if got := webView2Failure(err); got != want {
t.Errorf("%v: %t", err, got)
}
}
}
func TestWebView2Try(t *testing.T) {
if webView2Try("") != 0 || webView2Try("2") != 2 || webView2Try("-1") != 0 || webView2Try("x") != 0 {
t.Fatal("try")
}
}
// the start waits for the folder to be let go, and gives up after max
func TestAwaitWebView2Folder(t *testing.T) {
n := 0
var slept time.Duration
free := func() bool { n++; return n > 3 }
sleep := func(d time.Duration) { slept += d }
if !awaitWebView2Folder(free, time.Second, 100*time.Millisecond, sleep) || slept != 300*time.Millisecond {
t.Fatal(n, slept)
}
slept = 0
if awaitWebView2Folder(func() bool { return false }, time.Second, 100*time.Millisecond, sleep) || slept != time.Second {
t.Fatal(slept)
}
}
+77
View File
@@ -3,11 +3,18 @@
package gui
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"time"
"unsafe"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
"golang.org/x/sys/windows"
)
@@ -50,3 +57,73 @@ func webView2Box(title, body string) int {
webView2BoxStyle)
return int(r)
}
// webView2Dir is the profile folder WebView2 will use.
func webView2Dir() string {
exe, _ := os.Executable()
return webView2Folder(appdir.WebView(), os.Getenv("AppData"), exe)
}
// webView2Free says whether no other process holds the profile folder.
// Chromium keeps EBWebView\lockfile open without sharing while its browser
// process runs, so opening it fails with a sharing violation until the
// previous magpie's msedgewebview2 has gone.
func webView2Free(dir string) bool {
if dir == "" {
return true
}
f, err := os.OpenFile(filepath.Join(dir, "EBWebView", "lockfile"), os.O_RDWR, 0)
if err != nil {
return !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED)
}
f.Close()
return true
}
// webView2Prepare runs before the first window. A start after a failed
// one backs off first; then it waits, up to 30s, for the previous
// process' WebView2 to let go of the profile folder.
func webView2Prepare() {
try := webView2Try(os.Getenv(webView2TryEnv))
if try > 0 {
log.Printf("magpie: WebView2 start %d of %d, after a failure", try+1, webView2Tries)
time.Sleep(webView2Backoff(try))
}
dir := webView2Dir()
start := time.Now()
if !awaitWebView2Folder(func() bool { return webView2Free(dir) }, 30*time.Second, 250*time.Millisecond, time.Sleep) {
log.Printf("magpie: WebView2 folder %s is still held by another process after 30s; going on", dir)
} else if d := time.Since(start); d > time.Second {
log.Printf("magpie: waited %s for WebView2 folder %s to be free", d.Round(100*time.Millisecond), dir)
}
}
// webView2Failed is Wails' ErrorHandler; Wails exits as soon as it
// returns. It logs the error with what is needed to read it, and for a
// WebView2 failure starts magpie again (up to webView2Tries starts), the
// last failure shown in a box with the log's place.
func webView2Failed(app *application.App, err error) {
dir := webView2Dir()
ver := "unknown"
if app != nil {
ver = fmt.Sprint(app.Env.Info().PlatformInfo["WebView2"])
}
log.Printf("magpie: %v (WebView2 runtime %q, profile folder %s, held by another process: %t)", err, ver, dir, !webView2Free(dir))
if !webView2Failure(err) {
return
}
try := webView2Try(os.Getenv(webView2TryEnv)) + 1
if try < webView2Tries {
log.Printf("magpie: starting again (start %d of %d)", try+1, webView2Tries)
if rerr := update.Respawn(fmt.Sprintf("%s=%d", webView2TryEnv, try)); rerr != nil {
log.Println("magpie: starting again:", rerr)
} else {
return
}
}
title, body := webView2FailedNotice(trayLang(settings.Load().Lang, systemLang), err.Error(), ver)
procMessageBoxW.Call(0,
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(body))),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(title))),
mbIconError|mbSetForeground|mbTopmost)
}
+13
View File
@@ -216,3 +216,16 @@ func ReadBlocked(current string) *Blocked {
// ClearBlocked forgets the note: the version started after all.
func ClearBlocked() { os.Remove(blockedFile()) }
// Respawn starts this program again with the arguments it was started
// with and extra (NAME=value) added to its environment, detached. The new
// process waits for this one to exit, as a relaunch does (AwaitPredecessor).
func Respawn(extra ...string) error {
exe, err := os.Executable()
if err != nil {
return err
}
env := append(os.Environ(), "MAGPIE_REPLACES="+strconv.Itoa(os.Getpid()))
_, _, err = launch(exe, os.Args[1:], append(env, extra...))
return err
}