Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): you can see what the model has forgotten

esengined27a4ef40323
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index 7a401f79a..68107b98d 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -424,13 +424,32 @@ class AnthropicSession implements AgentSession {
return Math.max(this.lastInputTokens, Math.ceil(chars / 4));
}
- private compactOldest(keepRuns: number): void {
- const next = compactHistory(this.messages, this.turnStarts, this.dropped, keepRuns, this.folded);
- if (!next) return;
+ /**
+ * Fold the oldest runs away if this conversation has outgrown its budget.
+ *
+ * @returns how many runs went, 0 when none did. The caller SAYS it — a
+ * conversation losing part of its memory with nothing on screen to
+ * show for it is the thing this number exists to end.
+ */
+ private compactIfNeeded(): number {
+ if (this.contextUsed() <= this.opts.contextWindow * COMPACT_AT) return 0;
+ const next = compactHistory(
+ this.messages, this.turnStarts, this.dropped, KEEP_WHOLE_RUNS, this.folded,
+ );
+ if (!next) return 0;
+ const runs = next.dropped - this.dropped;
this.messages.splice(0, this.messages.length, ...next.messages);
this.turnStarts.splice(0, this.turnStarts.length, ...next.turnStarts);
this.dropped = next.dropped;
this.folded = next.folded;
+ // What the endpoint billed describes a history that no longer exists, and
+ // it is the LARGER half of contextUsed() on an honest endpoint. Left in
+ // place it would report the conversation as still full immediately after
+ // emptying it: no visible drop, and the next step would fold again for a
+ // reason that had already been dealt with. The estimate carries the reading
+ // until the next call reports a real one.
+ this.lastInputTokens = 0;
+ return runs;
}
pushContext(text: string): void {
@@ -487,9 +506,15 @@ class AnthropicSession implements AgentSession {
async *step(signal: AbortSignal): AsyncIterable<StepEvent> {
this.flushContext();
- // Fold the oldest runs away BEFORE a call that would not fit.
- if (this.contextUsed() > this.opts.contextWindow * COMPACT_AT) {
- this.compactOldest(KEEP_WHOLE_RUNS);
+ // Fold the oldest runs away BEFORE a call that would not fit, and report
+ // both halves of it: what the model lost, and where that leaves the
+ // conversation. The reading is stated here as well as after the answer
+ // because this is the moment it moves DOWN, and a gauge that only ever
+ // climbed would make the fold invisible in the one place it shows.
+ const folded = this.compactIfNeeded();
+ if (folded > 0) {
+ yield { type: 'compacted', runs: folded };
+ yield { type: 'context', used: this.contextUsed(), window: this.opts.contextWindow };
}
const request = buildStepRequest({
@@ -560,6 +585,11 @@ class AnthropicSession implements AgentSession {
outputTokens: message.usage.output_tokens ?? 0,
};
}
+ // Where the conversation stands now — separate from `usage`, which is what
+ // this one call cost. A level and a cost project differently (the editor
+ // replaces one and sums the other), and an endpoint that reports no usage
+ // at all still has a context this can answer for from the estimate.
+ yield { type: 'context', used: this.contextUsed(), window: this.opts.contextWindow };
// Again, now with the PARSED arguments — the streamed deltas are display
// text, and the kernel needs a real object to dispatch. The editor treats a
diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.ts
index a24c6840d..7368fce83 100644
--- a/desktop/electron/agent/types.ts
+++ b/desktop/electron/agent/types.ts
@@ -64,7 +64,27 @@ export type StepEvent =
| { type: 'tool_args'; id: string; delta: string }
/** Why the model stopped. `refusal` is a provider-level decline, not an error. */
| { type: 'stop'; reason: 'end_turn' | 'tool_use' | 'refusal' | 'max_tokens' }
- | { type: 'usage'; inputTokens: number; outputTokens: number };
+ | { type: 'usage'; inputTokens: number; outputTokens: number }
+ /**
+ * How full the conversation's context is, as of the call that just answered.
+ *
+ * The provider is the only side that can say it: the number is the larger of
+ * what the endpoint billed and what the history obviously weighs, and both of
+ * those are in the session. A window counting the characters of its own
+ * transcript would be measuring a different thing — it never saw the system
+ * prompt, the tool schemas, or the results that were truncated on the way.
+ */
+ | { type: 'context'; used: number; window: number }
+ /**
+ * The oldest runs were folded out of the model's memory to make room.
+ *
+ * The one thing that happens to a conversation without anyone asking for it:
+ * the model stops being able to answer about its earliest runs while the
+ * transcript on screen still shows them in full. Silence there is what makes
+ * a model look like it has started ignoring what it was told. What was ASKED
+ * survives verbatim — see compactHistory — and the tool traffic is what goes.
+ */
+ | { type: 'compacted'; runs: number };
/**
* One conversation. Stateful on purpose — see the file header. The kernel
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index c21b3eebb..592b9609c 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -27,16 +27,17 @@ import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState, useSyn
import {
X, Plus, PanelRight, ArrowUp, Square, ChevronRight, ChevronDown, Check, TriangleAlert,
Loader, Copy, Pencil, Eye, KeyRound, Boxes, Stethoscope, Image as ImageIcon, RotateCcw,
- File as FileIcon, ArrowRight, History as HistoryIcon, Trash2,
+ File as FileIcon, ArrowRight, History as HistoryIcon, Trash2, FoldVertical,
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import {
useAgent, sendAgentMessage, stopAgentTurn, confirmAgentCall, startNewConversation,
peekEntities, entitiesInInput, effectiveSelection, selectAgentModel, retryAgentTurn, setAgentDraft,
RESUMABLE, openAgentHistory, closeAgentHistory, resumeConversation, forgetConversation,
- addAgentAttachments, removeAgentAttachment,
+ addAgentAttachments, removeAgentAttachment, latestContext,
type AgentTurn, type AgentEntry, type AgentToolEntry, type AgentProseEntry,
} from '@/store/AgentStore';
+import { COMPACT_AT } from '@/settings/agentIds';
import type { ConfirmAnswer } from '../../electron/agent/types';
import {
agentProviders, agentProvider, agentKeyId, parseModelList, subscribeProviders, providersRevision,
@@ -461,6 +462,20 @@ function Entries({ entries, streaming, onRerun }: {
<span className="ag-ask-hd">{entry.message}</span>
</div>,
);
+ } else if (entry.kind === 'folded') {
+ // Where the model stopped remembering. The runs it lost are still on
+ // screen above this line, which is exactly why the line has to be here:
+ // a transcript that shows them and a model that cannot answer about them
+ // otherwise disagree with nothing to explain it.
+ out.push(
+ <div className="ag-folded" key={i}>
+ <FoldVertical size={13} strokeWidth={1.8} />
+ <span>
+ {entry.runs === 1 ? t('agent.folded.one') : t('agent.folded', { count: entry.runs })}
+ <span className="ag-folded-w">{t('agent.folded.why')}</span>
+ </span>
+ </div>,
+ );
} else if (entry.kind === 'thinking') out.push(<Thinking key={i} entry={entry} />);
else out.push(<Prose key={i} text={entry.text} streaming={streaming && i === entries.length - 1} onRerun={onRerun} />);
});
@@ -1005,6 +1020,38 @@ function mentionMatches(query: string): Mention[] {
return [...entities, ...assets];
}
+/**
+ * How much of the model's memory this conversation has filled.
+ *
+ * In the header, beside the button that starts a new conversation — which is
+ * the action a filling context prompts, and the reading is about the whole
+ * conversation rather than about any run in it. (Under the composer it also had
+ * to share a line with four keyboard hints, and at an ordinary drawer width one
+ * of them lost.)
+ *
+ * Not coloured as it fills. Folding is ordinary — the conversation carries on,
+ * having lost the tool traffic of its oldest runs — and spending the amber that
+ * means "this cannot be undone" on it would make that warning mean less.
+ */
+function ContextMeter() {
+ const context = useAgent((s) => latestContext(s.turns));
+ if (!context || context.window <= 0) return null;
+ const pct = Math.min(100, Math.round((context.used / context.window) * 100));
+ return (
+ <span
+ className={`ag-ctx${context.used > context.window * COMPACT_AT ? ' near' : ''}`}
+ title={t('agent.context.why', {
+ used: compact(context.used),
+ window: compact(context.window),
+ at: Math.round(COMPACT_AT * 100),
+ })}
+ >
+ <span className="ag-ctx-bar"><i style={{ width: `${pct}%` }} /></span>
+ {t('agent.context', { pct })}
+ </span>
+ );
+}
+
function Compose({ autoFocus }: { autoFocus?: boolean }) {
const status = useAgent((s) => s.status);
const draft = useAgent((s) => s.draft);
@@ -1241,6 +1288,7 @@ export function AgentPanel({ docked }: { docked?: boolean }) {
<AgentMark size={docked ? 13 : 15} live={status.phase !== 'idle'} />
{!docked && <span className="ag-ttl">{t('agent.title')}</span>}
<span className="ag-sp" />
+ <ContextMeter />
<button
type="button"
className={historyOpen ? 'on' : undefined}
diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.ts
index 3c3d70e97..88193fd09 100644
--- a/desktop/src/i18n/messages/agent.ts
+++ b/desktop/src/i18n/messages/agent.ts
@@ -99,6 +99,25 @@ export const agentMessages = defineMessages({
en: '{count} earlier runs are no longer shown here',
zh: '更早的 {count} 轮已不在此窗口',
},
+ // Once a conversation is past the threshold every further run folds exactly
+ // one, so the singular is the COMMON case rather than the edge one.
+ 'agent.folded.one': {
+ en: 'The earliest run was folded out of the model’s memory',
+ zh: '最早的一轮已折叠出模型的记忆',
+ },
+ 'agent.folded': {
+ en: 'The earliest {count} runs were folded out of the model’s memory',
+ zh: '最早的 {count} 轮已折叠出模型的记忆',
+ },
+ 'agent.folded.why': {
+ en: 'The conversation outgrew the context window. What you asked is kept word for word; the tool calls and their results are gone — have it re-read the scene rather than trusting what it said about them.',
+ zh: '对话超出了上下文窗口。你问过的话原样保留,工具调用和结果已丢弃 —— 让它重新读一遍场景,别信它对那些内容的转述。',
+ },
+ 'agent.context': { en: '{pct}% context', zh: '上下文 {pct}%' },
+ 'agent.context.why': {
+ en: 'This conversation fills {used} of the model’s {window} token window. Past {at}% the earliest runs are folded out of its memory — what you asked is kept, the tool calls and their results are not.',
+ zh: '这段对话占了模型 {window} token 上下文窗口中的 {used}。超过 {at}% 后,最早的几轮会被折叠出它的记忆 —— 你问过的话保留,工具调用和结果不保留。',
+ },
'agent.stopped': { en: 'stopped', zh: '已中止' },
'agent.declined': { en: 'skipped', zh: '已跳过' },
'agent.turn.aborted': { en: 'Stopped part-way.', zh: '中途停止。' },
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index a11085b75..8a3e03a69 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -78,7 +78,20 @@ export interface AgentErrorEntry {
message: string;
}
-export type AgentEntry = AgentProseEntry | AgentToolEntry | AgentErrorEntry;
+/**
+ * The point at which the model stopped remembering its earliest runs.
+ *
+ * An entry rather than a badge on the run, because it happened at a moment —
+ * mid-run, between two tool calls — and the runs it took away are still on
+ * screen above it. Reading the transcript afterwards, this is the line that
+ * explains why the model cannot answer about them.
+ */
+export interface AgentFoldEntry {
+ kind: 'folded';
+ runs: number;
+}
+
+export type AgentEntry = AgentProseEntry | AgentToolEntry | AgentErrorEntry | AgentFoldEntry;
export type TurnReason = 'end_turn' | 'aborted' | 'error' | 'refusal' | 'max_rounds';
@@ -94,6 +107,16 @@ export interface AgentTurn {
entries: AgentEntry[];
inputTokens: number;
outputTokens: number;
+ /**
+ * How full the model's context was as of this run's last answer — null for
+ * one that never got that far.
+ *
+ * Kept per run rather than beside the conversation so it is rebuilt by the
+ * same replay everything else here is: a window that reloads mid-conversation
+ * gets the reading back with the transcript, instead of a blank gauge under a
+ * conversation that is nearly full.
+ */
+ context: { used: number; window: number } | null;
/** What one Undo would take back, once the turn ended. 0 means don't offer it. */
steps: number;
/** Where that Undo would go back to (EditorHistory.undoToMark). */
@@ -338,10 +361,12 @@ function appendProse(entries: readonly AgentEntry[], kind: 'text' | 'thinking',
}
/** A prose block is over the moment anything else begins — another kind of
- * block, a tool call, the end of the run. Idempotent. */
+ * block, a tool call, the end of the run. Idempotent. Named by what it CAN
+ * close rather than by what it cannot: a kind added later is not prose, and
+ * listing the exceptions is how it would come to be treated as some. */
function closeProse(entries: readonly AgentEntry[]): AgentEntry[] {
const last = entries[entries.length - 1];
- if (!last || last.kind === 'tool' || last.kind === 'error' || last.endedAt !== null) {
+ if (!last || (last.kind !== 'text' && last.kind !== 'thinking') || last.endedAt !== null) {
return entries as AgentEntry[];
}
return [...entries.slice(0, -1), { ...last, endedAt: Date.now() }];
@@ -380,6 +405,7 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):
entries: [],
inputTokens: 0,
outputTokens: 0,
+ context: null,
steps: 0,
mark: null,
reason: null,
@@ -458,6 +484,14 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):
outputTokens: open.outputTokens + event.outputTokens,
});
+ // A level, not a cost: the newest reading REPLACES the last one, where the
+ // token counts beside it accumulate.
+ case 'context':
+ return patchLast(turns, { context: { used: event.used, window: event.window } });
+
+ case 'compacted':
+ return withEntries(turns, [...closeProse(open.entries), { kind: 'folded', runs: event.runs }]);
+
case 'error':
return withEntries(turns, [...closeProse(open.entries), { kind: 'error', message: event.message }]);
@@ -479,6 +513,22 @@ export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent):
}
}
+/**
+ * The most recent reading the conversation produced, or null before there is
+ * one (a conversation that has not had an answer yet has no context to be full
+ * of).
+ *
+ * Searched backwards rather than read off the last run, because a run that has
+ * only just started carries none — and a gauge that blanked at the top of every
+ * turn would go missing exactly while the thing it measures is growing fastest.
+ */
+export function latestContext(turns: readonly AgentTurn[]): { used: number; window: number } | null {
+ for (let i = turns.length - 1; i >= 0; i--) {
+ if (turns[i].context) return turns[i].context;
+ }
+ return null;
+}
+
/**
* A tool's result as the ONE cell beside its row: the "58" next to
* `get_scene_tree`, not the tree. The full text stays in `summary`, one click
diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.css
index 9a516eacd..8e9a19a72 100644
--- a/desktop/src/theme/agent.css
+++ b/desktop/src/theme/agent.css
@@ -55,6 +55,28 @@
.ag-head button:hover { color: var(--text-hi); background: var(--hover); }
.ag-head button.on { color: var(--text-hi); background: var(--pressed); }
+/* How full the model's memory is, beside the button that starts a fresh
+ conversation. Quiet: it is a reading, and it sits among controls. */
+.ag-ctx {
+ display: flex; align-items: center; gap: 6px;
+ flex: none;
+ margin-right: 6px;
+ font-size: var(--fs-2xs);
+ color: var(--text-faint);
+ white-space: nowrap;
+}
+.ag-ctx-bar {
+ width: 32px; height: 3px;
+ border-radius: 2px;
+ background: var(--line);
+ overflow: hidden;
+}
+.ag-ctx-bar i { display: block; height: 100%; background: var(--text-faint); }
+/* Past the point where the oldest runs start being folded away. Emphasis, not
+ alarm — see ContextMeter on why this is not the amber. */
+.ag-ctx.near { color: var(--text-dim); }
+.ag-ctx.near .ag-ctx-bar i { background: var(--text-dim); }
+
.ag-log { flex: 1; overflow-y: auto; overflow-x: hidden; min-height: 0; padding-bottom: 12px; }
/* ── The mark ───────────────────────────────────────────────────────────────
@@ -103,6 +125,21 @@
}
.ag-sys::before, .ag-sys::after { content: ''; height: 1px; background: var(--line); flex: 1; }
+/* Where the model stopped remembering its earliest runs. Not one of the
+ hairline notes above: those are asides about a message, and this one is about
+ the conversation itself — it needs a second sentence, because "folded away"
+ without "your questions are kept" reads as the agent having lost the plot. */
+.ag-folded {
+ display: flex; gap: 9px;
+ padding: 10px 14px;
+ border-top: 1px solid var(--line);
+ border-bottom: 1px solid var(--line);
+ font-size: var(--fs-xs);
+ color: var(--text-dim);
+}
+.ag-folded > svg { flex: none; margin-top: 2px; color: var(--text-faint); }
+.ag-folded-w { display: block; margin-top: 3px; color: var(--text-faint); }
+
/* ── A run ─────────────────────────────────────────────────────────────────
The unit of work, so it gets a header: what was asked plus the numbers that
get checked afterwards. Only the CURRENT run sticks — every past header
diff --git a/desktop/tests/agent-compaction.test.ts b/desktop/tests/agent-compaction.test.ts
index 94e8aacc1..dd691bf40 100644
--- a/desktop/tests/agent-compaction.test.ts
+++ b/desktop/tests/agent-compaction.test.ts
@@ -9,7 +9,8 @@
* conversation, so they must outlive the messages they pointed at.
*/
import { describe, it, expect } from 'vitest';
-import { compactHistory } from '../electron/agent/anthropic';
+import { compactHistory, createAnthropicProvider } from '../electron/agent/anthropic';
+import { KEEP_WHOLE_RUNS, COMPACT_AT } from '../src/settings/agentIds';
type Message = Parameters<typeof compactHistory>[0][number];
@@ -126,3 +127,62 @@ describe('compacting a long conversation', () => {
.toEqual([{ role: 'user', content: 'ask 6' }]);
});
});
+
+/**
+ * When the session decides to fold, and what it can then SAY about it — the
+ * half a person sees. A conversation that quietly stopped remembering its
+ * earliest runs, while the transcript on screen still showed them in full, is
+ * the state this reporting exists to end.
+ */
+describe('a session deciding to compact', () => {
+ /** A session of `runs` bulky runs against a deliberately small window. Reached
+ * through the private surface because step() past this point is the network,
+ * and the decision is made before that — the same trick the dialect suite
+ * uses for flushContext(). */
+ const conversation = (runs: number, contextWindow = 4000) => {
+ const session = createAnthropicProvider({ apiKey: 'k', contextWindow })
+ .createSession({ system: 'be useful', tools: [] });
+ for (let i = 0; i < runs; i++) {
+ session.pushUser(`ask ${i}`);
+ session.pushToolResults([{ id: `c${i}`, content: 'x'.repeat(4000), isError: false }]);
+ }
+ return session as unknown as {
+ compactIfNeeded(): number;
+ contextUsed(): number;
+ lastInputTokens: number;
+ turnIndex: number;
+ };
+ };
+
+ it('says how many runs went, because nothing else can', () => {
+ const session = conversation(6);
+ expect(session.compactIfNeeded()).toBe(6 - KEEP_WHOLE_RUNS);
+ });
+
+ it('leaves a conversation inside its window alone, and reports nothing', () => {
+ expect(conversation(6, 1_000_000).compactIfNeeded()).toBe(0);
+ });
+
+ // The coordinate the editor names runs by. Folding messages away must not
+ // renumber the runs that are left — see the suite above.
+ it('does not renumber what survives', () => {
+ const session = conversation(6);
+ expect(session.turnIndex).toBe(6);
+ session.compactIfNeeded();
+ expect(session.turnIndex).toBe(6);
+ });
+
+ // What the endpoint billed is the LARGER half of the reading on an honest
+ // endpoint, and it describes the history that was just rewritten. Left in
+ // place, the gauge would not move after a fold that emptied most of the
+ // conversation, and the next step would fold again over a stale full reading.
+ it('stops reporting the request it just threw away', () => {
+ const session = conversation(12, 8000);
+ session.lastInputTokens = 20_000; // what the endpoint billed
+ expect(session.contextUsed()).toBe(20_000); // the larger half wins
+
+ expect(session.compactIfNeeded()).toBe(12 - KEEP_WHOLE_RUNS);
+ // It now reads what is actually there — back under the threshold that fired.
+ expect(session.contextUsed()).toBeLessThan(8000 * COMPACT_AT);
+ });
+});
diff --git a/desktop/tests/agent-queue.test.ts b/desktop/tests/agent-queue.test.ts
index 5099e541e..ce47f4122 100644
--- a/desktop/tests/agent-queue.test.ts
+++ b/desktop/tests/agent-queue.test.ts
@@ -113,7 +113,7 @@ describe('messages typed while a turn runs', () => {
*/
describe('asking a run again', () => {
const turn = (id: number, prompt: string) => ({
- id, prompt, model: 'm', entries: [], inputTokens: 0, outputTokens: 0,
+ id, prompt, model: 'm', entries: [], inputTokens: 0, outputTokens: 0, context: null,
steps: 0, mark: null, reason: 'end_turn' as const, startedAt: 0, endedAt: 1,
});
diff --git a/desktop/tests/agent-transcript.test.ts b/desktop/tests/agent-transcript.test.ts
index 2aeacfb52..02065efe7 100644
--- a/desktop/tests/agent-transcript.test.ts
+++ b/desktop/tests/agent-transcript.test.ts
@@ -9,7 +9,7 @@
*/
import { describe, it, expect } from 'vitest';
import {
- applyAgentEvent, entitiesInInput, touchedEntities, briefResult,
+ applyAgentEvent, entitiesInInput, touchedEntities, briefResult, latestContext,
type AgentTurn, type AgentToolEntry, type AgentProseEntry,
} from '../src/store/AgentStore';
import type { AgentEvent, ToolCall } from '../electron/agent/types';
@@ -186,6 +186,48 @@ describe('the transcript projection', () => {
expect(turn).toMatchObject({ inputTokens: 2600, outputTokens: 110 });
});
+ // A level, where usage is a cost. The newest reading replaces the last one —
+ // added up, the gauge would pass the window in three turns and claim a
+ // conversation was full while the model was still answering it.
+ it('replaces the context reading rather than accumulating it', () => {
+ const [turn] = fold(
+ started(),
+ { type: 'context', used: 12_000, window: 200_000 },
+ { type: 'context', used: 31_000, window: 200_000 },
+ );
+ expect(turn.context).toEqual({ used: 31_000, window: 200_000 });
+ });
+
+ // The runs it folded away are still on screen above this line, which is why
+ // the line has to be in the run where it happened rather than a badge on it.
+ it('marks where the model stopped remembering its earliest runs', () => {
+ const [turn] = fold(
+ started(),
+ { type: 'thinking', delta: 'this is a long one' },
+ { type: 'compacted', runs: 4 },
+ { type: 'text', delta: 'Carrying on.' },
+ );
+ expect(turn.entries.map((e) => e.kind)).toEqual(['thinking', 'folded', 'text']);
+ expect(turn.entries[1]).toEqual({ kind: 'folded', runs: 4 });
+ // The block above it is over: a fold is something else beginning.
+ expect((turn.entries[0] as AgentProseEntry).endedAt).not.toBeNull();
+ });
+
+ // A run that has only just started carries no reading, and a gauge that
+ // blanked at the top of every turn would go missing exactly while the thing
+ // it measures grows fastest.
+ it('reads the latest context back through runs that have none', () => {
+ expect(latestContext([])).toBeNull();
+ const turns = fold(
+ started('one'),
+ { type: 'context', used: 90_000, window: 200_000 },
+ ended(),
+ started('two', 1),
+ );
+ expect(turns[1].context).toBeNull();
+ expect(latestContext(turns)).toEqual({ used: 90_000, window: 200_000 });
+ });
+
// Stamped on this side of the IPC because it is what the PERSON waited.
it('stamps when the run started and when it stopped', () => {
const [running] = fold(started());
@@ -257,8 +299,8 @@ describe('which entities a turn touched', () => {
state: 'ok', summary: 'ok', brief: 'ok', image: null, argText: '', reason: null, ...over,
});
const turn = (entries: AgentToolEntry[], id = 0): AgentTurn => ({
- id, prompt: 'p', model: 'opus-5', entries, inputTokens: 0, outputTokens: 0, steps: 1,
- mark: { seq: 1 }, reason: 'end_turn', startedAt: 0, endedAt: 1,
+ id, prompt: 'p', model: 'opus-5', entries, inputTokens: 0, outputTokens: 0, context: null,
+ steps: 1, mark: { seq: 1 }, reason: 'end_turn', startedAt: 0, endedAt: 1,
});
it('reads the ids out of the argument names the catalog uses', () => {