Files
xscapes/frames.go
T
donlucasandClaude Fable 5.1 9189a4a2d1 The spend counter: a number top-right in every scape, summed off the transcript
His ask: "can we add the token spent counter? Maybe it can be a simple
number on the top right of the xscape? should we do it xxxx/1M? can xscapes
automatically detect the max context window?"

The figure comes off the agent's transcript (internal/spend): every
assistant line carries the API's usage, a streamed message repeats it once
per content block (six times, measured), so a response counts once per
message id; subagents' transcripts under the session's directory count too.
Claude Code's status payload carries only the WINDOW's tokens from the last
response and a dollar figure, per its docs, so the statusline event now
carries the window size alone (parked) and the hook forwards the
transcript path. The frame loop polls the tally every two seconds, bytes
past the last offset only. This session's own transcript: 22.77M tokens
over 79 responses, cache reads 97% of it, which is why "/1M" would mislead:
the spend passes the window many times over, and the window's fill is the
moon's channel already. No denominator.

drawTokens, both scapes: row one, one cell in from the right, the balloon's
darkened ground, the readout's dim ink; "23M tokens" from 60 columns, the
bare number from 40, nothing under the shore's floor (the star-touch sweep
at 30x8 went 54 -> 56 with even four cells reserved). Placed stars keep off
its cells: the shore re-throws only the darts that land there, so every
other star stays where it was (the golden constellation holds); the vista
moves such a star one row down. A falling star shows through it: over the
arrival sweep 2,232 of 26,694 flights (8.4%) cross the counter's cells on
row 1, and blocking them cost his flight floors (88.6 -> 84.3%), so the
label yields a cell to a star on it for the frame or two it is there.

Hidden under the vista's floor, where the owl's box holds the corner.

Tests: TestFormatTokens (four characters at every magnitude; 999,999 is
"1.0M"), TestNoPlacedStarSitsUnderTheSpendCounter,
TestNoVistaStarSitsUnderTheSpendCounter,
TestTheSpendCounterSitsTopRightInEveryScape (both scapes, four sizes, four
hours, at least 100 luma over the ground), TestTheTallyCountsEachResponseOnce,
TestTheStatuslineCarriesTheWindow. frames.compose is shared by the live
frame and the tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 16:24:57 -07:00

283 lines
10 KiB
Go

package main
import (
"time"
"github.com/donlucasx/xscapes/internal/canvas"
"github.com/donlucasx/xscapes/internal/companion"
"github.com/donlucasx/xscapes/internal/event"
"github.com/donlucasx/xscapes/internal/notify"
"github.com/donlucasx/xscapes/internal/reduce"
"github.com/donlucasx/xscapes/internal/scape"
"github.com/donlucasx/xscapes/internal/scenes"
"github.com/donlucasx/xscapes/internal/spend"
"github.com/donlucasx/xscapes/internal/term"
)
// frames paints the scape one frame at a time.
//
// It exists because there are now two places that need a frame -- the pane
// that owns its whole window, and the band below a hosted agent -- and a
// scene assembled twice is a scene that drifts. Everything about what the
// scape looks like lives here; the callers only decide where to put it.
type frames struct {
// spend sums the tokens off the agent's transcript, polled every two
// seconds from state(); the counter in the top-right corner.
spend *spend.Tally
spendAt time.Time
c *canvas.Canvas
sh *scape.Shore
cat *companion.Cat
lay layout
ccw, chh int
mirror bool
profile term.Profile
seed int64
// Set once a session is found. Until then the demo cycle runs.
bus *event.Bus
red *reduce.Reducer
player *notify.Player
knocker notify.Knocker
ctxUsed, tod float64
start time.Time
// nextCompanionCheck paces refreshCompanion; see it for why this is not
// read every frame.
nextCompanionCheck time.Time
// lastFrame is when the previous frame was painted, and it exists only to
// give Approach a real dt. It cannot be derived from the frame rate: -fps
// is a flag, the two launchers disagree about it already (12 in inside.go,
// 20 in main.go), and a frame that arrives late after a resize or a
// compaction would otherwise advance the walk by the wrong amount. Zero on
// the first frame, which yields dt = 0 and no movement.
lastFrame time.Time
// The scape. sh is always built -- the shore is the default and the
// demo, the site and the mockups draw it -- and vista is set while the
// preference names it (refreshScape). ascii is kept so a switch can
// build the vista the same way the shore was.
vista *scenes.Vista
scapeName string
ascii bool
nextScapeCheck time.Time
}
// companionPoll is how often a running scape re-reads the saved companion.
// Half a second is under the threshold where a switch feels like it did not
// work, and it is 24x less file reading than doing it every frame.
const companionPoll = 500 * time.Millisecond
// refreshCompanion swaps the animal when the saved preference changes, so
// `xscapes companion cat` takes effect in a scape that is already running.
//
// It did not, and the CLI and the README both promised it did (2026-09-08, he
// switched to the cat and the crab stayed on the beach). companionPref() was
// read exactly once, inside newFrames, which runs at startup; even resize()
// recomputed the layout from the companion width it already had.
//
// The layout is recomputed here exactly as newFrames and resize do it. Today
// that is a no-op: both animals report the same Size(), because Size() returns
// the BOX and not the ink, and the cat's ink uses only nine of its twelve
// columns. It is done anyway because compose() takes the companion's width and
// places the companion's margin, the litter's room and the moon's column from
// it -- a companion with a different box would otherwise be drawn into the old
// one's hole, and nothing in the swap would say so.
func (f *frames) refreshCompanion(now time.Time) {
if now.Before(f.nextCompanionCheck) {
return
}
f.nextCompanionCheck = now.Add(companionPoll)
name := companionPref()
if name == f.cat.Name() {
return
}
c := companion.New(name)
c.FaceLeft(f.mirror)
f.cat = c
f.ccw, f.chh = c.Size()
f.lay = compose(f.c.W, f.ccw, f.mirror)
f.sh.MoonX = f.lay.MoonX
}
func newFrames(w, h int, seed int64, ascii, mirror bool, ctxUsed, tod float64) *frames {
c := canvas.New(w, h, canvas.AlphaFar, canvas.AlphaMid, canvas.AlphaNear)
sh := scape.NewShore(seed, ascii)
cat := companion.New(companionPref())
cat.FaceLeft(mirror)
ccw, chh := cat.Size()
lay := compose(w, ccw, mirror)
sh.MoonX = lay.MoonX
f := &frames{
c: c, sh: sh, cat: cat, lay: lay, ccw: ccw, chh: chh,
mirror: mirror, profile: term.DetectProfile(), seed: seed,
player: notify.New(), ctxUsed: ctxUsed, tod: tod, start: time.Now(),
ascii: ascii, scapeName: ScapeShore,
}
f.refreshScape(time.Time{})
return f
}
// refreshScape re-reads the scape preference on the companion's clock, so
// `xscapes scape vista` reaches a running scape without a restart -- the
// same defect the companion switch had until 2026-09-08, not repeated.
func (f *frames) refreshScape(now time.Time) {
if !now.IsZero() && now.Before(f.nextScapeCheck) {
return
}
f.nextScapeCheck = now.Add(companionPoll)
name := scapePref()
if name == f.scapeName && (name == ScapeShore || f.vista != nil) {
return
}
f.scapeName = name
if name == ScapeVista {
f.vista = scenes.NewVista(f.seed, f.ascii)
} else {
f.vista = nil
}
}
// resize refits the scene, and says whether the window got smaller -- the only
// case that needs the terminal cleared, since growing paints strictly more
// cells than the frame before it.
func (f *frames) resize(w, h int) (shrank bool) {
shrank = w < f.c.W || h < f.c.H
f.c.Resize(w, h)
f.lay = compose(w, f.ccw, f.mirror)
f.sh.MoonX = f.lay.MoonX
return shrank
}
func (f *frames) size() (w, h int) { return f.c.W, f.c.H }
// follow attaches the scene to a session's event bus.
func (f *frames) follow(bus *event.Bus, red *reduce.Reducer) { f.bus, f.red = bus, red }
func (f *frames) following() bool { return f.red != nil }
// state drains everything that has arrived since the last frame and returns
// what the scene should show now. Non-blocking: a frame must never wait on
// the bus.
func (f *frames) state(now time.Time, t float64) reduce.State {
if f.red == nil {
// The sky is the world: time of day is the wall clock whether or not
// there is a session to follow. Without this the demo ran at tod 0 --
// midnight, which is deliberately monochrome -- so every launch showed
// a black-and-white scene for the second or two before the agent
// announced itself, and then jumped to colour.
tod := f.tod
if tod == 0 {
tod = timeOfDay(now)
}
return demoState(t, f.ctxUsed, tod)
}
// A reducer with no bus is fed by the launcher itself: the generic
// adapter (internal/watch) applies what it synthesised before each
// frame, so there is nothing here to drain.
for draining := f.bus != nil; draining; {
select {
case e := <-f.bus.C:
f.red.Apply(e, now)
default:
draining = false
}
}
st := f.red.State(now)
// The spend, summed off the transcript every two seconds (his ask of
// 2026-09-16, drawTokens). An adapter that sends a figure of its own
// wins; the Claude adapter sends none, its payload has no such total.
if now.Sub(f.spendAt) >= 2*time.Second {
if f.spend == nil {
f.spend = spend.New()
}
f.spend.Poll(st.Transcript)
f.spendAt = now
}
if st.Act.Tokens == 0 && f.spend != nil {
st.Act.Tokens = f.spend.Total()
}
// Re-render the sand to the columns this layout actually leaves it, so a
// narrow pane loses whole pieces of a line rather than getting a path
// chopped mid-word. The vista's band runs the whole width.
budget := f.lay.SandTo - f.lay.SandFrom
if f.vista != nil {
budget = f.c.W - 4
}
st.Tail = st.FitTail(now, budget)
// The sky is the world: time of day is the wall clock, never anything the
// agent did.
st.Act.TimeOfDay = timeOfDay(now)
if f.tod != 0 {
st.Act.TimeOfDay = f.tod
}
if f.ctxUsed != 0 {
st.Act.ContextUsed = f.ctxUsed
}
return st
}
// frame paints one frame and returns it as ANSI, rows joined by newlines.
//
// It also rings the audible half of the nudge, keyed off the bubble rather
// than the pose and edge-detected, so a sixty-second permission nag knocks
// once rather than once a minute. Only when following a real session: the
// demo cycles every state on a timer, and a scape nobody attached to has
// nothing to announce.
func (f *frames) frame(now time.Time) string {
f.refreshCompanion(now)
t := now.Sub(f.start).Seconds()
st := f.state(now, t)
if f.red != nil {
// The pose is consulted for one thing only: a finish while the
// companion is still worried is the third knock (his ruling of
// 2026-09-15). The ask and the edge detection stay keyed off the bubble.
if k, ring := f.knocker.Knock(st.Bubble, st.BubbleAsk, st.Pose == companion.Worried); ring {
f.player.Play(k)
}
}
// The approach. His idea, 2026-09-10: when the agent needs him, the
// companion should "walk up closer to the screen and get bigger" before it
// prompts -- so it is driven by the POSE, eased over real seconds, and it
// retreats through the same call the moment the ask is answered.
//
// It is NOT a delay in front of the notification. The knock above has
// already rung and the balloon goes up this same frame; the walk happens
// underneath it. His asks stay open a median 130 s (28 closed ask windows
// over 30 recordings), so there is no shortage of time to cross the sand.
//
// Only NeedsYou brings it forward. Done is a knock he can answer whenever
// he likes, and Worried persists for a median 795 s -- a companion parked
// at full size for thirteen minutes is not an approach, it is a new
// default size.
dt := 0.0
if !f.lastFrame.IsZero() {
dt = now.Sub(f.lastFrame).Seconds()
}
f.lastFrame = now
f.cat.Approach(dt, st.Pose == companion.NeedsYou)
f.refreshScape(now)
f.compose(st, t)
return f.c.Render(f.profile)
}
// compose paints one state at one time into f.c through the scape in use:
// the vista or the shore, each through its own composer. The live frame
// and the tests share it, so a test composes exactly what the loop draws.
func (f *frames) compose(st reduce.State, t float64) {
if f.vista != nil {
f.vista.OwlX = f.lay.CatX
f.vista.Update(f.c, t, st.Act)
drawVista(f.c, f.vista, f.lay, st, t)
return
}
f.sh.Update(f.c, t, st.Act)
top := f.c.H - 2 - f.chh
drawScene(f.c, f.sh, f.cat, f.lay, st, t, f.seed, top)
}