Official
claude
Claude Code agent provider: runs the Claude Code CLI headless for each account.
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/claude@0.2.5
Permissions in 0.2.5
Files
history.test.ts38.6 KB
// Ported from the Rust plugin's history.rs and subagents.rs tests.
import * as wire from "./wire.ts";
import type * as z from "zod";
import assert from "node:assert/strict";
import { itemAs, required, test, run as runEffect, files, tempDir, useApi } from "./testing.ts";
import { diskFs, fakeApi } from "../sdk/testing.ts";
import { CHUNK } from "./files.ts";
import { Mapper } from "./map.ts";
import { streamedAliases } from "./records.ts";
import { appendFileSync } from "node:fs";
import type { TranscriptItem } from "./types.ts";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import {
encodeWorkspace,
listSessions,
readFile,
readSession,
readSessionFile,
recordsAfter,
rewindBefore,
rewindTarget,
Tails,
turnFromElsewhere,
userRecords,
} from "./history.ts";
function write(path: string, records: unknown[]) {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(
path,
records.map((record) => (typeof record === "string" ? record : JSON.stringify(record))).join("\n"),
);
}
/// The CLI's own records of a background task's end, of a stop and its
/// notes (`isMeta`) are not the user's words: no prompt bubble for any.
test("the CLI's own records are not prompts", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
write(path, [
{ type: "user", uuid: "u1", message: { role: "user", content: [{ type: "text", text: "hello" }] } },
{
type: "user",
uuid: "u2",
origin: { kind: "task-notification" },
message: { role: "user", content: "<task-notification>\n<task-id>a1</task-id>\n</task-notification>" },
},
{
type: "user",
uuid: "u3",
message: { role: "user", content: [{ type: "text", text: "[Request interrupted by user for tool use]" }] },
},
{
type: "user",
uuid: "u4",
isMeta: true,
message: { role: "user", content: "[Image: original 3840x76, displayed at 2000x40.]" },
},
]);
// A stop shows as the host's own notice, as it does live.
const items = await runEffect(readFile(files(), path));
assert.deepEqual(
items.map((item) => item.role),
["user"],
);
});
/// What the CLI records around `/compact` (CLI 2.1.322): the summary that
/// starts the compacted conversation, a note, the command in its markup
/// under the uuid it was sent with, and what it printed. A run shows only
/// the command as it was typed, so a read does too, and none of it counts
/// as a prompt from elsewhere.
test("a local command reads back as it was typed, without its summary or output", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
const text = (uuid: string, content: string, extra = {}) => ({
type: "user",
uuid,
...extra,
message: { role: "user", content },
});
const records = [
{ type: "assistant", uuid: "a1", message: { id: "msg-1", role: "assistant", content: [{ type: "text", text: "ok" }] } },
{ type: "system", subtype: "compact_boundary", uuid: "b1", compactMetadata: { trigger: "manual" } },
text("s1", "This session is being continued from a previous conversation.", {
isCompactSummary: true,
isVisibleInTranscriptOnly: true,
}),
text("m1", "<local-command-caveat>The command below was run directly in Claude Code.</local-command-caveat>", {
isMeta: true,
}),
text(
"u2",
"<command-name>/compact</command-name>\n <command-message>compact</command-message>\n <command-args>keep the plan</command-args>",
),
text("o1", "<local-command-stdout>Compacted </local-command-stdout>"),
text("o2", "<local-command-stderr>Nothing to compact</local-command-stderr>"),
];
write(path, records);
const items = await runEffect(readFile(files(), path));
assert.deepEqual(
items.map((item) => [item.id, item.role === "user" ? item.blocks : null]),
[
["a1:0", null],
["u2", [{ type: "text", text: "/compact keep the plan" }]],
],
);
const parsed = records.map((record) => wire.record.parse(record));
// The reply was not streamed by this process, and still no turn ran
// elsewhere: the command was sent from here.
assert.equal(turnFromElsewhere(parsed, new Set(["u2"]), new Set()), false);
});
/// An image the user sent is read back with its bytes, so a chat read from
/// the CLI's record keeps the picture the message showed when it was sent.
test("a prompt's images are read back", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
write(path, [
{
type: "user",
uuid: "u1",
message: {
role: "user",
content: [
{ type: "text", text: "what is this" },
{ type: "image", source: { type: "base64", media_type: "image/png", data: "AAA=" } },
],
},
},
]);
const items = await runEffect(readFile(files(), path));
assert.deepEqual(itemAs(items[0], "user").blocks, [
{ type: "text", text: "what is this" },
{ type: "image", mimeType: "image/png", data: "AAA=" },
]);
});
/// A message sent while a turn runs is stored as a queued command, not a
/// user record. It reads back under the uuid it was sent with, which the
/// host already knows it by, at its place in the turn.
test("a message sent during a turn is read back where it was taken", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
const queued = (uuid: string, attachment: object) => ({
type: "attachment",
uuid,
attachment: { type: "queued_command", ...attachment },
});
write(path, [
{ type: "user", uuid: "u1", message: { role: "user", content: [{ type: "text", text: "start" }] } },
{
type: "assistant",
uuid: "a1",
message: { id: "m1", role: "assistant", content: [{ type: "text", text: "working" }] },
},
queued("q1", {
commandMode: "prompt",
source_uuid: "sent-1",
prompt: [
{ type: "image", source: { type: "base64", media_type: "image/jpeg", data: "AA==" } },
{ type: "text", text: "look here" },
],
}),
queued("q2", { commandMode: "prompt", source_uuid: "sent-2", prompt: "and here", origin: { kind: "human" } }),
// A subagent's hand-back is queued as a prompt too, but nobody typed it.
queued("q4", {
commandMode: "prompt",
source_uuid: "peer-1",
prompt: '<agent-message from="a2">\n[Subagent hand-back] The report follows',
origin: { kind: "peer", from: "a2" },
}),
queued("q3", {
commandMode: "task-notification",
source_uuid: "n1",
prompt: "<task-notification>\n<task-id>a1</task-id>\n</task-notification>",
}),
{
type: "assistant",
uuid: "a2",
message: { id: "m2", role: "assistant", content: [{ type: "text", text: "done" }] },
},
]);
const items = await runEffect(readFile(files(), path));
assert.deepEqual(
items.map((item) => [item.id, item.role, item.role === "user" ? item.blocks : undefined]),
[
["u1", "user", [{ type: "text", text: "start" }]],
["a1:0", "assistant", undefined],
[
"sent-1",
"user",
[
{ type: "image", mimeType: "image/jpeg", data: "AA==" },
{ type: "text", text: "look here" },
],
],
["sent-2", "user", [{ type: "text", text: "and here" }]],
["a2:0", "assistant", undefined],
],
);
});
/// The live stream names a block `<message id>:<block>` and a tool call by
/// its id; the file names each row by its record. A read reports what each
/// row was streamed as, or switching back to a chat run here shows its turns
/// twice. A row the stream never had (the plan, a stop) is not read either:
/// the host could not place it among the rows it knows.
test("history rows name the ids the live stream gave them", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
const assistant = (uuid: string, id: string, block: z.infer<typeof wire.block>) => ({
type: "assistant",
uuid,
parent_tool_use_id: null,
message: { id, role: "assistant", content: [block] },
});
const result = (uuid: string, tool: string) => ({
type: "user",
uuid,
message: { role: "user", content: [{ type: "tool_result", tool_use_id: tool, content: "ok" }] },
});
const records: wire.Record[] = [
{ type: "user", uuid: "u1", message: { role: "user", content: [{ type: "text", text: "go" }] } },
assistant("r1", "msg_a", { type: "thinking", thinking: "orient" }),
// Claude's second summary of the same thinking joins the first's row.
assistant("r1b", "msg_a", { type: "thinking", thinking: "Then look." }),
assistant("r2", "msg_a", { type: "text", text: "Looking." }),
assistant("r3", "msg_a", { type: "tool_use", id: "toolu_1", name: "Bash", input: { command: "ls" } }),
result("u2", "toolu_1"),
assistant("r4", "msg_b", {
type: "tool_use",
id: "toolu_2",
name: "TodoWrite",
input: { todos: [{ content: "one", status: "pending" }] },
}),
result("u3", "toolu_2"),
assistant("r5", "msg_c", { type: "text", text: "Done." }),
{
type: "user",
uuid: "u4",
message: { role: "user", content: [{ type: "text", text: "[Request interrupted by user]" }] },
},
];
write(path, records);
const mapper = new Mapper();
const live = new Set<string>();
for (const record of records)
for (const { kind } of mapper.handle(record)) {
if (kind.event === "text_delta" || kind.event === "reasoning_delta") live.add(kind.itemId);
if (kind.event === "tool_call_started") live.add(kind.id);
}
const items = await runEffect(readFile(files(), path));
assert.deepEqual(
items.map((item) => item.role),
["user", "reasoning", "assistant", "tool", "tool", "assistant"],
);
assert.equal(itemAs(items[1]!, "reasoning").text, "orient\n\nThen look.");
const streamed = streamedAliases(items);
assert.deepEqual(
streamed.map((alias) => alias.nativeItemId),
items.slice(1).map((item) => item.id),
);
assert.deepEqual(new Set(streamed.map((alias) => alias.streamedItemId)), live);
});
/// What the host sends ahead of a prompt (a code mode catalog update) is
/// not the user's: a replayed session shows only their own text.
test("a replayed user message leaves out the instructions sent with it", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
write(path, [
{
type: "user",
uuid: "u1",
message: {
role: "user",
content: [
{
type: "text",
text: "<divergence-instructions>\nThe Code Mode tool catalog has changed.\n</divergence-instructions>\n\n",
},
{ type: "text", text: "hello" },
],
},
},
{
type: "user",
uuid: "u2",
message: {
role: "user",
content:
"<divergence-instructions>\nThe Code Mode tool catalog has changed.\n</divergence-instructions>\n\nagain",
},
},
]);
const items = await runEffect(readFile(files(), path));
assert.deepEqual(
items.map((item) => item.role === "user" && item.blocks),
[[{ type: "text", text: "hello" }], [{ type: "text", text: "again" }]],
);
});
test("the workspace encoding matches the CLI", () => {
assert.equal(encodeWorkspace("/private/tmp"), "-private-tmp");
assert.equal(encodeWorkspace("/private/tmp/pr.obe_dir/x"), "-private-tmp-pr-obe-dir-x");
});
/// One message to the host carries at most 64 MiB, and a transcript can be
/// larger. Reading one whole ended the plugin's runtime; it is read, and
/// listed, a piece at a time.
test("a transcript larger than one read is read and listed in pieces", async () => {
const home = tempDir();
const workspace = "/w/long";
const output = "x".repeat(1024 * 1024);
const records: string[] = [
'{"type":"user","uuid":"u1","timestamp":"2026-09-14T12:00:00.000Z","message":{"role":"user","content":[{"type":"text","text":"start"}]}}',
];
for (let at = 0; at * output.length < CHUNK + 1024 * 1024; at += 1)
records.push(
JSON.stringify({
type: "user",
uuid: `r${at}`,
timestamp: "2026-09-14T12:00:01.000Z",
message: { role: "user", content: [{ type: "tool_result", tool_use_id: `t${at}`, content: output }] },
}),
);
records.push('{"type":"custom-title","customTitle":"Long session","sessionId":"s1"}');
records.push(
'{"type":"assistant","uuid":"a1","timestamp":"2026-09-14T12:00:02.000Z","message":{"content":[{"type":"text","text":"done"}]}}',
);
write(join(home, "projects", encodeWorkspace(workspace), "s1.jsonl"), records);
const reads = countReads();
const sessions = await runEffect(listSessions(files(), home, workspace));
assert.deepEqual(sessions, [
{ id: "s1", title: "Long session", createdAt: "2026-09-14T12:00:00.000Z", updatedAt: "2026-09-14T12:00:02.000Z" },
]);
const items = await runEffect(readSession(files(), home, workspace, "s1"));
assert.equal(itemAs(required(items.at(-1)), "assistant").text, "done");
const largest = Math.max(...[...reads.values()].flat());
assert.ok(largest <= CHUNK, `a read of ${largest} bytes`);
});
test("a transcript becomes items, and the sessions are listed", async () => {
const home = tempDir();
const workspace = "/w/project";
write(join(home, "projects", encodeWorkspace(workspace), "s1.jsonl"), [
'{"type":"ai-title","aiTitle":"Rename the widget","sessionId":"s1"}',
'{"type":"user","uuid":"u1","timestamp":"2026-09-14T12:00:00.000Z","message":{"role":"user","content":[{"type":"text","text":"rename it"}]}}',
'{"type":"assistant","uuid":"a1","timestamp":"2026-09-14T12:00:01.000Z","message":{"content":[{"type":"thinking","thinking":"plan"},{"type":"text","text":"on it"},{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"ls"}}]}}',
'{"type":"user","uuid":"u2","timestamp":"2026-09-14T12:00:02.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"a.txt\\n"}]}}',
]);
const sessions = await runEffect(listSessions(files(), home, workspace));
assert.deepEqual(sessions, [
{
id: "s1",
title: "Rename the widget",
createdAt: "2026-09-14T12:00:00.000Z",
updatedAt: "2026-09-14T12:00:02.000Z",
},
]);
const items = await runEffect(readSession(files(), home, workspace, "s1"));
assert.equal(items[0].role, "user");
assert.equal(items[0].blocks.length, 1);
assert.deepEqual([items[1].role, itemAs(items[1], "reasoning").text], ["reasoning", "plan"]);
assert.deepEqual([items[2].role, itemAs(items[2], "assistant").text], ["assistant", "on it"]);
assert.equal(itemAs(items[3], "tool").call.status, "completed");
assert.equal(itemAs(items[3], "tool").call.kind, "execute");
assert.deepEqual(itemAs(items[3], "tool").call.content, [{ type: "terminal", command: "ls", output: "a.txt\n" }]);
assert.equal(items.length, 4, "the tool result updates the call instead of adding an item");
assert.deepEqual(await runEffect(listSessions(files(), home, "/w/none")), []);
});
/// The CLI stores an error's `toolUseResult` as its text, and some MCP
/// results as an array. Such a record was dropped whole, so the call it
/// ends stayed running for ever; so was any record with one field in an
/// unexpected shape.
test("a stored tool result in any shape ends its call", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
const call = (uuid: string, id: string) => ({
type: "assistant",
uuid,
message: { content: [{ type: "tool_use", id, name: "Bash", input: { command: "false" } }] },
});
const result = (uuid: string, id: string, extra: object) => ({
type: "user",
uuid,
message: {
role: "user",
content: [{ type: "tool_result", tool_use_id: id, is_error: true, content: "Exit code 1" }],
},
...extra,
});
write(path, [
call("a1", "t1"),
result("u1", "t1", { toolUseResult: "Error: Exit code 1" }),
call("a2", "t2"),
result("u2", "t2", { toolUseResult: [{ type: "text", text: "Exit code 1" }] }),
call("a3", "t3"),
result("u3", "t3", { timestamp: 17 }),
]);
const items = await runEffect(readFile(files(), path));
assert.deepEqual(
items.map((item) => [itemAs(item, "tool").call.id, itemAs(item, "tool").call.status]),
[
["t1", "failed"],
["t2", "failed"],
["t3", "failed"],
],
);
});
/// The host names its own message ids, which never appear in the CLI's
/// file; the prompt is matched to its user record by position instead.
test("a prompt is found again by its position among user records", () => {
const records = [
{ type: "user", uuid: "u1", parentUuid: null, message: { role: "user", content: [{ type: "text", text: "one" }] } },
{
type: "assistant",
uuid: "a1",
parentUuid: "u1",
message: { role: "assistant", content: [{ type: "text", text: "ok" }] },
},
{
type: "user",
uuid: "side",
isSidechain: true,
parentUuid: "a1",
message: { role: "user", content: [{ type: "text", text: "sub" }] },
},
{ type: "user", uuid: "u2", parentUuid: "a1", message: { role: "user", content: [{ type: "text", text: "two" }] } },
];
const users = userRecords(records);
assert.equal(users.length, 2, "sidechain records are not the user's own messages");
assert.deepEqual(rewindBefore(users[1]), { at: "a1" });
// The first message has nothing before it: forgetting it means an empty
// conversation, not an error.
assert.deepEqual(rewindBefore(users[0]), { fresh: true });
});
/// `--resume-session-at` keeps the message it names, so rewinding to an
/// item means resuming at the item's parent.
test("rewinding resumes at the record before the item", async () => {
const home = tempDir();
const workspace = "/w/rewind";
write(join(home, "projects", encodeWorkspace(workspace), "s3.jsonl"), [
{ type: "user", uuid: "u1", parentUuid: null, message: { role: "user", content: [{ type: "text", text: "one" }] } },
{ type: "assistant", uuid: "a1", parentUuid: "u1", message: { content: [{ type: "text", text: "done" }] } },
{ type: "user", uuid: "u2", parentUuid: "a1", message: { role: "user", content: [{ type: "text", text: "two" }] } },
]);
assert.equal(await runEffect(rewindTarget(files(), home, workspace, "s3", "u2")), "a1");
// An assistant item's id carries its block index.
assert.equal(await runEffect(rewindTarget(files(), home, workspace, "s3", "a1:0")), "u1");
// Nothing comes before the first message: refused, not half done.
assert.equal(await runEffect(rewindTarget(files(), home, workspace, "s3", "u1")), null);
assert.equal(await runEffect(rewindTarget(files(), home, workspace, "s3", "missing")), null);
});
test("the title falls back to the first prompt", async () => {
const home = tempDir();
const workspace = "/w/other";
write(join(home, "projects", encodeWorkspace(workspace), "s2.jsonl"), [
'{"type":"user","uuid":"u1","timestamp":"2026-09-14T12:00:00.000Z","message":{"role":"user","content":[{"type":"text","text":"fix the build\\nplease"}]}}',
]);
assert.equal((await runEffect(listSessions(files(), home, workspace)))[0].title, "fix the build");
});
// --- stored subagents (subagents.rs) --------------------------------------------
const user = (uuid: string, parent: string | null, time: string, content: unknown) =>
wire.record.parse({ type: "user", uuid, parentUuid: parent, timestamp: time, message: { role: "user", content } });
const assistant = (uuid: string, parent: string | null, time: string, content: unknown) =>
wire.record.parse({
type: "assistant",
uuid,
parentUuid: parent,
timestamp: time,
message: { model: "claude-haiku-4-5", content },
});
const sidechain = (record: wire.Record, agent: string) => ({ ...record, isSidechain: true, agentId: agent });
const toolId = (item: TranscriptItem) => (item.role === "tool" ? item.call.id : null);
/// A redacted copy of the layout claude 2.1.280 writes: a foreground agent
/// that starts a nested one, and a background agent that reports through a
/// queued notification.
test("stored subagents come back as nested tasks", async () => {
const home = tempDir();
const main = join(home, "s1.jsonl");
const dir = join(home, "s1", "subagents");
write(main, [
user("m1", null, "2026-09-22T10:00:00Z", "look around"),
assistant("m2", "m1", "2026-09-22T10:00:01Z", [
{
type: "tool_use",
id: "toolu_A",
name: "Agent",
input: { description: "Survey the parser", prompt: "Read the parser.", subagent_type: "Explore" },
},
{
type: "tool_use",
id: "toolu_C",
name: "Agent",
input: { prompt: "\nWatch the build\nand report", run_in_background: true },
},
]),
{
type: "user",
uuid: "m3",
parentUuid: "m2",
timestamp: "2026-09-22T10:00:02Z",
toolUseResult: { isAsync: true, status: "async_launched", agentId: "ccc" },
message: { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_C", content: "Launched" }] },
},
{
type: "user",
uuid: "m4",
parentUuid: "m3",
timestamp: "2026-09-22T10:01:00Z",
toolUseResult: {
status: "completed",
agentId: "aaa",
totalTokens: 900,
totalToolUseCount: 2,
content: [{ type: "text", text: "The parser is fine." }],
},
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "toolu_A",
content: [
{ type: "text", text: "The parser is fine." },
{ type: "text", text: "agentId: aaa" },
],
},
],
},
},
{
type: "queue-operation",
operation: "enqueue",
timestamp: "2026-09-22T10:02:00Z",
content:
'<task-notification>\n<task-id>ccc</task-id>\n<status>completed</status>\n<summary>Agent "Watch" finished</summary>\n<result>Build is green & fast.</result>\n</task-notification>',
},
]);
write(join(dir, "agent-aaa.jsonl"), [
sidechain(user("a1", null, "2026-09-22T10:00:03Z", "Read the parser."), "aaa"),
sidechain({ type: "attachment", uuid: "a1x", parentUuid: "a1", attachment: {} }, "aaa"),
sidechain(
assistant("a2", "a1x", "2026-09-22T10:00:04Z", [
{ type: "text", text: "Starting." },
{ type: "tool_use", id: "toolu_B", name: "Agent", input: { description: "Check tokens", prompt: "Check." } },
]),
"aaa",
),
// An abandoned branch the chain must skip.
sidechain(assistant("a2dead", "a1", "2026-09-22T10:00:04Z", [{ type: "text", text: "dead" }]), "aaa"),
sidechain(
{
type: "user",
uuid: "a3",
parentUuid: "a2",
timestamp: "2026-09-22T10:00:30Z",
toolUseResult: { status: "completed", agentId: "bbb", content: [{ type: "text", text: "Tokens ok." }] },
message: { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_B", content: "Tokens ok." }] },
},
"aaa",
),
sidechain(assistant("a4", "a3", "2026-09-22T10:00:59Z", [{ type: "text", text: "The parser is fine." }]), "aaa"),
]);
write(join(dir, "agent-aaa.meta.json"), [
{
agentType: "Explore",
description: "Survey the parser",
toolUseId: "toolu_A",
spawnDepth: 1,
requestShape: "foreground",
},
]);
const nested = join(dir, "workflows", "agent-bbb.jsonl");
write(nested, [
sidechain(user("b1", null, "2026-09-22T10:00:05Z", "Check."), "bbb"),
sidechain(assistant("b2", "b1", "2026-09-22T10:00:06Z", [{ type: "text", text: "Tokens ok." }]), "bbb"),
]);
write(join(dir, "workflows", "agent-bbb.meta.json"), [
{
agentType: "general-purpose",
description: "Check tokens",
toolUseId: "toolu_B",
parentAgentId: "aaa",
spawnDepth: 2,
model: "claude-sonnet-5",
},
]);
write(join(dir, "agent-ccc.jsonl"), [
sidechain(user("c1", null, "2026-09-22T10:00:03Z", "Watch the build"), "ccc"),
sidechain(assistant("c2", "c1", "2026-09-22T10:01:50Z", [{ type: "text", text: "Green." }]), "ccc"),
]);
write(join(dir, "agent-ccc.meta.json"), [
{ agentType: "general-purpose", toolUseId: "toolu_C", spawnDepth: 1, requestShape: "background" },
]);
const items = await runEffect(readFile(files(), main));
const atA = items.findIndex((item) => toolId(item) === "toolu_A");
const atC = items.findIndex((item) => toolId(item) === "toolu_C");
assert.equal(items[atA + 1].id, "task-toolu_A");
assert.equal(items[atC + 1].id, "task-toolu_C");
const { task: a, items: aItems } = itemAs(items[atA + 1], "task");
assert.equal(a.id, "toolu_A");
assert.equal(a.toolCallId, "toolu_A");
assert.equal(a.title, "Survey the parser");
assert.equal(a.name, "Explore");
assert.equal(a.prompt, "Read the parser.");
assert.equal(a.model, "claude-haiku-4-5");
assert.equal(a.status, "completed");
assert.equal(a.background, undefined);
assert.equal(a.summary, "The parser is fine.");
assert.equal(required(a.usage).usedTokens, 900);
assert.equal(a.toolUses, 2);
assert.ok(a.startedAt && a.endedAt);
// Its own transcript, without the prompt record or the dead branch, and
// the nested agent right after the call that started it.
assert.deepEqual(
required(aItems)
.filter((item) => item.role === "assistant")
.map((item) => item.text),
["Starting.", "The parser is fine."],
);
assert.ok(required(aItems).every((item) => item.role !== "user"));
const atB = required(aItems).findIndex((item) => toolId(item) === "toolu_B");
const { task: b, items: bItems } = itemAs(required(aItems)[atB + 1], "task");
assert.equal(b.title, "Check tokens");
assert.equal(b.parentTaskId, "toolu_A");
assert.equal(b.summary, "Tokens ok.");
assert.equal(required(bItems).length, 1);
assert.ok(!items.some((item) => item.id === "task-toolu_B"), "a nested agent is not at the top level");
const { task: c, items: cItems } = itemAs(items[atC + 1], "task");
assert.equal(c.title, "Watch the build", "the prompt's first line when there is no description");
assert.equal(c.background, true);
assert.equal(c.status, "completed");
assert.equal(c.summary, "Build is green & fast.", "the notification's result, not its status line");
assert.equal(required(cItems).length, 1);
});
/// A notification that names several agents is a status line about all of
/// them; it sets their status and never their result.
test("a shared notification is not a result", async () => {
const home = tempDir();
const main = join(home, "s2.jsonl");
write(main, [
assistant("m1", null, "2026-09-22T10:00:00Z", [
{ type: "tool_use", id: "toolu_X", name: "Agent", input: { description: "X", run_in_background: true } },
]),
user(
"m2",
"m1",
"2026-09-22T10:05:00Z",
"<task-notification>\n<task-id>xxx</task-id>\n<task-id>yyy</task-id>\n<status>stopped</status>\n<summary>2 background agents didn't finish</summary>\n</task-notification>",
),
]);
const dir = join(home, "s2", "subagents");
write(join(dir, "agent-xxx.jsonl"), [
sidechain(user("x1", null, "2026-09-22T10:00:01Z", "X"), "xxx"),
sidechain(assistant("x2", "x1", "2026-09-22T10:00:02Z", [{ type: "text", text: "Half done." }]), "xxx"),
]);
write(join(dir, "agent-xxx.meta.json"), [{ agentType: "general-purpose", description: "X", toolUseId: "toolu_X" }]);
const items = await runEffect(readFile(files(), main));
const x = itemAs(required(items.find((item) => item.id === "task-toolu_X")), "task").task;
assert.equal(x.status, "cancelled");
assert.equal(x.summary, "Half done.");
});
/// Bytes each read of a file answered, by path.
function countReads() {
const reads = new Map<string, number[]>();
useApi(fakeApi({ fs: diskFs({ onRead: (path, bytes) => reads.set(path, [...(reads.get(path) ?? []), bytes]) }) }));
return reads;
}
test("a second read of a transcript takes only what was appended", async () => {
const reads = countReads();
const path = join(tempDir(), "s.jsonl");
const line = (uuid: string, text: string) =>
JSON.stringify({ type: "user", uuid, message: { role: "user", content: [{ type: "text", text }] } }) + "\n";
writeFileSync(path, line("u1", "one") + line("u2", "two"));
const first = await runEffect(readSessionFile(files(), path, { tasks: "all" }));
assert.equal(first.items.length, 2);
const added = line("u3", "three");
appendFileSync(path, added);
const second = await runEffect(readSessionFile(files(), path, { tail: first.tail, tasks: "all" }));
assert.deepEqual(
second.items.map((item) => item.id),
["u1", "u2", "u3"],
);
assert.equal(required(reads.get(path))[1], Buffer.byteLength(added) + 1, "the appended bytes and the newline before");
// A file rewritten shorter is read whole.
writeFileSync(path, line("v1", "new"));
const third = await runEffect(readSessionFile(files(), path, { tail: second.tail, tasks: "all" }));
assert.deepEqual(
third.items.map((item) => item.id),
["v1"],
);
});
/// Every session read kept its parsed records until it was closed, three
/// times the size of its transcript, and a few long chats took the runtime
/// past its memory limit, which ended it and every Claude process with it.
test("the kept tails cover a bounded amount of transcript, the session read last always", () => {
const tail = (offset: number) => ({ path: "p", offset, records: [] });
const tails = new Tails(100);
tails.set("a", tail(40));
tails.set("b", tail(40));
tails.get("a");
tails.set("c", tail(40));
assert.equal(tails.get("b"), undefined, "the session read longest ago goes first");
assert.ok(tails.get("a") && tails.get("c"));
tails.set("d", tail(500));
assert.equal(tails.get("d")?.offset, 500, "the session read last keeps its tail past the budget");
assert.equal(tails.get("a"), undefined);
assert.equal(tails.get("c"), undefined);
});
test("a settled subagent's file is read only when its task is asked for", async () => {
const reads = countReads();
const home = tempDir();
const main = join(home, "s3.jsonl");
const dir = join(home, "s3", "subagents");
write(main, [
user("m1", null, "2026-09-22T10:00:00Z", "go"),
assistant("m2", "m1", "2026-09-22T10:00:01Z", [
{ type: "tool_use", id: "toolu_A", name: "Agent", input: { description: "Done one", prompt: "A" } },
{ type: "tool_use", id: "toolu_R", name: "Agent", input: { description: "Still going", prompt: "R" } },
]),
{
type: "user",
uuid: "m3",
parentUuid: "m2",
timestamp: "2026-09-22T10:01:00Z",
toolUseResult: { status: "completed", agentId: "aaa", content: [{ type: "text", text: "A done." }] },
message: { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_A", content: "A done." }] },
},
]);
for (const [agent, tool] of [
["aaa", "toolu_A"],
["rrr", "toolu_R"],
] as const) {
write(join(dir, `agent-${agent}.jsonl`), [
sidechain(user(`${agent}1`, null, "2026-09-22T10:00:02Z", "Work."), agent),
sidechain(
assistant(`${agent}2`, `${agent}1`, "2026-09-22T10:00:03Z", [{ type: "text", text: "Working." }]),
agent,
),
]);
write(join(dir, `agent-${agent}.meta.json`), [{ agentType: "general-purpose", toolUseId: tool }]);
}
const task = (items: TranscriptItem[], id: string) => itemAs(required(items.find((item) => item.id === id)), "task");
const lazy = await runEffect(readSessionFile(files(), main, { tasks: new Set() }));
assert.deepEqual(lazy.omitted, ["toolu_A"]);
assert.deepEqual(task(lazy.items, "task-toolu_A").items, []);
assert.equal(task(lazy.items, "task-toolu_A").task.summary, "A done.", "what the main transcript says stays");
assert.equal(required(task(lazy.items, "task-toolu_R").items).length, 1, "a running subagent is read");
assert.ok(!reads.has(join(dir, "agent-aaa.jsonl")), "the settled one's file is not");
const asked = await runEffect(readSessionFile(files(), main, { tasks: new Set(["toolu_A"]) }));
assert.deepEqual(asked.omitted, []);
assert.equal(required(task(asked.items, "task-toolu_A").items).length, 1);
});
/// A turn run on the conversation by another program (the CLI in a
/// terminal, Claude's desktop app) is a prompt this session did not send
/// answered by a reply it did not stream. The session's own turns, its
/// steers, tool results, the end of a background task, a subagent's
/// hand-back and a reply alone (a stop the CLI wrote) are not.
test("a turn run elsewhere is told from the session's own", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
const user = (uuid: string, content: unknown, extra: object = {}) => ({
type: "user",
uuid,
message: { role: "user", content },
...extra,
});
const reply = (uuid: string) => ({
type: "assistant",
uuid,
message: { id: `m-${uuid}`, role: "assistant", content: [{ type: "text", text: "ok" }] },
});
write(path, [user("old", "before this process"), reply("old-reply"), ""]);
const start = (await runEffect(recordsAfter(files(), path, 0))).offset;
appendFileSync(
path,
[
user("sent-1", [{ type: "text", text: "mine" }]),
reply("r1"),
user("tool", [{ type: "tool_result", tool_use_id: "t1", content: "done" }]),
{
type: "attachment",
uuid: "q1",
attachment: { type: "queued_command", commandMode: "prompt", source_uuid: "sent-2", prompt: "steer" },
},
{
type: "attachment",
uuid: "q2",
attachment: { type: "queued_command", commandMode: "prompt", source_uuid: "peer", prompt: "report", origin: { kind: "peer" } },
},
user("note", "<task-notification>", { origin: { kind: "task-notification" } }),
user("meta", "Caveat", { isMeta: true }),
reply("stopped"),
]
.map((record) => JSON.stringify(record))
.join("\n") + "\n",
);
const sent = new Set(["sent-1", "sent-2"]);
const streamed = new Set(["r1"]);
const ours = await runEffect(recordsAfter(files(), path, start));
assert.deepEqual(
ours.records.map((record) => record.uuid),
["sent-1", "r1", "tool", "q1", "q2", "note", "meta", "stopped"],
"only what was written after the mark",
);
assert.equal(turnFromElsewhere(ours.records, sent, streamed), false);
appendFileSync(path, [user("elsewhere", "typed in the desktop app"), reply("r2")].map((r) => JSON.stringify(r)).join("\n") + "\n");
const theirs = await runEffect(recordsAfter(files(), path, ours.offset));
assert.deepEqual(theirs.records.map((record) => record.uuid), ["elsewhere", "r2"]);
assert.equal(turnFromElsewhere(theirs.records, sent, streamed), true);
// A line still being written waits for the next read.
appendFileSync(path, JSON.stringify(user("half", "x")).slice(0, 10));
const half = await runEffect(recordsAfter(files(), path, theirs.offset));
assert.deepEqual(half, { records: [], offset: theirs.offset });
});
/// A fork made in Claude Code starts with a copy of its origin's messages
/// and keeps its title in the file. It is listed as Claude Code shows it,
/// with " (fork)" on the end; a fork with a title of its own keeps it.
test("a fork is listed under the name Claude Code gives it", async () => {
const home = tempDir();
const workspace = "/w/project";
const folder = join(home, "projects", encodeWorkspace(workspace));
const conversation = [
'{"type":"user","uuid":"u1","timestamp":"2026-10-01T12:00:00.000Z","message":{"role":"user","content":"fix the build"}}',
'{"type":"assistant","uuid":"a1","timestamp":"2026-10-01T12:00:01.000Z","message":{"content":[{"type":"text","text":"done"}]}}',
'{"type":"ai-title","aiTitle":"Fix the build","sessionId":"x"}',
];
const forked = (at: string) => `{"type":"queue-operation","operation":"enqueue","timestamp":"${at}"}`;
write(join(folder, "origin.jsonl"), conversation);
write(join(folder, "fork.jsonl"), [forked("2026-10-02T09:00:00.000Z"), ...conversation]);
write(join(folder, "renamed.jsonl"), [
forked("2026-10-02T10:00:00.000Z"),
...conversation,
'{"type":"custom-title","customTitle":"Try the other fix","sessionId":"renamed"}',
]);
const titles = Object.fromEntries(
(await runEffect(listSessions(files(), home, workspace))).map((session) => [session.id, session.title]),
);
assert.deepEqual(titles, { origin: "Fix the build", fork: "Fix the build (fork)", renamed: "Try the other fix" });
});
/// A message another session sent reads back as a message from it, at its
/// place: whether it started a turn (a user record) or came during one (a
/// queued command). A reply to the address it came from names that session,
/// and a message that could not be delivered is a failed call.
test("messages between sessions read back with who sent them", async () => {
const dir = tempDir();
const path = join(dir, "s.jsonl");
const origin = { kind: "peer", from: "uds:/tmp/cc-socks/7.sock", name: "nexus-a1", fromMode: "prompting" };
const send = (id: string, input: object) => ({
type: "assistant",
uuid: `r-${id}`,
message: { id: `m-${id}`, role: "assistant", content: [{ type: "tool_use", id, name: "SendMessage", input }] },
});
const result = (id: string, toolUseResult: object) => ({
type: "user",
uuid: `t-${id}`,
toolUseResult,
message: { role: "user", content: [{ type: "tool_result", tool_use_id: id, content: JSON.stringify(toolUseResult) }] },
});
write(path, [
{
type: "user",
uuid: "c1",
isMeta: true,
origin: { ...origin, body: "Please avoid render.rs." },
message: { role: "user", content: "Another Claude session sent a message:\n<cross-session-message>…" },
},
send("s1", { to: "uds:/tmp/cc-socks/7.sock", summary: "Agreed", message: "I will stay out of it." }),
result("s1", { success: true, message: "sent" }),
{
type: "attachment",
uuid: "q1",
attachment: {
type: "queued_command",
commandMode: "prompt",
source_uuid: "c2",
prompt: "<cross-session-message>…",
origin: { ...origin, body: "Done with the tree." },
},
},
send("s2", { to: "nexus-ee [0ec673]", message: "Heads-up." }),
result("s2", { success: false, message: "nexus-ee is not running" }),
]);
const items = await runEffect(readFile(files(), path));
const first = itemAs(required(items[0]), "user");
assert.equal(first.id, "c1");
assert.equal(first.from, "nexus-a1");
assert.deepEqual(first.blocks, [{ type: "text", text: "Please avoid render.rs." }]);
const reply = itemAs(required(items[1]), "tool").call;
assert.equal(reply.title, "Message to nexus-a1: Agreed");
assert.deepEqual(reply.message, { to: "nexus-a1", text: "I will stay out of it." });
assert.equal(reply.status, "completed");
assert.deepEqual(reply.content, []);
const second = itemAs(required(items[2]), "user");
assert.deepEqual([second.id, second.from], ["c2", "nexus-a1"]);
const failed = itemAs(required(items[3]), "tool").call;
assert.equal(failed.message?.to, "nexus-ee");
assert.equal(failed.status, "failed");
assert.deepEqual(failed.content, [{ type: "text", text: "nexus-ee is not running" }]);
});Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.7latest | Nov 21, 2026 | >=5 <6 | 207.5 KB | 4 permissions | Listed |
| 0.2.6 | Nov 16, 2026 | >=5 <6 | 206 KB | 4 permissions | Listed |
| 0.2.5 | Nov 11, 2026 | >=5 <6 | 168.3 KB | 4 permissions | Listed |
| 0.2.4 | Nov 9, 2026 | >=5 <6 | 166.1 KB | 4 permissions | Listed |
| 0.2.3 | Oct 27, 2026 | >=2 <4 | 151.6 KB | 4 permissions | Listed |
No comments yet.