Compare commits

..

3 Commits

Author SHA1 Message Date
Aleksandr Slapoguzov
1a014a7bec perf: scan a parent transcript incrementally for new nested launches
The launch scan of a child that launched children searched for the ids of
its known nested launches, and kept them in the key of its cached scan. A
new nested launch changed the key, so the next status read searched the
whole parent transcript again.

The scan now looks for every Agent and Task launch call, the results of the
calls it found and the task notifications. A new launch is in the appended
bytes, so the scan stays incremental. The read filters the lines by the
launches of the metadata when it parses them. A file that was replaced or
shortened, whose found lines moved, or whose scanned bytes no longer end a
line, is scanned again from the start. So is a file whose scan did not find
a launch that the metadata names, once for each such launch.
2026-12-04 15:36:18 +01:00
Aleksandr Slapoguzov
8a97739cc4 perf: rebuild only the status after a child append in a status read
A cached status cursor checked the file version of every child transcript,
and any change rendered the whole root history again. The root render does
not depend on the transcript of a child that launched no children: the read
uses only its end, for the status update, which is outside the cursor.

When only such transcripts changed, the read now reads their ends again and
sends the cached root part, the same cursor and the new status. A change to
the transcript of a child that launched children still renders again,
because the launches in it are on that child's stream.
2026-12-04 15:36:18 +01:00
Aleksandr Slapoguzov
13f2aa9fd6 perf: keep the quiet read path for tools that render from the transcript
The cached cursor of a root or child read skipped the render only when
every tool call was Bash, PowerShell, Read, Write, Edit, Glob or Grep (and
SubagentHandback in a child). One TodoWrite, ToolSearch, SendMessage,
Skill, Artifact or MCP call made every poll render again. The check is now
a deny-list of the tools whose render reads other files.

Audit of the render path (v1 `replaySessionHistory`, v2
`renderSessionRead`, the tool reporters, `toolUseMeta`, the subagent
replays and the async task replay):

| Tool | Files its render reads | Root read | Child read |
|---|---|---|---|
| Agent, Task | subagent metadata and transcripts | denied (status read compares them) | denied |
| ExitPlanMode | whether the plan file exists (AIR `planFile`) | denied | denied |
| Skill | the SKILL.md that AIR's link names, in the cwd and home folder (AIR clients only) | compared on AIR clients, allowed otherwise | denied |
| SendMessage | none without an Agent or Task launch in the history; in a child read every transcript | allowed | denied |
| Bash, PowerShell, Read, Write, Edit, NotebookEdit, Glob, Grep, WebFetch, WebSearch, TodoWrite, Task*, TaskOutput, TaskStop, Monitor, ListAgents, AskUserQuestion, EnterPlanMode, ReportFindings, SubagentHandback, MCP and unknown tools | none: stored input and result only | allowed | allowed |

For an AIR client, a root checkpoint stores the SKILL.md path of each
skill of its Skill calls and resolves them again on the next poll, so a
new or removed skill makes the poll render. Other clients get no link, so
their checkpoint does not look at skill files.

On a synthetic 100 MB root with TodoWrite, MCP and ToolSearch calls, a
quiet status poll took 1.07 s and now takes 1 ms; a quiet default poll of
the same root without Agent calls took 1.0 s and now takes under 1 ms.
2026-12-04 15:35:17 +01:00
7 changed files with 620 additions and 94 deletions

View File

@@ -14,7 +14,7 @@ A missing transcript returns `-32002`. A session already open, opening, closing
## Polling cost and scope
A reader with a cached cursor for a root transcript checks the root file identity, size and timestamps, the rewind file, and the stored title when needed. When they match, it skips rendering history. This also covers sessions using Bash, PowerShell, Read, Write, Edit, Glob or Grep. Other tools can depend on child transcripts or workspace files, so their sessions take the full replay path. A reader restart, a pending rewind, or a change to the transcript or its title file also triggers full validation. A new or changed cursor is checked against a second render before delivery. Recorded children share the root request and can append independently. The unit of delivery is the whole suffix, including updates from recorded children. Clients can virtualize that history for display.
A reader with a cached cursor for a root transcript checks the root file identity, size and timestamps, the rewind file, and the stored title when needed. When they match, it skips rendering history. Most tools, MCP tools included, render from their stored input and result, so their sessions keep this quiet path. Agent and Task calls render from the subagent transcripts, and ExitPlanMode from whether its plan file still exists, so a default read of a session with one of them takes the full replay path. A [status read](#status-read) checks the subagent files instead. For a Skill call, an AIR client gets a link to its `SKILL.md`, so for such a client the reader also checks that file in the working directory and the home folder. A reader restart, a pending rewind, or a change to the transcript or its title file also triggers full validation. A new or changed cursor is checked against a second render before delivery. Recorded children share the root request and can append independently. The unit of delivery is the whole suffix, including updates from recorded children. Clients can virtualize that history for display.
The title is the custom title from the transcript tail or `custom-title.json`, as in Claude’s session index. Otherwise it is the last `custom-title` record, or else the last `ai-title` record, of the whole captured transcript. The index reads only the first and last 64 KB of the file, so a large tool result would otherwise hide an unchanged title. The quiet check assumes the local filesystem updates file identity or timestamps on rewrites. The cursor describes the rendered transcript. For current session activity, AIR clients can use the [session index](air-extensions.md#session-index). For clients also talking to older adapters, a successful cursor request that returns `{}` means a full replay. Replace the saved view and clear the cursor.
@@ -38,7 +38,7 @@ Send `filters.subagents: "status"` with a root read:
The read renders the root history as a default read does, with the announcement of each child on its parent's stream: `subagent_spawned` for AIR clients on v1, `subagent_update` with `running` on the RFD form and on v2. It sends none of the end states that a default read sends after the history (`subagent_state_update` on v1 AIR, `subagent_update` with an end otherwise). The status update below holds the current state of each child. A child's stream gets at most the prompt of its launch, the lifecycle updates of its own children and, on v2, its `replay_complete`. No message or tool call of a child's own history is sent.
The read parses no child transcript. Of each child it reads the metadata file and the end of the transcript: the last 64 KB, or twice as many bytes each time while they do not hold a whole record with the model and the end of the last turn, up to 4 MB. A child whose metadata names a working directory, such as a worktree child, also has its transcript read up to the first line with a `cwd`. The transcript of a child that launched children is searched as bytes for the lines that name those launches, and only those lines are parsed. The adapter keeps the places of those lines for each file, so a later read searches only the bytes appended since. A rewritten or replaced file is searched again from the start. A v1 connection without native subagent sessions ignores `filters.subagents` and sends a default read.
The read parses no child transcript. Of each child it reads the metadata file and the end of the transcript: the last 64 KB, or twice as many bytes each time while they do not hold a whole record with the model and the end of the last turn, up to 4 MB. A child whose metadata names a working directory, such as a worktree child, also has its transcript read up to the first line with a `cwd`. The transcript of a child that launched children is searched as bytes for the lines that name an Agent or Task launch: the launch calls, their results and the task notifications. Only those lines are parsed. The adapter keeps the places of those lines for each file, so a later read searches only the bytes appended since, also when they hold a new launch. A replaced or shortened file is searched again from the start, and so is a file whose found lines no longer start and end where they did. A file is also searched again from the start, once, when the metadata names a launch that the search did not find. Other rewrites in place, which keep every line in its place, are not noticed: Claude Code only appends to these transcripts. A v1 connection without native subagent sessions ignores `filters.subagents` and sends a default read.
After the replay and its cursor update, and before the title, each status read sends one update with the current status of every announced child. It is outside the cursor: it comes on every poll, also when the cursor stays the same, and replaces the previous one. The title follows it outside the cursor on v1 too, as on v2 in step 2 above: a null title clears the previous one.
@@ -93,7 +93,7 @@ V1 has no custom update variants, so on v1 the update is a `session_info_update`
- `state` uses the vocabulary of the lifecycle updates. On v1 AIR clients it is a string: `running`, `idle`, `completed`, `failed`, `cancelled` or `disconnected`. Otherwise it is a `subagent_update` state: `{"state":"running"}`, `{"state":"idle"}`, or `{"state":"idle","stopReason":"end_turn" | "cancelled" | "error"}`. The end comes from the last task notification of the child, then from a stop by the user, then from the result of a foreground launch. A background launch's result is no end. A launch whose parent cannot be restored, or a launch with neither a metadata file nor an end, is `disconnected` on v1 AIR clients. Without an end, a child is `idle` when the last user or assistant record of its transcript ends the turn, else `running`. An answer ends the turn with any stop reason except `tool_use` and `pause_turn`, such as `end_turn`, `max_tokens` or `refusal`. So do a record that no model wrote (model `<synthetic>`, such as an API error) and the successful result of a `SubagentHandback` call. `model` is the model of the last record that a model wrote. On the RFD form and v2 a full read reports such a child `idle` too. Past 4 MB without a whole record, a child is `running` with no `model` or `updatedAt`.
- `background`, `agentType` and `cwd` come from the metadata file. `model`, `updatedAt` (the `timestamp` of the last record) and `size` (bytes) come from the transcript. A child without a transcript yet has no `size`.
A child that continues after its end, such as one resumed by `SendMessage`, keeps its end in `state`, and its `size` and `updatedAt` grow. Compare `size` with the previous status to see new work. Because the cursor covers no end state and no title, a child that ends, a stop by the user and a title change keep the cursor valid. The next cursor read returns only new records and the current status. A cached status cursor also covers sessions with Agent and Task calls: it checks the metadata of every child and the file version of each child transcript. A child transcript that is not a regular file, such as a symbolic link, gives no cached cursor.
A child that continues after its end, such as one resumed by `SendMessage`, keeps its end in `state`, and its `size` and `updatedAt` grow. Compare `size` with the previous status to see new work. Because the cursor covers no end state and no title, a child that ends, a stop by the user and a title change keep the cursor valid. The next cursor read returns only new records and the current status. A cached status cursor also covers sessions with Agent and Task calls: it checks the metadata of every child and the file version of each child transcript. When only the transcripts of children that launched no children changed, the read does not render the history again: it reads the ends of those transcripts and sends the same cursor with the new status. A change to the transcript of a child that launched children renders the history again, because the launches in it are on that child's stream. A child transcript that is not a regular file, such as a symbolic link, gives no cached cursor.
Limits:
@@ -118,7 +118,7 @@ Send the root session and one child session id that the client got:
The response and the updates are those of a root read, restricted to the child's stream: every update has the child's session id, including the `cursor_update` and, on v2, the `replay_complete`. They are the updates of that stream in a default read. A child read sends no title. The child id can be the agent id, the agent id with a `:generation:<n>` suffix of a live child, or AIR's `<root>:replay-subagent:<launch id>`. All ids of one child share its stream and cursor.
The cursor belongs to that child: its scope includes the stream, so a root cursor, or another child's, returns `invalid_cursor`. A root cursor is refused before the render, another child's only after it, because the read must find the child's stream first. A rewritten child transcript, such as after a compaction, invalidates it too. The read renders only the transcripts of the child and its ancestors, and of the children it launched. A child that sends or gets a `SendMessage` renders every transcript, because the messages link both streams. A cached child cursor checks the child's transcript, the subagent metadata and the root's rewind file. It skips the render when they are unchanged, unless the child used a tool other than Bash, PowerShell, Read, Write, Edit, Glob, Grep or SubagentHandback.
The cursor belongs to that child: its scope includes the stream, so a root cursor, or another child's, returns `invalid_cursor`. A root cursor is refused before the render, another child's only after it, because the read must find the child's stream first. A rewritten child transcript, such as after a compaction, invalidates it too. The read renders only the transcripts of the child and its ancestors, and of the children it launched. A child that sends or gets a `SendMessage` renders every transcript, because the messages link both streams. A cached child cursor checks the child's transcript, the subagent metadata and the root's rewind file. It skips the render when they are unchanged, unless the child made an Agent, Task, ExitPlanMode, SendMessage or Skill call.
A child that was just launched and has no transcript yet has no records on its stream: its read returns no cursor until the first record is written. Poll it from the start until then. Cached cursors of child reads and of root reads share one limit of 32 per connection; the oldest is dropped first, and its next read renders again.

View File

@@ -23,6 +23,7 @@ import { sanitizeTitle } from "./session-titles.js";
import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
import { withReplyBranches } from "./transcript-branches.js";
import { isNativeSubagentControlTool } from "./native-subagents.js";
import { resolveSkillPath } from "./tool-calls/reporters/interaction.js";
import {
isMissing,
subagentHistory,
@@ -93,8 +94,8 @@ type ReadOptions = {
historyEnd?: number;
title?: string;
storage?: SessionReadStorage;
/** For a status read: the status update, which goes out outside the cursor. */
status?: SessionReadFrame;
/** For a status read: the status, whose update goes out outside the cursor. */
status?: SubagentStatus;
/** For a child read: the session id of the child's stream in `frames`. */
stream?: string;
}>;
@@ -111,6 +112,8 @@ export type SessionReadStorage = {
subagents?: string;
/** Undefined when replay skipped the sidecar, null when it had no title. */
sidecarTitle?: string | null;
/** The SKILL.md of each skill of the root's Skill calls (see {@link skillPaths}). */
skills?: { cwd: string; paths: [name: string, path: string | null][] };
};
function fileVersion(stats: BigIntStats): string {
@@ -155,69 +158,131 @@ function subagentRecords(history: SubagentHistory): string {
return json([...history.agents].sort(([a], [b]) => a.localeCompare(b)));
}
/** Checks the transcript's metadata and the sidecar inputs read by the replay. */
async function storageUnchanged(sessionId: string, storage: SessionReadStorage): Promise<boolean> {
/**
* Checks the transcript's metadata and the sidecar inputs read by the
* replay. Returns the subagent transcripts in `storage.files` that changed,
* with their current versions: empty when nothing changed, undefined when
* another input changed or a file is not a regular file.
*/
async function storageChanges(
sessionId: string,
storage: SessionReadStorage,
): Promise<[path: string, version: string | null][] | undefined> {
try {
// A move or a different matching project must go through the ordinary lookup.
const transcript = await findTranscript(sessionId, { strict: true });
if (transcript !== storage.transcript) return false;
const matchesTranscript = async () => {
if (transcript !== storage.transcript) return undefined;
const transcriptChanges = async () => {
if (storage.version !== undefined) {
const root = await lstat(transcript, { bigint: true });
if (!root.isFile() || fileVersion(root) !== storage.version) return false;
if (!root.isFile() || fileVersion(root) !== storage.version) return undefined;
}
const changed: [string, string | null][] = [];
for (const [file, version] of storage.files ?? []) {
const current = await fileVersionAt(file);
if (current === undefined || current !== version) return false;
if (current === undefined) return undefined;
if (current !== version) changed.push([file, current]);
}
return true;
return changed;
};
if (!(await matchesTranscript())) return false;
if (!(await transcriptChanges())) return undefined;
if (
storage.subagents !== undefined &&
subagentRecords(await subagentHistory(sessionId, { strict: true, transcript })) !==
storage.subagents
)
return false;
return undefined;
if (storage.sidecarTitle !== undefined) {
const title = await readSidecarTitle(transcript, { strict: true });
if ((title ?? null) !== storage.sidecarTitle) return false;
if ((title ?? null) !== storage.sidecarTitle) return undefined;
}
if (await readRewindPoint(sessionId, undefined, { transcript })) return false;
return await matchesTranscript();
if (await readRewindPoint(sessionId, undefined, { transcript })) return undefined;
if (
storage.skills &&
json(
skillPaths(
storage.skills.paths.map(([name]) => name),
storage.skills.cwd,
),
) !== json(storage.skills.paths)
)
return undefined;
// The versions of this second check: the caller reads the changed files after them.
return await transcriptChanges();
} catch {
// An uncertain probe leaves validation and errors to the ordinary replay.
return false;
return undefined;
}
}
/** These tools render their stored input and result, with no child or workspace reads. */
const ROOT_ONLY_TOOLS = new Set(["Bash", "PowerShell", "Read", "Write", "Edit", "Glob", "Grep"]);
/** A child's hand-back renders from its own input and result too. */
const CHILD_ONLY_TOOLS = new Set([...ROOT_ONLY_TOOLS, "SubagentHandback"]);
/**
* The tools whose render reads files besides the transcript and the inputs
* that a checkpoint compares. Every other tool, MCP and unknown tools
* included, renders from its stored input and result. A renderer that starts
* to read a file for a tool must add the tool here.
*
* - Agent and Task: the subagent metadata and transcripts. A status read
* compares them, so there they are no such tools.
* - ExitPlanMode: whether the plan file exists, for AIR clients with `planFile`.
*
* Skill is not here: AIR's link to its SKILL.md depends on files in the
* working directory and the home folder, and a root checkpoint of an AIR
* client compares that link (see {@link skillPaths}). Other clients get no link.
*/
const ROOT_FILE_TOOLS = new Set(["Agent", "Task", "ExitPlanMode"]);
/**
* Whether `content` has a tool call that renders from files that a
* checkpoint does not observe. A status read observes the subagent files, so
* an Agent or Task call is no such call there.
* A child checkpoint compares only the child's own transcript. A SendMessage
* makes the read render every transcript (see {@link findChild}), and the
* child's SKILL.md links are not compared.
*/
function hasIndependentHistory(
content: unknown,
tools = ROOT_ONLY_TOOLS,
launches = false,
): boolean {
const CHILD_FILE_TOOLS = new Set([...ROOT_FILE_TOOLS, "SendMessage", "Skill"]);
const TOOL_USES = ["tool_use", "server_tool_use", "mcp_tool_use"];
/**
* Whether `content` has a tool call of `tools`, which renders from files that
* a checkpoint does not compare. With `launches`, the subagent files are
* compared, so an Agent or Task call is no such call.
*/
function readsOtherFiles(content: unknown, tools: Set<string>, launches = false): boolean {
return (
Array.isArray(content) &&
content.some(
(block) =>
["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type) &&
!tools.has(block.name) &&
TOOL_USES.includes(block?.type) &&
tools.has(block.name) &&
!(launches && isNativeSubagentControlTool(block.name)),
)
);
}
/** The skill names of the Skill calls in `messages`, sorted, each once. */
function skillNames(messages: readonly { message?: unknown }[]): string[] {
const names = new Set<string>();
for (const message of messages) {
const content = contentOf(message);
if (!Array.isArray(content)) continue;
for (const block of content) {
if (TOOL_USES.includes(block?.type) && block.name === "Skill") {
const skill = (block.input as { skill?: unknown } | null)?.skill;
if (typeof skill === "string") names.add(skill);
}
}
}
return [...names].sort();
}
/**
* The SKILL.md that AIR's `_meta` of a Skill call links for each skill in
* `names`, null for none, as the renderer resolves it in `cwd`. It depends
* on the skill folders of `cwd` and of the home folder, so a checkpoint
* resolves it again.
*/
function skillPaths(names: string[], cwd: string): [string, string | null][] {
return names.map((name) => [name, resolveSkillPath(name, cwd) ?? null]);
}
function contentOf(message: { message?: unknown }): unknown {
return (message.message as { content?: unknown } | null)?.content;
}
@@ -268,9 +333,7 @@ export class SessionReadChild {
/** The storage of a checkpoint, when the child's stream renders from its own files alone. */
storage(transcript: string, rewound: boolean): SessionReadStorage | undefined {
if (!this.files || rewound || !this.messages) return undefined;
if (
this.messages.some((message) => hasIndependentHistory(contentOf(message), CHILD_ONLY_TOOLS))
)
if (this.messages.some((message) => readsOtherFiles(contentOf(message), CHILD_FILE_TOOLS)))
return undefined;
return { transcript, files: this.files, subagents: subagentRecords(this.history) };
}
@@ -351,6 +414,8 @@ export async function readSessionTranscript(
cwd?: string,
observeStorage = false,
scope: SessionReadScope = {},
/** Whether the render links each Skill call to its SKILL.md, as for AIR clients (see `toolUseMeta`). */
skillLinks = false,
) {
if (!isSessionId(sessionId)) {
throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
@@ -421,11 +486,11 @@ export async function readSessionTranscript(
const quiet =
version &&
!rewind &&
!messages.some((message) =>
hasIndependentHistory(contentOf(message), ROOT_ONLY_TOOLS, statusRead),
);
!messages.some((message) => readsOtherFiles(contentOf(message), ROOT_FILE_TOOLS, statusRead));
// Before the transcript ends, so that a checkpoint never pairs them with a later append.
const files = quiet && history ? await fileVersions(subagentFiles(history)) : undefined;
// Before the render, so that a checkpoint never pairs the links with a later change.
const skills = quiet && skillLinks ? skillNames(messages) : [];
return {
messages,
cwd: effectiveCwd,
@@ -444,6 +509,9 @@ export async function readSessionTranscript(
version,
sidecarTitle,
...(files && history ? { files, subagents: subagentRecords(history) } : {}),
...(skills.length > 0
? { skills: { cwd: effectiveCwd, paths: skillPaths(skills, effectiveCwd) } }
: {}),
}
: undefined,
};
@@ -625,7 +693,7 @@ type Checkpoint = {
storage: SessionReadStorage;
boundaries: SessionReadFrame[];
title?: string;
status?: SessionReadFrame;
status?: SubagentStatus;
/** The root session, for a child read too. */
root: string;
/** The child's stream, for a child read. */
@@ -792,7 +860,7 @@ export class SessionReads {
outgoing: SessionReadFrame[],
cursorId: string | undefined,
title: string | undefined,
current: SessionReadFrame | undefined,
current: SubagentStatus | undefined,
) => {
for (const frame of outgoing) {
check();
@@ -801,7 +869,7 @@ export class SessionReads {
// The subagent status is current, outside the replay cursor.
if (current) {
check();
await options.send(current);
await options.send(current.frame(sessionId, options.protocol));
}
// On v2, and in a v1 status read, the title is current session info, outside the replay cursor.
if (
@@ -822,16 +890,37 @@ export class SessionReads {
// Before the render, which can take seconds on a large session.
if (cursor !== undefined && tagOf(cursor) !== tag) throw invalidCursor();
const cached = cursor ? this.checkpoints.get(key) : undefined;
if (
const changes =
cached &&
cached.cursorId === cursor &&
(cached.requestedCwd === cwd || cached.cwd === cwd) &&
cached.processCwd === processCwd &&
cached.scope === scopeFor(cached.cwd, cached.stream) &&
(await storageUnchanged(sessionId, cached.storage)) &&
cached.processCwd === currentDirectory()
) {
return await deliver(cached.boundaries, cached.cursorId, cached.title, cached.status);
cached.scope === scopeFor(cached.cwd, cached.stream)
? await storageChanges(sessionId, cached.storage)
: undefined;
if (cached && changes && cached.processCwd === currentDirectory()) {
if (changes.length === 0) {
return await deliver(cached.boundaries, cached.cursorId, cached.title, cached.status);
}
// Only child transcripts changed. When the render does not depend on
// them, only the status changes, and it is outside the cursor.
const status = await cached.status?.afterAppend(changes.map(([file]) => file));
if (status) {
const result = await deliver(cached.boundaries, cached.cursorId, cached.title, status);
const versions = new Map(changes);
this.checkpoints.set(key, {
...cached,
storage: {
...cached.storage,
files: cached.storage.files!.map(([file, version]) => [
file,
versions.has(file) ? versions.get(file)! : version,
]),
},
status,
});
return result;
}
}
check();
if (useCursor) this.checkpoints.delete(key);

View File

@@ -14,7 +14,9 @@
* bytes appended since (see `readLaunches`).
*
* The read reports each announced child once more, in one update outside the
* cursor (see {@link SubagentStatus.frame}).
* cursor (see {@link SubagentStatus.frame}). An append to a child that
* launched no children changes only that update (see
* {@link SubagentStatus.afterAppend}).
*/
import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
import { open, type FileHandle } from "node:fs/promises";
@@ -22,6 +24,7 @@ import type { SubagentState } from "./acp-subagents.js";
import { HANDBACK_TOOL, type WorkState } from "./native-subagents.js";
import {
isMissing,
subagentLaunchIds,
subagentTranscript,
withPath,
type SubagentHistory,
@@ -74,13 +77,29 @@ export type NestedLaunches = {
const NO_LAUNCHES: NestedLaunches = { messages: [], notifications: [] };
/** What a {@link SubagentStatusEntry} comes from, to build it again with new transcript ends. */
type EntrySource = {
sessionId: string;
parentSessionId: string | undefined;
record: SubagentRecord | undefined;
/** The state, from the child's transcript end when it has no end of its own (see `activity`). */
state(status: SubagentStatus): SubagentStatusEntry["state"];
};
export class SubagentStatus {
private readonly tails = new Map<string, ChildTail>();
/** The launches of each child that launched children, by its agent id. */
private readonly nested = new Map<string, NestedLaunches>();
private reported: SubagentStatusEntry[] = [];
private readonly sources = new WeakMap<SubagentStatusEntry, EntrySource>();
/** The agent ids that a metadata file names as `parentAgentId`. */
private readonly launchers: Set<string>;
private constructor(readonly history: SubagentHistory) {}
private constructor(readonly history: SubagentHistory) {
this.launchers = new Set(
[...history.agents.values()].flatMap((record) => record.parentAgentId ?? []),
);
}
/** Reads the transcript ends of the children of `history`, and the launches of nested children. */
static async read(history: SubagentHistory): Promise<SubagentStatus> {
@@ -145,7 +164,7 @@ export class SubagentStatus {
child.sessionId,
parentSessionId,
record,
end ?? (record ? this.activity(record) : "disconnected"),
(status) => end ?? (record ? status.activity(record) : "disconnected"),
);
}
@@ -160,11 +179,12 @@ export class SubagentStatus {
.map((child) => {
const ended =
child.notified ?? (child.record.stoppedByUser ? "cancelled" : child.launchEnd);
const end = ended ? replayEndState(child) : undefined;
return this.entry(
child.sessionId,
child.parentSessionId === rootSessionId ? undefined : child.parentSessionId,
child.record,
ended ? replayEndState(child) : { state: this.activity(child.record) },
(status) => end ?? { state: status.activity(child.record) },
);
});
}
@@ -174,6 +194,50 @@ export class SubagentStatus {
this.reported = entries;
}
/**
* The status after appends to the child transcripts `files`, which it
* reads the ends of again, with the entries of the same replay. Undefined
* when one of them is not the transcript of a child of `history`, or is
* the transcript of a child that launched children: the replay renders
* the launches in it, so it must render again.
*
* The replay depends on the other inputs only: the root transcript, the
* metadata files and the transcripts of the children that launched
* children. The caller checks that they are unchanged. The entries then
* equal those of a new replay.
*/
async afterAppend(files: string[]): Promise<SubagentStatus | undefined> {
const agents = new Map(
[...this.history.agents.values()].flatMap(({ agentId }) => {
const file = this.file(agentId);
return file ? [[file, agentId] as const] : [];
}),
);
const changed = files.map((file) => agents.get(file));
const sources = this.reported.map((entry) => this.sources.get(entry));
if (
changed.some((agentId) => agentId === undefined || this.launchers.has(agentId)) ||
sources.some((source) => source === undefined)
)
return undefined;
const status = new SubagentStatus(this.history);
for (const [agentId, tail] of this.tails) status.tails.set(agentId, tail);
for (const [agentId, launches] of this.nested) status.nested.set(agentId, launches);
await Promise.all(
(changed as string[]).map(async (agentId) => {
const tail = await readTail(this.file(agentId)!);
if (tail) status.tails.set(agentId, tail);
else status.tails.delete(agentId);
}),
);
status.report(
(sources as EntrySource[]).map((source) =>
status.entry(source.sessionId, source.parentSessionId, source.record, source.state),
),
);
return status;
}
/**
* The status update of the root session `sessionId`, with the {@link report}ed
* entries: `_subagent_status` on v2, which accepts custom variants that start
@@ -202,13 +266,13 @@ export class SubagentStatus {
sessionId: string,
parentSessionId: string | undefined,
record: SubagentRecord | undefined,
state: SubagentStatusEntry["state"],
state: EntrySource["state"],
): SubagentStatusEntry {
const tail = record && this.tails.get(record.agentId);
return {
const entry: SubagentStatusEntry = {
sessionId,
...(parentSessionId ? { parentSessionId } : {}),
state,
state: state(this),
...(record?.background ? { background: true } : {}),
...(record?.agentType ? { agentType: record.agentType } : {}),
...(record?.cwd ? { cwd: record.cwd } : {}),
@@ -216,6 +280,8 @@ export class SubagentStatus {
...(tail?.updatedAt ? { updatedAt: tail.updatedAt } : {}),
...(tail ? { size: tail.size } : {}),
};
this.sources.set(entry, { sessionId, parentSessionId, record, state });
return entry;
}
private file(agentId: string): string | undefined {
@@ -359,14 +425,17 @@ function handbackResults(content: { type?: unknown }[]): Set<string> | undefined
}
/**
* The lines of one transcript that name launches, from earlier status reads.
* Only their places are kept, so a later read scans only the appended bytes.
* The lines of one transcript that name Agent or Task launches, from earlier
* status reads. Only their places are kept, so a later read scans only the
* appended bytes, also when they hold a new launch.
*/
type LaunchScan = {
/** The device and inode of the file. */
identity: string;
/** The launches that the scan looks for. */
launches: string;
/** The ids of the launch calls found. */
launchIds: Set<string>;
/** Launches named by metadata that a scan from the start of this file did not find. */
missing: Set<string>;
/** The bytes scanned: up to the end of the last whole line. */
scanned: number;
/** The start and the end (the newline) of each line that names a launch, in file order. */
@@ -383,9 +452,13 @@ export const launchScanStats = { bytes: 0 };
/**
* The launch calls `launchIds`, their results and their task notifications
* in the transcript `file` (see {@link NestedLaunches}). The file is searched
* as bytes; only the lines that name a launch are parsed. A scan of an
* earlier read is continued from where it ended, while the file has the same
* identity and did not shrink.
* as bytes for the lines that name any Agent or Task launch (see
* `scanLaunches`); only those lines are parsed. A scan of an earlier read is
* continued from where it ended, also when the appended bytes hold a new
* launch, while the file has the same identity, did not shrink, and still has
* line ends where the scan found them. Otherwise it is scanned from the start.
* It is also scanned from the start, once, when the metadata names a launch
* that the scan did not find.
*/
async function readLaunches(
file: string,
@@ -451,19 +524,34 @@ async function readLaunches(
};
}
/** The lines of the open transcript `file` that name the launches `launchIds`, in file order. */
/**
* The lines of the open transcript `file` that name an Agent or Task launch,
* in file order: the launch calls, the results of those calls, and the task
* notifications. The search for results relies on each result coming after
* its call in the file, as Claude Code writes them.
*/
async function scanLaunches(
handle: FileHandle,
file: string,
launchIds: string[],
/** The launches that the metadata names. */
named: string[],
): Promise<string[]> {
const stats = await handle.stat({ bigint: true });
const identity = `${stats.dev}:${stats.ino}`;
const size = Number(stats.size);
const launches = [...launchIds].sort().join(",");
let scan = launchScans.get(file);
if (!scan || scan.identity !== identity || scan.launches !== launches || scan.scanned > size) {
scan = { identity, launches, scanned: 0, lines: [] };
if (!scan || scan.identity !== identity || scan.scanned > size) {
scan = { identity, launchIds: new Set(), missing: new Set(), scanned: 0, lines: [] };
}
const rescan = () => {
launchScans.delete(file);
return scanLaunches(handle, file, named);
};
// The scanned bytes still end a line, else the file was rewritten.
if (scan.scanned > 0) {
const last = Buffer.alloc(1);
const { bytesRead } = await handle.read(last, 0, 1, scan.scanned - 1);
if (bytesRead !== 1 || last[0] !== 10) return rescan();
}
// The lines found before, each still a whole line, else the file was rewritten.
const known: string[] = [];
@@ -476,8 +564,7 @@ async function scanLaunches(
buffer[bytesRead - 1] !== 10 ||
(start > 0 && buffer[0] !== 10)
) {
launchScans.delete(file);
return scanLaunches(handle, file, launchIds);
return rescan();
}
known.push(buffer.toString("utf8", start - from, bytesRead - 1));
}
@@ -496,15 +583,30 @@ async function scanLaunches(
at = buffer.indexOf(needle, end);
}
};
for (const id of launchIds) {
collect(`"id":"${id}"`);
collect(`"tool_use_id":"${id}"`);
// The launch calls first, so that the results of the new launches are found too.
const launchIds = new Set(scan.launchIds);
for (const name of ["Agent", "Task"]) collect(`"name":"${name}"`);
for (const [start, end] of lines) {
const record = parse(buffer.toString("utf8", start, end)) as {
type?: unknown;
message?: { content?: unknown };
} | null;
if (record?.type !== "assistant") continue;
for (const id of subagentLaunchIds(record.message?.content)) launchIds.add(id);
}
for (const id of launchIds) collect(`"tool_use_id":"${id}"`);
collect(`<task-notification>`);
// A launch of the metadata that no scan found. Its call may not be written
// yet, or a rewrite in place that kept every line end may have added it:
// scan from the start, once for each such launch.
const missing = named.filter((id) => !launchIds.has(id) && !scan.missing.has(id));
if (missing.length > 0 && scan.scanned > 0) return rescan();
const added = [...lines].sort(([a], [b]) => a - b);
launchScans.delete(file);
launchScans.set(file, {
...scan,
identity,
launchIds,
missing: new Set([...scan.missing, ...missing]),
scanned: scan.scanned + buffer.length,
lines: [
...scan.lines,

View File

@@ -315,6 +315,43 @@ describe.each(["rfd", "air", "v2"] as const)("child _session/read (%s)", (form)
}
});
it.each([
["TodoWrite", { todos: [{ content: "Step", status: "pending", activeForm: "Step" }] }, false],
["mcp__docs__search", { query: "cursor" }, false],
["Skill", { skill: "example" }, true],
["SendMessage", { to: "b2222222222222222", message: "Continue" }, true],
] as const)(
"renders a quiet child poll with a %s call only when it reads other files",
async (name, input, renders) => {
await writeTranscript(
directory,
`agent-${childA}`,
[
...childRecords("a", 1),
{
...transcriptAssistant("tool", ""),
message: {
role: "assistant",
id: "msg_tool",
content: [{ type: "tool_use", id: "toolu_tool", name, input }],
},
},
].map((record) => ({ sessionId, cwd, agentId: childA, isSidechain: true, ...record })),
);
const r = await reader(form);
try {
const params = { sessionId, subagentSessionId: streamOf(childA, "toolu_a") };
const { cursorId } = (await r.read({ ...params, replayFrom: start })).response;
vi.mocked(getSessionMessages).mockClear();
const quiet = await r.read({ ...params, replayFrom: { type: "cursor", cursorId } });
expect(quiet.response).toEqual({ cursorId });
expect(vi.mocked(getSessionMessages).mock.calls.length > 0).toBe(renders);
} finally {
await r.dispose();
}
},
);
it("reads a nested child through its ancestors only, with the frames of a full read", async () => {
const nested = "c3333333333333333";
// A launches the nested child; its metadata names A as its parent.
@@ -652,11 +689,12 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form)
let configDir: string;
let session: StatusSession;
let sessionId: string;
let cwd: string;
const status = { filters: { subagents: "status" } };
beforeEach(async () => {
const folder = await configFolder();
({ configDir, sessionId } = folder);
({ configDir, sessionId, cwd } = folder);
session = new StatusSession(sessionId, folder.project, folder.directory, folder.cwd);
await session.create();
});
@@ -894,6 +932,200 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form)
}
});
it("skips the render of a quiet poll with TodoWrite, MCP and Skill calls in the root", async () => {
const calls = [
["TodoWrite", { todos: [{ content: "Step", status: "pending", activeForm: "Step" }] }],
["mcp__docs__search", { query: "cursor" }],
["Skill", { skill: "example" }],
] as const;
for (const [name, input] of calls) {
const id = `toolu_${name}`;
await session.assistant(undefined, [{ type: "tool_use", id, name, input }], "tool_use");
await session.user(undefined, [{ type: "tool_result", tool_use_id: id, content: "ok" }]);
}
const r = await reader(form);
try {
const first = await r.read({ sessionId, replayFrom: start, ...status });
const cursorId = first.response.cursorId!;
const poll = () => r.read({ sessionId, replayFrom: { type: "cursor", cursorId }, ...status });
vi.mocked(getSessionMessages).mockClear();
expect((await poll()).response).toEqual({ cursorId });
expect(getSessionMessages).not.toHaveBeenCalled();
// A child's append is in the status of the next poll.
const sizeOf = (frames: SessionReadFrame[]) =>
statusOf(frames).find((entry) => entry.sessionId === idOf("bgrun"))!.size as number;
await session.bash(session.agentIdOf("bgrun"));
expect(sizeOf((await poll()).frames)).toBeGreaterThan(sizeOf(first.frames));
// On AIR, the link of the Skill call names its SKILL.md: a new one renders
// the history again, also together with a child's append.
const skill = path.join(cwd, ".claude", "skills", "example", "SKILL.md");
await mkdir(path.dirname(skill), { recursive: true });
await writeFile(skill, "---\nname: example\n---\nExample skill\n");
await session.bash(session.agentIdOf("bgrun"));
vi.mocked(getSessionMessages).mockClear();
if (form === "air") {
await expect(poll()).rejects.toMatchObject(invalidCursor);
expect(getSessionMessages).toHaveBeenCalled();
} else {
expect((await poll()).response).toEqual({ cursorId });
expect(getSessionMessages).not.toHaveBeenCalled();
}
} finally {
await r.dispose();
}
});
it("rebuilds only the status after an append to a child that launched no children", async () => {
const r = await reader(form);
try {
const first = await r.read({ sessionId, replayFrom: start, ...status });
const cursorId = first.response.cursorId!;
const sizeOf = (frames: SessionReadFrame[]) =>
statusOf(frames).find((entry) => entry.sessionId === idOf("bgrun"))!.size as number;
await session.bash(session.agentIdOf("bgrun"));
await session.answer(session.agentIdOf("bgrun")!);
vi.mocked(getSessionMessages).mockClear();
const reads = vi.spyOn(resumedSession, "readTranscriptEntries");
const next = await r.read({
sessionId,
replayFrom: { type: "cursor", cursorId },
...status,
});
// No render: the root part is the same, the status is new.
expect(getSessionMessages).not.toHaveBeenCalled();
expect(reads).not.toHaveBeenCalled();
expect(next.response).toEqual({ cursorId });
expect(statesOf(next.frames)[idOf("bgrun")]).toEqual(stateOf("idle"));
expect(sizeOf(next.frames)).toBeGreaterThan(sizeOf(first.frames));
// The status of a full render, and the cursor of the read from the start.
const fresh = await r.read({ sessionId, replayFrom: start, ...status });
expect(statusOf(next.frames)).toEqual(statusOf(fresh.frames));
expect(fresh.response).toEqual({ cursorId });
// The checkpoint has the new versions: the next poll is quiet.
vi.mocked(getSessionMessages).mockClear();
const quiet = await r.read({
sessionId,
replayFrom: { type: "cursor", cursorId },
...status,
});
expect(getSessionMessages).not.toHaveBeenCalled();
expect(statusOf(quiet.frames)).toEqual(statusOf(fresh.frames));
} finally {
await r.dispose();
}
});
it("renders again after an append to a child that launched children, and finds its new launch", async () => {
const r = await reader(form);
try {
let { cursorId } = (await r.read({ sessionId, replayFrom: start, ...status })).response;
const poll = async () => {
const next = await r.read({
sessionId,
replayFrom: { type: "cursor", cursorId },
...status,
});
cursorId = next.response.cursorId ?? cursorId;
return next;
};
// The metadata of a child of `bgrun` comes before its launch call in `bgrun`'s transcript.
const owner = session.agentIdOf("bgrun")!;
const agentId = "adeep000000000000";
session.agents.set("deep", { agentId, launch: "toolu_deep" });
await writeFile(
path.join(session.directory, `agent-${agentId}.meta.json`),
JSON.stringify({ agentType: "Explore", toolUseId: "toolu_deep", parentAgentId: owner }),
);
expect(statesOf((await poll()).frames)).not.toHaveProperty(idOf("deep"));
const before = cursorId;
await session.assistant(owner, [
{
type: "tool_use",
id: "toolu_deep",
name: "Agent",
input: { description: "Task deep", prompt: "Do deep", subagent_type: "Explore" },
},
]);
vi.mocked(getSessionMessages).mockClear();
const launched = await poll();
expect(getSessionMessages).toHaveBeenCalled();
expect(cursorId).not.toBe(before);
expect(statusOf(launched.frames).find((entry) => entry.sessionId === idOf("deep"))).toEqual(
expect.objectContaining({ parentSessionId: idOf("bgrun"), state: stateOf("running") }),
);
} finally {
await r.dispose();
}
});
it("scans only the appended bytes of a parent for a new nested launch, and a rewritten parent again", async () => {
const r = await reader(form);
try {
let { cursorId } = (await r.read({ sessionId, replayFrom: start, ...status })).response;
const poll = async () => {
const next = await r.read({
sessionId,
replayFrom: { type: "cursor", cursorId },
...status,
});
cursorId = next.response.cursorId ?? cursorId;
return next;
};
const outer = path.join(session.directory, `agent-${session.agentIdOf("outer")}.jsonl`);
const before = (await stat(outer)).size;
await session.agent("nestedlate", "outer", { finish: false });
const appended = (await stat(outer)).size - before;
let scanned = launchScanStats.bytes;
const launched = await poll();
expect(launchScanStats.bytes - scanned).toBe(appended);
expect(statusOf(launched.frames).find((e) => e.sessionId === idOf("nestedlate"))).toEqual(
expect.objectContaining({ parentSessionId: idOf("outer"), state: stateOf("running") }),
);
// A rewrite in place keeps the file identity but moves the lines: the scan starts again.
const text = await readFile(outer, "utf8");
await writeFile(outer, text.replace('"content":"Do outer"', '"content":"Do outer now"'));
scanned = launchScanStats.bytes;
const rewritten = await poll();
expect(launchScanStats.bytes - scanned).toBe((await stat(outer)).size);
expect(statesOf(rewritten.frames)).toEqual(statesOf(launched.frames));
// A rewrite of the same size that turns a Bash call into a launch keeps every line end.
// The metadata names a launch that the scan did not find, so the scan starts again.
const before2 = await readFile(outer, "utf8");
const call = /"id":"(toolu_bash\d+)","name":"Bash","input":\{"command":"date"\}/.exec(
before2,
)!;
const launchId = call[1]!;
const after = before2.replace(
call[0],
`"id":"${launchId}","name":"Agent","input":{"prompt":"date"}`,
);
expect(after.length).toBe(before2.length);
await writeFile(outer, after);
const agentId = "ainplace000000000";
session.agents.set("inplace", { agentId, launch: launchId });
await writeFile(
path.join(session.directory, `agent-${agentId}.meta.json`),
JSON.stringify({
agentType: "Explore",
toolUseId: launchId,
parentAgentId: session.agentIdOf("outer"),
}),
);
// The new launch is before others on the stream of `outer`, so the cursor cannot continue.
await expect(poll()).rejects.toMatchObject(invalidCursor);
const inPlace = await r.read({ sessionId, replayFrom: start, ...status });
expect(statusOf(inPlace.frames).find((e) => e.sessionId === idOf("inplace"))).toEqual(
expect.objectContaining({ parentSessionId: idOf("outer") }),
);
} finally {
await r.dispose();
}
});
it("reports a child that handed back its report as the full read does, past long records", async () => {
// A hand-back whose call is longer than the 64 KB window, and a child whose last record is.
await session.agent("handback", undefined, { background: true, finish: false });

View File

@@ -261,35 +261,45 @@ describe("_session/read on v1", () => {
}
});
it.each([
["Read", false],
["Skill", true],
])("checks whether %s replay needs a full scan", async (name, needsReplay) => {
const toolId = "toolu_saved";
await store([
/** A root history with one call of `name` and its result. */
function storeToolCall(name: string, input: Record<string, unknown>) {
return store([
history[0]!,
{
...transcriptAssistant("use", ""),
message: {
role: "assistant",
id: "msg_use",
content: [
{
type: "tool_use",
id: toolId,
name,
input:
name === "Read" ? { file_path: path.join(cwd, "saved.txt") } : { skill: "example" },
},
],
content: [{ type: "tool_use", id: "toolu_saved", name, input }],
},
},
{
type: "user",
uuid: "result",
message: {
role: "user",
content: [{ type: "tool_result", tool_use_id: "toolu_saved", content: "Done" }],
},
},
]);
}
it.each([
["Read", { file_path: "saved.txt" }, false],
["TodoWrite", { todos: [{ content: "Step", status: "pending", activeForm: "Step" }] }, false],
["mcp__docs__search", { query: "cursor" }, false],
["Skill", { skill: "example" }, false],
["ToolSearch", { query: "select:WebFetch" }, false],
["SendMessage", { to: "a1111111111111111", message: "Continue" }, false],
["ExitPlanMode", { plan: "Plan", planFilePath: "/plans/plan.md" }, true],
["Agent", { prompt: "Check", description: "Check" }, true],
])("checks whether %s replay needs a full scan", async (name, input, needsReplay) => {
await storeToolCall(name, input);
const { agent, updates } = captureUpdates();
try {
await initializeClient(agent, { session: { cursors: {} } });
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
expect(updates.some(({ update }) => update.sessionUpdate === "tool_call")).toBe(true);
expect(cursorId).toBeTruthy();
updates.length = 0;
vi.mocked(getSessionMessages).mockClear();
@@ -313,6 +323,93 @@ describe("_session/read on v1", () => {
}
});
it.each([true, false])(
"follows the SKILL.md that a Skill call links only for an AIR client (AIR: %s)",
async (air) => {
await storeToolCall("Skill", { skill: "example" });
const { agent, updates } = captureUpdates();
const skillOf = () =>
updates
.map(({ update }) => update._meta as { jetbrains?: { air?: Record<string, unknown> } })
.find((meta) => meta?.jetbrains?.air?.skill)?.jetbrains?.air?.skill;
try {
await initializeClient(agent, {
session: { cursors: {} },
...(air ? { _meta: { jetbrains: { air: { version: 1, capabilities: [] } } } } : {}),
} as never);
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
expect(skillOf()).toEqual(air ? { name: "example" } : undefined);
updates.length = 0;
vi.mocked(getSessionMessages).mockClear();
expect(
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
).toEqual({ cursorId });
expect(getSessionMessages).not.toHaveBeenCalled();
const skill = path.join(cwd, ".claude", "skills", "example", "SKILL.md");
await mkdir(path.dirname(skill), { recursive: true });
await writeFile(skill, "---\nname: example\n---\nExample skill\n");
updates.length = 0;
if (!air) {
// No link depends on the file, so the poll stays quiet.
expect(
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
).toEqual({ cursorId });
expect(getSessionMessages).not.toHaveBeenCalled();
return;
}
// The link of an already sent call changed: the client reads from the start.
await expect(
agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
).rejects.toMatchObject(invalidCursor);
expect(getSessionMessages).toHaveBeenCalledTimes(1);
await agent.readSession({ sessionId, replayFrom: start });
expect(skillOf()).toEqual({ name: "example", path: skill });
} finally {
await agent.dispose();
}
},
);
it("renders a quiet poll of a full read again after its child appends", async () => {
const agentId = "a1111111111111111";
await storeToolCall("Agent", { prompt: "Check", description: "Check" });
const subagents = path.join(project, sessionId, "subagents");
await mkdir(subagents, { recursive: true });
await writeFile(
path.join(subagents, `agent-${agentId}.meta.json`),
JSON.stringify({ toolUseId: "toolu_saved", description: "Check" }),
);
const child = (records: Record<string, unknown>[]) =>
writeTranscript(
subagents,
`agent-${agentId}`,
records.map((record) => ({ cwd, sessionId, agentId, isSidechain: true, ...record })),
);
await child([transcriptUser("c1", "Check"), transcriptAssistant("c2", "First report")]);
const { agent, updates } = captureUpdates();
try {
await initializeClient(agent, { session: { cursors: {} }, subagents: {} } as never);
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
await child([
transcriptUser("c1", "Check"),
transcriptAssistant("c2", "First report"),
transcriptAssistant("c3", "Second report"),
]);
updates.length = 0;
const next = await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } });
expect(next.cursorId).not.toBe(cursorId);
expect(updates).toContainEqual(
expect.objectContaining({
sessionId: agentId,
update: expect.objectContaining({ content: { type: "text", text: "Second report" } }),
}),
);
} finally {
await agent.dispose();
}
});
it("invalidates a saved cursor after a sidecar title in the replay changes", async () => {
await store(history);
const transcript = path.join(project, `${sessionId}.jsonl`);

View File

@@ -62,7 +62,13 @@ export class V1SessionReads {
assertRoot: options.assertRoot,
signal,
replay: async (sessionId, cwd, observeStorage, scope) => {
const transcript = await readSessionTranscript(sessionId, cwd, observeStorage, scope);
const transcript = await readSessionTranscript(
sessionId,
cwd,
observeStorage,
scope,
options.airClient,
);
const { child, subagentStatus } = transcript;
const form = options.subagentForm;
// `SessionReads` refuses a child read without native subagent sessions.
@@ -100,7 +106,7 @@ export class V1SessionReads {
? child.storage(transcript.transcript, transcript.rewound)
: transcript.storage,
...(child && form ? { stream: child.streamId(form) } : {}),
...(subagentStatus ? { status: subagentStatus.frame(sessionId, 1) } : {}),
...(subagentStatus ? { status: subagentStatus } : {}),
historyEnd,
title: transcript.title === undefined ? undefined : options.clientTitle(transcript.title),
};

View File

@@ -60,7 +60,7 @@ export async function renderSessionRead(
}
if (subagentStatus) {
subagentStatus.report(subagents?.statusEntries() ?? []);
return { frames, cwd, historyEnd, title, storage, status: subagentStatus.frame(sessionId, 2) };
return { frames, cwd, historyEnd, title, storage, status: subagentStatus };
}
return { frames, cwd, historyEnd, title, storage };
}