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

MessagesTimeline.logic.ts

678 lines21.3 KB

1import * as Equal from "effect/Equal";
2import {
3 formatDuration,
4 timelineEntryIsPersistentResourceCard,
5 type TimelineEntry,
6 type WorkLogEntry,
7} from "../../session-logic";
8import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
9import {
10 type MessageId,
11 type OrchestrationV2ProjectedTurnItem,
12 type RunAttemptId,
13 type RunId,
14} from "@t3tools/contracts";
15import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell";
16​
17export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
18export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
19export const TIMELINE_MINIMAP_MIN_ITEMS = 2;
20export const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)";
21export const TIMELINE_CONTENT_MAX_WIDTH = 768;
22export const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
23​
24export interface TimelineEndState {
25 readonly isAtEnd?: boolean;
26 readonly isNearEnd?: boolean;
28​
29export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
30 return state?.isNearEnd ?? state?.isAtEnd;
32​
33export function resolveTimelineMinimapHeightStyle(itemCount: number): string {
34 const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);
35 return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;
37​
38export function resolveTimelineMinimapTopPercent(index: number, itemCount: number): number {
39 if (itemCount <= 1) {
40 return 0;
41 }
42 return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100;
44​
45export function resolveTimelineMinimapIndexFromPointer(input: {
46 readonly itemCount: number;
47 readonly railTop: number;
48 readonly railHeight: number;
49 readonly pointerY: number;
50}): number | null {
51 if (input.itemCount <= 0 || input.railHeight <= 0) {
52 return null;
53 }
54 if (input.itemCount === 1) {
55 return 0;
56 }
57​
58 const progress = Math.max(0, Math.min(1, (input.pointerY - input.railTop) / input.railHeight));
59 return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
61​
62export function resolveTimelineMinimapHasPersistentGutter(viewportWidth: number): boolean {
63 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
64 return false;
65 }
66​
67 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
68 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
69 return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER;
71​
72function computeElapsedMs(startIso: string, endIso: string): number | null {
73 const start = Date.parse(startIso);
74 const end = Date.parse(endIso);
75 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
76 return Math.max(0, end - start);
78​
79function maxIsoTimestamp(a: string | null, b: string | null): string | null {
80 if (a === null) return b;
81 if (b === null) return a;
82 const aMs = Date.parse(a);
83 const bMs = Date.parse(b);
84 if (!Number.isFinite(aMs)) return b;
85 if (!Number.isFinite(bMs)) return a;
86 return bMs > aMs ? b : a;
88​
89export interface TimelineDurationMessage {
90 id: string;
91 role: "user" | "assistant" | "system";
92 createdAt: string;
93 updatedAt: string;
94 streaming: boolean;
96​
97export type TimelineLatestRun = Pick<
98 ThreadRunSummary,
99 "runId" | "status" | "startedAt" | "completedAt"
100>;
101​
102export type MessagesTimelineRow =
103 | {
104 kind: "work";
105 id: string;
106 createdAt: string;
107 groupedEntries: WorkLogEntry[];
108 }
109 | {
110 kind: "turn-fold";
111 id: string;
112 createdAt: string;
113 runId: RunId;
114 label: string;
115 expanded: boolean;
116 }
117 | {
118 kind: "attempt-fold";
119 id: string;
120 createdAt: string;
121 runId: RunId;
122 attemptId: RunAttemptId;
123 label: string;
124 expanded: boolean;
125 }
126 | {
127 kind: "message";
128 id: string;
129 createdAt: string;
130 message: ChatMessage;
131 projectedItem?: OrchestrationV2ProjectedTurnItem;
132 durationStart: string;
133 showAssistantMeta: boolean;
134 showAssistantCopyButton: boolean;
135 assistantCopyStreaming: boolean;
136 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
137 revertTurnCount?: number | undefined;
138 }
139 | {
140 kind: "event";
141 id: string;
142 createdAt: string;
143 projectedItem: OrchestrationV2ProjectedTurnItem;
144 }
145 | {
146 kind: "proposed-plan";
147 id: string;
148 createdAt: string;
149 proposedPlan: ProposedPlan;
150 }
151 | { kind: "working"; id: string; createdAt: string | null };
152​
153export interface StableMessagesTimelineRowsState {
154 byId: Map<string, MessagesTimelineRow>;
155 result: MessagesTimelineRow[];
157​
158export function computeMessageDurationStart(
159 messages: ReadonlyArray<TimelineDurationMessage>,
160): Map<string, string> {
161 const result = new Map<string, string>();
162 let lastBoundary: string | null = null;
163​
164 for (const message of messages) {
165 if (message.role === "user") {
166 lastBoundary = message.createdAt;
167 }
168 result.set(message.id, lastBoundary ?? message.createdAt);
169 if (message.role === "assistant" && !message.streaming) {
170 lastBoundary = message.updatedAt;
171 }
172 }
173​
174 return result;
176​
177export function normalizeCompactToolLabel(value: string): string {
178 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
180​
181export function resolveAssistantMessageCopyState({
182 text,
183 showCopyButton,
184 streaming,
185}: {
186 text: string | null;
187 showCopyButton: boolean;
188 streaming: boolean;
189}) {
190 const hasText = text !== null && text.trim().length > 0;
191 return {
192 text: hasText ? text : null,
193 visible: showCopyButton && hasText && !streaming,
194 };
196​
197function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
198 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
199 let nullTurnResponseIndex = 0;
200​
201 for (const timelineEntry of timelineEntries) {
202 if (timelineEntry.kind !== "message") {
203 continue;
204 }
205 const { message } = timelineEntry;
206 if (message.role === "user") {
207 nullTurnResponseIndex += 1;
208 continue;
209 }
210 if (message.role !== "assistant") {
211 continue;
212 }
213​
214 const responseKey = message.runId
215 ? `turn:${message.runId}`
216 : `unkeyed:${nullTurnResponseIndex}`;
217 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
218 }
219​
220 return new Set(lastAssistantMessageIdByResponseKey.values());
222​
223interface TurnFold {
224 runId: RunId;
225 anchorEntryId: string;
226 createdAt: string;
227 hiddenEntryIds: ReadonlySet<string>;
228 label: string;
230​
231interface SupersededAttemptFold {
232 readonly runId: RunId;
233 readonly attemptId: RunAttemptId;
234 readonly anchorEntryId: string;
235 readonly createdAt: string;
236 readonly hiddenEntryIds: ReadonlySet<string>;
238​
239/**
240 * Groups only provider output owned by an explicitly superseded V2 attempt.
241 * User messages remain visible because they are inputs to the logical run,
242 * including the steer message that started the replacement attempt.
243 */
244function deriveSupersededAttemptFolds(
245 timelineEntries: ReadonlyArray<TimelineEntry>,
246): ReadonlyMap<string, SupersededAttemptFold> {
247 const entriesByAttemptId = new Map<RunAttemptId, TimelineEntry[]>();
248 for (const entry of timelineEntries) {
249 if (
250 entry.attempt?.status !== "superseded" ||
251 (entry.kind === "message" && entry.message.role === "user") ||
252 timelineEntryIsPersistentResourceCard(entry)
253 ) {
254 continue;
255 }
256 const entries = entriesByAttemptId.get(entry.attempt.id) ?? [];
257 entries.push(entry);
258 entriesByAttemptId.set(entry.attempt.id, entries);
259 }
260​
261 const foldsByAnchorEntryId = new Map<string, SupersededAttemptFold>();
262 for (const entries of entriesByAttemptId.values()) {
263 const firstEntry = entries[0];
264 const attempt = firstEntry?.attempt;
265 if (firstEntry === undefined || attempt === undefined) continue;
266 foldsByAnchorEntryId.set(firstEntry.id, {
267 runId: attempt.runId,
268 attemptId: attempt.id,
269 anchorEntryId: firstEntry.id,
270 createdAt: firstEntry.createdAt,
271 hiddenEntryIds: new Set(entries.map((entry) => entry.id)),
272 });
273 }
274 return foldsByAnchorEntryId;
276​
277/**
278 * The latest turn counts as unsettled while it is still running (or has not
279 * recorded a completion). This is deliberately keyed on the turn's own
280 * lifecycle rather than transient working state: right after the user sends
281 * a message, the previous turn is still the "active" one until the server
282 * creates the new turn, and folding must not flicker through that window.
283 */
284function deriveUnsettledRunId(latestRun: TimelineLatestRun | null): RunId | null {
285 if (!latestRun) {
286 return null;
287 }
288 const isSettled =
289 latestRun.completedAt !== null &&
290 latestRun.status !== "running" &&
291 latestRun.status !== "starting" &&
292 latestRun.status !== "waiting";
293 return isSettled ? null : latestRun.runId;
295​
296function timelineEntryFoldRunId(entry: TimelineEntry): RunId | null {
297 if (entry.kind === "message" && entry.message.role === "assistant") {
298 return entry.message.runId ?? null;
299 }
300 if (entry.kind === "work") {
301 return entry.entry.runId ?? null;
302 }
303 if (entry.kind === "event" && timelineEntryIsPersistentResourceCard(entry)) {
304 return entry.projectedItem.item.runId;
305 }
306 return null;
308​
309/**
310 * Settled turns fold their commentary and tool activity behind a
311 * "Worked for ..." row anchored at the turn's first foldable entry; the
312 * terminal assistant message stays visible below the fold.
313 */
314function deriveTurnFolds(input: {
315 timelineEntries: ReadonlyArray<TimelineEntry>;
316 terminalAssistantMessageIds: ReadonlySet<string>;
317 latestRun: TimelineLatestRun | null;
318 unsettledRunId: RunId | null;
319}): ReadonlyMap<string, TurnFold> {
320 const interruptedRunIds = new Set<RunId>();
321 for (const entry of input.timelineEntries) {
322 if (
323 entry.kind === "event" &&
324 entry.projectedItem.item.runId !== null &&
325 (entry.projectedItem.item.type === "run_interrupt_request" ||
326 entry.projectedItem.item.type === "run_interrupt_result")
327 ) {
328 interruptedRunIds.add(entry.projectedItem.item.runId);
329 }
330 }
331​
332 interface TurnGroup {
333 entries: Array<TimelineEntry>;
334 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
335 hasStreamingMessage: boolean;
336 /**
337 * The user message that kicked the turn off. Entry timestamps alone
338 * undercount the duration (the first entry appears only once the
339 * provider starts producing output), and a turn cut short by a steer may
340 * hold a single instantaneous commentary message.
341 */
342 startBoundary: string | null;
343 }
344 const groupsByRunId = new Map<RunId, TurnGroup>();
345​
346 let pendingUserBoundary: string | null = null;
347 for (const entry of input.timelineEntries) {
348 if (entry.kind === "message" && entry.message.role === "user") {
349 pendingUserBoundary = entry.message.createdAt;
350 continue;
351 }
352 const runId = timelineEntryFoldRunId(entry);
353 if (!runId) {
354 continue;
355 }
356 let group = groupsByRunId.get(runId);
357 if (!group) {
358 group = {
359 entries: [],
360 terminalEntry: null,
361 hasStreamingMessage: false,
362 // Each user boundary starts at most one turn; a second turn after the
363 // same user message (e.g. a steer-superseded continuation) falls back
364 // to its own first entry.
365 startBoundary: pendingUserBoundary,
366 };
367 pendingUserBoundary = null;
368 groupsByRunId.set(runId, group);
369 }
370 group.entries.push(entry);
371 if (entry.kind === "message") {
372 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
373 group.terminalEntry = entry;
374 }
375 if (entry.message.streaming) {
376 group.hasStreamingMessage = true;
377 }
378 }
379 }
380​
381 const foldsByAnchorEntryId = new Map<string, TurnFold>();
382 for (const [runId, group] of groupsByRunId) {
383 if (runId === input.unsettledRunId || interruptedRunIds.has(runId)) {
384 continue;
385 }
386 if (group.hasStreamingMessage) {
387 continue;
388 }
389 const hiddenEntryIds = new Set<string>();
390 for (const entry of group.entries) {
391 if (entry.id !== group.terminalEntry?.id && !timelineEntryIsPersistentResourceCard(entry)) {
392 hiddenEntryIds.add(entry.id);
393 }
394 }
395 if (hiddenEntryIds.size === 0) {
396 continue;
397 }
398​
399 const firstEntry = group.entries[0];
400 const lastEntry = group.entries.at(-1);
401 if (!firstEntry || !lastEntry) {
402 continue;
403 }
404​
405 const isLatestInterruptedTurn =
406 input.latestRun?.runId === runId && input.latestRun.status === "interrupted";
407 // A turn cut short by a steer leaves trailing work entries behind its
408 // terminal message — take whichever ended last.
409 const lastEntryEnd =
410 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
411 const elapsedMs =
412 input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt
413 ? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt)
414 : computeElapsedMs(
415 group.startBoundary ?? firstEntry.createdAt,
416 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
417 lastEntryEnd,
418 );
419 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
420 const label = isLatestInterruptedTurn
421 ? duration
422 ? `You stopped after ${duration}`
423 : "You stopped this response"
424 : duration
425 ? `Worked for ${duration}`
426 : "Worked";
427​
428 foldsByAnchorEntryId.set(firstEntry.id, {
429 runId,
430 anchorEntryId: firstEntry.id,
431 createdAt: firstEntry.createdAt,
432 hiddenEntryIds,
433 label,
434 });
435 }
436 return foldsByAnchorEntryId;
438​
439export function deriveMessagesTimelineRows(input: {
440 timelineEntries: ReadonlyArray<TimelineEntry>;
441 latestRun?: TimelineLatestRun | null;
442 expandedRunIds?: ReadonlySet<RunId>;
443 expandedAttemptIds?: ReadonlySet<RunAttemptId>;
444 isWorking: boolean;
445 activeTurnStartedAt: string | null;
446 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
447 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
448}): MessagesTimelineRow[] {
449 const nextRows: MessagesTimelineRow[] = [];
450 const durationStartByMessageId = computeMessageDurationStart(
451 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
452 );
453 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
454 const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null);
455 const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds(input.timelineEntries);
456 const foldsByAnchorEntryId = deriveTurnFolds({
457 timelineEntries: input.timelineEntries,
458 terminalAssistantMessageIds,
459 latestRun: input.latestRun ?? null,
460 unsettledRunId,
461 });
462 const collapsedEntryIds = new Set<string>();
463 for (const fold of foldsByAnchorEntryId.values()) {
464 if (!input.expandedRunIds?.has(fold.runId)) {
465 for (const entryId of fold.hiddenEntryIds) {
466 collapsedEntryIds.add(entryId);
467 }
468 }
469 }
470 const collapsedSupersededEntryIds = new Set<string>();
471 for (const fold of supersededFoldsByAnchorEntryId.values()) {
472 if (!input.expandedAttemptIds?.has(fold.attemptId)) {
473 for (const entryId of fold.hiddenEntryIds) {
474 collapsedSupersededEntryIds.add(entryId);
475 }
476 }
477 }
478​
479 for (let index = 0; index < input.timelineEntries.length; index += 1) {
480 const timelineEntry = input.timelineEntries[index];
481 if (!timelineEntry) {
482 continue;
483 }
484​
485 const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
486 if (turnFold) {
487 nextRows.push({
488 kind: "turn-fold",
489 id: `turn-fold:${turnFold.runId}`,
490 createdAt: turnFold.createdAt,
491 runId: turnFold.runId,
492 label: turnFold.label,
493 expanded: input.expandedRunIds?.has(turnFold.runId) ?? false,
494 });
495 }
496​
497 if (collapsedEntryIds.has(timelineEntry.id)) {
498 continue;
499 }
500​
501 const supersededFold = supersededFoldsByAnchorEntryId.get(timelineEntry.id);
502 if (supersededFold) {
503 nextRows.push({
504 kind: "attempt-fold",
505 id: `attempt-fold:${supersededFold.attemptId}`,
506 createdAt: supersededFold.createdAt,
507 runId: supersededFold.runId,
508 attemptId: supersededFold.attemptId,
509 label: "Superseded attempt",
510 expanded: input.expandedAttemptIds?.has(supersededFold.attemptId) ?? false,
511 });
512 }
513​
514 if (collapsedSupersededEntryIds.has(timelineEntry.id)) {
515 continue;
516 }
517​
518 if (timelineEntry.kind === "work") {
519 const groupedEntries = [timelineEntry.entry];
520 let cursor = index + 1;
521 while (cursor < input.timelineEntries.length) {
522 const nextEntry = input.timelineEntries[cursor];
523 if (
524 !nextEntry ||
525 nextEntry.kind !== "work" ||
526 collapsedEntryIds.has(nextEntry.id) ||
527 collapsedSupersededEntryIds.has(nextEntry.id) ||
528 foldsByAnchorEntryId.has(nextEntry.id) ||
529 supersededFoldsByAnchorEntryId.has(nextEntry.id) ||
530 nextEntry.attempt?.id !== timelineEntry.attempt?.id
531 ) {
532 break;
533 }
534 groupedEntries.push(nextEntry.entry);
535 cursor += 1;
536 }
537 nextRows.push({
538 kind: "work",
539 id: timelineEntry.id,
540 createdAt: timelineEntry.createdAt,
541 groupedEntries,
542 });
543 index = cursor - 1;
544 continue;
545 }
546​
547 if (timelineEntry.kind === "proposed-plan") {
548 nextRows.push({
549 kind: "proposed-plan",
550 id: timelineEntry.id,
551 createdAt: timelineEntry.createdAt,
552 proposedPlan: timelineEntry.proposedPlan,
553 });
554 continue;
555 }
556​
557 if (timelineEntry.kind === "event") {
558 nextRows.push({
559 kind: "event",
560 id: timelineEntry.id,
561 createdAt: timelineEntry.createdAt,
562 projectedItem: timelineEntry.projectedItem,
563 });
564 continue;
565 }
566​
567 const assistantTurnStillInProgress =
568 timelineEntry.message.role === "assistant" &&
569 unsettledRunId !== null &&
570 timelineEntry.message.runId === unsettledRunId;
571​
572 const durationStart =
573 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
574​
575 // While the turn is still running, the latest assistant message is only
576 // provisionally terminal — withhold the metadata row until the turn
577 // settles so commentary doesn't flash timestamps mid-work.
578 const showAssistantMeta =
579 timelineEntry.message.role === "assistant" &&
580 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
581 !assistantTurnStillInProgress;
582​
583 nextRows.push({
584 kind: "message",
585 id: timelineEntry.id,
586 createdAt: timelineEntry.createdAt,
587 message: timelineEntry.message,
588 ...(timelineEntry.projectedItem === undefined
589 ? {}
590 : { projectedItem: timelineEntry.projectedItem }),
591 durationStart,
592 showAssistantMeta,
593 showAssistantCopyButton: showAssistantMeta,
594 assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
595 assistantTurnDiffSummary:
596 timelineEntry.message.role === "assistant"
597 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
598 : undefined,
599 revertTurnCount:
600 timelineEntry.message.role === "user"
601 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
602 : undefined,
603 });
604 }
605​
606 if (input.isWorking) {
607 nextRows.push({
608 kind: "working",
609 id: "working-indicator-row",
610 createdAt: input.activeTurnStartedAt,
611 });
612 }
613​
614 return nextRows;
616​
617export function computeStableMessagesTimelineRows(
618 rows: MessagesTimelineRow[],
619 previous: StableMessagesTimelineRowsState,
620): StableMessagesTimelineRowsState {
621 const next = new Map<string, MessagesTimelineRow>();
622 let anyChanged = rows.length !== previous.byId.size;
623​
624 const result = rows.map((row, index) => {
625 const prevRow = previous.byId.get(row.id);
626 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
627 next.set(row.id, nextRow);
628 if (!anyChanged && previous.result[index] !== nextRow) {
629 anyChanged = true;
630 }
631 return nextRow;
632 });
633​
634 return anyChanged ? { byId: next, result } : previous;
636​
637/** Shallow field comparison per row variant — avoids deep equality cost. */
638function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
639 if (a.kind !== b.kind || a.id !== b.id) return false;
640​
641 switch (a.kind) {
642 case "working":
643 return a.createdAt === (b as typeof a).createdAt;
644​
645 case "turn-fold": {
646 const bf = b as typeof a;
647 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
648 }
649​
650 case "attempt-fold": {
651 const bf = b as typeof a;
652 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
653 }
654​
655 case "proposed-plan":
656 return a.proposedPlan === (b as typeof a).proposedPlan;
657​
658 case "event":
659 return a.projectedItem === (b as typeof a).projectedItem;
660​
661 case "work":
662 return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
663​
664 case "message": {
665 const bm = b as typeof a;
666 return (
667 a.message === bm.message &&
668 a.projectedItem === bm.projectedItem &&
669 a.durationStart === bm.durationStart &&
670 a.showAssistantMeta === bm.showAssistantMeta &&
671 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
672 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
673 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
674 a.revertTurnCount === bm.revertTurnCount
675 );
676 }
677 }