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

ActivityPayloadProjection.test.ts

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