Open History to see the last commit
1import {
2 EventId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 TurnId,
7 type OrchestrationEvent,
8 type OrchestrationThread,
9 type OrchestrationThreadActivity,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "vite-plus/test";
12
13import { buildThreadFeed, type ThreadFeedActivity } from "../../mobile/src/lib/threadActivity.ts";
14import { deriveLatestContextWindowSnapshot } from "../../web/src/lib/contextWindow.ts";
15import { deriveWorkLogEntries } from "../../web/src/session-logic.ts";
16import {
17 projectActivityEvent,
18 projectActivityPayload,
19 projectThreadDetailSnapshot,
20} from "../src/orchestration/ActivityPayloadProjection.ts";
21
22function makeActivity(
23 id: string,
24 itemType: string,
25 data: Record<string, unknown>,
26): OrchestrationThreadActivity {
27 return {
28 id: EventId.make(id),
29 tone: "tool",
30 kind: "tool.completed",
31 summary: `Completed ${itemType}`,
32 payload: {
33 itemType,
34 title: itemType,
35 detail: `${itemType} detail`,
36 status: "completed",
37 requestKind: "command",
38 data,
39 },
40 turnId: TurnId.make(`turn-${id}`),
41 createdAt: "2026-07-27T00:00:00.000Z",
42 };
43}
44
45function makeThread(activities: ReadonlyArray<OrchestrationThreadActivity>): OrchestrationThread {
46 return {
47 id: ThreadId.make("thread-projection"),
48 projectId: ProjectId.make("project-projection"),
49 title: "Activity projection",
50 modelSelection: {
51 instanceId: ProviderInstanceId.make("codex"),
52 model: "gpt-5.4",
53 },
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 branch: null,
57 worktreePath: null,
58 latestTurn: null,
59 createdAt: "2026-07-27T00:00:00.000Z",
60 updatedAt: "2026-07-27T00:00:00.000Z",
61 archivedAt: null,
62 settledOverride: null,
63 settledAt: null,
64 deletedAt: null,
65 messages: [],
66 proposedPlans: [],
67 activities,
68 checkpoints: [],
69 session: null,
70 };
71}
72
73const fixtures = [
74 makeActivity("command", "command_execution", {
75 item: {
76 command: ["bash", "-lc", "pnpm test"],
77 input: { command: "fallback input", ignored: "input bulk" },
78 result: { command: "fallback result", aggregatedOutput: "x".repeat(10_000) },
79 commandActions: [{ type: "unknown", output: "y".repeat(5_000) }],
80 },
81 command: "fallback data",
82 kind: "execute",
83 toolCallId: "tool-command",
84 rawOutput: {
85 content: "\n```\nfirst useful line\nsecond line",
86 stdout: "unused stdout",
87 ignored: "raw bulk",
88 },
89 ignored: "top-level bulk",
90 }),
91 makeActivity("file-change", "file_change", {
92 item: {
93 changes: [
94 { oldPath: "src/old.ts", newPath: "src/new.ts", patch: "large patch".repeat(1_000) },
95 { filePath: "src/second.ts" },
96 ],
97 },
98 ignored: "top-level bulk",
99 }),
100 makeActivity("dynamic", "dynamic_tool_call", {
101 toolCallId: "tool-dynamic",
102 rawOutput: {
103 stdout: "dynamic summary\nlong output".repeat(1_000),
104 },
105 ignored: "top-level bulk",
106 }),
107 makeActivity("collab", "collab_agent_tool_call", {
108 kind: "delegate",
109 rawOutput: {
110 content: "``` \n```",
111 stdout: "must not be used when content is present",
112 },
113 ignored: "top-level bulk",
114 }),
115 makeActivity("mcp", "mcp_tool_call", {
116 item: {
117 server: "repository",
118 tool: "search",
119 arguments: { query: "activity projection" },
120 aggregatedOutput: "mcp payload remains available",
121 },
122 ignored: "MCP data is rendered verbatim",
123 }),
124 makeActivity("search", "web_search", {
125 rawOutput: {
126 totalFiles: 42,
127 truncated: true,
128 content: "ignored because totalFiles wins",
129 },
130 ignored: "top-level bulk",
131 }),
132 makeActivity("image", "image_view", {
133 ignored: "top-level bulk",
134 }),
135] satisfies ReadonlyArray<OrchestrationThreadActivity>;
136
137describe("projectActivityPayload", () => {
138 function comparableActivity(activity: ThreadFeedActivity) {
139 return {
140 ...activity,
141 fullDetail: activity.getFullDetail(),
142 copyText: activity.getCopyText(),
143 getFullDetail: undefined,
144 getCopyText: undefined,
145 };
146 }
147
148 function comparableThreadFeed(activities: ReadonlyArray<OrchestrationThreadActivity>) {
149 return buildThreadFeed(makeThread(activities)).map((entry) =>
150 entry.type === "activity-group"
151 ? {
152 ...entry,
153 activities: entry.activities.map(comparableActivity),
154 }
155 : entry,
156 );
157 }
158
159 it("drops unread bulk while retaining command, file, tool, and summary inputs", () => {
160 const projected = projectActivityPayload(fixtures[0]!);
161 expect(projected.payload).toEqual({
162 itemType: "command_execution",
163 title: "command_execution",
164 detail: "command_execution detail",
165 status: "completed",
166 requestKind: "command",
167 data: {
168 item: {
169 command: ["bash", "-lc", "pnpm test"],
170 input: { command: "fallback input" },
171 result: { command: "fallback result" },
172 },
173 command: "fallback data",
174 toolCallId: "tool-command",
175 kind: "execute",
176 rawOutput: { content: "first useful line" },
177 },
178 });
179
180 expect(projectActivityPayload(fixtures[1]!).payload).toMatchObject({
181 data: {
182 files: [{ path: "src/new.ts" }, { path: "src/old.ts" }, { path: "src/second.ts" }],
183 },
184 });
185 });
186
187 it("passes MCP tool data through unchanged", () => {
188 expect(projectActivityPayload(fixtures[4]!)).toBe(fixtures[4]);
189 });
190
191 it("keeps current web and mobile derived output identical for every tool item type", () => {
192 for (const activity of fixtures) {
193 const projected = projectActivityPayload(activity);
194 expect(deriveWorkLogEntries([projected])).toEqual(deriveWorkLogEntries([activity]));
195 expect(comparableThreadFeed([projected])).toEqual(comparableThreadFeed([activity]));
196 }
197 });
198
199 it("projects snapshot and event transports without mutating their sources", () => {
200 const activity = fixtures[0]!;
201 const thread = makeThread([activity]);
202 const snapshot = { snapshotSequence: 7, thread };
203 const projectedSnapshot = projectThreadDetailSnapshot(snapshot);
204
205 expect(projectedSnapshot.thread.activities[0]).not.toBe(activity);
206 expect(snapshot.thread.activities[0]).toBe(activity);
207
208 const event = {
209 sequence: 8,
210 eventId: EventId.make("event-activity"),
211 aggregateKind: "thread",
212 aggregateId: thread.id,
213 occurredAt: "2026-07-27T00:00:01.000Z",
214 commandId: null,
215 causationEventId: null,
216 correlationId: null,
217 metadata: {},
218 type: "thread.activity-appended",
219 payload: {
220 threadId: thread.id,
221 activity,
222 },
223 } satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
224
225 const projectedEvent = projectActivityEvent(event);
226 expect(projectedEvent).not.toBe(event);
227 expect(
228 projectedEvent.type === "thread.activity-appended"
229 ? projectedEvent.payload.activity
230 : undefined,
231 ).toEqual(projectActivityPayload(activity));
232 expect(event.payload.activity).toBe(activity);
233 });
234});
235
236describe("context-window snapshot dedup", () => {
237 function makeContextWindowActivity(
238 id: string,
239 usedTokens: number,
240 turn = `turn-${id}`,
241 ): OrchestrationThreadActivity {
242 return {
243 id: EventId.make(id),
244 tone: "info",
245 kind: "context-window.updated",
246 summary: "Context window updated",
247 payload: { usedTokens, maxTokens: 200_000 },
248 turnId: TurnId.make(turn),
249 createdAt: "2026-07-27T00:00:00.000Z",
250 };
251 }
252
253 it("keeps only the latest context-window activity per turn in snapshots", () => {
254 const stale1 = makeContextWindowActivity("ctx-1", 1_000, "turn-a");
255 const latestA = makeContextWindowActivity("ctx-2", 2_000, "turn-a");
256 const latestB = makeContextWindowActivity("ctx-3", 3_000, "turn-b");
257 const tool = fixtures[0]!;
258
259 const projected = projectThreadDetailSnapshot({
260 snapshotSequence: 7,
261 thread: makeThread([stale1, tool, latestA, latestB]),
262 });
263
264 expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
265 tool.id,
266 latestA.id,
267 latestB.id,
268 ]);
269 // The retained rows keep their payloads untouched — the tool-data
270 // projection only rewrites payloads with a `data` record.
271 expect(projected.thread.activities[2]?.payload).toEqual(latestB.payload);
272 });
273
274 it("still resolves a meter value after the client reverts the newest turn", () => {
275 // A live thread.reverted makes the client drop all activities from
276 // discarded turns; each surviving turn must keep a usable row.
277 const olderTurn = makeContextWindowActivity("ctx-old", 1_500, "turn-kept");
278 const revertedTurn = makeContextWindowActivity("ctx-new", 9_000, "turn-reverted");
279
280 const projected = projectThreadDetailSnapshot({
281 snapshotSequence: 7,
282 thread: makeThread([olderTurn, revertedTurn]),
283 });
284 const afterRevert = projected.thread.activities.filter(
285 (activity) => activity.turnId === TurnId.make("turn-kept"),
286 );
287
288 expect(deriveLatestContextWindowSnapshot(afterRevert)).toEqual(
289 deriveLatestContextWindowSnapshot([olderTurn]),
290 );
291 });
292
293 it("matches what the web client derives from the full history", () => {
294 const activities = [
295 makeContextWindowActivity("ctx-1", 1_000),
296 makeContextWindowActivity("ctx-2", 2_000),
297 ];
298 const projected = projectThreadDetailSnapshot({
299 snapshotSequence: 7,
300 thread: makeThread(activities),
301 });
302
303 expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
304 deriveLatestContextWindowSnapshot(activities),
305 );
306 });
307
308 it("does not let a malformed row shadow an earlier valid row in the same turn", () => {
309 const valid = makeContextWindowActivity("ctx-valid", 5_000, "turn-a");
310 const malformed: OrchestrationThreadActivity = {
311 ...makeContextWindowActivity("ctx-broken", 0, "turn-a"),
312 payload: { usedTokens: null },
313 };
314
315 const projected = projectThreadDetailSnapshot({
316 snapshotSequence: 7,
317 thread: makeThread([valid, malformed]),
318 });
319
320 // The malformed row passes through, the valid row survives, and the
321 // client's backward walk resolves the same value as with full history.
322 expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
323 valid.id,
324 malformed.id,
325 ]);
326 expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
327 deriveLatestContextWindowSnapshot([valid, malformed]),
328 );
329 });
330
331 it("leaves snapshots without context-window activities untouched", () => {
332 const projected = projectThreadDetailSnapshot({
333 snapshotSequence: 7,
334 thread: makeThread([fixtures[4]!]),
335 });
336 expect(projected.thread.activities).toEqual([fixtures[4]]);
337 });
338
339 it("does not filter live activity-appended events", () => {
340 const activity = makeContextWindowActivity("ctx-live", 4_000);
341 const event = {
342 sequence: 9,
343 eventId: EventId.make("event-ctx"),
344 aggregateKind: "thread",
345 aggregateId: ThreadId.make("thread-projection"),
346 occurredAt: "2026-07-27T00:00:02.000Z",
347 commandId: null,
348 causationEventId: null,
349 correlationId: null,
350 metadata: {},
351 type: "thread.activity-appended",
352 payload: {
353 threadId: ThreadId.make("thread-projection"),
354 activity,
355 },
356 } satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
357
358 const projected = projectActivityEvent(event);
359 expect(
360 projected.type === "thread.activity-appended" ? projected.payload.activity : undefined,
361 ).toEqual(activity);
362 });
363});