mirror of
https://github.com/garrytan/gstack.git
synced 2026-07-08 00:58:05 +02:00
tab guardrail (50/200 thresholds) + sidebar action toast
Server side (browser-manager.ts):
Idempotent threshold tracker fires an activity entry exactly once at
each upward crossing of 50 (soft warn) and 200 (hard warn). Re-arms
when the count drops below. Activity-feed surface gives the
audit-trail invariant even with the sidebar closed; the toast UX
lives in the sidebar.
Sidebar side (extension/sidepanel.{html,css,js}):
Every /memory poll evaluates two trigger conditions:
- Any single tab > 4 GB JS heap (catches the WebGL/video runaway
case Codex flagged on the eng review).
- Tab count >= 200.
Toast shows top 5 tabs ranked by max(jsHeap, nodes*1KB + listeners*200)
so a WebGL-heavy tab with small JS heap still surfaces. Default-selected
checkboxes + "Close selected" run \`\$B closetab <id>\` through the
existing /command path — no chrome.tabs.remove bridge needed. "Snooze"
bumps tabsAbove/heapAbove thresholds in chrome.storage.session so the
toast stays hidden until the user accumulates more tabs OR one tab
grows another 2 GB.
Tests: browse/test/tab-guardrail.test.ts pins the server-side
fires-once + re-arms invariants without spinning up Chromium.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1152,6 +1152,88 @@ footer {
|
||||
.footer-mem.bad {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
/* ─── Memory pressure toast ─────────────────────────────────── */
|
||||
.mem-toast {
|
||||
position: fixed;
|
||||
left: 12px;
|
||||
right: 12px;
|
||||
bottom: 44px;
|
||||
z-index: 9999;
|
||||
background: var(--bg-elevated, #1f1f23);
|
||||
border: 1px solid #ef4444;
|
||||
border-radius: var(--radius-md, 6px);
|
||||
padding: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12px;
|
||||
}
|
||||
.mem-toast-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.mem-toast-header strong {
|
||||
color: var(--text-heading);
|
||||
font-size: 13px;
|
||||
}
|
||||
.mem-toast-close {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-meta);
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.mem-toast-close:hover { color: var(--text-heading); }
|
||||
.mem-toast-body {
|
||||
margin-bottom: 8px;
|
||||
color: var(--text-body);
|
||||
line-height: 1.4;
|
||||
}
|
||||
.mem-toast-body .mem-toast-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 0;
|
||||
}
|
||||
.mem-toast-body .mem-toast-row label {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mem-toast-body .mem-toast-size {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--text-meta);
|
||||
width: 70px;
|
||||
text-align: right;
|
||||
}
|
||||
.mem-toast-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.mem-toast-btn {
|
||||
background: var(--bg-base);
|
||||
border: 1px solid var(--zinc-600);
|
||||
border-radius: var(--radius-sm, 4px);
|
||||
color: var(--text-body);
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
padding: 4px 12px;
|
||||
}
|
||||
.mem-toast-btn:hover { background: var(--zinc-700); }
|
||||
.mem-toast-btn.primary {
|
||||
background: #ef4444;
|
||||
border-color: #ef4444;
|
||||
color: #fff;
|
||||
}
|
||||
.mem-toast-btn.primary:hover { background: #dc2626; }
|
||||
.port-input {
|
||||
width: 56px;
|
||||
padding: 2px 6px;
|
||||
|
||||
@@ -159,6 +159,19 @@
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Tab guardrail toast (hidden until /memory poll trips a threshold) -->
|
||||
<div class="mem-toast" id="mem-toast" role="dialog" aria-label="Memory pressure warning" style="display:none">
|
||||
<div class="mem-toast-header">
|
||||
<strong id="mem-toast-title">High memory pressure</strong>
|
||||
<button class="mem-toast-close" id="mem-toast-close" aria-label="Dismiss">×</button>
|
||||
</div>
|
||||
<div class="mem-toast-body" id="mem-toast-body"></div>
|
||||
<div class="mem-toast-actions">
|
||||
<button class="mem-toast-btn primary" id="mem-toast-close-selected">Close selected</button>
|
||||
<button class="mem-toast-btn" id="mem-toast-snooze">Snooze</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer with connection + debug toggle -->
|
||||
<footer>
|
||||
<div class="footer-left">
|
||||
|
||||
@@ -341,6 +341,11 @@ async function pollMemoryOnce() {
|
||||
if (!resp.ok) return { ok: false, slow: elapsed > MEM_POLL_SLOW_THRESHOLD_MS };
|
||||
const snapshot = await resp.json();
|
||||
renderMemFooter(snapshot);
|
||||
// Evaluate guardrail triggers (single-heavy-tab OR tab-count crossing 200).
|
||||
// Toast is hidden when no trigger fires; snooze state suppresses re-fire.
|
||||
try { evaluateMemToast(snapshot); } catch (err) {
|
||||
console.debug('[gstack sidebar] mem-toast evaluation failed:', err && err.message);
|
||||
}
|
||||
return { ok: true, slow: elapsed > MEM_POLL_SLOW_THRESHOLD_MS };
|
||||
} catch (err) {
|
||||
const elapsed = Date.now() - start;
|
||||
@@ -383,6 +388,198 @@ function stopMemPolling() {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Tab guardrail toast (D5 + Codex single-tab flag) ───────
|
||||
//
|
||||
// Each /memory poll evaluates two trigger conditions:
|
||||
// 1. Tab count crossed 200 — show "top 5 tabs by max(jsHeap, ...)" with
|
||||
// Close-selected + Snooze.
|
||||
// 2. Any single tab over 4 GB JS heap — show one-tab toast (catches the
|
||||
// Codex case where a runaway WebGL/video page balloons one tab).
|
||||
// Snooze persists in chrome.storage.session: next warn fires at tabCount +
|
||||
// snoozeBumpTabs OR when a single tab crosses (snoozedJsHeapBytes + 1).
|
||||
//
|
||||
// "Close selected" runs $B closetab <id> via the existing /command path —
|
||||
// no chrome.tabs.remove bridge needed.
|
||||
|
||||
const HEAVY_TAB_HEAP_BYTES = 4 * 1024 * 1024 * 1024; // 4 GB per Codex flag
|
||||
const TOAST_SNOOZE_TAB_BUMP = 50; // re-warn at 200+50
|
||||
const TOAST_SNOOZE_HEAP_BUMP = 2 * 1024 * 1024 * 1024;
|
||||
|
||||
const memToastSnooze = {
|
||||
tabsAbove: 0, // suppress the count-toast until tabs strictly exceeds this
|
||||
heapAbove: 0, // suppress the single-tab toast until heap strictly exceeds this
|
||||
};
|
||||
|
||||
async function loadSnoozeState() {
|
||||
if (!chrome?.storage?.session) return;
|
||||
try {
|
||||
const stored = await chrome.storage.session.get(['memToastSnooze']);
|
||||
if (stored?.memToastSnooze) {
|
||||
memToastSnooze.tabsAbove = stored.memToastSnooze.tabsAbove | 0;
|
||||
memToastSnooze.heapAbove = stored.memToastSnooze.heapAbove | 0;
|
||||
}
|
||||
} catch (err) {
|
||||
console.debug('[gstack sidebar] mem-toast snooze load failed:', err && err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSnoozeState() {
|
||||
if (!chrome?.storage?.session) return;
|
||||
try {
|
||||
await chrome.storage.session.set({ memToastSnooze: { ...memToastSnooze } });
|
||||
} catch (err) {
|
||||
console.debug('[gstack sidebar] mem-toast snooze save failed:', err && err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function dismissMemToast() {
|
||||
const toast = document.getElementById('mem-toast');
|
||||
if (toast) toast.style.display = 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort key for "RAM-heavy" tabs. JS heap × 4 is a rough proxy for total
|
||||
* tab footprint (renderers tend to spend ~4× their JS heap on native +
|
||||
* Skia + cache); when a tab is heavy via WebGL/video the JS heap is
|
||||
* small but listeners/nodes spike. Take the max.
|
||||
*/
|
||||
function tabRamScore(tab) {
|
||||
const heap = tab?.jsHeapUsed || 0;
|
||||
const nodes = tab?.nodes || 0;
|
||||
const listeners = tab?.listeners || 0;
|
||||
// ~1 KB per DOM node + ~200 bytes per listener as a back-of-envelope
|
||||
// native-memory estimate. Keeps the sort meaningful when JS heap is small.
|
||||
const nativeEstimate = nodes * 1024 + listeners * 200;
|
||||
return Math.max(heap, nativeEstimate);
|
||||
}
|
||||
|
||||
function showMemToast(title, body, tabsForClose) {
|
||||
const toast = document.getElementById('mem-toast');
|
||||
const titleEl = document.getElementById('mem-toast-title');
|
||||
const bodyEl = document.getElementById('mem-toast-body');
|
||||
const closeBtn = document.getElementById('mem-toast-close-selected');
|
||||
if (!toast || !titleEl || !bodyEl || !closeBtn) return;
|
||||
|
||||
titleEl.textContent = title;
|
||||
bodyEl.innerHTML = '';
|
||||
|
||||
for (const t of tabsForClose) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'mem-toast-row';
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
cb.id = `mem-toast-tab-${t.id}`;
|
||||
cb.value = String(t.id);
|
||||
cb.checked = true; // default-selected so a fast user just hits Close
|
||||
const label = document.createElement('label');
|
||||
label.htmlFor = cb.id;
|
||||
const urlShort = (t.url || '').length > 50 ? t.url.slice(0, 47) + '...' : (t.url || '(no url)');
|
||||
label.textContent = `tab #${t.id} — ${urlShort}`;
|
||||
const size = document.createElement('span');
|
||||
size.className = 'mem-toast-size';
|
||||
size.textContent = fmtBytesShort(tabRamScore(t));
|
||||
row.appendChild(cb);
|
||||
row.appendChild(label);
|
||||
row.appendChild(size);
|
||||
bodyEl.appendChild(row);
|
||||
}
|
||||
|
||||
toast.style.display = '';
|
||||
|
||||
closeBtn.onclick = async () => {
|
||||
const ids = tabsForClose
|
||||
.filter((t) => document.getElementById(`mem-toast-tab-${t.id}`)?.checked)
|
||||
.map((t) => t.id);
|
||||
dismissMemToast();
|
||||
for (const id of ids) {
|
||||
try {
|
||||
await fetch(`${serverUrl}/command`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify({ command: 'closetab', args: [String(id)] }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[gstack sidebar] mem-toast closetab failed:', id, err && err.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Driven by every successful /memory poll. Decides whether to surface
|
||||
* the toast and which payload to show.
|
||||
*/
|
||||
function evaluateMemToast(snapshot) {
|
||||
if (!snapshot || !Array.isArray(snapshot.tabs)) return;
|
||||
const tabs = snapshot.tabs;
|
||||
|
||||
// Trigger 1: any single tab over 4 GB JS heap. Catches the WebGL/video
|
||||
// case before the tab count threshold ever fires.
|
||||
const heavyTab = tabs.find((t) => (t.jsHeapUsed || 0) > HEAVY_TAB_HEAP_BYTES);
|
||||
if (heavyTab && (heavyTab.jsHeapUsed || 0) > memToastSnooze.heapAbove) {
|
||||
showMemToast(
|
||||
`Heavy tab: ${fmtBytesShort(heavyTab.jsHeapUsed)} JS heap`,
|
||||
'',
|
||||
[heavyTab],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Trigger 2: tab count crossed the hard guardrail (200) and isn't snoozed.
|
||||
if (tabs.length >= 200 && tabs.length > memToastSnooze.tabsAbove) {
|
||||
const top5 = [...tabs].sort((a, b) => tabRamScore(b) - tabRamScore(a)).slice(0, 5);
|
||||
showMemToast(
|
||||
`${tabs.length} tabs open — close some?`,
|
||||
'',
|
||||
top5,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// No trigger: keep toast hidden.
|
||||
}
|
||||
|
||||
function setupMemToastWiring() {
|
||||
const close = document.getElementById('mem-toast-close');
|
||||
if (close) close.addEventListener('click', dismissMemToast);
|
||||
const snooze = document.getElementById('mem-toast-snooze');
|
||||
if (snooze) {
|
||||
snooze.addEventListener('click', async () => {
|
||||
// Snooze logic: bump the thresholds above the current snapshot so the
|
||||
// toast won't re-fire until the user has accumulated MORE tabs or one
|
||||
// tab has grown ANOTHER 2 GB beyond what we just warned about. Stored
|
||||
// in chrome.storage.session so a sidebar reload doesn't lose the
|
||||
// snooze (but a Chrome restart does).
|
||||
try {
|
||||
const resp = await fetch(`${serverUrl}/memory`, {
|
||||
headers: { 'Authorization': `Bearer ${serverToken}` },
|
||||
signal: AbortSignal.timeout(MEM_POLL_TIMEOUT_MS),
|
||||
credentials: 'include',
|
||||
});
|
||||
if (resp.ok) {
|
||||
const snap = await resp.json();
|
||||
const tabs = Array.isArray(snap.tabs) ? snap.tabs : [];
|
||||
memToastSnooze.tabsAbove = tabs.length + TOAST_SNOOZE_TAB_BUMP;
|
||||
const maxHeap = tabs.reduce((m, t) => Math.max(m, t.jsHeapUsed || 0), 0);
|
||||
memToastSnooze.heapAbove = maxHeap + TOAST_SNOOZE_HEAP_BUMP;
|
||||
await saveSnoozeState();
|
||||
}
|
||||
} catch (err) {
|
||||
console.debug('[gstack sidebar] mem-toast snooze fetch failed:', err && err.message);
|
||||
}
|
||||
dismissMemToast();
|
||||
});
|
||||
}
|
||||
void loadSnoozeState();
|
||||
}
|
||||
|
||||
// Wire the toast on DOM ready.
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', setupMemToastWiring);
|
||||
} else {
|
||||
setupMemToastWiring();
|
||||
}
|
||||
|
||||
// ─── Refs Tab ───────────────────────────────────────────────────
|
||||
|
||||
async function fetchRefs() {
|
||||
|
||||
Reference in New Issue
Block a user