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

ActivityPayloadProjection.test.ts

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