test(orchestrator): align merged V2 compatibility checks

Remove the unreferenced V1 activity payload projection that arrived from main and assert only the public serialized SchemaError shape under Effect beta.102.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-08-15 16:50:11 +02:00
1 parent 9b547f9e4f
commit cb3fc2a81a
3 files changed
-1107

No files matched your search

@@ -68,7 +68,6 @@ describe("decodeProviderReplayNdjson", () => {
}
const causeRecord = cause as Record<string, unknown>;
assert.equal(causeRecord.name, "SchemaError");
assert.equal(causeRecord._tag, "SchemaError");
assert.doesNotThrow(() => JSON.stringify(encoded));
}),
);
@@ -1,546 +0,0 @@
import type {
OrchestrationEvent,
OrchestrationThreadActivity,
OrchestrationThreadDetailSnapshot,
} from "@t3tools/contracts";
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function asTrimmedString(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function pushChangedFile(target: string[], seen: Set<string>, value: unknown): void {
const normalized = asTrimmedString(value);
if (!normalized || seen.has(normalized)) {
return;
}
seen.add(normalized);
target.push(normalized);
}
function collectChangedFiles(
value: unknown,
target: string[],
seen: Set<string>,
depth: number,
): void {
if (depth > 4 || target.length >= 12) {
return;
}
if (Array.isArray(value)) {
for (const entry of value) {
collectChangedFiles(entry, target, seen, depth + 1);
if (target.length >= 12) {
return;
}
}
return;
}
const record = asRecord(value);
if (!record) {
return;
}
pushChangedFile(target, seen, record.path);
pushChangedFile(target, seen, record.filePath);
pushChangedFile(target, seen, record.relativePath);
pushChangedFile(target, seen, record.filename);
pushChangedFile(target, seen, record.newPath);
pushChangedFile(target, seen, record.oldPath);
for (const nestedKey of [
"item",
"result",
"input",
"data",
"changes",
"files",
"edits",
"patch",
"patches",
"operations",
]) {
if (!(nestedKey in record)) {
continue;
}
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
if (target.length >= 12) {
return;
}
}
}
function projectCommandData(data: Record<string, unknown>): Record<string, unknown> | undefined {
const item = asRecord(data.item);
if (!item) {
return undefined;
}
const projectedItem: Record<string, unknown> = {};
if ("command" in item) {
projectedItem.command = item.command;
}
const aggregatedOutput = asTrimmedString(item.aggregatedOutput);
if (aggregatedOutput) {
const summary = summarizeToolTextOutput(aggregatedOutput);
if (summary) {
projectedItem.aggregatedOutput = summary;
}
}
const input = asRecord(item.input);
if (input && "command" in input) {
projectedItem.input = { command: input.command };
}
const result = asRecord(item.result);
if (result) {
const projectedResult: Record<string, unknown> = {};
if ("command" in result) {
projectedResult.command = result.command;
}
const content = asTrimmedString(result.content);
if (content) {
const summary = summarizeToolTextOutput(content);
if (summary) {
projectedResult.content = summary;
}
}
if (Object.keys(projectedResult).length > 0) {
projectedItem.result = projectedResult;
}
}
return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;
}
function summarizeToolTextOutput(value: string): string | null {
const lines: string[] = [];
for (const rawLine of value.split(/\r?\n/u)) {
const line = rawLine.replace(/\s+/g, " ").trim();
if (line.length > 0) {
lines.push(line);
}
}
const firstLine = lines.find((line) => line !== "```");
if (firstLine) {
return firstLine.length <= 84 ? firstLine : `${firstLine.slice(0, 83).trimEnd()}…`;
}
if (lines.length > 1) {
return `${lines.length.toLocaleString()} lines`;
}
return null;
}
/**
* Fields of an MCP tool-call item both clients render in the expanded
* work-log row. Everything else — notably `result`, which carries the full
* tool output and dominates wire size on MCP-heavy threads — is summarized
* or dropped. Full payloads remain in persistence.
*/
const MCP_ITEM_KEPT_FIELDS = [
"type",
"id",
"tool",
"server",
"status",
"arguments",
"appContext",
"error",
"durationMs",
] as const;
/**
* Pulls renderable text out of an MCP tool result: either a Codex-style
* `{content: [{type: "text", text}, ...]}` record or a raw Claude
* `tool_result` block whose `content` is a string or block array.
*/
function extractMcpResultText(result: unknown): string | null {
const record = asRecord(result);
if (!record) {
return typeof result === "string" ? result : null;
}
if (typeof record.content === "string") {
return record.content;
}
if (Array.isArray(record.content)) {
const texts: string[] = [];
for (const entry of record.content) {
const text = asRecord(entry)?.text;
if (typeof text === "string" && text.trim().length > 0) {
texts.push(text);
}
}
if (texts.length > 0) {
return texts.join("\n");
}
}
return null;
}
function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
if (result === undefined || result === null) {
return undefined;
}
const text = extractMcpResultText(result);
const summary = text ? summarizeToolTextOutput(text) : null;
return summary ? { content: summary } : undefined;
}
/**
* MCP tool calls carry full tool results (`data.item.result` on Codex,
* `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
* keep the expanded-row UI working. Keep the fields the UI actually renders
* and summarize the result like regular tool output.
*/
function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
const projectedData: Record<string, unknown> = {};
const item = asRecord(data.item);
if (item) {
const projectedItem: Record<string, unknown> = {};
for (const key of MCP_ITEM_KEPT_FIELDS) {
if (key in item) {
projectedItem[key] = item[key];
}
}
const result = summarizeMcpResult(item.result);
if (result) {
projectedItem.result = result;
}
projectedData.item = projectedItem;
}
if ("toolName" in data) {
projectedData.toolName = data.toolName;
}
if ("input" in data) {
projectedData.input = data.input;
}
if (!item) {
const result = summarizeMcpResult(data.result);
if (result) {
projectedData.result = result;
}
}
if ("toolCallId" in data) {
projectedData.toolCallId = data.toolCallId;
}
if ("kind" in data) {
projectedData.kind = data.kind;
}
const changedFiles: string[] = [];
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
if (changedFiles.length > 0) {
projectedData.files = changedFiles.map((path) => ({ path }));
}
return projectedData;
}
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
const direct = asTrimmedString(value);
if (direct) {
const summary = summarizeToolTextOutput(direct);
return summary ? { content: summary } : undefined;
}
const rawOutput = asRecord(value);
if (!rawOutput) {
return undefined;
}
if (typeof rawOutput.totalFiles === "number" && Number.isFinite(rawOutput.totalFiles)) {
return {
totalFiles: rawOutput.totalFiles,
...(rawOutput.truncated === true ? { truncated: true } : {}),
};
}
const content = asTrimmedString(rawOutput.content);
if (content) {
const summary = summarizeToolTextOutput(content);
return summary ? { content: summary } : undefined;
}
const stdout = asTrimmedString(rawOutput.stdout);
if (stdout) {
const summary = summarizeToolTextOutput(stdout);
return summary ? { content: summary } : undefined;
}
const stderr = asTrimmedString(rawOutput.stderr);
if (stderr) {
const summary = summarizeToolTextOutput(stderr);
return summary ? { content: summary } : undefined;
}
return undefined;
}
function projectAcpContent(value: unknown): Record<string, unknown> | undefined {
if (!Array.isArray(value)) {
return undefined;
}
const text = value
.map((entryValue) => {
const entry = asRecord(entryValue);
const content = asRecord(entry?.content);
return entry?.type === "content" && content?.type === "text"
? asTrimmedString(content.text)
: null;
})
.filter((entry): entry is string => entry !== null)
.join("\n");
const summary = summarizeToolTextOutput(text);
return summary ? { content: summary } : undefined;
}
/**
* Removes activity payload fields that no current client reads while retaining
* the full payload in persistence and the event store.
*/
export function projectActivityPayload(
activity: OrchestrationThreadActivity,
): OrchestrationThreadActivity {
const payload = asRecord(activity.payload);
const data = asRecord(payload?.data);
if (!payload || !data) {
return activity;
}
if (payload.itemType === "mcp_tool_call") {
return {
...activity,
payload: {
...payload,
data: projectMcpToolCallData(data),
},
};
}
const projectedData: Record<string, unknown> = {};
const item = projectCommandData(data);
if (item) {
projectedData.item = item;
}
if ("command" in data) {
projectedData.command = data.command;
}
const changedFiles: string[] = [];
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
if (changedFiles.length > 0) {
// Both clients discover file names by walking objects with path-like keys.
projectedData.files = changedFiles.map((path) => ({ path }));
}
if ("toolCallId" in data) {
projectedData.toolCallId = data.toolCallId;
}
if ("kind" in data) {
projectedData.kind = data.kind;
}
const rawOutput = projectRawOutput(data.rawOutput) ?? projectAcpContent(data.content);
if (rawOutput) {
projectedData.rawOutput = rawOutput;
}
return {
...activity,
payload: {
...payload,
data: projectedData,
},
};
}
/**
* Matches the validity rule in the web client's
* `deriveLatestContextWindowSnapshot`: rows without a finite, non-negative
* `usedTokens` are skipped during its backward walk, so they must not shadow
* an earlier resolvable row here.
*/
function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
if (activity.kind !== "context-window.updated") {
return false;
}
const payload = asRecord(activity.payload);
const usedTokens = payload?.usedTokens;
return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
}
/**
* Drops all but the last resolvable context-window activity per turn from a
* snapshot. Clients only ever read the latest usage value (walking the array
* backwards), so shipping the full history — often thousands of rows on long
* threads — buys nothing. Retention is per turn rather than per thread because
* a live `thread.reverted` makes the client discard whole turns; keeping each
* turn's latest row means the meter can still resolve a value from the turns
* that survive. Malformed rows pass through untouched rather than shadowing a
* valid earlier row. Live `thread.activity-appended` events are untouched:
* newer updates still stream through and supersede the retained rows on the
* client.
*/
function dropStaleContextWindowActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const latestIndexByTurn = new Map<string | null, number>();
for (let index = 0; index < activities.length; index += 1) {
if (isResolvableContextWindowActivity(activities[index]!)) {
latestIndexByTurn.set(activities[index]!.turnId, index);
}
}
if (latestIndexByTurn.size === 0) {
return activities;
}
return activities.filter(
(activity, index) =>
!isResolvableContextWindowActivity(activity) ||
latestIndexByTurn.get(activity.turnId) === index,
);
}
/**
* Identity both clients use to fold a tool lifecycle row into the call it
* belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and
* mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter
* emits one, otherwise the itemType/title/detail triple. Returns null for rows
* with no identity at all — those never collapse on the client either, so they
* must not be dropped here.
*/
function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
const payload = asRecord(activity.payload);
if (!payload) {
return null;
}
const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);
if (toolCallId) {
return `id:${toolCallId}`;
}
const itemType = asTrimmedString(payload.itemType) ?? "";
// Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
// gain a trailing "complete"/"completed" the in-flight updates lack.
const label = (asTrimmedString(payload.title) ?? activity.summary)
.replace(/\s+(?:complete|completed)\s*$/iu, "")
.trim();
const detail = asTrimmedString(payload.detail) ?? "";
if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
return null;
}
return [itemType, label, detail].join("");
}
/**
* Drops `tool.updated` rows a `tool.completed` row already supersedes. An
* update is the in-flight snapshot of a call; once the call completes, the
* completion carries the final state and the clients fold every matching
* update into it, so shipping the updates buys nothing — 47k such rows exist
* in one real database, and a single thread carries 2,291 of them totalling
* ~1MB post-slimming.
*
* Matching is per turn for the same reason `dropStaleContextWindowActivities`
* retains per turn: a live `thread.reverted` makes the client discard whole
* turns, so a completion in a different turn could vanish and leave the
* dropped update unrepresented. The completion must also come *after* the
* update within the turn — a later update belongs to a subsequent call that
* reuses the same identity and is still in flight. Rows without a lifecycle
* identity pass through, matching the clients, which never collapse them.
* Live `thread.activity-appended` events are untouched: updates still stream
* in real time and the completion supersedes them on the client as before.
*
* Deliberate divergence from client collapse: clients fold only *adjacent*
* lifecycle rows, so a superseded update separated from its completion by an
* interleaved parallel call renders as its own row today, and this drop
* removes it. Measured against a real database, that affects 1.5% of dropped
* rows (553 of 36,581), all pure in-flight state whose final result the
* retained completion still shows. Dropping them is intentional; matching
* adjacency server-side would forfeit most of the win for parallel-heavy
* threads, which are exactly the heavy ones. Superseding completions always
* carry a payload superset of their updates (verified across all 49,515
* update rows: zero dropped rows held a client-merged field — detail, title,
* command, item, kind, files — their completion lacked), so no expanded-row
* content is lost.
*/
function dropSupersededToolUpdatedActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const completionIndicesByKey = new Map<string, number[]>();
for (let index = 0; index < activities.length; index += 1) {
const activity = activities[index]!;
if (activity.kind !== "tool.completed") {
continue;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
continue;
}
const key = `${activity.turnId ?? ""}${identity}`;
const indices = completionIndicesByKey.get(key);
if (indices) {
indices.push(index);
} else {
completionIndicesByKey.set(key, [index]);
}
}
if (completionIndicesByKey.size === 0) {
return activities;
}
return activities.filter((activity, index) => {
if (activity.kind !== "tool.updated") {
return true;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
return true;
}
const indices = completionIndicesByKey.get(`${activity.turnId ?? ""}${identity}`);
return !indices?.some((completionIndex) => completionIndex > index);
});
}
export function projectThreadDetailSnapshot(
snapshot: OrchestrationThreadDetailSnapshot,
): OrchestrationThreadDetailSnapshot {
return {
...snapshot,
thread: {
...snapshot.thread,
activities: dropSupersededToolUpdatedActivities(
dropStaleContextWindowActivities(snapshot.thread.activities),
).map(projectActivityPayload),
},
};
}
export function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {
if (event.type !== "thread.activity-appended") {
return event;
}
return {
...event,
payload: {
...event.payload,
activity: projectActivityPayload(event.payload.activity),
},
};
}
@@ -1,560 +0,0 @@
import {
EventId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationEvent,
type OrchestrationThread,
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildThreadFeed, type ThreadFeedActivity } from "../../mobile/src/lib/threadActivity.ts";
import { deriveLatestContextWindowSnapshot } from "../../web/src/lib/contextWindow.ts";
import { deriveWorkLogEntries } from "../../web/src/session-logic.ts";
import {
projectActivityEvent,
projectActivityPayload,
projectThreadDetailSnapshot,
} from "../src/orchestration/ActivityPayloadProjection.ts";
function makeActivity(
id: string,
itemType: string,
data: Record<string, unknown>,
): OrchestrationThreadActivity {
return {
id: EventId.make(id),
tone: "tool",
kind: "tool.completed",
summary: `Completed ${itemType}`,
payload: {
itemType,
title: itemType,
detail: `${itemType} detail`,
status: "completed",
requestKind: "command",
data,
},
turnId: TurnId.make(`turn-${id}`),
createdAt: "2026-07-27T00:00:00.000Z",
};
}
function makeThread(activities: ReadonlyArray<OrchestrationThreadActivity>): OrchestrationThread {
return {
id: ThreadId.make("thread-projection"),
projectId: ProjectId.make("project-projection"),
title: "Activity projection",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-07-27T00:00:00.000Z",
updatedAt: "2026-07-27T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities,
checkpoints: [],
session: null,
};
}
const fixtures = [
makeActivity("command", "command_execution", {
item: {
command: ["bash", "-lc", "pnpm test"],
input: { command: "fallback input", ignored: "input bulk" },
result: { command: "fallback result", aggregatedOutput: "x".repeat(10_000) },
commandActions: [{ type: "unknown", output: "y".repeat(5_000) }],
},
command: "fallback data",
kind: "execute",
toolCallId: "tool-command",
rawOutput: {
content: "\n```\nfirst useful line\nsecond line",
stdout: "unused stdout",
ignored: "raw bulk",
},
ignored: "top-level bulk",
}),
makeActivity("file-change", "file_change", {
item: {
changes: [
{ oldPath: "src/old.ts", newPath: "src/new.ts", patch: "large patch".repeat(1_000) },
{ filePath: "src/second.ts" },
],
},
ignored: "top-level bulk",
}),
makeActivity("dynamic", "dynamic_tool_call", {
toolCallId: "tool-dynamic",
rawOutput: {
stdout: "dynamic summary\nlong output".repeat(1_000),
},
ignored: "top-level bulk",
}),
makeActivity("collab", "collab_agent_tool_call", {
kind: "delegate",
rawOutput: {
content: "``` \n```",
stdout: "must not be used when content is present",
},
ignored: "top-level bulk",
}),
makeActivity("mcp", "mcp_tool_call", {
item: {
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
aggregatedOutput: "mcp bulk is dropped",
},
ignored: "top-level bulk",
}),
makeActivity("search", "web_search", {
rawOutput: {
totalFiles: 42,
truncated: true,
content: "ignored because totalFiles wins",
},
ignored: "top-level bulk",
}),
makeActivity("image", "image_view", {
ignored: "top-level bulk",
}),
] satisfies ReadonlyArray<OrchestrationThreadActivity>;
describe("projectActivityPayload", () => {
function comparableActivity(activity: ThreadFeedActivity) {
return {
...activity,
fullDetail: activity.getFullDetail(),
copyText: activity.getCopyText(),
getFullDetail: undefined,
getCopyText: undefined,
};
}
function comparableThreadFeed(activities: ReadonlyArray<OrchestrationThreadActivity>) {
return buildThreadFeed(makeThread(activities)).map((entry) =>
entry.type === "activity-group"
? {
...entry,
activities: entry.activities.map(comparableActivity),
}
: entry,
);
}
it("drops unread bulk while retaining command, file, tool, and summary inputs", () => {
const projected = projectActivityPayload(fixtures[0]!);
expect(projected.payload).toEqual({
itemType: "command_execution",
title: "command_execution",
detail: "command_execution detail",
status: "completed",
requestKind: "command",
data: {
item: {
command: ["bash", "-lc", "pnpm test"],
input: { command: "fallback input" },
result: { command: "fallback result" },
},
command: "fallback data",
toolCallId: "tool-command",
kind: "execute",
rawOutput: { content: "first useful line" },
},
});
expect(projectActivityPayload(fixtures[1]!).payload).toMatchObject({
data: {
files: [{ path: "src/new.ts" }, { path: "src/old.ts" }, { path: "src/second.ts" }],
},
});
});
it("slims MCP tool data to the fields the expanded row renders", () => {
expect(projectActivityPayload(fixtures[4]!).payload).toEqual({
itemType: "mcp_tool_call",
title: "mcp_tool_call",
detail: "mcp_tool_call detail",
status: "completed",
requestKind: "command",
data: {
item: {
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
},
},
});
});
it("keeps current web and mobile derived output identical for every tool item type", () => {
for (const activity of fixtures) {
const projected = projectActivityPayload(activity);
if (activity === fixtures[4]) {
// MCP is the one deliberate difference: the expanded row's toolData
// loses result bulk but keeps the rendered identity fields.
const [entry] = deriveWorkLogEntries([projected]);
expect(entry?.toolData).toEqual({
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
});
continue;
}
expect(deriveWorkLogEntries([projected])).toEqual(deriveWorkLogEntries([activity]));
expect(comparableThreadFeed([projected])).toEqual(comparableThreadFeed([activity]));
}
});
it("projects snapshot and event transports without mutating their sources", () => {
const activity = fixtures[0]!;
const thread = makeThread([activity]);
const snapshot = { snapshotSequence: 7, thread };
const projectedSnapshot = projectThreadDetailSnapshot(snapshot);
expect(projectedSnapshot.thread.activities[0]).not.toBe(activity);
expect(snapshot.thread.activities[0]).toBe(activity);
const event = {
sequence: 8,
eventId: EventId.make("event-activity"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: "2026-07-27T00:00:01.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.activity-appended",
payload: {
threadId: thread.id,
activity,
},
} satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
const projectedEvent = projectActivityEvent(event);
expect(projectedEvent).not.toBe(event);
expect(
projectedEvent.type === "thread.activity-appended"
? projectedEvent.payload.activity
: undefined,
).toEqual(projectActivityPayload(activity));
expect(event.payload.activity).toBe(activity);
});
});
describe("superseded tool.updated snapshot dedup", () => {
function makeToolLifecycleActivity(
id: string,
kind: "tool.updated" | "tool.completed",
options: {
readonly turn?: string;
readonly title?: string;
readonly detail?: string;
readonly toolCallId?: string;
} = {},
): OrchestrationThreadActivity {
const { turn = "turn-a", title = "File change", detail, toolCallId } = options;
return {
id: EventId.make(id),
tone: "tool",
kind,
summary: title,
payload: {
itemType: "file_change",
title,
...(detail ? { detail } : {}),
data: {
...(toolCallId ? { toolCallId } : {}),
toolName: "Edit",
input: { file_path: "src/app.ts" },
},
},
turnId: TurnId.make(turn),
createdAt: "2026-07-27T00:00:00.000Z",
};
}
function projectedIds(activities: ReadonlyArray<OrchestrationThreadActivity>) {
return projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread(activities),
}).thread.activities.map((activity) => activity.id);
}
it("drops updates a later completion supersedes in the same turn", () => {
const update1 = makeToolLifecycleActivity("upd-1", "tool.updated");
const update2 = makeToolLifecycleActivity("upd-2", "tool.updated");
const completed = makeToolLifecycleActivity("done-1", "tool.completed");
expect(projectedIds([update1, update2, completed])).toEqual([completed.id]);
});
it("matches on toolCallId when the adapter emits one", () => {
const otherCall = makeToolLifecycleActivity("upd-other", "tool.updated", {
toolCallId: "call-b",
});
const update = makeToolLifecycleActivity("upd-a", "tool.updated", { toolCallId: "call-a" });
const completed = makeToolLifecycleActivity("done-a", "tool.completed", {
toolCallId: "call-a",
});
// Same itemType/title, different call: only call-a's update is superseded.
expect(projectedIds([otherCall, update, completed])).toEqual([otherCall.id, completed.id]);
});
it("keeps updates with no matching completion", () => {
const inFlight = makeToolLifecycleActivity("upd-live", "tool.updated", { title: "Running" });
const other = makeToolLifecycleActivity("upd-other", "tool.updated", { title: "Reading" });
const completed = makeToolLifecycleActivity("done-other", "tool.completed", {
title: "Reading",
});
expect(projectedIds([inFlight, other, completed])).toEqual([inFlight.id, completed.id]);
});
it("drops interleaved superseded updates even when a parallel call separates them", () => {
// Deliberate divergence from the clients' adjacency-based collapse: a
// superseded update separated from its completion by an interleaved
// parallel call renders as its own in-flight row on full history, and the
// snapshot omits it. Its final state still shows via the retained
// completion (1.5% of dropped rows on real data; see the projection's doc
// comment).
const updateA = makeToolLifecycleActivity("upd-a", "tool.updated", { toolCallId: "call-a" });
const updateB = makeToolLifecycleActivity("upd-b", "tool.updated", { toolCallId: "call-b" });
const completedA = makeToolLifecycleActivity("done-a", "tool.completed", {
toolCallId: "call-a",
});
const completedB = makeToolLifecycleActivity("done-b", "tool.completed", {
toolCallId: "call-b",
});
expect(projectedIds([updateA, updateB, completedA, completedB])).toEqual([
completedA.id,
completedB.id,
]);
});
it("keeps an update whose completion lives in another turn", () => {
// A live thread.reverted can discard the completing turn while keeping
// the updating one, which would leave the call unrepresented.
const update = makeToolLifecycleActivity("upd-kept", "tool.updated", { turn: "turn-kept" });
const completed = makeToolLifecycleActivity("done-later", "tool.completed", {
turn: "turn-reverted",
});
expect(projectedIds([update, completed])).toEqual([update.id, completed.id]);
});
it("keeps an update that follows its completion", () => {
// A later update under the same identity is the next call, still in flight.
const completed = makeToolLifecycleActivity("done-first", "tool.completed");
const nextCall = makeToolLifecycleActivity("upd-next", "tool.updated");
expect(projectedIds([completed, nextCall])).toEqual([completed.id, nextCall.id]);
});
it("keeps identity-less rows the clients never collapse", () => {
const anonymous: OrchestrationThreadActivity = {
id: EventId.make("upd-anon"),
tone: "tool",
kind: "tool.updated",
summary: " ",
payload: { data: { toolName: "Edit" } },
turnId: TurnId.make("turn-a"),
createdAt: "2026-07-27T00:00:00.000Z",
};
const completed: OrchestrationThreadActivity = {
...anonymous,
id: EventId.make("done-anon"),
kind: "tool.completed",
};
expect(projectedIds([anonymous, completed])).toEqual([anonymous.id, completed.id]);
});
it("does not filter live activity-appended events", () => {
const update = makeToolLifecycleActivity("upd-live-event", "tool.updated");
const event = {
sequence: 11,
eventId: EventId.make("event-tool-updated"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-projection"),
occurredAt: "2026-07-27T00:00:03.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.activity-appended",
payload: {
threadId: ThreadId.make("thread-projection"),
activity: update,
},
} satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
const projected = projectActivityEvent(event);
expect(
projected.type === "thread.activity-appended" ? projected.payload.activity.id : undefined,
).toEqual(update.id);
});
it("leaves the collapsed work log identical to the full history", () => {
const activities = [
makeToolLifecycleActivity("upd-1", "tool.updated", { detail: "writing" }),
makeToolLifecycleActivity("upd-2", "tool.updated", { detail: "writing" }),
makeToolLifecycleActivity("done-1", "tool.completed", { detail: "writing" }),
];
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread(activities),
});
const before = deriveWorkLogEntries(activities);
const after = deriveWorkLogEntries(projected.thread.activities);
expect(after).toHaveLength(before.length);
expect(after.map((entry) => entry.label)).toEqual(before.map((entry) => entry.label));
});
});
describe("context-window snapshot dedup", () => {
function makeContextWindowActivity(
id: string,
usedTokens: number,
turn = `turn-${id}`,
): OrchestrationThreadActivity {
return {
id: EventId.make(id),
tone: "info",
kind: "context-window.updated",
summary: "Context window updated",
payload: { usedTokens, maxTokens: 200_000 },
turnId: TurnId.make(turn),
createdAt: "2026-07-27T00:00:00.000Z",
};
}
it("keeps only the latest context-window activity per turn in snapshots", () => {
const stale1 = makeContextWindowActivity("ctx-1", 1_000, "turn-a");
const latestA = makeContextWindowActivity("ctx-2", 2_000, "turn-a");
const latestB = makeContextWindowActivity("ctx-3", 3_000, "turn-b");
const tool = fixtures[0]!;
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread([stale1, tool, latestA, latestB]),
});
expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
tool.id,
latestA.id,
latestB.id,
]);
// The retained rows keep their payloads untouched — the tool-data
// projection only rewrites payloads with a `data` record.
expect(projected.thread.activities[2]?.payload).toEqual(latestB.payload);
});
it("still resolves a meter value after the client reverts the newest turn", () => {
// A live thread.reverted makes the client drop all activities from
// discarded turns; each surviving turn must keep a usable row.
const olderTurn = makeContextWindowActivity("ctx-old", 1_500, "turn-kept");
const revertedTurn = makeContextWindowActivity("ctx-new", 9_000, "turn-reverted");
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread([olderTurn, revertedTurn]),
});
const afterRevert = projected.thread.activities.filter(
(activity) => activity.turnId === TurnId.make("turn-kept"),
);
expect(deriveLatestContextWindowSnapshot(afterRevert)).toEqual(
deriveLatestContextWindowSnapshot([olderTurn]),
);
});
it("matches what the web client derives from the full history", () => {
const activities = [
makeContextWindowActivity("ctx-1", 1_000),
makeContextWindowActivity("ctx-2", 2_000),
];
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread(activities),
});
expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
deriveLatestContextWindowSnapshot(activities),
);
});
it("does not let a malformed row shadow an earlier valid row in the same turn", () => {
const valid = makeContextWindowActivity("ctx-valid", 5_000, "turn-a");
const malformed: OrchestrationThreadActivity = {
...makeContextWindowActivity("ctx-broken", 0, "turn-a"),
payload: { usedTokens: null },
};
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread([valid, malformed]),
});
// The malformed row passes through, the valid row survives, and the
// client's backward walk resolves the same value as with full history.
expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
valid.id,
malformed.id,
]);
expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
deriveLatestContextWindowSnapshot([valid, malformed]),
);
});
it("applies only payload slimming when there are no context-window activities", () => {
const projected = projectThreadDetailSnapshot({
snapshotSequence: 7,
thread: makeThread([fixtures[4]!]),
});
expect(projected.thread.activities).toEqual([projectActivityPayload(fixtures[4]!)]);
});
it("does not filter live activity-appended events", () => {
const activity = makeContextWindowActivity("ctx-live", 4_000);
const event = {
sequence: 9,
eventId: EventId.make("event-ctx"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-projection"),
occurredAt: "2026-07-27T00:00:02.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.activity-appended",
payload: {
threadId: ThreadId.make("thread-projection"),
activity,
},
} satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
const projected = projectActivityEvent(event);
expect(
projected.type === "thread.activity-appended" ? projected.payload.activity : undefined,
).toEqual(activity);
});
});