A local-first multi-agent app development platform, built on PenguinHarness
fix: a history window names the model of the context it starts in (#903)
Yaowei Zheng0730efbe59d1
diff --git a/changelog/unreleased/2026-09-30-history-window-context-model.md b/changelog/unreleased/2026-09-30-history-window-context-model.mdnew file mode 100644index 00000000..addacbba--- /dev/null+++ b/changelog/unreleased/2026-09-30-history-window-context-model.md@@ -0,0 +1,15 @@+# A history window names the model of the context it starts in++- **Date:** 2026-09-30+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#903](https://github.com/Prism-Shadow/penguin-harness/pull/903)++[中文版](2026-09-30-history-window-context-model.zh.md)++A windowed read of `GET /api/sessions/:sessionId/messages` that started partway into a model context did not say which model that context ran on: the `session_meta` naming it heads the context's Trace file, ahead of the window. After an [in-session model switch](2026-09-16-in-session-model-switch.md) the Web App therefore priced the Tasks at the top of such a window on the Session's current model, and showed no "Model switched" marker for a switch whose old context began before the window. The page envelope now carries that model.++## Details++- Windowed responses gained `page.contextModel` (`{ provider, modelId }`): the model named by the `session_meta` heading the Trace file the window's first unit lies in. It is absent for a Session with no Trace. No record is repeated to say it, so windows still tile the transcript exactly.+- The Web App seeds every window it loads, the tail and each earlier page, with that model. A Task's cost estimate is priced on the model the Task ran on wherever the window starts, and a switch inside a window is marked even when the context it closed began before the window.diff --git a/changelog/unreleased/2026-09-30-history-window-context-model.zh.md b/changelog/unreleased/2026-09-30-history-window-context-model.zh.mdnew file mode 100644index 00000000..60acebd4--- /dev/null+++ b/changelog/unreleased/2026-09-30-history-window-context-model.zh.md@@ -0,0 +1,15 @@+# 历史窗口带上其起点所在上下文的模型++- **Date:** 2026-09-30+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#903](https://github.com/Prism-Shadow/penguin-harness/pull/903)++[English](2026-09-30-history-window-context-model.md)++`GET /api/sessions/:sessionId/messages` 的窗口式读取若从某个模型上下文的中途开始,响应里并不说明这个上下文运行在哪个模型上:记录模型的 `session_meta` 位于该上下文 Trace 文件的开头,在窗口之前。[会话内切换模型](2026-09-16-in-session-model-switch.zh.md)之后,Web App 因此把这类窗口开头几个 Task 的费用按 Session 当前模型计价;旧上下文始于窗口之前的那次切换,也不显示「模型已切换」标记。现在分页信息带上了这个模型。++## 细节++- 窗口式响应新增 `page.contextModel`(`{ provider, modelId }`):窗口第一个单元所在 Trace 文件开头那条 `session_meta` 所记的模型;Session 还没有 Trace 时不带。为此不重复任何记录,各窗口仍然恰好拼成完整的消息历史。+- Web App 加载的每个窗口(尾部窗口与每个更早的分页)都以这个模型为起点:无论窗口从哪里开始,Task 的费用估算都按它实际运行的模型计价;窗口内的切换即使其旧上下文始于窗口之前,也会显示标记。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 0b89e4bf..be4ad2be 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -688,7 +688,7 @@ Two conventions apply to every route here. A Session the caller cannot access al- `GET /` returns the Session's info. Unlike the list rows, the single-Session response also carries `tracePath`, the absolute path of the latest Trace file. `orgId` marks a Session that company mode's caches own (a desk session, or a session contributing to one of that organization's tickets); it is absent on every ordinary Session, and the list route sets it too.- `PATCH /` with `thinkingLevel` pins the level on this Session durably, from its very next LLM request. The thinking level is soft-limited: it can change mid-context, at the cost of the provider's cached context, which is why the level picker advises compacting first. The pinned level comes back as `SessionInfo.thinkingLevel`; when that is absent, no level was ever pinned and the agent config applies.-- `GET /messages` without parameters returns the full OmniMessage history. `tailLimit=n` reads the newest n Task-aligned units instead, and `before=<cursor>&limit=n` reads the n units before a cursor. The two forms are exclusive, `n` is between 1 and 1000, and `limit` defaults to 200. The bundled Web App opens a conversation on its latest 50 turns and loads earlier ones as you scroll. A windowed response carries `page`, with the cursor for the next page (`before`), the number of turns before the window (`earlierTurns`) and the cumulative stats before it (`prior`). While a Task runs, the response also carries `live`; see [The live field on GET /messages](#the-live-field-on-get-messages).+- `GET /messages` without parameters returns the full OmniMessage history. `tailLimit=n` reads the newest n Task-aligned units instead, and `before=<cursor>&limit=n` reads the n units before a cursor. The two forms are exclusive, `n` is between 1 and 1000, and `limit` defaults to 200. The bundled Web App opens a conversation on its latest 50 turns and loads earlier ones as you scroll. A windowed response carries `page`, with the cursor for the next page (`before`), the number of turns before the window (`earlierTurns`), the cumulative stats before it (`prior`), and the model of the context the window starts in (`contextModel`): a Session can switch models between contexts, and a window that starts partway into one does not hold the `session_meta` that names its model. While a Task runs, the response also carries `live`; see [The live field on GET /messages](#the-live-field-on-get-messages).- `GET /context` returns the parts the current model context is made of, plus `compactionThreshold`: the context size, in tokens, at which the Session's next request starts compaction. That threshold is the agent's `compaction.max_context_length`, capped by the room the model's context window leaves. It is `null` when compaction is disabled, when the agent's config cannot be read, or when the threshold is not below the window. The route reads the newest Trace file on every call, so the figures are a snapshot rather than a live counter.- `GET /goal` returns `{goal}`, which is `null` if the Session never ran a goal, or otherwise `{objective, status, budget, used, rounds}`. `status` is `active`, `complete`, `blocked`, `budget_limited` or `aborted`, and a `budget` of -1 means unlimited. A goal lives only inside its run, so a goal that still reads as active while the Session is not running is reported as `aborted`. See [Goal mode](/goal-mode).diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 9fceb579..1497d42a 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -688,7 +688,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估- `GET /` 返回 Session 的信息。与列表行不同,单个 Session 的响应还带 `tracePath`,即最新 Trace 文件的绝对路径。`orgId` 标记公司模式缓存持有的会话(工位会话,或这个组织某个工单的贡献会话);普通 Session 一律不带这个字段,列表路由同样会设置它。- `PATCH /` 带 `thinkingLevel` 会把这个思考等级持久地固定到这个 Session,从下一次 LLM 请求开始生效。思考等级是软性限制:可以在上下文中途更改,代价是损失供应商已缓存的上下文,因此等级选择器会建议先压缩。固定后的等级以 `SessionInfo.thinkingLevel` 返回;没有这个字段说明从未固定等级,此时采用 Agent 配置。-- `GET /messages` 不带参数时返回完整的 OmniMessage 历史。`tailLimit=n` 改为读取最新的 n 个按 Task 对齐的单元,`before=<cursor>&limit=n` 读取某个游标之前的 n 个单元。两种形式互斥,`n` 在 1 到 1000 之间,`limit` 默认为 200。内置 Web App 打开一段对话时先显示最近 50 轮,滚动时再加载更早的内容。窗口式响应带 `page`,包含下一页的游标(`before`)、窗口之前的轮数(`earlierTurns`)和此前累计的统计(`prior`)。Task 运行期间,响应还会带 `live`;见 [GET /messages 上的 live 字段](#get-messages-上的-live-字段)。+- `GET /messages` 不带参数时返回完整的 OmniMessage 历史。`tailLimit=n` 改为读取最新的 n 个按 Task 对齐的单元,`before=<cursor>&limit=n` 读取某个游标之前的 n 个单元。两种形式互斥,`n` 在 1 到 1000 之间,`limit` 默认为 200。内置 Web App 打开一段对话时先显示最近 50 轮,滚动时再加载更早的内容。窗口式响应带 `page`,包含下一页的游标(`before`)、窗口之前的轮数(`earlierTurns`)、此前累计的统计(`prior`),以及窗口起点所在上下文的模型(`contextModel`):Session 可以在上下文之间切换模型,而从某个上下文中途开始的窗口并不包含记录其模型的那条 `session_meta`。Task 运行期间,响应还会带 `live`;见 [GET /messages 上的 live 字段](#get-messages-上的-live-字段)。- `GET /context` 返回当前模型上下文的各个组成部分,外加 `compactionThreshold`:上下文达到多大(以 Token 计)时,Session 的下一个请求会开始压缩。这个阈值就是 Agent 的 `compaction.max_context_length`,上限不超过模型上下文窗口的剩余空间。压缩未启用、读不到 Agent 配置,或阈值不低于窗口时,这个值是 `null`。这条路由每次调用都读取最新的 Trace 文件,所以数值是快照,不是实时计数器。- `GET /goal` 返回 `{goal}`:Session 从未跑过目标时为 `null`,否则为 `{objective, status, budget, used, rounds}`。`status` 取值为 `active`、`complete`、`blocked`、`budget_limited` 或 `aborted`,`budget` 为 -1 表示不限制。目标只存活在它的运行期间,所以 Session 已停止运行、目标却仍是 active 时,会报告为 `aborted`。见[目标模式](/goal-mode)。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 4a0ccb30..1cbca80c 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1815,6 +1815,14 @@ export interface MessagesPageInfo {sessionTokens: number;contextTokens: number;};+ /**+ * The model of the context this window starts in — what the `session_meta` heading that+ * context's Trace file names. A Session can switch models between contexts, and a window+ * that starts partway into one does not hold that record: the client seeds it, so the Tasks+ * ahead of the window's first `session_meta` have their model, and a switch further down the+ * window is told from a plain rotation. Absent when the Session has no Trace yet.+ */+ contextModel?: ModelRefDto;}/** Message history: the full messages and events from concatenating all of this Session's Trace files in order (excludes partial_*). */diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 3151874f..4e1c063b 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -956,6 +956,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {sessionTokens: result.prior.sessionTokens,contextTokens: result.prior.contextTokens,},+ ...(result.contextModel !== undefined ? { contextModel: result.contextModel } : {}),};return c.json({messages: appendPendingInputs(result.messages, pendingInputs),diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex 59e44fad..810efd43 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -178,6 +178,12 @@ export interface MessagesPageResult {before?: string;/** Cumulative stats before the window (earlierTurns = prior.turns). */prior: WindowPriorStats;+ /**+ * The model of the context the window starts in: the `session_meta` heading the shard its+ * first unit lies in. One shard is one model context, and a window that starts partway into+ * one does not hold that record. Absent for an empty transcript.+ */+ contextModel?: { provider: string; modelId: string };}export interface ForkTraceResult {@@ -629,7 +635,21 @@ export class TraceService implements Traces {}}const expanded = await this.expandMessages(projectId, windowRaw, ctx);- return { messages: expanded, ...(before !== undefined ? { before } : {}), prior };+ // The start shard was read for the window above, so its head is on hand.+ const startMeta = shardMessages.get(start.pos)?.find(isSessionMeta);+ return {+ messages: expanded,+ ...(before !== undefined ? { before } : {}),+ prior,+ ...(startMeta+ ? {+ contextModel: {+ provider: startMeta.payload.provider,+ modelId: startMeta.payload.model_id,+ },+ }+ : {}),+ };}/**diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.tsindex dba8d3d0..f461f3d6 100644--- a/packages/server/test/messages-page.test.ts+++ b/packages/server/test/messages-page.test.ts@@ -653,4 +653,80 @@ describe("messages windowed reads", () => {expect(tail.prior.turns).toBe(0);expect(tail.messages).toEqual(await service.readMessages(P, A, S));});++ it("names the model of the context a window starts in: the session_meta heading that shard, which the window does not hold", async () => {+ // A Session that switched models: shard 1 on m1, closed by the switch's compaction; shard 2+ // on another provider's m2, opened with its summary and continued for two turns.+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [+ sessionMeta(metaPayload({ model_id: "m1" })),+ ...turn(0, 1, 1000),+ ...turn(1, 2, 2000),+ at(+ "2026-07-20T10:02:00.000Z",+ compactionBegin({ reason: "manual", mode: "summarize", context: 102, turns: 2 }),+ ),+ at("2026-07-20T10:02:01.000Z", requestBegin()),+ at("2026-07-20T10:02:02.000Z", assistantText("[summary]s[/summary]")),+ at("2026-07-20T10:02:03.000Z", requestEnd("completed")),+ at(+ "2026-07-20T10:02:04.000Z",+ compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }),+ ),+ ]);+ await writeTraceFile(root, P, A, "2026-07-20", S, 2, [+ sessionMeta(metaPayload({ provider: "other", model_id: "m2" })),+ at("2026-07-20T10:02:05.000Z", userText("[context_summary]\ns\n[/context_summary]")),+ ...turn(3, 3, 3000),+ ...turn(4, 4, 4000),+ ]);+ const M1 = { provider: "custom", modelId: "m1" };+ const M2 = { provider: "other", modelId: "m2" };+ const metas = (ms: OmniMessage[]) => ms.filter((m) => m.type === "session_meta");++ // Partway into the context after the switch: no meta in the window, and it runs on m2.+ const last = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 1 });+ expect(userTexts(last.messages)).toEqual(["q4"]);+ expect(metas(last.messages)).toEqual([]);+ expect(last.contextModel).toEqual(M2);++ // From that context's first prompt: still m2 — the records it opened with (its meta, the+ // summary) close the unit before, so they belong to the window before.+ const afterSwitch = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 2 });+ expect(userTexts(afterSwitch.messages)).toEqual(["q3", "q4"]);+ expect(metas(afterSwitch.messages)).toEqual([]);+ expect(afterSwitch.contextModel).toEqual(M2);++ // Partway into the context the switch closed: it starts on m1, and the m2 meta further+ // down is what tells the switch.+ const acrossSwitch = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 3 });+ expect(userTexts(acrossSwitch.messages)[0]).toBe("q2");+ expect(acrossSwitch.contextModel).toEqual(M1);+ expect(+ metas(acrossSwitch.messages).map((m) => (m.payload as SessionMetaPayload).model_id),+ ).toEqual(["m2"]);++ // The window before the switched context ends with that context's opening records.+ const older = await service.readMessagesPage(P, A, S, {+ kind: "before",+ cursor: decodeCursor(afterSwitch.before!)!,+ limit: 1,+ });+ expect(userTexts(older.messages)[0]).toBe("q2");+ expect(older.contextModel).toEqual(M1);+ expect((older.messages.at(-2)!.payload as SessionMetaPayload).model_id).toBe("m2");++ // A window that reaches the beginning holds the first meta itself and names the same model.+ const whole = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 50 });+ expect(whole.before).toBeUndefined();+ expect(whole.contextModel).toEqual(M1);+ // Nothing is repeated to say so: the windows still tile the transcript exactly.+ const first = await service.readMessagesPage(P, A, S, {+ kind: "before",+ cursor: decodeCursor(older.before!)!,+ limit: 5,+ });+ expect([...first.messages, ...older.messages, ...afterSwitch.messages]).toEqual(+ await service.readMessages(P, A, S),+ );+ });});diff --git a/packages/server/test/session-fork.test.ts b/packages/server/test/session-fork.test.tsindex abfed01f..4153e262 100644--- a/packages/server/test/session-fork.test.ts+++ b/packages/server/test/session-fork.test.ts@@ -418,6 +418,8 @@ describe("session fork", () => {(message) => (message.payload as { text?: string }).text === "fork shard two",);expect(selected?.tracePosition).toEqual({ fileIndex: 2, ordinal: 4 });+ // The window starts partway into shard two: the page says which model that context is on.+ expect(tail.page?.contextModel).toEqual({ provider: meta.provider, modelId: meta.model_id });const response = await api.post(`/api/sessions/${SID}/fork`, {position: selected!.tracePosition,diff --git a/packages/web/src/features/chat/model-switch.ts b/packages/web/src/features/chat/model-switch.tsindex 41217820..62908930 100644--- a/packages/web/src/features/chat/model-switch.ts+++ b/packages/web/src/features/chat/model-switch.ts@@ -48,9 +48,8 @@ export function switchContextShape(items: ReadonlyArray<ThinkingSwitchItem>): Sw* context's `session_meta` (the stream model's `contextModel`) is of this Session and says so —* a switch completed, on this tab or another one watching the Session, or the row was held from* before a switch. The page then moves the row to that model; the server moved its own before- * it published the record. False while no meta of this Session has been seen: a history window- * that starts after the context's meta derives nothing, and the stream of a conversation the- * page has just left says nothing about the row it now holds.+ * it published the record. False while the stream says nothing of this Session's model: before+ * its history has loaded, and for the stream of a conversation the page has just left.*/export function sessionRowStale(contextModel: (ModelRefDto & { sessionId: string }) | null,diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.tsindex d2e4c61d..2a7af9b9 100644--- a/packages/web/src/features/chat/use-session-stream.ts+++ b/packages/web/src/features/chat/use-session-stream.ts@@ -235,6 +235,7 @@ export function useSessionStream(};const controller = createStreamController({+ sessionId,// The whole response rides through: `live` (in-progress stream tail) lets the// controller seed the currently streaming message after a reload, and `page` (the// windowed-history envelope) drives tail-first loading (see stream-controller).diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.tsindex 3e87c40d..5a2fd2d7 100644--- a/packages/web/src/lib/omni/stream-controller.ts+++ b/packages/web/src/lib/omni/stream-controller.ts@@ -104,6 +104,8 @@ export const OLDER_UNITS = 50;const PREPEND_ID_SPAN = 1_000_000;export interface StreamControllerDeps {+ /** The Session whose stream this is: the owner of the model a history window starts on (see MessagesPageInfo.contextModel). */+ sessionId: string;/*** Fetch history messages (GET /api/sessions/:id/messages), including the live tail while* running. `serverNowMs` is the server's clock at read time (the response's `Date` header);@@ -423,6 +425,19 @@ export function createStreamController(deps: StreamControllerDeps): StreamControreturn [...pre, ...seeds, ...post];};+ /**+ * Seeds a model with what came before the window it is about to take: the stats accrued+ * ahead of it, so header chips and per-turn cumulative rows equal a full load (see+ * seedPriorStats), and the model its first context runs on, whose `session_meta` a window+ * that starts partway into that context does not hold.+ */+ const seedWindow = (target: StreamModel, page: MessagesPageInfo): void => {+ seedPriorStats(target.stats, page.prior);+ if (page.contextModel !== undefined) {+ target.contextModel = { sessionId: deps.sessionId, ...page.contextModel };+ }+ };+const load = async (currentEpoch: number,freshModel?: StreamModel,@@ -459,9 +474,7 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro// freshModel and keep operating on the current model.if (freshModel) model = freshModel;const target = model;- // Windowed loads seed the stats accrued before the window, so header chips and- // per-turn cumulative rows equal a full load (see seedPriorStats).- if (res.page !== undefined) seedPriorStats(target.stats, res.page.prior);+ if (res.page !== undefined) seedWindow(target, res.page);pushMessages(target, messages, now(), serverNowMs ?? null);const dedup = buildDedupIndex(messages, 100);// Replay the buffer (events that arrived while fetching history), with dedup; while a@@ -529,7 +542,7 @@ export function createStreamController(deps: StreamControllerDeps): StreamControprependCount += 1;const m = createStreamModel(localDecisions);m.nextItemId = -prependCount * PREPEND_ID_SPAN;- seedPriorStats(m.stats, res.page.prior);+ seedWindow(m, res.page);pushMessages(m, res.messages, now(), null);finalizeHistory(m);prefixItems = [...m.items, ...prefixItems];diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.tsindex c40ab566..eac50a86 100644--- a/packages/web/src/lib/omni/stream-model.ts+++ b/packages/web/src/lib/omni/stream-model.ts@@ -449,8 +449,10 @@ export interface TaskStatsItem {memoryChanges?: MemoryChangeRow[];/*** The model this Task ran on — the one its context's `session_meta` names (see- * `StreamModel.contextModel`). Absent when the window held no meta before the Task began;- * the cost shown beside the row is then priced on the Session's current model.+ * `StreamModel.contextModel`). Absent when nothing had said which by the time the Task+ * began — the history was read before the Session's Trace existed, and a first context's+ * meta is never streamed; the cost shown beside the row is then priced on the Session's+ * current model.*/model?: { provider: string; modelId: string };}@@ -500,10 +502,11 @@ export interface StreamModel {agentState: string | null;/*** The model the running context was opened on, and the Session its `session_meta` names (null- * until one arrives). A Session's model can change between contexts — each context's meta- * records its own — so this follows rotations, and a main-session meta naming another model- * than the one held pushes a model-change marker. The chat page moves its Session row to this- * model when the two disagree (see `sessionRowStale`).+ * until one arrives, or a history window says which model it starts on). A Session's model+ * can change between contexts — each context's meta records its own — so this follows+ * rotations, and a main-session meta naming another model than the one held pushes a+ * model-change marker. The chat page moves its Session row to this model when the two+ * disagree (see `sessionRowStale`).*/contextModel: { sessionId: string; provider: string; modelId: string } | null;/** `contextModel` as the open Task began: a switch only happens between Tasks, so this is the model the whole Task runs on (see `TaskStatsItem.model`). */@@ -775,8 +778,8 @@ export function pushMessage(// child, on which model); the main session takes the rest of its identity/config from the// Session DTO. A rewritten session_meta (file rotation) overwrites with the same values. On// the main session a meta naming another model than the one held means the Session switched- // models: a marker says so — never for the window's first meta, a same-model rewrite, or a- // nested child's meta.+ // models: a marker says so — never for a same-model rewrite, a nested child's meta, or the+ // first meta of a model that was told nothing of the context it starts in.if (msg.type === "session_meta") {const p = msg.payload as SessionMetaPayload;model.agentState = p.agent_state;diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.tsindex 3fc2c369..0c613ead 100644--- a/packages/web/test/stream-controller.test.ts+++ b/packages/web/test/stream-controller.test.ts@@ -10,8 +10,11 @@ import { describe, expect, it } from "vitest";import {approvalDecision,assistantText,+ compactionBegin,+ compactionEnd,partialText,partialToolCallOutput,+ sessionMeta,tokenUsage,toolCall,userText,@@ -82,6 +85,7 @@ function createHarness(): Harness {const pageArgs: Array<MessagesPageQuery | undefined> = [];let calls = 0;const controller = createStreamController({+ sessionId: "s1",loadMessages: (page) =>new Promise<{messages: OmniMessage[];@@ -619,6 +623,61 @@ describe("windowed history: tail-first load + scroll-up backfill", () => {expect(oldStats.stats!.tokens).toBe(400);});+ it("a window is seeded with the model of the context it starts in: its first Tasks name it and a switch further down is marked, in the tail and in a backfilled window alike", async () => {+ const metaOn = (provider: string, modelId: string): OmniMessage =>+ sessionMeta({+ session_id: "s1",+ provider,+ model_id: modelId,+ model_context_window: 1000,+ system_prompt: "",+ agent_state: "/tmp/a",+ workspace: "/tmp/w",+ });+ const A = { provider: "anthropic", modelId: "a-1" };+ const B = { provider: "openai", modelId: "b-2" };+ const h = createHarness();+ const p = h.controller.load();+ h.controller.handleServer({ type: "task_state", state: "idle" });+ // The tail starts partway into a context on a-1 — no meta of it in the window — and crosses+ // a switch: an ordinary manual compaction, then the next context's meta on b-2.+ h.resolveLoad(+ [+ ...HISTORY_TASK,+ at(+ compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 1 }),+ "2026-07-05T00:01:00.000Z",+ ),+ at(+ compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }),+ "2026-07-05T00:01:05.000Z",+ ),+ at(metaOn(B.provider, B.modelId), "2026-07-05T00:01:06.000Z"),+ at(userText("next question"), "2026-07-05T00:02:00.000Z"),+ at(assistantText("next answer"), "2026-07-05T00:02:03.000Z"),+ at(tokenUsage(counts(300), counts(300)), "2026-07-05T00:02:05.000Z"),+ ],+ undefined,+ null,+ pageInfo({ before: "1:8", earlierTurns: 1, contextModel: A }),+ );+ await p;+ const items = h.controller.model.items;+ const stats = items.filter((i) => i.kind === "task_stats") as TaskStatsItem[];+ expect(stats.map((s) => s.model)).toEqual([A, B]);+ expect(items.filter((i) => i.kind === "model_change")).toMatchObject([{ from: A, to: B }]);+ // The running context is the one the window ends in, under the Session the stream is of.+ expect(h.controller.model.contextModel).toEqual({ sessionId: "s1", ...B });++ // The window before starts in an earlier context of its own.+ const C = { provider: "zhipu", modelId: "c-0" };+ const older = h.controller.loadOlder();+ h.resolveLoad(OLD_TURN, undefined, null, pageInfo({ earlierTurns: 0, contextModel: C }));+ await older;+ const oldStats = h.controller.prefixItems.find((i) => i.kind === "task_stats") as TaskStatsItem;+ expect(oldStats.model).toEqual(C);+ });+it("loadOlder without more history, while loading, or before the initial load is a no-op", async () => {const h = createHarness();const early = h.controller.loadOlder(); // buffering phase: ignored