Files
magpie/internal/gui/memtarget_windows.go
T
yetone d159314e35 gui: a hidden window's WebView2 goes on its low memory target on Windows
molamaker11 on X: "magpie后台占用快接近600MB了。win端 这个能优化一下吗。比如剔除一些动画".

Cause. On Windows the tray panel and the main window are both made at
start and only hidden when closed, so two WebView2 renderers, the GPU
process and the browser process stay up in the tray. They were kept at
WebView2's normal memory target, so a hidden window held what it last
drew: after the window had been open, the GPU process kept ~85 MB and the
main renderer ~70 MB. Animations are not the cost: hidden pages run no
layout or style (LayoutCount/RecalcStyleCount 0 over CDP), the JS heaps
are 5 to 8 MB each, and the Go process is ~40 MB private (liveHeap 25 MB).

Fix. lowWhileHidden (memtarget_windows.go) sets
ICoreWebView2_19::put_MemoryUsageTargetLevel to LOW on each hide and on a
page that comes while the window is hidden (both windows are made hidden,
and get no hide), and back to NORMAL on each show. The page stays loaded
and running, unlike lightweight mode, whose default the owner turned off
on 10-21 because reopening reloaded the page. The vtable slot is 120:
ICoreWebView2_19's vtable holds every inherited method, counted in
WebView2.h of SDK 1.0.2210.55 (a first build that used slot 4 called
get_Source and crashed at start). zoom_windows_arm64.go's reflection walk
to the controller is now chromiumPart, shared with it. macOS and Linux:
WKWebView and WebKitGTK have no memory target magpie can set, so
memtarget_other.go is a no-op.

Numbers. xiaomi-gpu, Windows 11, WebView2 156.0.4314.50, a release build
of each (-tags production,comlauncher -H windowsgui) in its own sandbox
profile with the same seeded sessions and usage (~248 MB of Claude
projects, 72 Codex rollouts, a 4.2 MB usage.jsonl), tray start. The whole
process tree (magpie plus msedgewebview2), private working set (Task
Manager's Memory column) / commit, MB:

                                       v0.1.2297     this change
  fresh tray, window never opened      205-209/316-332   81/323
  window open, every page clicked      304/482          236/467
  1 min after closing it               265/479           69/459
  5 min after closing it               ~203/~476         64/453
  idle 15-30 min later (sampled /5min) 200-214/474-481   -

  1 min after closing, by process: GPU 85 -> 2.6, main renderer 70 ->
  7.3, panel renderer ~50 -> 1.3, browser ~30 -> 6.2; magpie itself
  ~47 either way.

The commit charge barely moves: WebView2 trims the pages out of RAM to
the standby list and the page file rather than freeing them, so the
saving is RAM other apps get, not address space.

Reopening. Three trials, each window closed 3 to 5 minutes first, the
time for a view switch and two frames over CDP: the first trial took
901 ms on the first switch after reopening (v0.1.2297: 47 ms), then
12 to 31 ms; the other two trials were the same on both builds (first
frame 132 vs 131 ms, first switch 28 vs 30 ms, then 9 to 46 ms either
way).

Run: gofmt -l internal/gui (clean); on mote GOOS=windows go vet ./...,
GOOS=windows GOARCH=arm64 go vet ./internal/gui, GOOS=linux go vet -tags
nogui ./..., go vet ./..., go build; go test -timeout 45m ./... on this
tree (057c21b30, this commit with a draft message, on 91ffe5429): 80 packages ok, internal/gui and
internal/proc red. proc: TestNoCommandBypassesProc on
internal/claudetui/child_unix.go (c59c547c5, #4491). gui: ten AppKit
tests killed at their 30s bar on mote (#4125; TestDockJoinLeadsCommandTab,
TestPanelCloseHidesIt, TestCoveredWindowStaysUp and TestMainWindowCorners
red the same at 91ffe5429 alone) and TestSettingsSaveKeepsWhatItDoesNotSend
(#4514, red at 91ffe5429 too). This change adds no code to darwin; win-run go test ./internal/gui at this head: 6 red, the
same 6 at its parent 91ffe5429 run alone (TestGatewayHeldByAContainer,
#2107/#4115; TestLodyImportHandoff, TestImportStatusUnreadableIsUnknown,
TestAionUiImportRow, TestUpdateThatWontStart, #4115;
TestSettingsSaveKeepsWhatItDoesNotSend, #4514).

Not tried: a real user's profile with plugins (no bun/node host ran in
the sandbox) or signed-in accounts; an idle of many hours on the fix
build (#2515's 28h growth); Windows on arm64 (built and vetted, not run);
a WebView2 older than 1.0.2210, which answers E_NOINTERFACE and is
logged and left alone. No unit test: the call needs a live WebView2; it was checked on the box
by the numbers above. No GUI suite: app.js is unchanged.
2026-10-31 10:57:56 +08:00

122 lines
4.4 KiB
Go

//go:build windows && !nogui
package gui
import (
"fmt"
"log"
"reflect"
"syscall"
"unsafe"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
"golang.org/x/sys/windows"
)
// A closed window on Windows is hidden, its WebView2 kept: the tray panel
// and the main window both stay loaded, so each opens at once. Kept at
// WebView2's normal memory target, a hidden one held what it last drew:
// the GPU process's tiles and the renderer's caches, ~100 MB more after
// the window had been open than before (molamaker11 on X: "后台占用快接近
// 600MB"). lowWhileHidden puts a window's WebView2 on the low memory
// target while it is hidden, the level Microsoft gives for a webview out
// of sight (ICoreWebView2_19::put_MemoryUsageTargetLevel), and back on
// normal as it is shown. The page stays loaded and running, unlike
// lightweight mode, which lets the webview go.
// lowWhileHidden sets w's memory target on each hide and show, and on the
// low one once its first page has come while it is still hidden (a window
// made hidden, as both are at the start, is never sent a hide).
func lowWhileHidden(w *application.WebviewWindow) {
set := func(low bool) {
application.InvokeAsync(func() {
if low && w.IsVisible() {
return // shown again meanwhile
}
if err := memoryTarget(w, low); err != nil {
log.Printf("webview memory target (%s window): %v", w.Name(), err)
}
})
}
w.OnWindowEvent(events.Windows.WindowHide, func(*application.WindowEvent) { set(true) })
w.OnWindowEvent(events.Windows.WindowShow, func(*application.WindowEvent) { set(false) })
w.OnWindowEvent(events.Windows.WebViewNavigationCompleted, func(*application.WindowEvent) { set(true) })
}
// WebView2's COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL values.
const (
memoryTargetNormal = 0
memoryTargetLow = 1
)
// iidCoreWebView2_19 is ICoreWebView2_19's interface id (WebView2.h).
var iidCoreWebView2_19 = windows.GUID{Data1: 0x6921f954, Data2: 0x79b0, Data3: 0x437f,
Data4: [8]byte{0xa9, 0x97, 0xc8, 0x58, 0x11, 0x89, 0x7c, 0x68}}
// memoryTarget puts w's WebView2 on the low memory target, or back on the
// normal one; on the main thread. A runtime older than ICoreWebView2_19
// (WebView2 1.0.2210) answers E_NOINTERFACE, and nothing changes.
func memoryTarget(w *application.WebviewWindow, low bool) error {
wv := chromiumPart(w, "webview")
if wv == nil {
return nil // no webview yet: its page's coming sets it
}
// Slots in ICoreWebView2_19Vtbl, which holds every method it inherits:
// IUnknown's three, then ICoreWebView2 to _18's, then
// get_MemoryUsageTargetLevel (119) and put_MemoryUsageTargetLevel (120),
// counted in WebView2.h of SDK 1.0.2210.55.
const queryInterface, release, putLevel = 0, 2, 120
var wv19 unsafe.Pointer
if hr, _, _ := syscall.SyscallN(comMethod(wv, queryInterface), uintptr(wv),
uintptr(unsafe.Pointer(&iidCoreWebView2_19)), uintptr(unsafe.Pointer(&wv19))); int32(hr) < 0 || wv19 == nil {
return fmt.Errorf("ICoreWebView2_19: %w", windows.Errno(hr))
}
defer syscall.SyscallN(comMethod(wv19, release), uintptr(wv19))
level := uintptr(memoryTargetNormal)
if low {
level = memoryTargetLow
}
if hr, _, _ := syscall.SyscallN(comMethod(wv19, putLevel), uintptr(wv19), level); int32(hr) < 0 {
return fmt.Errorf("put_MemoryUsageTargetLevel(%d): %w", level, windows.Errno(hr))
}
return nil
}
// comMethod is the slot'th method of the COM object at p's vtable.
func comMethod(p unsafe.Pointer, slot uintptr) uintptr {
vtbl := *(*unsafe.Pointer)(p)
return *(*uintptr)(unsafe.Add(vtbl, slot*unsafe.Sizeof(uintptr(0))))
}
// chromiumPart is one of the COM objects Wails' edge.Chromium holds for
// w ("controller", "webview"), nil before WebView2 has made it. Wails
// keeps them unexported: WebviewWindow.impl, a *windowsWebviewWindow,
// holds chromium, an *edge.Chromium (Wails v3.0.0-beta.24). A Wails
// without that path gives nil.
func chromiumPart(w *application.WebviewWindow, part string) unsafe.Pointer {
if w == nil {
return nil
}
v := reflect.ValueOf(w).Elem()
for _, name := range []string{"impl", "chromium", part} {
if v.Kind() != reflect.Struct {
return nil
}
v = v.FieldByName(name)
for v.IsValid() && v.Kind() == reflect.Interface {
if v.IsNil() {
return nil
}
v = v.Elem()
}
if !v.IsValid() || v.Kind() != reflect.Pointer || v.IsNil() {
return nil
}
if name != part {
v = v.Elem()
}
}
return v.UnsafePointer()
}