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

MessagesTimeline.logic.ts

663 lines21.4 KB

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