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

MessagesTimeline.logic.ts

640 lines20.3 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 hiddenEntryIds.add(entry.id);
357 }
358 }
359 if (hiddenEntryIds.size === 0) {
360 continue;
361 }
362​
363 const firstEntry = group.entries[0];
364 const lastEntry = group.entries.at(-1);
365 if (!firstEntry || !lastEntry) {
366 continue;
367 }
368​
369 const isLatestInterruptedTurn =
370 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
371 // A turn cut short by a steer leaves trailing work entries behind its
372 // terminal message — take whichever ended last.
373 const lastEntryEnd =
374 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
375 const elapsedMs =
376 input.latestTurn?.turnId === turnId &&
377 input.latestTurn.startedAt &&
378 input.latestTurn.completedAt
379 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
380 : computeElapsedMs(
381 group.startBoundary ?? firstEntry.createdAt,
382 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
383 lastEntryEnd,
384 );
385 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
386 const label = isLatestInterruptedTurn
387 ? duration
388 ? `You stopped after ${duration}`
389 : "You stopped this response"
390 : duration
391 ? `Worked for ${duration}`
392 : "Worked";
393​
394 foldsByAnchorEntryId.set(firstEntry.id, {
395 turnId,
396 anchorEntryId: firstEntry.id,
397 createdAt: firstEntry.createdAt,
398 hiddenEntryIds,
399 label,
400 });
401 }
402 return foldsByAnchorEntryId;
404​
405export function deriveMessagesTimelineRows(input: {
406 timelineEntries: ReadonlyArray<TimelineEntry>;
407 latestTurn?: TimelineLatestTurn | null;
408 runningTurnId?: TurnId | null;
409 expandedTurnIds?: ReadonlySet<TurnId>;
410 expandedWorkGroupIds?: ReadonlySet<string>;
411 isWorking: boolean;
412 activeTurnStartedAt: string | null;
413 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
414 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
415}): MessagesTimelineRow[] {
416 const nextRows: MessagesTimelineRow[] = [];
417 const durationStartByMessageId = computeMessageDurationStart(
418 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
419 );
420 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
421 const unsettledTurnId = deriveUnsettledTurnId(
422 input.latestTurn ?? null,
423 input.runningTurnId ?? null,
424 );
425 const foldsByAnchorEntryId = deriveTurnFolds({
426 timelineEntries: input.timelineEntries,
427 terminalAssistantMessageIds,
428 latestTurn: input.latestTurn ?? null,
429 unsettledTurnId,
430 });
431 const collapsedEntryIds = new Set<string>();
432 for (const fold of foldsByAnchorEntryId.values()) {
433 if (!input.expandedTurnIds?.has(fold.turnId)) {
434 for (const entryId of fold.hiddenEntryIds) {
435 collapsedEntryIds.add(entryId);
436 }
437 }
438 }
439​
440 for (let index = 0; index < input.timelineEntries.length; index += 1) {
441 const timelineEntry = input.timelineEntries[index];
442 if (!timelineEntry) {
443 continue;
444 }
445​
446 const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
447 if (turnFold) {
448 nextRows.push({
449 kind: "turn-fold",
450 id: `turn-fold:${turnFold.turnId}`,
451 createdAt: turnFold.createdAt,
452 turnId: turnFold.turnId,
453 label: turnFold.label,
454 expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
455 });
456 }
457​
458 if (collapsedEntryIds.has(timelineEntry.id)) {
459 continue;
460 }
461​
462 if (timelineEntry.kind === "work") {
463 const groupedEntries = [timelineEntry.entry];
464 let cursor = index + 1;
465 while (cursor < input.timelineEntries.length) {
466 const nextEntry = input.timelineEntries[cursor];
467 if (
468 !nextEntry ||
469 nextEntry.kind !== "work" ||
470 collapsedEntryIds.has(nextEntry.id) ||
471 foldsByAnchorEntryId.has(nextEntry.id)
472 ) {
473 break;
474 }
475 groupedEntries.push(nextEntry.entry);
476 cursor += 1;
477 }
478 const visibleGroupedEntries = groupedEntries.filter(
479 (entry) => !workEntryIndicatesToolNeutralStatus(entry),
480 );
481 if (visibleGroupedEntries.length > 0) {
482 if (visibleGroupedEntries.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
483 nextRows.push({
484 kind: "work",
485 id: timelineEntry.id,
486 createdAt: timelineEntry.createdAt,
487 groupedEntries: visibleGroupedEntries,
488 });
489 } else {
490 const groupId = `work-group:${timelineEntry.id}`;
491 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
492 const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
493 const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
494 const renderedEntries = expanded ? [...hiddenEntries, ...visibleEntries] : visibleEntries;
495​
496 for (const workEntry of renderedEntries) {
497 nextRows.push({
498 kind: "work",
499 id: workEntry.id,
500 createdAt: workEntry.createdAt,
501 groupedEntries: [workEntry],
502 });
503 }
504​
505 nextRows.push({
506 kind: "work-toggle",
507 id: `work-toggle:${timelineEntry.id}`,
508 createdAt: timelineEntry.createdAt,
509 groupId,
510 hiddenCount: hiddenEntries.length,
511 expanded,
512 onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),
513 });
514 }
515 }
516 index = cursor - 1;
517 continue;
518 }
519​
520 if (timelineEntry.kind === "proposed-plan") {
521 nextRows.push({
522 kind: "proposed-plan",
523 id: timelineEntry.id,
524 createdAt: timelineEntry.createdAt,
525 proposedPlan: timelineEntry.proposedPlan,
526 });
527 continue;
528 }
529​
530 const assistantTurnStillInProgress =
531 timelineEntry.message.role === "assistant" &&
532 unsettledTurnId !== null &&
533 timelineEntry.message.turnId === unsettledTurnId;
534​
535 const durationStart =
536 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
537​
538 // While the turn is still running, the latest assistant message is only
539 // provisionally terminal — withhold the metadata row until the turn
540 // settles so commentary doesn't flash timestamps mid-work.
541 const showAssistantMeta =
542 timelineEntry.message.role === "assistant" &&
543 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
544 !assistantTurnStillInProgress;
545​
546 nextRows.push({
547 kind: "message",
548 id: timelineEntry.id,
549 createdAt: timelineEntry.createdAt,
550 message: timelineEntry.message,
551 durationStart,
552 showAssistantMeta,
553 showAssistantCopyButton: showAssistantMeta,
554 assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
555 assistantTurnDiffSummary:
556 timelineEntry.message.role === "assistant"
557 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
558 : undefined,
559 revertTurnCount:
560 timelineEntry.message.role === "user"
561 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
562 : undefined,
563 });
564 }
565​
566 if (input.isWorking) {
567 nextRows.push({
568 kind: "working",
569 id: "working-indicator-row",
570 createdAt: input.activeTurnStartedAt,
571 });
572 }
573​
574 return nextRows;
576​
577export function computeStableMessagesTimelineRows(
578 rows: MessagesTimelineRow[],
579 previous: StableMessagesTimelineRowsState,
580): StableMessagesTimelineRowsState {
581 const next = new Map<string, MessagesTimelineRow>();
582 let anyChanged = rows.length !== previous.byId.size;
583​
584 const result = rows.map((row, index) => {
585 const prevRow = previous.byId.get(row.id);
586 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
587 next.set(row.id, nextRow);
588 if (!anyChanged && previous.result[index] !== nextRow) {
589 anyChanged = true;
590 }
591 return nextRow;
592 });
593​
594 return anyChanged ? { byId: next, result } : previous;
596​
597/** Shallow field comparison per row variant — avoids deep equality cost. */
598function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
599 if (a.kind !== b.kind || a.id !== b.id) return false;
600​
601 switch (a.kind) {
602 case "working":
603 return a.createdAt === (b as typeof a).createdAt;
604​
605 case "turn-fold": {
606 const bf = b as typeof a;
607 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
608 }
609​
610 case "proposed-plan":
611 return a.proposedPlan === (b as typeof a).proposedPlan;
612​
613 case "work":
614 return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
615​
616 case "work-toggle": {
617 const bw = b as typeof a;
618 return (
619 a.createdAt === bw.createdAt &&
620 a.groupId === bw.groupId &&
621 a.hiddenCount === bw.hiddenCount &&
622 a.expanded === bw.expanded &&
623 a.onlyToolEntries === bw.onlyToolEntries
624 );
625 }
626​
627 case "message": {
628 const bm = b as typeof a;
629 return (
630 a.message === bm.message &&
631 a.durationStart === bm.durationStart &&
632 a.showAssistantMeta === bm.showAssistantMeta &&
633 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
634 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
635 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
636 a.revertTurnCount === bm.revertTurnCount
637 );
638 }
639 }