This repository was archived by the owner on Aug 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 488
Expand file tree
/
Copy pathAssistantMessageCell.tsx
More file actions
257 lines (242 loc) · 10.5 KB
/
Copy pathAssistantMessageCell.tsx
File metadata and controls
257 lines (242 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import {
type ChatMessage,
ContextItemSource,
type Guardrails,
type Model,
ModelTag,
type PromptString,
contextItemsFromPromptEditorValue,
filterContextItemsFromPromptEditorValue,
isAbortErrorOrSocketHangUp,
reformatBotMessageForChat,
serializedPromptEditorStateFromChatMessage,
} from '@sourcegraph/cody-shared'
import { DeepCodyAgentID } from '@sourcegraph/cody-shared/src/models/client'
import type { PromptEditorRefAPI } from '@sourcegraph/prompt-editor'
import isEqual from 'lodash/isEqual'
import { type FunctionComponent, type RefObject, memo, useMemo } from 'react'
import type { ApiPostMessage, UserAccountInfo } from '../../../../Chat'
import {
ChatMessageContent,
type CodeBlockActionsProps,
} from '../../../ChatMessageContent/ChatMessageContent'
import styles from '../../../ChatMessageContent/ChatMessageContent.module.css'
import { CopyButton } from '../../../ChatMessageContent/EditButtons'
import { ErrorItem, RequestErrorItem } from '../../../ErrorItem'
import { TokenUsageDisplay } from '../../../TokenUsageDisplay'
import { type Interaction, editHumanMessage } from '../../../Transcript'
import { BaseMessageCell } from '../BaseMessageCell'
import { SubMessageCell } from './SubMessageCell'
/**
* A component that displays a chat message from the assistant.
*/
export const AssistantMessageCell: FunctionComponent<{
message: ChatMessage
models: Model[]
/** Information about the human message that led to this assistant response. */
humanMessage: PriorHumanMessageInfo | null
userInfo: UserAccountInfo
isLoading: boolean
copyButtonOnSubmit?: CodeBlockActionsProps['copyButtonOnSubmit']
insertButtonOnSubmit?: CodeBlockActionsProps['insertButtonOnSubmit']
onRegenerate: CodeBlockActionsProps['onRegenerate']
regeneratingCodeBlocks: CodeBlockActionsProps['regeneratingCodeBlocks']
smartApply?: CodeBlockActionsProps['smartApply']
isThoughtProcessOpened?: boolean
setThoughtProcessOpened?: (open: boolean) => void
postMessage?: ApiPostMessage
guardrails: Guardrails
}> = memo(
({
message,
models,
humanMessage,
userInfo,
isLoading,
copyButtonOnSubmit,
insertButtonOnSubmit,
onRegenerate,
regeneratingCodeBlocks,
postMessage,
guardrails,
smartApply,
isThoughtProcessOpened,
setThoughtProcessOpened,
}) => {
const displayMarkdown = useMemo(
() => (message.text ? reformatBotMessageForChat(message.text).toString() : ''),
[message.text]
)
const chatModel = useChatModelByID(message.model, models)
const isAborted = isAbortErrorOrSocketHangUp(message.error)
const hasLongerResponseTime = chatModel?.tags?.includes(ModelTag.StreamDisabled)
const messageIntent = humanMessage?.intent ?? message.intent ?? 'chat'
const isSearchIntent = messageIntent === 'search'
return (
<BaseMessageCell
content={
<>
{message.error && !isAborted ? (
typeof message.error === 'string' ? (
<RequestErrorItem error={message.error} humanMessage={humanMessage} />
) : (
<ErrorItem
error={message.error}
userInfo={userInfo}
postMessage={postMessage}
humanMessage={humanMessage}
/>
)
) : null}
{!isSearchIntent && displayMarkdown ? (
<ChatMessageContent
displayMarkdown={displayMarkdown}
isMessageLoading={isLoading}
copyButtonOnSubmit={copyButtonOnSubmit}
insertButtonOnSubmit={insertButtonOnSubmit}
onRegenerate={onRegenerate}
regeneratingCodeBlocks={regeneratingCodeBlocks}
guardrails={guardrails}
humanMessage={humanMessage}
smartApply={smartApply}
isThoughtProcessOpened={!!isThoughtProcessOpened}
setThoughtProcessOpened={setThoughtProcessOpened}
/>
) : (
isLoading &&
message.subMessages === undefined && (
<div>
{hasLongerResponseTime && (
<p className="tw-m-4 tw-mt-0 tw-text-muted-foreground">
This model may take longer to respond because it takes time
to "think". Recommended for complex reasoning & coding tasks.
</p>
)}
</div>
)
)}
{message.subMessages?.length &&
message.subMessages.length > 0 &&
message.subMessages.map((piece, i) => (
<SubMessageCell
// biome-ignore lint/suspicious/noArrayIndexKey:
key={`piece-${i}`}
piece={piece}
guardrails={guardrails}
onRegenerate={onRegenerate}
regeneratingCodeBlocks={regeneratingCodeBlocks}
/>
))}
</>
}
footer={
<div className="tw-py-3 tw-flex tw-flex-col tw-gap-2">
{isAborted && (
<div className="tw-py-3 tw-flex tw-flex-col tw-gap-2">
<div className="tw-text-sm tw-text-muted-foreground tw-mt-4">
Output stream stopped
</div>
</div>
)}
{!isLoading &&
(!message.error || isAborted) &&
// Do not display copy button for non-chat mode.
// NOTE: Empty intent is defaulted to chat.
messageIntent === 'chat' && (
<div
className={`tw-flex tw-items-center tw-justify-end tw-gap-4 ${styles.buttonsContainer}`}
>
<CopyButton
text={message.text?.toString() || ''}
onCopy={copyButtonOnSubmit}
showLabel={false}
className={'tw-transition tw-opacity-65 hover:tw-opacity-100'}
title="Copy Message"
/>
</div>
)}
<TokenUsageDisplay tokenUsage={message.tokenUsage} />
</div>
}
speaker="assistant"
/>
)
},
isEqual
)
export interface HumanMessageInitialContextInfo {
repositories: boolean
files: boolean
}
export interface PriorHumanMessageInfo {
text?: PromptString
intent?: ChatMessage['intent']
hasInitialContext: HumanMessageInitialContextInfo
rerunWithDifferentContext: (withInitialContext: HumanMessageInitialContextInfo) => void
hasExplicitMentions: boolean
appendAtMention: () => void
}
export function makeHumanMessageInfo(
{ humanMessage, assistantMessage }: Interaction,
humanEditorRef: RefObject<PromptEditorRefAPI>
): PriorHumanMessageInfo {
if (assistantMessage === null) {
throw new Error('unreachable')
}
const editorValue = serializedPromptEditorStateFromChatMessage(humanMessage)
const contextItems = contextItemsFromPromptEditorValue(editorValue)
return {
text: humanMessage.text,
intent: humanMessage.intent,
hasInitialContext: {
repositories: Boolean(
contextItems.some(item => item.type === 'repository' || item.type === 'tree')
),
files: Boolean(
contextItems.some(
item => item.type === 'file' && item.source === ContextItemSource.Initial
)
),
},
rerunWithDifferentContext: withInitialContext => {
const editorValue = humanEditorRef.current?.getSerializedValue()
if (editorValue) {
const newEditorValue = filterContextItemsFromPromptEditorValue(
editorValue,
item =>
((item.type === 'repository' || item.type === 'tree') &&
withInitialContext.repositories) ||
(item.type === 'file' && withInitialContext.files)
)
editHumanMessage({
messageIndexInTranscript: assistantMessage.index - 1,
editorValue: newEditorValue,
})
}
},
hasExplicitMentions: Boolean(contextItems.some(item => item.source === ContextItemSource.User)),
appendAtMention: () => {
if (humanEditorRef.current?.getSerializedValue().text.trim().endsWith('@')) {
humanEditorRef.current?.setFocus(true, { moveCursorToEnd: true })
} else {
humanEditorRef.current?.appendText('@')
}
},
}
}
function useChatModelByID(
model: string | undefined,
chatModels: Model[]
): Pick<Model, 'id' | 'title' | 'provider' | 'tags'> | undefined {
return (
chatModels?.find(m => m.id === model) ??
(model
? {
id: model,
title: model?.includes(DeepCodyAgentID) ? 'Deep Cody (Experimental)' : model,
provider: 'unknown',
tags: [],
}
: undefined)
)
}