Open History to see the last commit
1import type {
2 MessagePart,
3 ToolApprovalInterrupt,
4 ToolCallPart,
5 ToolResultPart,
6 UIMessage,
7} from '../types'
8import type {
9 ChatUIInterrupt,
10 ChatUIPartKey,
11 ChatUISelectInput,
12 ChatUISelectedMessage,
13 ChatUISelectedPart,
14 ChatUISelection,
15} from './types'
16
17const PART_KEY_BY_TYPE: Record<string, ChatUIPartKey> = {
18 text: 'text',
19 image: 'image',
20 audio: 'audio',
21 video: 'video',
22 document: 'document',
23 thinking: 'thinking',
24 activity: 'activity',
25 'tool-call': 'toolCall',
26 'tool-result': 'toolResult',
27 'structured-output': 'structuredOutput',
28 'ui-resource': 'uiResource',
29 subagent: 'subagent',
30}
31
32export function partTypeToKey(type: string): ChatUIPartKey | string {
33 const mapped = PART_KEY_BY_TYPE[type]
34 if (mapped) return mapped
35 return type.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())
36}
37
38export function collectInlineToolNames(
39 toolInterrupts?: Record<string, unknown>,
40 mappedToolNames?: ReadonlyArray<string>,
41): Array<string> {
42 const listPlaced = new Set(Object.keys(toolInterrupts ?? {}))
43 return (mappedToolNames ?? []).filter((name) => !listPlaced.has(name))
44}
45
46export function resolveInterruptComponent(
47 interrupt: ChatUIInterrupt,
48 interruptsMap:
49 | {
50 tools?: Record<string, unknown>
51 generic?: Record<string, unknown>
52 }
53 | undefined,
54): unknown {
55 if (!interruptsMap) return undefined
56 if (interrupt.kind === 'tool-approval') {
57 return interruptsMap.tools?.[interrupt.toolName]
58 }
59 const generic = interruptsMap.generic
60 if (!generic) return undefined
61 const definitionId =
62 'definitionId' in interrupt && typeof interrupt.definitionId === 'string'
63 ? interrupt.definitionId
64 : undefined
65 if (definitionId && definitionId !== 'fallback') {
66 const registered = generic[definitionId]
67 if (registered) return registered
68 }
69 return generic.fallback
70}
71
72function isToolCallPart(part: MessagePart): part is ToolCallPart {
73 return part.type === 'tool-call'
74}
75
76function isToolResultPart(part: MessagePart): part is ToolResultPart {
77 return part.type === 'tool-result'
78}
79
80function isToolApproval(
81 interrupt: ChatUIInterrupt,
82): interrupt is ToolApprovalInterrupt {
83 return interrupt.kind === 'tool-approval'
84}
85
86export function selectChatUI(input: ChatUISelectInput): ChatUISelection {
87 const messages = input.messages
88 const interrupts = input.interrupts ?? []
89 const inlineToolNames = new Set(input.inlineToolNames ?? [])
90
91 const resultsByCallId = new Map<string, ToolResultPart>()
92 const callIds = new Set<string>()
93 for (const message of messages) {
94 for (const part of message.parts) {
95 if (isToolCallPart(part)) callIds.add(part.id)
96 if (isToolResultPart(part)) resultsByCallId.set(part.toolCallId, part)
97 }
98 }
99
100 const approvalByCallId = new Map<string, ToolApprovalInterrupt>()
101 for (const interrupt of interrupts) {
102 if (isToolApproval(interrupt)) {
103 approvalByCallId.set(interrupt.toolCallId, interrupt)
104 }
105 }
106
107 const selectedMessages: Array<ChatUISelectedMessage> = messages.map(
108 (message) => ({
109 message,
110 parts: message.parts.map((part) =>
111 toSelectedPart(part, resultsByCallId, approvalByCallId, callIds),
112 ),
113 }),
114 )
115
116 return {
117 messages: selectedMessages,
118 interrupts: interrupts.filter((interrupt) => {
119 if (!isToolApproval(interrupt)) return true
120 if (!inlineToolNames.has(interrupt.toolName)) return true
121 return !callIds.has(interrupt.toolCallId)
122 }),
123 }
124}
125
126function toSelectedPart(
127 part: MessagePart,
128 resultsByCallId: Map<string, ToolResultPart>,
129 approvalByCallId: Map<string, ToolApprovalInterrupt>,
130 callIds: Set<string>,
131): ChatUISelectedPart {
132 if (isToolCallPart(part)) {
133 const result = resultsByCallId.get(part.id)
134 const interrupt = approvalByCallId.get(part.id)
135 return {
136 key: 'toolCall',
137 part,
138 ...(result ? { result } : {}),
139 ...(interrupt ? { interrupt } : {}),
140 input: part.input,
141 output: part.output,
142 }
143 }
144
145 if (isToolResultPart(part)) {
146 return {
147 key: 'toolResult',
148 part,
149 matched: callIds.has(part.toolCallId),
150 }
151 }
152
153 return {
154 key: partTypeToKey(part.type) as Exclude<
155 ChatUIPartKey,
156 'toolCall' | 'toolResult'
157 >,
158 part,
159 }
160}
161
162export function automaticPartsForMessage(
163 selected: ChatUISelectedMessage,
164): Array<ChatUISelectedPart> {
165 return selected.parts.filter(
166 (part) => !(part.key === 'toolResult' && part.matched),
167 )
168}
169
170export function selectMessageUI(
171 message: UIMessage,
172 input: Omit<ChatUISelectInput, 'messages'>,
173): ChatUISelectedMessage {
174 return (
175 selectChatUI({ ...input, messages: [message] }).messages[0] ?? {
176 message,
177 parts: [],
178 }
179 )
180}