Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ActivityPayloadProjection.test.ts

544 lines18.2 KB

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 };
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 };
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 bulk is dropped",
121 },
122 ignored: "top-level bulk",
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("slims MCP tool data to the fields the expanded row renders", () => {
188 expect(projectActivityPayload(fixtures[4]!).payload).toEqual({
189 itemType: "mcp_tool_call",
190 title: "mcp_tool_call",
191 detail: "mcp_tool_call detail",
192 status: "completed",
193 requestKind: "command",
194 data: {
195 item: {
196 server: "repository",
197 tool: "search",
198 arguments: { query: "activity projection" },
199 },
200 },
201 });
202 });
203​
204 it("keeps current web and mobile derived output identical for every tool item type", () => {
205 for (const activity of fixtures) {
206 const projected = projectActivityPayload(activity);
207 if (activity === fixtures[4]) {
208 // MCP is the one deliberate difference: the expanded row's toolData
209 // loses result bulk but keeps the rendered identity fields.
210 const [entry] = deriveWorkLogEntries([projected]);
211 expect(entry?.toolData).toEqual({
212 server: "repository",
213 tool: "search",
214 arguments: { query: "activity projection" },
215 });
216 continue;
217 }
218 expect(deriveWorkLogEntries([projected])).toEqual(deriveWorkLogEntries([activity]));
219 expect(comparableThreadFeed([projected])).toEqual(comparableThreadFeed([activity]));
220 }
221 });
222​
223 it("preserves failed stored tool outcomes for web and mobile clients", () => {
224 const activities = [
225 makeActivity("failed-command", "command_execution", {
226 item: {
227 command: "vp test run",
228 exitCode: 1,
229 status: "failed",
230 },
231 }),
232 makeActivity("failed-mcp", "mcp_tool_call", {
233 item: {
234 server: "simulator",
235 tool: "build",
236 arguments: {},
237 status: "failed",
238 },
239 }),
240 ];
241​
242 for (const activity of activities) {
243 const projected = projectActivityPayload(activity);
244 expect(projected.payload).toMatchObject({ status: "failed" });
245​
246 const [webEntry] = deriveWorkLogEntries([projected]);
247 expect(webEntry?.toolLifecycleStatus).toBe("failed");
248​
249 const [mobileGroup] = buildThreadFeed(makeThread([projected]));
250 expect(mobileGroup).toMatchObject({ type: "activity-group" });
251 if (mobileGroup?.type === "activity-group") {
252 expect(mobileGroup.activities[0]?.status).toBe("failure");
253 }
254 }
255 });
256​
257 it("projects snapshot and event transports without mutating their sources", () => {
258 const activity = fixtures[0]!;
259 const thread = makeThread([activity]);
260 const snapshot = { snapshotSequence: 7, thread };
261 const projectedSnapshot = projectThreadDetailSnapshot(snapshot);
262​
263 expect(projectedSnapshot.thread.activities[0]).not.toBe(activity);
264 expect(snapshot.thread.activities[0]).toBe(activity);
265​
266 const event = {
267 sequence: 8,
268 eventId: EventId.make("event-activity"),
269 aggregateKind: "thread",
270 aggregateId: thread.id,
271 occurredAt: "2026-07-27T00:00:01.000Z",
272 commandId: null,
273 causationEventId: null,
274 correlationId: null,
275 metadata: {},
276 type: "thread.activity-appended",
277 payload: {
278 threadId: thread.id,
279 activity,
280 },
281 } satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
282​
283 const projectedEvent = projectActivityEvent(event);
284 expect(projectedEvent).not.toBe(event);
285 expect(
286 projectedEvent.type === "thread.activity-appended"
287 ? projectedEvent.payload.activity
288 : undefined,
289 ).toEqual(projectActivityPayload(activity));
290 expect(event.payload.activity).toBe(activity);
291 });
292});
293​
294describe("superseded tool.updated snapshot dedup", () => {
295 function makeToolLifecycleActivity(
296 id: string,
297 kind: "tool.updated" | "tool.completed",
298 options: {
299 readonly turn?: string;
300 readonly title?: string;
301 readonly detail?: string;
302 readonly toolCallId?: string;
303 } = {},
304 ): OrchestrationThreadActivity {
305 const { turn = "turn-a", title = "File change", detail, toolCallId } = options;
306 return {
307 id: EventId.make(id),
308 tone: "tool",
309 kind,
310 summary: title,
311 payload: {
312 itemType: "file_change",
313 title,
314 ...(detail ? { detail } : {}),
315 data: {
316 ...(toolCallId ? { toolCallId } : {}),
317 toolName: "Edit",
318 input: { file_path: "src/app.ts" },
319 },
320 },
321 turnId: TurnId.make(turn),
322 createdAt: "2026-07-27T00:00:00.000Z",
323 };
324 }
325​
326 function projectedIds(activities: ReadonlyArray<OrchestrationThreadActivity>) {
327 return projectThreadDetailSnapshot({
328 snapshotSequence: 7,
329 thread: makeThread(activities),
330 }).thread.activities.map((activity) => activity.id);
331 }
332​
333 it("drops updates a later completion supersedes in the same turn", () => {
334 const update1 = makeToolLifecycleActivity("upd-1", "tool.updated");
335 const update2 = makeToolLifecycleActivity("upd-2", "tool.updated");
336 const completed = makeToolLifecycleActivity("done-1", "tool.completed");
337​
338 expect(projectedIds([update1, update2, completed])).toEqual([completed.id]);
339 });
340​
341 it("matches on toolCallId when the adapter emits one", () => {
342 const otherCall = makeToolLifecycleActivity("upd-other", "tool.updated", {
343 toolCallId: "call-b",
344 });
345 const update = makeToolLifecycleActivity("upd-a", "tool.updated", { toolCallId: "call-a" });
346 const completed = makeToolLifecycleActivity("done-a", "tool.completed", {
347 toolCallId: "call-a",
348 });
349​
350 // Same itemType/title, different call: only call-a's update is superseded.
351 expect(projectedIds([otherCall, update, completed])).toEqual([otherCall.id, completed.id]);
352 });
353​
354 it("keeps updates with no matching completion", () => {
355 const inFlight = makeToolLifecycleActivity("upd-live", "tool.updated", { title: "Running" });
356 const other = makeToolLifecycleActivity("upd-other", "tool.updated", { title: "Reading" });
357 const completed = makeToolLifecycleActivity("done-other", "tool.completed", {
358 title: "Reading",
359 });
360​
361 expect(projectedIds([inFlight, other, completed])).toEqual([inFlight.id, completed.id]);
362 });
363​
364 it("drops interleaved superseded updates even when a parallel call separates them", () => {
365 // Deliberate divergence from the clients' adjacency-based collapse: a
366 // superseded update separated from its completion by an interleaved
367 // parallel call renders as its own in-flight row on full history, and the
368 // snapshot omits it. Its final state still shows via the retained
369 // completion (1.5% of dropped rows on real data; see the projection's doc
370 // comment).
371 const updateA = makeToolLifecycleActivity("upd-a", "tool.updated", { toolCallId: "call-a" });
372 const updateB = makeToolLifecycleActivity("upd-b", "tool.updated", { toolCallId: "call-b" });
373 const completedA = makeToolLifecycleActivity("done-a", "tool.completed", {
374 toolCallId: "call-a",
375 });
376 const completedB = makeToolLifecycleActivity("done-b", "tool.completed", {
377 toolCallId: "call-b",
378 });
379​
380 expect(projectedIds([updateA, updateB, completedA, completedB])).toEqual([
381 completedA.id,
382 completedB.id,
383 ]);
384 });
385​
386 it("keeps an update whose completion lives in another turn", () => {
387 // A live thread.reverted can discard the completing turn while keeping
388 // the updating one, which would leave the call unrepresented.
389 const update = makeToolLifecycleActivity("upd-kept", "tool.updated", { turn: "turn-kept" });
390 const completed = makeToolLifecycleActivity("done-later", "tool.completed", {
391 turn: "turn-reverted",
392 });
393​
394 expect(projectedIds([update, completed])).toEqual([update.id, completed.id]);
395 });
396​
397 it("keeps an update that follows its completion", () => {
398 // A later update under the same identity is the next call, still in flight.
399 const completed = makeToolLifecycleActivity("done-first", "tool.completed");
400 const nextCall = makeToolLifecycleActivity("upd-next", "tool.updated");
401​
402 expect(projectedIds([completed, nextCall])).toEqual([completed.id, nextCall.id]);
403 });
404​
405 it("keeps identity-less rows the clients never collapse", () => {
406 const anonymous: OrchestrationThreadActivity = {
407 id: EventId.make("upd-anon"),
408 tone: "tool",
409 kind: "tool.updated",
410 summary: " ",
411 payload: { data: { toolName: "Edit" } },
412 turnId: TurnId.make("turn-a"),
413 createdAt: "2026-07-27T00:00:00.000Z",
414 };
415 const completed: OrchestrationThreadActivity = {
416 ...anonymous,
417 id: EventId.make("done-anon"),
418 kind: "tool.completed",
419 };
420​
421 expect(projectedIds([anonymous, completed])).toEqual([anonymous.id, completed.id]);
422 });
423​
424 it("leaves the collapsed work log identical to the full history", () => {
425 const activities = [
426 makeToolLifecycleActivity("upd-1", "tool.updated", { detail: "writing" }),
427 makeToolLifecycleActivity("upd-2", "tool.updated", { detail: "writing" }),
428 makeToolLifecycleActivity("done-1", "tool.completed", { detail: "writing" }),
429 ];
430 const projected = projectThreadDetailSnapshot({
431 snapshotSequence: 7,
432 thread: makeThread(activities),
433 });
434​
435 const before = deriveWorkLogEntries(activities);
436 const after = deriveWorkLogEntries(projected.thread.activities);
437 expect(after).toHaveLength(before.length);
438 expect(after.map((entry) => entry.label)).toEqual(before.map((entry) => entry.label));
439 });
440});
441​
442describe("context-window snapshot dedup", () => {
443 function makeContextWindowActivity(
444 id: string,
445 usedTokens: number,
446 turn = `turn-${id}`,
447 ): OrchestrationThreadActivity {
448 return {
449 id: EventId.make(id),
450 tone: "info",
451 kind: "context-window.updated",
452 summary: "Context window updated",
453 payload: { usedTokens, maxTokens: 200_000 },
454 turnId: TurnId.make(turn),
455 createdAt: "2026-07-27T00:00:00.000Z",
456 };
457 }
458​
459 it("keeps only the latest context-window activity per turn in snapshots", () => {
460 const stale1 = makeContextWindowActivity("ctx-1", 1_000, "turn-a");
461 const latestA = makeContextWindowActivity("ctx-2", 2_000, "turn-a");
462 const latestB = makeContextWindowActivity("ctx-3", 3_000, "turn-b");
463 const tool = fixtures[0]!;
464​
465 const projected = projectThreadDetailSnapshot({
466 snapshotSequence: 7,
467 thread: makeThread([stale1, tool, latestA, latestB]),
468 });
469​
470 expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
471 tool.id,
472 latestA.id,
473 latestB.id,
474 ]);
475 // The retained rows keep their payloads untouched — the tool-data
476 // projection only rewrites payloads with a `data` record.
477 expect(projected.thread.activities[2]?.payload).toEqual(latestB.payload);
478 });
479​
480 it("still resolves a meter value after the client reverts the newest turn", () => {
481 // A live thread.reverted makes the client drop all activities from
482 // discarded turns; each surviving turn must keep a usable row.
483 const olderTurn = makeContextWindowActivity("ctx-old", 1_500, "turn-kept");
484 const revertedTurn = makeContextWindowActivity("ctx-new", 9_000, "turn-reverted");
485​
486 const projected = projectThreadDetailSnapshot({
487 snapshotSequence: 7,
488 thread: makeThread([olderTurn, revertedTurn]),
489 });
490 const afterRevert = projected.thread.activities.filter(
491 (activity) => activity.turnId === TurnId.make("turn-kept"),
492 );
493​
494 expect(deriveLatestContextWindowSnapshot(afterRevert)).toEqual(
495 deriveLatestContextWindowSnapshot([olderTurn]),
496 );
497 });
498​
499 it("matches what the web client derives from the full history", () => {
500 const activities = [
501 makeContextWindowActivity("ctx-1", 1_000),
502 makeContextWindowActivity("ctx-2", 2_000),
503 ];
504 const projected = projectThreadDetailSnapshot({
505 snapshotSequence: 7,
506 thread: makeThread(activities),
507 });
508​
509 expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
510 deriveLatestContextWindowSnapshot(activities),
511 );
512 });
513​
514 it("does not let a malformed row shadow an earlier valid row in the same turn", () => {
515 const valid = makeContextWindowActivity("ctx-valid", 5_000, "turn-a");
516 const malformed: OrchestrationThreadActivity = {
517 ...makeContextWindowActivity("ctx-broken", 0, "turn-a"),
518 payload: { usedTokens: null },
519 };
520​
521 const projected = projectThreadDetailSnapshot({
522 snapshotSequence: 7,
523 thread: makeThread([valid, malformed]),
524 });
525​
526 // The malformed row passes through, the valid row survives, and the
527 // client's backward walk resolves the same value as with full history.
528 expect(projected.thread.activities.map((activity) => activity.id)).toEqual([
529 valid.id,
530 malformed.id,
531 ]);
532 expect(deriveLatestContextWindowSnapshot(projected.thread.activities)).toEqual(
533 deriveLatestContextWindowSnapshot([valid, malformed]),
534 );
535 });
536​
537 it("applies only payload slimming when there are no context-window activities", () => {
538 const projected = projectThreadDetailSnapshot({
539 snapshotSequence: 7,
540 thread: makeThread([fixtures[4]!]),
541 });
542 expect(projected.thread.activities).toEqual([projectActivityPayload(fixtures[4]!)]);
543 });
544});