gui: a closed or hidden page lets its Sessions and Usage caches go in 30 s

What a visit to the app's page read stayed until each cache's own idle
timer fired: the Sessions stats after 2 minutes, the Requests chunks
trimmed at 2 and forgotten 5 after that, each chunk's derived keys at 3.
On a real history (acctp, requests-v1.bin 71.5 MB) a web page open 70 s
and closed held 123 MB at the close, 108 MB a minute on, 74-76 MB three
to five minutes on, and was back to the tray's 52 MB only at ten.

The page now says it has gone from view (POST /api/page-away, sent from
the visibilitychange listener every window already has, when hidden: a
browser fires it as a tab closes, and the Mac window's orderOut
dispatches it too). 30 s later (pageAwayFor), unless a Sessions or Usage read
was in flight or ended since, the stats, overviews and tags go
(letGoStats, split out of forgetIdleStats), the Requests chunks and each
chunk's derived caches go (usage.ForgetPages: trim(0) + dropDerived,
idle timers stopped) and the pages go back to the system. A second tab
still polling, or a tab looked away from for under 30 s, keeps them. The
beacon writes nothing, so held's provider.Changed passes it by. The panel
sends it as well when it hides; it reads no Sessions or Usage page, so
there is nothing of its own to keep.

Tests: TestPageAwayLetsStatsGo (red with the forget skipped, and red
when a read after the beacon is ignored, both broken by hand) and
TestForgetPagesLetsChunksGoAtOnce.

The core script budget goes up 83 bytes, with the reason in its
comment: the beacon is folded into the existing listener and packed to
its shortest form (335 over as first written, with a pagehide listener
and a panel check).

Measured on mote (pageclose2.sh, the acctp history, a web page open
70 s and closed, footprint-overlay build like the release):
  before (w88): close 123 MB, +60 s 108, +180 s 76, +300 s 74, +600 s 52;
                peak 154
  after  (w89): close 123 MB, +45 s 92, +90 s 90, +180 s 54, +600 s 53;
                peak 149, 3.08 s CPU over 11 min
  final (w90, visibilitychange only): close 122 MB, +45 s 93, +90 s 90,
                +180 s 55, +600 s 52; peak 152

Run: go test ./internal/gui ./internal/usage on mote (ok);
GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... (ok);
16 visibility GUI files + i18n-keys in chromium and webkit: red only in
routing-pin-away (the same subtest red alone at origin/main 4739ec92c,
This commit is contained in:
yetone
2026-11-14 17:00:00 +08:00
parent 09aa60d4ae
commit 80a315a70a
8 changed files with 194 additions and 6 deletions
+7 -1
View File
@@ -1209,6 +1209,12 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
pluginPageRoutes(mux, isWeb(w))
feedbackRoutes(mux)
appearanceRoutes(mux)
// the app's page closed or hidden: what its pages keep goes soon
// (awayPage); a write of nothing, so held's Changed passes it by
mux.HandleFunc("POST /api/page-away", func(rw http.ResponseWriter, r *http.Request) {
awayPage()
rw.WriteHeader(http.StatusNoContent)
})
// boot.js hands the page the saved language and theme before it paints:
// they came only with the settings, so the tabs showed English first
mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) {
@@ -3261,7 +3267,7 @@ func held(h http.Handler) http.Handler {
// 5x the CPU.
defer tightenGC()()
}
if !(api && r.Method == http.MethodGet) && r.URL.Path != "/api/update/using" {
if !(api && r.Method == http.MethodGet) && r.URL.Path != "/api/update/using" && r.URL.Path != "/api/page-away" {
// anything that may have written drops what was held, once it
// has answered with it (a page's word of input writes nothing)
defer provider.Changed()
+4 -1
View File
@@ -24310,7 +24310,10 @@ function loadBack() {
loadBack.flight = flight;
return flight.done;
}
document.addEventListener("visibilitychange", () => { if (!document.hidden) { loadBack(); wag(); refreshLanes(); } });
// and one gone from view, hidden or closed (which hides it first), says
// so: what its Sessions and Usage pages keep goes 30 s later unless a page
// asks again (pageAwayFor)
document.addEventListener("visibilitychange", () => { if (!document.hidden) { loadBack(); wag(); refreshLanes(); } else fetch("/api/page-away", { method: "POST", keepalive: true }).catch(() => {}); });
// an agent's config can be rewritten, or the agent run round magpie, while the
// window is up: ask what drifted now and then, and redraw only on a change —
// never under an open menu
+1 -1
View File
@@ -18,7 +18,7 @@ import (
// `git log -L` of this file.
const (
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
coreScriptBudget = 1_269_929 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it
coreScriptBudget = 1_270_012 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to
)
// codeBytes is how many bytes of b are code: its blank lines, its lines
+48
View File
@@ -86,3 +86,51 @@ func releaseIfPagesRest() {
}
debug.FreeOSMemory()
}
// pageAwayFor is how long after the app's page says it has gone away
// (closed, or its window or tab hidden: /api/page-away) what its Sessions
// and Usage pages keep goes, unless a page asked for them meanwhile. The
// idle timers each page's caches have (statsIdle, requestIdle, then
// requestForget, derivedIdle) took 5 to 10 minutes between them: a real
// history's window closed after a minute held 123 MB, 76 MB three minutes
// later, and was back to the tray's 52 MB only after ten. A tab looked away
// from for less than this keeps them, and so does a second one still open.
var pageAwayFor = 30 * time.Second
var pageAway struct {
sync.Mutex
t *time.Timer
at time.Time
}
// awayPage arms forgetAwayPage for pageAwayFor from now.
func awayPage() {
pageAway.Lock()
defer pageAway.Unlock()
pageAway.at = time.Now()
if pageAway.t != nil {
pageAway.t.Reset(pageAwayFor)
return
}
pageAway.t = time.AfterFunc(pageAwayFor, forgetAwayPage)
}
// forgetAwayPage lets go of the Sessions and Usage pages' caches when no
// read of theirs has been in flight, or ended, since the page went away.
func forgetAwayPage() {
pageAway.Lock()
at := pageAway.at
pageAway.t = nil
pageAway.Unlock()
pageReads.Lock()
asked := pageReads.n != 0 || pageReads.last.After(at)
pageReads.Unlock()
if asked {
return
}
stats := letGoStats()
if usage.ForgetPages() || stats {
usage.ReleaseScratch()
debug.FreeOSMemory()
}
}
+46
View File
@@ -101,3 +101,49 @@ func TestHeldCountsPageReads(t *testing.T) {
}
}
}
// The app's page gone away (closed or hidden) has the Sessions page's
// stats let go pageAwayFor later, not the minutes the idle timers take;
// a page read since it went away keeps them.
func TestPageAwayLetsStatsGo(t *testing.T) {
forgetStats()
t.Cleanup(forgetStats)
old := pageAwayFor
pageAwayFor = 20 * time.Millisecond
t.Cleanup(func() {
pageAway.Lock()
if pageAway.t != nil {
pageAway.t.Stop()
pageAway.t = nil
}
pageAway.Unlock()
pageAwayFor = old
pageReads.Lock()
if pageReads.due != nil {
pageReads.due.Stop()
pageReads.due = nil
}
pageReads.Unlock()
})
kept := func() bool {
statsMemo.Lock()
defer statsMemo.Unlock()
return statsMemo.m[0] != nil
}
// read again after it went away: kept
statsFor(0)
awayPage()
readingPage()()
time.Sleep(100 * time.Millisecond)
if !kept() {
t.Fatal("stats let go though a page read them after it went away")
}
awayPage()
for deadline := time.Now().Add(10 * time.Second); kept(); time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("stats still kept after the page went away")
}
}
}
+12 -3
View File
@@ -858,12 +858,21 @@ func keepStatsWhileAsked() {
// hands the pages back to the system at once; a range being read again
// puts it off.
func forgetIdleStats() {
if !letGoStats() {
keepStatsWhileAsked()
return
}
debug.FreeOSMemory()
}
// letGoStats is forgetIdleStats' letting go, which a range being read
// puts off: it says whether they went.
func letGoStats() bool {
statsMemo.Lock()
for _, k := range statsMemo.m {
if k.busy {
statsMemo.Unlock()
keepStatsWhileAsked()
return
return false
}
}
statsMemo.m = nil
@@ -875,7 +884,7 @@ func forgetIdleStats() {
statsTags.m = nil
statsTags.Unlock()
sessions.ForgetKeptRanges()
debug.FreeOSMemory()
return true
}
func combinedSessionStats(days int) sessions.Stats {
+52
View File
@@ -584,3 +584,55 @@ func TestRequestTrimGivesBackTheMap(t *testing.T) {
idx.chunks["/s/kept"] = c // the map is usable after
runtime.KeepAlive(keys)
}
// ForgetPages lets the chunks go at once, the idle timers an hour off,
// and stops them; the next ask reads them back.
func TestForgetPagesLetsChunksGoAtOnce(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
oldIdle, oldForget := requestIdle, requestForget
t.Cleanup(func() {
requestCache.Lock()
requestIdle, requestForget = oldIdle, oldForget
requestCache.Unlock()
})
cacheBudget(t, 1<<30)
requestCache.Lock()
requestIdle, requestForget = time.Hour, time.Hour
requestCache.Unlock()
dir := filepath.Join(sessions.CodexDir(), "sessions")
os.MkdirAll(dir, 0700)
for i := range 3 {
meta := fmt.Sprintf(`{"type":"session_meta","payload":{"id":"s%d","model_provider":"custom"}}`, i) + "\n" + `{"type":"turn_context","payload":{"model":"m"}}` + "\n"
line := fmt.Sprintf(`{"timestamp":%q,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":10,"output_tokens":1},"last_token_usage":{"input_tokens":10,"output_tokens":1}}}}`+"\n", now.Add(-time.Duration(i)*time.Minute).Format(time.RFC3339Nano))
os.WriteFile(filepath.Join(dir, fmt.Sprintf("rollout-2026-09-30T00-00-0%d-s%d.jsonl", i, i)), []byte(meta+line), 0600)
}
ask := func() {
if p := QueryPage(All, Filter{}, 0, 100); p.Total != 3 {
t.Fatalf("total %d, want 3", p.Total)
}
}
ask()
requestCache.Lock()
had, armed := len(requestCache.chunks), requestCache.idle != nil
requestCache.Unlock()
if had != 3 || !armed {
t.Fatalf("after an ask: %d chunks, idle timer armed %v; want 3, true", had, armed)
}
if !ForgetPages() {
t.Fatal("ForgetPages says nothing went")
}
requestCache.Lock()
left, idle := len(requestCache.chunks), requestCache.idle
requestCache.Unlock()
if left != 0 || idle != nil {
t.Fatalf("after ForgetPages: %d chunks, idle timer %v; want 0, nil", left, idle)
}
ask() // read back from the file of them, the idle timer armed again
requestCache.Lock()
armed = requestCache.idle != nil
requestCache.Unlock()
if !armed {
t.Fatal("an ask after ForgetPages armed no idle timer")
}
}
+24
View File
@@ -122,3 +122,27 @@ func dropEffortPeriods() int {
}
return n
}
// ForgetPages lets go at once of what the Requests page and its heatmap
// keep for their next ask: the chunks (as requestForget does) and what is
// kept of each by its serial (as derivedIdle does). The app calls it once
// its page has gone away, closed or hidden, so that what a visit read
// goes in seconds, not the 7 minutes the idle timers take; the next visit
// reads the chunks back from the file of them. Says whether anything went.
func ForgetPages() bool {
idx := &requestCache
idx.Lock()
n := len(idx.chunks)
if idx.idle != nil {
idx.idle.Stop()
idx.idle = nil
}
if idx.forget != nil {
idx.forget.Stop()
idx.forget = nil
}
idx.trim(0)
idx.Unlock()
n += dropDerived()
return n > 0
}