Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.
TypeScript claude-code-mod
Streaming: the last texts and the final blocks kept at RESULTS_KEPT
razorback16e16e46ee32fb
diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsindex 96593f5..e2f102f 100644--- a/hooks/lib/answer.ts+++ b/hooks/lib/answer.ts@@ -111,7 +111,7 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawin})const seen = lastText.get(id)const changed = seen !== text- lastText.set(id, text)+ keep(lastText, id, text, RESULTS_KEPT)const job: Job = {key, requestId: id, text, columns, cell, theme: S.theme, size: S.size, grid: S.grid, themeDir: active.dir, env, epoch: S.epoch,...(base ? { base } : {}), ...(room ? { room } : {}), ...(o.onScreen !== undefined ? { onScreen: o.onScreen } : {}),diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex f341f28..02fdb95 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -233,8 +233,10 @@ export const settingsSet = new Set<string>()// The compile results by key (an LRU: set with `keep` at RESULTS_KEPT).export const results = new Map<string, Result | 'failed'>()// Streaming: model requests of the main loop in flight (`S.stepsLive`), the-// blocks drawn blank while their text streams (with the job to compile once-// final), and the blocks a request made final (they stay final).+// text each block last drew, the blocks drawn blank while their text streams+// (with the job to compile once final), and the blocks a request made final+// (they stay final). The texts and the final ones go past RESULTS_KEPT, as+// `results` (an id gone draws as one not seen yet).export const lastText = new Map<string, string>()export const live = new Map<string, { job: Job; still: { cancel: () => void } }>()export const finalized = new Set<string>()@@ -332,6 +334,16 @@ export function keep<T>(cache: Map<string, T>, key: string, value: T, max: numbe}}+// The same for a set: `key` as the newest; the oldest go past `max`.+export function keepIn(set: Set<string>, key: string, max: number) {+ set.delete(key)+ set.add(key)+ for (const old of set) {+ if (set.size <= max) break+ set.delete(old)+ }+}+// Redraws every reader of `done`; an invalidate where the write is refused.export function refresh($: EngineInterface) {void update($, done, n => n + 1).catch(() => invalidate($, 'ui.render'))diff --git a/hooks/lib/stream.ts b/hooks/lib/stream.tsindex 8849c09..0f82b0d 100644--- a/hooks/lib/stream.ts+++ b/hooks/lib/stream.ts@@ -6,7 +6,7 @@import type { EngineInterface } from 'claude-code'import { BLANK_AFTER_LIVE_MS, MAX_RUNNING, RESULTS_KEPT } from './settings'-import { finalized, keep, live, pending, queue, refresh, results, running, S, type Job } from './state'+import { finalized, keep, keepIn, live, pending, queue, refresh, results, running, S, type Job } from './state'import { hashOf } from './draw'import { noteDesign, recordDesign } from './designs'import { compile, logDebug } from './typst'@@ -91,7 +91,7 @@ export function finalize($: EngineInterface, requestId: string, isForGood: booleif (!was) returnwas.still.cancel()live.delete(requestId)- if (isForGood) finalized.add(requestId)+ if (isForGood) keepIn(finalized, requestId, RESULTS_KEPT)enqueue($, was.job)waitBlank($, requestId, hashOf([was.job.text]), BLANK_AFTER_LIVE_MS)refresh($)diff --git a/tests/stream.test.ts b/tests/stream.test.tsindex b663b14..ed2b8e5 100644--- a/tests/stream.test.ts+++ b/tests/stream.test.ts@@ -5,14 +5,14 @@ import { DEFAULT_CELL, DEFAULT_METRICS, DEFAULT_THEME, fontFit, hashOf, nextJob,// driven with this test's `$`: pagesOf and the queue and results it fills// are module state, which register.tsx does not export.import { epochOpen, lastKey, queue, results, running, S, type Env } from '../hooks/lib/state'-import { finalized, inlined, INLINE_KEPT, live, pending, type Job } from '../hooks/lib/state'+import { finalized, inlined, INLINE_KEPT, lastText, live, pending, type Job } from '../hooks/lib/state'import { enqueue, finalizeAll, forget, pump, waitBlank } from '../hooks/lib/stream'import { inlineOf } from '../hooks/lib/draw'import { pagesOf } from '../hooks/lib/answer'import { beginEpoch } from '../hooks/lib/epoch'import { forgetTouches } from '../hooks/lib/typst'import { INLINE_MAX_BYTES } from '../hooks/lib/terminal'-import { COMMIT_MIN_MS, TOUCH_FLUSH_MS } from '../hooks/lib/settings'+import { COMMIT_MIN_MS, RESULTS_KEPT, TOUCH_FLUSH_MS } from '../hooks/lib/settings'// The world beneath the mod for one compile: a cache folder, a typst whose// compile the test lets finish (or fail), and the PNG it "wrote".@@ -663,6 +663,59 @@ test('a blocks still live is final at once by finalizeAll: queued, blank, and drexpect(redraws()).toBe(2)})+test('the text each block drew and the blocks made final go past RESULTS_KEPT, the oldest first', async () => {+ const { $ } = idle()+ S.resizing = true+ lastText.clear()+ const draw = (id: string) => pagesOf($, { id, text: `Text of ${id}.`, frame: FRAME, env: ENV, canStream: false })+ for (let i = 0; i <= RESULTS_KEPT; i++) await draw(`t${i}`)+ expect(lastText.size).toBe(RESULTS_KEPT)+ expect(lastText.has('t0')).toBe(false)+ expect(lastText.get(`t${RESULTS_KEPT}`)).toBe(`Text of t${RESULTS_KEPT}.`)+ // A block drawn again is the newest: t2 stays, t1 goes.+ await draw('t2')+ await draw('t-new')+ expect(lastText.has('t1')).toBe(false)+ expect(lastText.has('t2')).toBe(true)+ for (let i = 0; i <= RESULTS_KEPT; i++) live.set(`f${i}`, { job: jobOf(`f${i}`), still: { cancel: () => {} } })+ finalizeAll($)+ expect(finalized.size).toBe(RESULTS_KEPT)+ expect(finalized.has('f0')).toBe(false)+ expect(finalized.has(`f${RESULTS_KEPT}`)).toBe(true)+ queue.length = 0+})++test('a block whose text was let go draws as one not seen yet: queued at once, or live during a request until it ends', async () => {+ const { $ } = idle()+ S.resizing = true+ lastText.clear()+ const text = 'Text of old.'+ await pagesOf($, { id: 'old', text, frame: FRAME, env: ENV, canStream: true })+ for (let i = 0; i < RESULTS_KEPT; i++) await pagesOf($, { id: `n${i}`, text: `Text of n${i}.`, frame: FRAME, env: ENV, canStream: false })+ expect(lastText.has('old')).toBe(false)+ // No request runs: final at once (queued), not held as live.+ queue.length = 0+ pending.clear()+ expect((await pagesOf($, { id: 'old', text, frame: FRAME, env: ENV, canStream: true })).kind).toBe('blank')+ expect(live.has('old')).toBe(false)+ expect(queue.map(j => j.requestId)).toEqual(['old'])+ // A request runs: live (blank) until the request moves on, then queued.+ lastText.delete('old')+ queue.length = 0+ S.stepsLive = 1+ try {+ expect((await pagesOf($, { id: 'old', text, frame: FRAME, env: ENV, canStream: true })).kind).toBe('blank')+ expect(live.has('old')).toBe(true)+ finalizeAll($)+ expect(live.has('old')).toBe(false)+ expect(finalized.has('old')).toBe(true)+ expect(queue.map(j => j.requestId)).toEqual(['old'])+ } finally {+ S.stepsLive = 0+ queue.length = 0+ }+})+test('forget stops the live and pending timers of a block', () => {idle()const cancelled: string[] = []