@@ -137,18 +137,61 @@ function toolMessageNode(msg: ToolResultMessage): Node {
137137 );
138138 }
139139
140-function conversationMessageNode(msg: Message): Node {
141- const body =
140+const messageBodyCache = new WeakMap<Message, { key: number; node: Node }>();
141+
142+function messageCacheKey(msg: Message): number {
143+ if (msg.role === "assistant") {
144+ let key = 0;
145+ for (const block of msg.content) {
146+ if (block.type === "thinking") key += block.thinking.length;
147+ if (block.type === "text") key += block.text.length;
148+ if (block.type === "toolCall" && block.arguments)
149+ key += JSON.stringify(block.arguments).length;
150+ }
151+ if (msg.stopReason) key += msg.stopReason.length;
152+ if (msg.errorMessage) key += msg.errorMessage.length;
153+ return key;
154+ }
155+ if (msg.role === "user") {
156+ if (typeof msg.content === "string") return msg.content.length;
157+ return msg.content.reduce(
158+ (sum, b) => (b.type === "text" ? sum + b.text.length : sum),
159+ 0,
160+ );
161+ }
162+ if (msg.role === "toolResult") {
163+ return msg.content.reduce(
164+ (sum, b) => (b.type === "text" ? sum + b.text.length : sum),
165+ 0,
166+ );
167+ }
168+ return 0;
169+}
170+
171+function cachedMessageBody(msg: Message): Node {
172+ const key = messageCacheKey(msg);
173+ const cached = messageBodyCache.get(msg);
174+ if (cached && cached.key === key) {
175+ return cached.node;
176+ }
177+ const node =
142178 msg.role === "assistant"
143179 ? agentMessageNode(msg)
144180 : msg.role === "user"
145181 ? userMessageNode(msg)
146182 : msg.role === "toolResult"
147183 ? toolMessageNode(msg)
148- : Text("Unknown message?", { wrap: "word", fgColor: theme.bwhite });
184+ : Text("Unknown message?", {
185+ wrap: "word",
186+ fgColor: theme.bwhite,
187+ });
188+ messageBodyCache.set(msg, { key, node });
189+ return node;
190+}
149191
192+function conversationMessageNode(msg: Message): Node {
150193 return VStack({ gap: 1 }, [
151- body,
194+ cachedMessageBody(msg),
152195 HStack({ gap: 1, justifyContent: "end" }, [
153196 Text(`${relativeTime(msg.timestamp)} ago.`, {
154197 fgColor: theme.bblack,