diff --git a/internal/gui/assets/context.css b/internal/gui/assets/context.css index 84edc5f85..5bebf5d38 100644 --- a/internal/gui/assets/context.css +++ b/internal/gui/assets/context.css @@ -338,3 +338,61 @@ i.dot.free { background: var(--k-free); box-shadow: inset 0 0 0 1px color-mix(in .ctx-text { margin: 0; width: 100%; box-sizing: border-box; padding: 8px 10px; border-radius: 6px; background: var(--pill); font-family: var(--code-font, var(--code)); font-size: 11.5px; line-height: 1.5; color: var(--fg); white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } .ctx-text-more[hidden] { display: none; } .ctx-view-all { margin-right: auto; } + +/* the window as a map (flohoeller's context map): each item a tile sized + by its tokens inside its part's, the free space hatched. The tiles glide + to their sizes as a live request grows; context.js lays them out */ +.ctx-viz { position: relative; } +.ctx-viz[data-look="map"] > .ctx-waffle, .ctx-viz[data-look="grid"] > .ctx-map { display: none; } +.ctx-map { position: relative; width: 100%; aspect-ratio: 3.1 / 1; min-height: 132px; max-height: 232px; margin: -1.5px 0; } +:where(.ctx-card.max520) .ctx-map { aspect-ratio: 2 / 1; } +.ctx-tile { + --t-ease: cubic-bezier(.32, .72, 0, 1); + position: absolute; box-sizing: border-box; overflow: hidden; display: flex; flex-direction: column; gap: 1px; + padding: 7px 9px; border-radius: 7px; cursor: pointer; + background: color-mix(in srgb, var(--k) 11%, var(--card)); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k) 24%, transparent); + transition: left .62s var(--t-ease), top .62s var(--t-ease), width .62s var(--t-ease), height .62s var(--t-ease), + background-color .22s ease, box-shadow .22s ease, opacity .24s ease; +} +.ctx-tile .n { font-size: 11.5px; font-weight: 550; line-height: 1.25; color: color-mix(in srgb, var(--k) 72%, var(--fg)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ctx-tile .v { font-size: 10.5px; line-height: 1.25; color: color-mix(in srgb, var(--k) 42%, var(--muted)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ctx-tile.low { padding-top: 5px; padding-bottom: 5px; } +.ctx-tile.low .v { display: none; } +.ctx-tile.bare > * { visibility: hidden; } +.ctx-tile:hover, .ctx-tile.on { + background: color-mix(in srgb, var(--k) 19%, var(--card)); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k) 48%, transparent); +} +.ctx-tile.free { + --k: var(--fg); cursor: default; + background: repeating-linear-gradient(-45deg, color-mix(in srgb, var(--fg) 5.5%, transparent) 0 1px, transparent 1px 6px), color-mix(in srgb, var(--fg) 1.5%, var(--card)); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--fg) 9%, transparent); +} +.ctx-tile.free .n { color: var(--muted); font-weight: 500; } +.ctx-tile.free .v { color: color-mix(in srgb, var(--muted) 78%, transparent); } +.ctx-tile.gone { pointer-events: none; } +.ctx-map[data-f] > .ctx-tile { opacity: .32; } +.ctx-map[data-f="system"] > .k-system, .ctx-map[data-f="tools"] > .k-tools, +.ctx-map[data-f="memory"] > .k-memory, .ctx-map[data-f="files"] > .k-files, +.ctx-map[data-f="results"] > .k-results, .ctx-map[data-f="chat"] > .k-chat, +.ctx-map[data-f="free"] > .free, .ctx-map[data-f="tile"] > .on { opacity: 1; } +.ctx-pane.still .ctx-tile { transition: none; } +@media (prefers-reduced-motion: reduce) { .ctx-tile { transition: background-color .2s, box-shadow .2s, opacity .2s; } } +.ctx-tip-head b { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ctx-tip-sub { color: #a1a1aa; font-size: 11px; } + +/* the look: the map or the grid, the reader's pick */ +.ctx-look { display: inline-flex; gap: 2px; margin-left: auto; padding: 2px; border-radius: 7px; background: var(--pill); align-self: center; } +.ctx-look-b { display: inline-grid; place-items: center; width: 24px; height: 20px; padding: 0; border: 0; border-radius: 5px; background: none; color: var(--faint); cursor: pointer; transition: background-color .2s ease, color .2s ease, box-shadow .2s ease; } +.ctx-look-b svg { fill: currentColor; } +.ctx-look-b:hover { color: var(--fg-2); } +.ctx-look-b.on { background: var(--card); color: var(--fg); box-shadow: 0 1px 2px rgba(0, 0, 0, .12), 0 0 0 .5px color-mix(in srgb, var(--fg) 10%, transparent); } + +/* an image the request carried, in its text */ +.ctx-pic { display: block; width: fit-content; max-width: 100%; margin: 4px 0 2px; padding: 0; border: 0; border-radius: 10px; overflow: hidden; background: color-mix(in srgb, var(--fg) 4%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--fg) 9%, transparent); cursor: zoom-in; transform-origin: top left; opacity: 0; transition: opacity .4s ease; } +.ctx-pic.in { opacity: 1; } +.ctx-pic img { display: block; max-width: min(100%, 420px); max-height: 240px; width: auto; height: auto; object-fit: contain; } +.ctx-pic.open { cursor: zoom-out; } +.ctx-pic.open img { max-width: 100%; max-height: none; } +@media (prefers-reduced-motion: reduce) { .ctx-pic { transition: none; } } diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 0b250de6d..31152045b 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -220,6 +220,127 @@ for (let i = kids.length; i < old.length; i++) old[i].remove(); } + // ---------- the map: the window as tiles (flohoeller's context map) ---------- + + // The card's window is drawn one of two ways, the reader's pick: the + // map, each item a tile sized by its tokens inside its part's, the free + // space a hatched tile of its share; or the grid, a cell for each 1/400 + // of the window. The map is the default; the grid is kept for those who + // had it. + let ctxLook = "map"; + try { if (localStorage.getItem("magpie.ctxLook") === "grid") ctxLook = "grid"; } catch {} + + // squarify lays vals ([{v}]) in the rect x, y, w, h as rects whose sides + // are as near alike as it can (Bruls, Huizing, van Wijk), in vals' order + function squarify(vals, x, y, w, h) { + const out = []; + vals = vals.filter((a) => a.v > 0); + const total = vals.reduce((s, a) => s + a.v, 0); + if (!total || w <= 0 || h <= 0) return out; + const k = (w * h) / total; + const worst = (row, side) => { + let sum = 0, hi = 0, lo = Infinity; + for (const a of row) { const s = a.v * k; sum += s; hi = Math.max(hi, s); lo = Math.min(lo, s); } + return Math.max((side * side * hi) / (sum * sum), (sum * sum) / (side * side * lo)); + }; + const lay = (row) => { + const sum = row.reduce((s, a) => s + a.v * k, 0); + if (w >= h) { + const cw = sum / h; + let cy = y; + for (const a of row) { const ch = (a.v * k) / cw; out.push({ a, x, y: cy, w: cw, h: ch }); cy += ch; } + x += cw; w -= cw; + } else { + const rh = sum / w; + let cx = x; + for (const a of row) { const cw = (a.v * k) / rh; out.push({ a, x: cx, y, w: cw, h: rh }); cx += cw; } + y += rh; h -= rh; + } + }; + let row = []; + for (const a of vals) { + const side = Math.min(w, h); + if (!row.length || worst([...row, a], side) <= worst(row, side)) { row.push(a); continue; } + lay(row); + row = [a]; + } + if (row.length) lay(row); + return out; + } + + // tilesOf lays a prompt out on a map W×H px: the used share of the + // window and the free space side by side along its long side (the + // used share eased, see usedLen), the used + // parts squarified in it, a part's items in the part. An item too small + // to read goes in one tile with the part's other small ones; a part too + // small for its items is one tile. Each tile: key (stays across draws), + // kind, its item (it), the items it stands for (its), rect in px. + const TILE_MIN = 1500, TILE_MAX = 12, TILE_FLOOR = 700; + // the look switch's marks: tiles, and a grid of cells + const LOOK_MAP = ''; + const LOOK_GRID = '"; + function tilesOf(p, window, W, H) { + const scale = Math.max(window, p.tokens, 1); + const across = W >= H; + const long = across ? W : H; + // the used share drawn on a gentle curve (share^0.35): a window 8% + // full still has room to read its tiles (41% of the map), a full one + // stays full, and the free tile says its own share in words + let usedLen = long; + if (p.tokens < scale) usedLen = Math.min(long, Math.max(long * Math.pow(p.tokens / scale, 0.35), Math.min(long, 36))); + const tiles = []; + const parts = PARTS.map((k) => p.parts.find((x) => x.kind === k)).filter((x) => x && x.tokens > 0); + const ur = across ? [0, 0, usedLen, H] : [0, 0, W, usedLen]; + // a tile is never laid smaller than TILE_FLOOR px² (a sliver can't be + // pointed at): its value raised to that share of the rect it is in + const floored = (vals, area) => { + const sum = vals.reduce((s, a) => s + a.v, 0); + const lo = (sum * TILE_FLOOR) / Math.max(1, area); + return vals.map((a) => ({ ...a, v: Math.max(a.v, lo) })); + }; + for (const r of squarify(floored(parts.map((x) => ({ v: x.tokens, x })), ur[2] * ur[3]), ...ur)) { + const x = r.a.x; + const items = (x.items || []).filter((it) => it.tokens > 0).sort((a, b) => b.tokens - a.tokens); + const isum = items.reduce((s, it) => s + it.tokens, 0); + const area = r.w * r.h; + if (!items.length || area < TILE_MIN * 2) { + tiles.push({ key: x.kind, kind: x.kind, its: items, tokens: x.tokens, x: r.x, y: r.y, w: r.w, h: r.h }); + continue; + } + // an item's share of the part's tokens, its tile's share of the rect + const kept = [], rest = []; + for (const it of items) { + if (kept.length < TILE_MAX && (it.tokens / isum) * area >= TILE_MIN) kept.push(it); + else rest.push(it); + } + const vals = kept.map((it) => ({ v: it.tokens, it })); + if (rest.length === 1 && !kept.length) vals.push({ v: rest[0].tokens, it: rest[0] }); + else if (rest.length) vals.push({ v: rest.reduce((s, it) => s + it.tokens, 0), rest }); + // a part whose items would leave one a strip too thin to read or + // point at is one tile + const laid = squarify(floored(vals, area), r.x, r.y, r.w, r.h); + if (laid.some((q) => Math.min(q.w, q.h) < 14)) { + tiles.push({ key: x.kind, kind: x.kind, its: items, tokens: x.tokens, x: r.x, y: r.y, w: r.w, h: r.h }); + continue; + } + for (const q of laid) { + const t0 = q.a; + const it = t0.it; + tiles.push({ + key: x.kind + "\x00" + (it ? (it.tag || "") + "\x00" + it.name : "\x01rest"), + kind: x.kind, it, its: it ? [it] : t0.rest, tokens: ((it ? it.tokens : t0.rest.reduce((s, y) => s + y.tokens, 0)) / isum) * x.tokens, + x: q.x, y: q.y, w: q.w, h: q.h, + }); + } + } + if (p.tokens < scale) { + const fr = across ? [usedLen, 0, W - usedLen, H] : [0, usedLen, W, H - usedLen]; + tiles.push({ key: "\x00free", kind: "", free: true, tokens: scale - p.tokens, x: fr[0], y: fr[1], w: fr[2], h: fr[3] }); + } + return tiles; + } + // ctxCard draws a route's prompt. opts: series (the session's prompts, // [{id, tokens, time}]), onPoint (a point of it clicked), cache ({read, // total}, when the route carries no usage), crumbs (the footer's path), @@ -246,6 +367,21 @@ // parts around them, and the tab the reader is on const grid = el("div", "ctx-waffle"); grid.setAttribute("role", "img"); + const map = el("div", "ctx-map"); + map.setAttribute("role", "img"); + // the map and the grid in one place, the reader's look shown + const viz = el("div", "ctx-viz"); + viz.dataset.look = ctxLook; + viz.append(map, grid); + // the map's tiles by key, kept across draws: a live request's tiles + // glide to their new sizes, and only a new item's comes in + const tiles = new Map(); + const focusOn = (f) => { grid.dataset.f = map.dataset.f = f; }; + const unfocus = () => { + delete grid.dataset.f; + delete map.dataset.f; + for (const e of viz.querySelectorAll(".on")) e.classList.remove("on"); + }; const tip = el("div", "ctx-tip"); tip.hidden = true; const contents = el("div", "ctx-contents"), ch = el("div", "ctx-contents-head"), list = el("div", "ctx-rows"); @@ -281,6 +417,10 @@ tip.append(th); grid.dataset.f = "free"; } + placeTip(target); + }; + // the tip over what it tells of, or under it where there's no room + const placeTip = (target) => { tip.hidden = false; const b = target.getBoundingClientRect(), cr = card.getBoundingClientRect(); const w = tip.offsetWidth, h = tip.offsetHeight; @@ -291,6 +431,144 @@ tip.style.left = left + "px"; tip.style.top = topY + "px"; }; + // a tile's tip: the item, its part and share; a part's or the small + // ones' tile, its largest items + const showMapTip = (n) => { + const { p, window } = cur; + const tl = n._tile; + tip.replaceChildren(); + const th = el("div", "ctx-tip-head"); + if (tl.free) { + th.append(el("i", "dot free"), el("b", "", t("Free space")), el("span", "grow"), + el("span", "", fmtK(Math.max(0, window - p.tokens)))); + tip.append(th); + } else if (tl.it) { + th.append(el("i", "dot k-" + tl.kind), el("b", "", itemName(tl.it))); + tip.append(th, el("div", "ctx-tip-sub", partName(tl.kind) + " · " + fmtK(tl.it.tokens) + " " + t("tokens") + " · " + pct(tl.it.tokens / Math.max(1, p.tokens)))); + } else { + th.append(el("i", "dot k-" + tl.kind), el("b", "", partName(tl.kind)), el("span", "grow"), + el("span", "", fmtK(tl.tokens) + " · " + pct(tl.tokens / Math.max(1, p.tokens)))); + tip.append(th); + const shown = tl.its.slice(0, 5); + for (const it of shown) { + const row = el("div", "ctx-tip-row"); + row.append(el("span", "n", itemName(it)), el("span", "v", fmtK(it.tokens))); + tip.append(row); + } + if (tl.its.length > shown.length) tip.append(el("div", "ctx-tip-more", t("{n} more", { n: tl.its.length - shown.length }))); + } + placeTip(n); + }; + const tileAt = (e) => { + const n = e.target.closest?.(".ctx-tile"); + return cur && n && n.parentElement === map && n._tile && !n.classList.contains("gone") ? n : null; + }; + map.addEventListener("pointerover", (e) => { + const n = tileAt(e); + if (!n) return; + map.dataset.f = "tile"; + for (const x of tiles.values()) x.classList.toggle("on", x === n); + showMapTip(n); + }); + map.addEventListener("pointerleave", () => { tip.hidden = true; unfocus(); }); + // a tile clicked opens the text of what it shows, as a cell does + map.addEventListener("click", (e) => { + const n = tileAt(e); + if (!n || n._tile.free) return; + e.stopPropagation(); + tip.hidden = true; + openCtxText(rid, n._tile.kind, n._tile.it); + }); + + // drawMap lays the map out at its size: a tile kept glides to its new + // place (CSS), a new one comes in, one gone fades. enter: every tile + // comes in, one after another (the first draw, or the map picked) + const drawMap = (enter) => { + if (!cur || viz.dataset.look !== "map") return; + const W = map.clientWidth, H = map.clientHeight; + // folded or not in the page yet: drawn once it has a size + if (!W || !H) return; + map.dataset.size = W + "x" + H; + const { p, window } = cur; + const quiet = opts.still || calm(); + enter = enter || !tiles.size; + const seen = new Set(); + tilesOf(p, window, W, H).forEach((tl, i) => { + seen.add(tl.key); + let n = tiles.get(tl.key); + const fresh = !n; + if (fresh) { + n = el("div", "ctx-tile"); + n.append(el("b", "n"), el("span", "v")); + tiles.set(tl.key, n); + map.append(n); + } + n._tile = tl; + const cls = "ctx-tile " + (tl.free ? "free" : "k-" + tl.kind) + (tl.w < 54 || tl.h < 30 ? " bare" : tl.h < 46 ? " low" : "") + (n.classList.contains("on") ? " on" : ""); + if (n.className !== cls) n.className = cls; + let name, v; + if (tl.free) { name = t("Free space"); v = fmtK(tl.tokens) + " · " + pct(tl.tokens / Math.max(window, p.tokens, 1)); } + else if (tl.it) { + name = itemName(tl.it); + if (tl.kind === "files" || tl.kind === "memory") name = name.slice(name.lastIndexOf("/", name.length - 2) + 1) || name; + v = fmtK(tl.tokens) + " · " + partName(tl.kind); + } else if (tl.key === tl.kind) { name = partName(tl.kind); v = fmtK(tl.tokens); } + else { name = t("{n} more", { n: tl.its.length }); v = fmtK(tl.tokens) + " · " + partName(tl.kind); } + if (n.firstChild.textContent !== name) n.firstChild.textContent = name; + if (n.lastChild.textContent !== v) n.lastChild.textContent = v; + // a gap of 3px between tiles: each 1.5px in from its rect + const pc = (a, b) => +((a / b) * 100).toFixed(3); + n.style.left = `calc(${pc(tl.x, W)}% + 1.5px)`; + n.style.top = `calc(${pc(tl.y, H)}% + 1.5px)`; + n.style.width = `max(0px, calc(${pc(tl.w, W)}% - 3px))`; + n.style.height = `max(0px, calc(${pc(tl.h, H)}% - 3px))`; + if (quiet || !n.animate || !(fresh || enter)) return; + n.animate([{ opacity: 0, transform: "scale(.94)", filter: "blur(4px)" }, { opacity: 1, transform: "none", filter: "none" }], + { duration: 560, easing: IOS_EASE, delay: enter ? 40 + Math.min(i, 16) * 32 : 0, fill: "backwards" }); + }); + for (const [k, n] of tiles) { + if (seen.has(k)) continue; + tiles.delete(k); + n.classList.add("gone"); + if (quiet || !n.animate) { n.remove(); continue; } + n.animate([{ opacity: 1 }, { opacity: 0, transform: "scale(.96)" }], { duration: 260, easing: IOS_EASE, fill: "forwards" }) + .finished.then(() => n.remove(), () => n.remove()); + } + }; + // the map's size changed (the card unfolded, the window resized): laid + // out again for it, its tiles' labels shown where they fit + const mapSizes = new ResizeObserver(() => { + if (!map.isConnected) return; + if (map.dataset.size !== map.clientWidth + "x" + map.clientHeight) drawMap(false); + }); + mapSizes.observe(map); + + // setLook shows the map or the grid, the reader's pick for every card; + // the place eases to the other's height, the map's tiles come in + const setLook = (k) => { + if (viz.dataset.look === k) return; + ctxLook = k; + try { localStorage.setItem("magpie.ctxLook", k); } catch {} + const quiet = opts.still || calm(); + const h0 = viz.offsetHeight; + tip.hidden = true; + unfocus(); + viz.dataset.look = k; + for (const b of card.querySelectorAll(".ctx-look-b")) { + const on = b.dataset.k === k; + b.classList.toggle("on", on); + b.setAttribute("aria-pressed", String(on)); + } + if (k === "map") { for (const n of tiles.values()) n.remove(); tiles.clear(); drawMap(true); } + if (quiet || !viz.animate) return; + const h1 = viz.offsetHeight; + if (h0 !== h1) { + viz.style.overflow = "hidden"; + viz.animate([{ height: h0 + "px" }, { height: h1 + "px" }], { duration: 520, easing: IOS_EASE }) + .finished.finally(() => { viz.style.overflow = ""; }).catch(() => {}); + } + }; + grid.addEventListener("pointerover", (e) => { if (cur && e.target.parentElement === grid) showTip(e.target); }); grid.addEventListener("pointerleave", () => { tip.hidden = true; delete grid.dataset.f; }); // a cell clicked opens the text of what it shows (masaka on Discord) @@ -334,11 +612,10 @@ row.onpointerenter = () => { grid.dataset.f = "item"; for (const [j, c] of cells.entries()) grid.children[j].classList.toggle("on", !!c && c.kind === kind && c.item === i); + map.dataset.f = "tile"; + for (const n of tiles.values()) n.classList.toggle("on", n._tile.kind === kind && !!n._tile.its?.includes(it)); }; - row.onpointerleave = () => { - delete grid.dataset.f; - for (const e of grid.querySelectorAll("i.on")) e.classList.remove("on"); - }; + row.onpointerleave = unfocus; return row; }); if (!rows.length) out.push(el("div", "ctx-empty", t("Nothing in it"))); @@ -497,6 +774,8 @@ }); cur = { p, window, cells, partOf }; if (!tip.hidden) tip.hidden = true; + map.setAttribute("aria-label", grid.getAttribute("aria-label")); + drawMap(false); // the legend: a part hovered lights its cells const legend = el("div", "ctx-legend"); @@ -507,17 +786,33 @@ li.title = t(PART_NOTES[kind]); li.append(el("i", "dot k-" + kind), el("span", "n", partName(kind)), el("span", "v", fmtK(part.tokens))); clickable(li, () => openCtxText(rid, kind)); - li.onpointerenter = () => { grid.dataset.f = kind; }; - li.onpointerleave = () => { delete grid.dataset.f; }; + li.onpointerenter = () => focusOn(kind); + li.onpointerleave = unfocus; legend.append(li); } if (window && window > p.tokens) { const li = el("span", "ctx-leg"); li.append(el("i", "dot free"), el("span", "n", t("Free space")), el("span", "v", fmtK(window - p.tokens))); - li.onpointerenter = () => { grid.dataset.f = "free"; }; - li.onpointerleave = () => { delete grid.dataset.f; }; + li.onpointerenter = () => focusOn("free"); + li.onpointerleave = unfocus; legend.append(li); } + // the look: the map or the grid + const look = el("span", "ctx-look"); + look.setAttribute("role", "group"); + for (const [k, name, ic] of [["map", "Context map", LOOK_MAP], ["grid", "Block grid", LOOK_GRID]]) { + const on = viz.dataset.look === k; + const b = el("button", "ctx-look-b" + (on ? " on" : "")); + b.type = "button"; + b.dataset.k = k; + b.title = t(name); + b.setAttribute("aria-label", t(name)); + b.setAttribute("aria-pressed", String(on)); + b.innerHTML = ic; + b.onclick = (e) => { e.stopPropagation(); setLook(k); }; + look.append(b); + } + legend.append(look); // the contents' tabs, drawn again only when they change const tabs = [["all", t("All")], ...PARTS.filter((k) => partOf.get(k)?.tokens > 0).map((k) => [k, partName(k)])]; @@ -548,7 +843,7 @@ if (!parts) { parts = { head, top, legend, foot, sp }; - card.append(head, top, grid, legend, contents, foot, ...(sp ? [sp] : []), tip); + card.append(head, top, viz, legend, contents, foot, ...(sp ? [sp] : []), tip); return; } for (const k of ["head", "top", "legend", "foot"]) parts[k] = morph(parts[k], { head, top, legend, foot }[k]); @@ -615,6 +910,33 @@ box.append(pre, more); return box; } + // picture: an image the request carried, as it sent it (a data: URL + // the gateway checked is a PNG, JPEG, GIF or WebP). It fades in once + // decoded; clicked, it opens to its own size and back + function picture(src) { + const fig = el("button", "ctx-pic"); + fig.type = "button"; + fig.setAttribute("aria-expanded", "false"); + const img = el("img"); + img.alt = t("Image"); + img.decoding = "async"; + img.onload = () => fig.classList.add("in"); + img.onerror = () => fig.replaceWith(el("div", "ctx-piece-note", t("An image: magpie doesn't show it here"))); + img.src = src; + fig.append(img); + fig.onclick = (e) => { + e.stopPropagation(); + const first = fig.getBoundingClientRect(); + const open = fig.classList.toggle("open"); + fig.setAttribute("aria-expanded", String(open)); + if (calm() || !fig.animate) return; + const last = fig.getBoundingClientRect(); + if (!first.width || !last.width) return; + fig.animate([{ transform: `scale(${first.width / last.width}, ${first.height / last.height})` }, { transform: "none" }], + { duration: 460, easing: IOS_EASE }); + }; + return fig; + } function pieceView(pc) { const box = el("div", "ctx-piece"); const head = el("div", "ctx-piece-head"); @@ -623,7 +945,8 @@ head.append(el("span", "grow")); if (pc.text) head.append(copyBtn(pc.text, pc.name || t(ROLE_NAMES[pc.role] || "Text"))); box.append(head); - if (pc.role === "image") box.append(el("div", "ctx-piece-note", t("An image: magpie doesn't show it here"))); + if (pc.role === "image" && pc.src) box.append(picture(pc.src)); + else if (pc.role === "image") box.append(el("div", "ctx-piece-note", t("An image: magpie doesn't show it here"))); else if (pc.role === "sealed") box.append(el("div", "ctx-piece-note", t("Sealed by the vendor, {n} bytes: only the vendor can read it", { n: (pc.size || 0).toLocaleString(intlLang()) }))); else { if (pc.size) box.append(el("div", "ctx-piece-note", t("Sealed by the vendor, {n} bytes: only the vendor can read it", { n: pc.size.toLocaleString(intlLang()) }))); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5b502a629..acb500127 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -190,6 +190,8 @@ const I18N = { "The vendor didn't say": "供应商未报告", "{used} of {window} tokens used": "已用 {used} / {window} token", "Free space": "剩余空间", + "Context map": "上下文地图", + "Block grid": "方格", "Nothing in it": "这里没有内容", "Show all {n}": "显示全部 {n} 项", "Contents": "内容", @@ -4109,6 +4111,8 @@ const I18N = { "The vendor didn't say": "供應商未回報", "{used} of {window} tokens used": "已用 {used} / {window} token", "Free space": "剩餘空間", + "Context map": "上下文地圖", + "Block grid": "方格", "Nothing in it": "這裡沒有內容", "Show all {n}": "顯示全部 {n} 項", "Contents": "內容", @@ -7975,6 +7979,8 @@ const I18N = { "The vendor didn't say": "ベンダーから報告なし", "{used} of {window} tokens used": "{window} トークン中 {used} 使用", "Free space": "空き", + "Context map": "コンテキストマップ", + "Block grid": "ブロックグリッド", "Nothing in it": "中身はありません", "Show all {n}": "{n} 件すべて表示", "Contents": "内訳", @@ -11862,6 +11868,8 @@ const I18N = { "The vendor didn't say": "Vom Anbieter nicht gemeldet", "{used} of {window} tokens used": "{used} von {window} Token belegt", "Free space": "Frei", + "Context map": "Kontextkarte", + "Block grid": "Blockraster", "Nothing in it": "Nichts darin", "Show all {n}": "Alle {n} anzeigen", "Contents": "Inhalt", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 76329a8f6..f813e67be 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_343_324 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23) - coreScriptBudget = 1_535_084 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added + coreScriptBudget = 1_549_478 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/context-map.test.cjs b/internal/gui/tests/context-map.test.cjs new file mode 100644 index 000000000..2845ea03b --- /dev/null +++ b/internal/gui/tests/context-map.test.cjs @@ -0,0 +1,268 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The context window card draws its window as a map by default (after +// flohoeller's context map on X): each item a tile sized by its tokens +// inside its part's, the free space a hatched tile. A tile hovered tells +// what it holds and dims the others; clicked, it opens its text, where an +// image the request sent inline is shown. The block grid is a switch +// away, and stays the reader's pick. A refresh keeps the tiles, and with +// motion reduced nothing moves. In every language, at a desk and a +// phone's width. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = Date.now(); +const ago = (m) => new Date(now - m * 60000).toISOString(); + +const latest = { + window: 272000, tokens: 21400, counted: true, turns: 3, + parts: [ + { kind: "system", tokens: 5200, items: [{ name: "prompt", tokens: 4900 }, { name: "environment_context", tokens: 300 }] }, + { kind: "tools", tokens: 5000, items: [{ name: "multi_agent_v1", tag: "namespace", n: 5, tokens: 2900 }, { name: "exec_command", tokens: 2100 }] }, + { kind: "memory", tokens: 3300, items: [{ name: "skills", tag: "skills", tokens: 3300 }] }, + { kind: "files", tokens: 5900, items: [{ name: "/work/app/prompt.go", tag: "shell", tokens: 2950 }, { name: "/work/app/context.go", tag: "shell", tokens: 2950 }] }, + { kind: "results", tokens: 1200, items: [{ name: "exec_command", tag: "result", n: 4, tokens: 1200 }] }, + { kind: "chat", tokens: 800, items: [{ name: "turn", tag: "turn", n: 3, tokens: 800 }] }, + ], +}; +const context = (days) => ({ + days, + agents: [ + { agent: "codex", requests: 9, sessions: 1, errors: 0, calls: 9, median: 17700, p90: 21400, baseline: 13300, window: 272000, cache: 0.74, growth: 228, peakFill: 0.08, compacts: 0, + shares: { system: 0.29, tools: 0.28, memory: 0.18, files: 0.18, results: 0.04, chat: 0.03 }, mcp: 0, + score: 94, scores: [{ key: "cache", points: 29, most: 35 }, { key: "lean", points: 25, most: 25 }, { key: "pace", points: 20, most: 20 }, { key: "reliable", points: 20, most: 20 }], + tags: [{ key: "lean", tone: "good", value: 13300 }, { key: "memory-heavy", tone: "info", value: 0.18 }], + models: ["live/codex/gpt-5.6-luna"], latestId: 19, latestTime: ago(4) }, + { agent: "claude", requests: 12, sessions: 2, errors: 3, calls: 15, median: 140000, p90: 180000, baseline: 70000, window: 200000, cache: 0.2, growth: 9000, peakFill: 0.9, compacts: 1, + shares: { system: 0.1, tools: 0.6, memory: 0.05, files: 0.1, results: 0.1, chat: 0.05 }, mcp: 28000, + score: 31, scores: [{ key: "cache", points: 8, most: 35 }, { key: "lean", points: 3, most: 25 }, { key: "pace", points: 10, most: 20 }, { key: "reliable", points: 10, most: 20 }], + tags: [{ key: "cache-misses", tone: "warn", value: 0.2 }, { key: "heavy-start", tone: "warn", value: 70000 }, { key: "mcp-heavy", tone: "info", value: 28000 }], + models: ["claude-sonnet-5"], latestId: 30, latestTime: ago(9) }, + ], + sessions: [ + { agent: "codex", key: "01a117b1-aecd-76e2-9b2f-3c1d", title: "Port the parser", model: "live/codex/gpt-5.6-luna", first: ago(12), last: ago(4), requests: 3, peak: 21400, window: 272000, + latest, latestId: 19, points: [{ id: 17, time: ago(12), tokens: 13000, cache: 0 }, { id: 18, time: ago(8), tokens: 17700, cache: 12000 }, { id: 19, time: ago(4), tokens: 21400, cache: 20900 }] }, + { agent: "claude", key: "ce0c93f6-1111-2222-3333-444444444444", model: "claude-sonnet-5", first: ago(30), last: ago(9), requests: 1, peak: 180000, window: 200000, + latest: { ...latest, window: 200000, tokens: 180000 }, latestId: 30, points: [{ id: 30, time: ago(9), tokens: 180000 }] }, + ], +}); + +// the text as /api/context/text gives it: request 19's is kept, 30's isn't +// a 2×2 PNG, as the gateway gives an image the request sent inline +const PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVR4AWP4z8DwHwyBGBMgEmAAAP0eB/k1J7hZAAAAAElFTkSuQmCC"; +const LONG = "You are Codex. ".repeat(20000); // 300,000 characters +const texts = { + system: [{ name: "prompt", tokens: 4900, pieces: [{ role: "system", text: LONG }] }, { name: "environment_context", tokens: 300, pieces: [{ role: "user", text: "cwd /work/app" }] }], + tools: [{ name: "multi_agent_v1", tag: "namespace", n: 5, tokens: 2900, pieces: [{ role: "tool", name: "spawn_agent", text: "{\n \"name\": \"spawn_agent\"\n}" }] }, + { name: "exec_command", tokens: 2100, pieces: [{ role: "tool", name: "exec_command", text: "{\n \"name\": \"exec_command\",\n \"description\": \"Runs a command in a PTY\"\n}" }] }], + files: [{ name: "/work/app/prompt.go", tag: "shell", tokens: 2950, pieces: [{ role: "result", name: "exec_command", text: "package gateway // prompt.go" }] }, + { name: "/work/app/context.go", tag: "shell", tokens: 2950, pieces: [{ role: "result", name: "exec_command", text: "package gui // context.go" }] }], + memory: [{ name: "skills", tag: "skills", tokens: 3300, pieces: [{ role: "system", text: "## Skills" }] }], + results: [{ name: "exec_command", tag: "result", n: 4, tokens: 1200, pieces: [{ role: "result", name: "exec_command", text: "ok" }] }], + chat: [{ name: "1", tag: "turn", tokens: 300, pieces: [{ role: "user", text: "port the parser" }, { role: "thinking", text: "", size: 900 }, { role: "call", name: "exec_command", text: "{\"cmd\": \"ls\"}" }] }, + { name: "2", tag: "turn", tokens: 500, pieces: [{ role: "image", src: PNG }, { role: "image" }, { role: "assistant", text: "Done." }] }], +}; +function text(url, r) { + if (url.searchParams.get("id") !== "19") return r.fulfill({ status: 404, body: "not kept" }); + const kind = url.searchParams.get("kind"), item = url.searchParams.get("item"); + const items = (texts[kind] || []).map((it, i) => item !== null && +item === i ? it : { ...it, pieces: undefined }); + return r.fulfill({ json: { id: 19, kind, items, kept: 10 } }); +} + +function serve(lang, asked) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }, { id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/context") { + asked.push(url.searchParams.get("days")); + return json(context(+url.searchParams.get("days"))); + } + // the text comes a moment after it is asked, as it does under load: + // the dialog says "Reading…" first, and the test waits past it + if (url.pathname === "/api/context/text") { await new Promise((ok) => setTimeout(ok, 200)); return text(url, r); } + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType, status: 200 }); + }; +} + +// the reader scrolls (the wheel) until what they'll point at is in view: +// the app puts back a scroll that isn't the reader's, a test's own included +async function wheelTo(page, l) { + // over the page, not the sidebar beside it + const v = await page.locator("#view-usage").boundingBox(); + await page.mouse.move(v.x + v.width / 2, 300); + for (let i = 0; i < 40 && await l.evaluate((b) => b.getBoundingClientRect().bottom > innerHeight - 70); i++) { + await page.mouse.wheel(0, 120); + await page.waitForTimeout(50); + } + // a wheel scroll is eased, and a window's cells scale in one after + // another (ctx-cell): hovered while either runs, Chromium scrolls the + // view to the cell, the app puts that scroll back, the cell moves out + // from under the pointer and its tip closes again. Wait until the target + // stops moving. + // Under load an eased scroll can pause for a frame and go on, so the + // target has to hold still for three looks in a row. + for (let last = null, same = 0, i = 0; i < 60 && same < 2; i++) { + await page.waitForTimeout(100); + const now = await l.evaluate((b) => { const r = b.getBoundingClientRect(); return r.x + "," + r.y + "," + document.querySelector("#view-usage")?.scrollTop; }); + same = now === last ? same + 1 : 0; + last = now; + } +} + +const words = { + en: { tools: "Tools", close: "Close", free: "Free space", map: "Context map", grid: "Block grid" }, + zh: { tools: "工具", close: "关闭", free: "剩余空间", map: "上下文地图", grid: "方格" }, + "zh-TW": { tools: "工具", close: "關閉", free: "剩餘空間", map: "上下文地圖", grid: "方格" }, + ja: { tools: "ツール", close: "閉じる", free: "空き", map: "コンテキストマップ", grid: "ブロックグリッド" }, + de: { tools: "Tools", close: "Schließen", free: "Frei", map: "Kontextkarte", grid: "Blockraster" }, +}; + + +async function open(page, lang, width, still) { + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, [])); + await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); sessionStorage.setItem("set", "1"); } } catch {} }); + await page.goto("http://magpie.test/?view=usage"); + const card = await openSession(page); + return { errors, card }; +} +async function openSession(page) { + const row = page.locator(".ctx-sess-row", { hasText: "Port the parser" }); + await row.waitFor(); + await wheelTo(page, row); + await row.click(); + const card = page.locator(".ctx-sess.open .ctx-card"); + await card.waitFor(); + return card; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: the context window as a map`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage(); + page.setDefaultTimeout(5000); + let { errors, card } = await open(page, lang, width); + + // the map is the default: tiles and the free space, the grid hidden + const map = card.locator(".ctx-map"); + await map.locator(".ctx-tile.k-tools").first().waitFor(); + assert.equal(await card.locator(".ctx-viz").getAttribute("data-look"), "map"); + assert.ok(await card.locator(".ctx-waffle").isHidden(), "the grid is hidden under the map"); + assert.equal(await map.locator(".ctx-tile.free").count(), 1); + assert.match(await map.locator(".ctx-tile.free").innerText(), new RegExp(w.free)); + assert.equal(await card.locator(".ctx-look-b.on").getAttribute("aria-label"), w.map); + // every tile inside the map, none on another + // read once the tiles have come in and the card has opened, the + // map and its tiles in one look + await page.waitForFunction(() => !document.getAnimations().some((a) => a.playState === "running" && a.effect?.target?.closest?.(".ctx-sess.open"))); + const { rects, box } = await map.evaluate((m) => { + const rc = (n) => { const r = n.getBoundingClientRect(); return [r.left, r.top, r.right, r.bottom]; }; + return { rects: [...m.querySelectorAll(".ctx-tile")].map(rc), box: rc(m) }; + }); + for (const [i, a] of rects.entries()) { + assert.ok(a[0] >= box[0] - 0.5 && a[1] >= box[1] - 0.5 && a[2] <= box[2] + 0.5 && a[3] <= box[3] + 0.5, `tile ${i} is outside the map: ${a} in ${box}`); + assert.ok(a[2] - a[0] >= 10 && a[3] - a[1] >= 10, `tile ${i} is a sliver: ${a}`); + for (const b of rects.slice(i + 1)) assert.ok(a[2] <= b[0] + 0.5 || b[2] <= a[0] + 0.5 || a[3] <= b[1] + 0.5 || b[3] <= a[1] + 0.5, "two tiles overlap"); + } + + // a tile hovered tells its part and dims the others + const tile = map.locator(".ctx-tile.k-tools").first(); + await wheelTo(page, card.locator(".ctx-look")); + await tile.hover(); + const tip = card.locator(".ctx-tip"); + await tip.waitFor({ state: "visible" }); + assert.match(await tip.innerText(), new RegExp(w.tools)); + assert.equal(await map.getAttribute("data-f"), "tile"); + assert.match(await tile.getAttribute("class"), /\bon\b/); + await page.mouse.move(2, 2); + await tip.waitFor({ state: "hidden" }); + + // a refresh with the same window keeps the tiles where they are + const kept = await tile.elementHandle(); + await page.evaluate(() => window.loadContext()); + await page.waitForTimeout(300); + assert.ok(await kept.evaluate((n) => n.isConnected), "the refresh drew the tiles again"); + + // clicked, a tile opens its text + await tile.click(); + const view = page.locator("#modal .ctx-view"); + await view.locator(".ctx-text").first().waitFor(); + await view.locator(".bar button", { hasText: w.close }).click(); + await page.locator("#modal").waitFor({ state: "hidden" }); + + // an image the request sent inline is shown in its turn; one it + // didn't send that way is named + await page.evaluate(() => window.openCtxText(19, "chat")); + await view.locator(".ctx-vi-head").nth(1).click(); + const pic = view.locator(".ctx-vi.open .ctx-pic"); + await pic.locator("img").waitFor(); + await page.waitForFunction(() => document.querySelector("#modal .ctx-pic img")?.naturalWidth === 2); + assert.equal(await view.locator(".ctx-vi.open .ctx-piece-note").count(), 1, "the image not sent inline is named"); + await pic.click(); + assert.equal(await pic.getAttribute("aria-expanded"), "true", "a picture clicked opens larger"); + assert.ok(await page.evaluate(() => { const d = document.querySelector("#modal .dialog").getBoundingClientRect(); return d.left >= 0 && d.right <= innerWidth; }), "the dialog fits the window"); + await view.locator(".bar button", { hasText: w.close }).click(); + await page.locator("#modal").waitFor({ state: "hidden" }); + + // the grid a switch away, and still the pick after a reload + await card.locator('.ctx-look-b[data-k="grid"]').click(); + await page.waitForFunction(() => document.querySelector(".ctx-sess.open .ctx-viz")?.dataset.look === "grid"); + assert.equal(await card.locator(".ctx-waffle > i").count(), 400); + assert.ok(await map.isHidden()); + assert.equal(await card.locator(".ctx-look-b.on").getAttribute("aria-label"), w.grid); + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.ctxLook")), "grid"); + await page.reload(); + card = await openSession(page); + await card.locator(".ctx-waffle > i").first().waitFor(); + assert.equal(await card.locator(".ctx-viz").getAttribute("data-look"), "grid"); + // and back: the tiles come in again + await wheelTo(page, card.locator(".ctx-look")); + await card.locator('.ctx-look-b[data-k="map"]').click(); + await card.locator(".ctx-map .ctx-tile.free").waitFor(); + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.ctxLook")), "map"); + + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + } + } + + // with motion reduced the tiles are simply there + test(`${engine}: the map holds still with motion reduced`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const { errors, card } = await open(page, "en", 1100); + await card.locator(".ctx-map .ctx-tile.free").waitFor(); + const moving = () => page.evaluate(() => document.getAnimations().filter((a) => a.effect?.target?.closest?.(".ctx-viz")).length); + assert.equal(await moving(), 0, "a tile came in with motion reduced"); + await wheelTo(page, card.locator(".ctx-look")); + await card.locator('.ctx-look-b[data-k="grid"]').click(); + assert.equal(await moving(), 0, "the switch moved with motion reduced"); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tests/context-text.test.cjs b/internal/gui/tests/context-text.test.cjs index 7245f40a6..55df8902b 100644 --- a/internal/gui/tests/context-text.test.cjs +++ b/internal/gui/tests/context-text.test.cjs @@ -144,7 +144,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], asked = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, asked)); - await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); sessionStorage.setItem("set", "1"); } } catch {} }); + await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); localStorage.setItem("magpie.ctxLook", "grid"); sessionStorage.setItem("set", "1"); } } catch {} }); await page.goto("http://magpie.test/?view=usage"); const row = page.locator(".ctx-sess-row", { hasText: "Port the parser" }); await row.waitFor(); diff --git a/internal/gui/tests/context-window.test.cjs b/internal/gui/tests/context-window.test.cjs index a9885bbc0..acc6301a7 100644 --- a/internal/gui/tests/context-window.test.cjs +++ b/internal/gui/tests/context-window.test.cjs @@ -117,7 +117,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = [], asked = []; page.on("pageerror", (e) => errors.push(e.message)); await page.route("**/*", serve(lang, asked)); - await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); sessionStorage.setItem("set", "1"); } } catch {} }); + await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); localStorage.setItem("magpie.ctxLook", "grid"); sessionStorage.setItem("set", "1"); } } catch {} }); await page.goto("http://magpie.test/?view=usage"); assert.equal(await page.locator("#usageTab button.on").innerText(), w.tab); @@ -201,7 +201,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", if (p === "/context.js" || p === "/api/state") order.push(p); await base(r); }); - await page.addInitScript(() => { try { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); } catch {} }); + await page.addInitScript(() => { try { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); await page.goto("http://magpie.test/?view=usage"); await page.locator(".ctx-agent", { hasText: "Codex" }).waitFor({ timeout: 2500 }); assert.equal(asked[0], "7"); @@ -229,7 +229,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", if (new URL(r.request().url()).pathname === "/api/state") await historyDrawn; await base(r); }); - await page.addInitScript(() => { try { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); } catch {} }); + await page.addInitScript(() => { try { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); await page.goto("http://magpie.test/?view=usage"); await page.waitForFunction(() => document.querySelectorAll(".ctx-agent").length === 2); drawn(); diff --git a/internal/gui/tests/held-animations.test.cjs b/internal/gui/tests/held-animations.test.cjs index 69aaf09c4..1985f43e3 100644 --- a/internal/gui/tests/held-animations.test.cjs +++ b/internal/gui/tests/held-animations.test.cjs @@ -60,6 +60,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage(); + // the block grid, the look these cells are drawn in (the map is the default) + await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); page.setDefaultTimeout(5000); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); diff --git a/internal/gui/tests/routing-context-fold.test.cjs b/internal/gui/tests/routing-context-fold.test.cjs index c2cc1a1c1..098341b20 100644 --- a/internal/gui/tests/routing-context-fold.test.cjs +++ b/internal/gui/tests/routing-context-fold.test.cjs @@ -74,6 +74,8 @@ function serve(lang) { async function open(browser, lang, width, height) { const context = await browser.newContext({ viewport: { width, height } }); const page = await context.newPage(); + // the block grid, the look these cells are drawn in (the map is the default) + await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); // folded is the reader's own choice, kept in magpie.ctxShut; set once, so a reload keeps what the page stores await page.addInitScript(() => { try { if (!sessionStorage.getItem("seeded")) { sessionStorage.setItem("seeded", "1"); localStorage.setItem("magpie.ctxShut", "1"); } } catch {} }); page.setDefaultTimeout(5000); diff --git a/internal/gui/tests/routing-ctx-fold.test.cjs b/internal/gui/tests/routing-ctx-fold.test.cjs index d980f6930..714f7d501 100644 --- a/internal/gui/tests/routing-ctx-fold.test.cjs +++ b/internal/gui/tests/routing-ctx-fold.test.cjs @@ -104,6 +104,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await t.test(`${width}x${height}`, async () => { const context = await browser.newContext({ viewport: { width, height } }); const page = await context.newPage(); + // the block grid, the look these cells are drawn in (the map is the default) + await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); page.setDefaultTimeout(5000); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); diff --git a/internal/gui/tests/routing-ctx-still.test.cjs b/internal/gui/tests/routing-ctx-still.test.cjs index b34e11425..098b4e42c 100644 --- a/internal/gui/tests/routing-ctx-still.test.cjs +++ b/internal/gui/tests/routing-ctx-still.test.cjs @@ -91,6 +91,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await t.test(`${lang} ${width}px`, async () => { const context = await browser.newContext({ viewport: { width, height: 900 } }); const page = await context.newPage(); + // the block grid, the look these cells are drawn in (the map is the default) + await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); page.setDefaultTimeout(5000); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); diff --git a/internal/gui/tests/routing-live-patch.test.cjs b/internal/gui/tests/routing-live-patch.test.cjs index 159f90754..c18f2f001 100644 --- a/internal/gui/tests/routing-live-patch.test.cjs +++ b/internal/gui/tests/routing-live-patch.test.cjs @@ -78,6 +78,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await t.test(`${width}x${height}, open`, async () => { const context = await browser.newContext({ viewport: { width, height } }); const page = await context.newPage(); + // the block grid, the look these cells are drawn in (the map is the default) + await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); page.setDefaultTimeout(5000); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); @@ -164,6 +166,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await t.test(`${width}x${height}, folded`, async () => { const context = await browser.newContext({ viewport: { width, height } }); const page = await context.newPage(); + // the block grid, the look these cells are drawn in (the map is the default) + await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxLook", "grid"); } catch {} }); await page.addInitScript(() => { try { localStorage.setItem("magpie.ctxShut", "1"); } catch {} }); page.setDefaultTimeout(5000); const errors = [];