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

MessagesTimeline.logic.ts

241 lines7.2 KB

1import * as Equal from "effect/Equal";
2import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
3import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
4import { type MessageId } from "@t3tools/contracts";
5​
6export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
7​
8export interface TimelineDurationMessage {
9 id: string;
10 role: "user" | "assistant" | "system";
11 createdAt: string;
12 completedAt?: string | undefined;
14​
15export type MessagesTimelineRow =
16 | {
17 kind: "work";
18 id: string;
19 createdAt: string;
20 groupedEntries: WorkLogEntry[];
21 }
22 | {
23 kind: "message";
24 id: string;
25 createdAt: string;
26 message: ChatMessage;
27 durationStart: string;
28 showCompletionDivider: boolean;
29 showAssistantCopyButton: boolean;
30 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
31 revertTurnCount?: number | undefined;
32 }
33 | {
34 kind: "proposed-plan";
35 id: string;
36 createdAt: string;
37 proposedPlan: ProposedPlan;
38 }
39 | { kind: "working"; id: string; createdAt: string | null };
40​
41export interface StableMessagesTimelineRowsState {
42 byId: Map<string, MessagesTimelineRow>;
43 result: MessagesTimelineRow[];
45​
46export function computeMessageDurationStart(
47 messages: ReadonlyArray<TimelineDurationMessage>,
48): Map<string, string> {
49 const result = new Map<string, string>();
50 let lastBoundary: string | null = null;
51​
52 for (const message of messages) {
53 if (message.role === "user") {
54 lastBoundary = message.createdAt;
55 }
56 result.set(message.id, lastBoundary ?? message.createdAt);
57 if (message.role === "assistant" && message.completedAt) {
58 lastBoundary = message.completedAt;
59 }
60 }
61​
62 return result;
64​
65export function normalizeCompactToolLabel(value: string): string {
66 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
68​
69export function resolveAssistantMessageCopyState({
70 text,
71 showCopyButton,
72 streaming,
73}: {
74 text: string | null;
75 showCopyButton: boolean;
76 streaming: boolean;
77}) {
78 const hasText = text !== null && text.trim().length > 0;
79 return {
80 text: hasText ? text : null,
81 visible: showCopyButton && hasText && !streaming,
82 };
84​
85function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
86 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
87 let nullTurnResponseIndex = 0;
88​
89 for (const timelineEntry of timelineEntries) {
90 if (timelineEntry.kind !== "message") {
91 continue;
92 }
93 const { message } = timelineEntry;
94 if (message.role === "user") {
95 nullTurnResponseIndex += 1;
96 continue;
97 }
98 if (message.role !== "assistant") {
99 continue;
100 }
101​
102 const responseKey = message.turnId
103 ? `turn:${message.turnId}`
104 : `unkeyed:${nullTurnResponseIndex}`;
105 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
106 }
107​
108 return new Set(lastAssistantMessageIdByResponseKey.values());
110​
111export function deriveMessagesTimelineRows(input: {
112 timelineEntries: ReadonlyArray<TimelineEntry>;
113 completionDividerBeforeEntryId: string | null;
114 isWorking: boolean;
115 activeTurnStartedAt: string | null;
116 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
117 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
118}): MessagesTimelineRow[] {
119 const nextRows: MessagesTimelineRow[] = [];
120 const durationStartByMessageId = computeMessageDurationStart(
121 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
122 );
123 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
124​
125 for (let index = 0; index < input.timelineEntries.length; index += 1) {
126 const timelineEntry = input.timelineEntries[index];
127 if (!timelineEntry) {
128 continue;
129 }
130​
131 if (timelineEntry.kind === "work") {
132 const groupedEntries = [timelineEntry.entry];
133 let cursor = index + 1;
134 while (cursor < input.timelineEntries.length) {
135 const nextEntry = input.timelineEntries[cursor];
136 if (!nextEntry || nextEntry.kind !== "work") break;
137 groupedEntries.push(nextEntry.entry);
138 cursor += 1;
139 }
140 nextRows.push({
141 kind: "work",
142 id: timelineEntry.id,
143 createdAt: timelineEntry.createdAt,
144 groupedEntries,
145 });
146 index = cursor - 1;
147 continue;
148 }
149​
150 if (timelineEntry.kind === "proposed-plan") {
151 nextRows.push({
152 kind: "proposed-plan",
153 id: timelineEntry.id,
154 createdAt: timelineEntry.createdAt,
155 proposedPlan: timelineEntry.proposedPlan,
156 });
157 continue;
158 }
159​
160 nextRows.push({
161 kind: "message",
162 id: timelineEntry.id,
163 createdAt: timelineEntry.createdAt,
164 message: timelineEntry.message,
165 durationStart:
166 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
167 showCompletionDivider:
168 timelineEntry.message.role === "assistant" &&
169 input.completionDividerBeforeEntryId === timelineEntry.id,
170 showAssistantCopyButton:
171 timelineEntry.message.role === "assistant" &&
172 terminalAssistantMessageIds.has(timelineEntry.message.id),
173 assistantTurnDiffSummary:
174 timelineEntry.message.role === "assistant"
175 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
176 : undefined,
177 revertTurnCount:
178 timelineEntry.message.role === "user"
179 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
180 : undefined,
181 });
182 }
183​
184 if (input.isWorking) {
185 nextRows.push({
186 kind: "working",
187 id: "working-indicator-row",
188 createdAt: input.activeTurnStartedAt,
189 });
190 }
191​
192 return nextRows;
194​
195export function computeStableMessagesTimelineRows(
196 rows: MessagesTimelineRow[],
197 previous: StableMessagesTimelineRowsState,
198): StableMessagesTimelineRowsState {
199 const next = new Map<string, MessagesTimelineRow>();
200 let anyChanged = rows.length !== previous.byId.size;
201​
202 const result = rows.map((row, index) => {
203 const prevRow = previous.byId.get(row.id);
204 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
205 next.set(row.id, nextRow);
206 if (!anyChanged && previous.result[index] !== nextRow) {
207 anyChanged = true;
208 }
209 return nextRow;
210 });
211​
212 return anyChanged ? { byId: next, result } : previous;
214​
215/** Shallow field comparison per row variant — avoids deep equality cost. */
216function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
217 if (a.kind !== b.kind || a.id !== b.id) return false;
218​
219 switch (a.kind) {
220 case "working":
221 return a.createdAt === (b as typeof a).createdAt;
222​
223 case "proposed-plan":
224 return a.proposedPlan === (b as typeof a).proposedPlan;
225​
226 case "work":
227 return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
228​
229 case "message": {
230 const bm = b as typeof a;
231 return (
232 a.message === bm.message &&
233 a.durationStart === bm.durationStart &&
234 a.showCompletionDivider === bm.showCompletionDivider &&
235 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
236 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
237 a.revertTurnCount === bm.revertTurnCount
238 );
239 }
240 }