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 pathChat.tsx
More file actions
232 lines (207 loc) · 7.53 KB
/
Copy pathChat.tsx
File metadata and controls
232 lines (207 loc) · 7.53 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
import type { Context } from '@opentelemetry/api'
import type React from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type {
AuthenticatedAuthStatus,
ChatMessage,
CodyIDE,
CurrentUserCodySubscription,
Guardrails,
Model,
PromptString,
} from '@sourcegraph/cody-shared'
import styles from './Chat.module.css'
import { Transcript } from './chat/Transcript'
import type { VSCodeWrapper } from './utils/VSCodeApi'
import { SpanManager } from './utils/spanManager'
import { getTraceparentFromSpanContext } from './utils/telemetry'
import { useUserAccountInfo } from './utils/useConfig'
interface ChatboxProps {
chatEnabled: boolean
messageInProgress: ChatMessage | null
transcript: ChatMessage[]
tokenUsage?:
| {
completionTokens?: number | null | undefined
promptTokens?: number | null | undefined
totalTokens?: number | null | undefined
}
| null
| undefined
models: Model[]
vscodeAPI: Pick<VSCodeWrapper, 'postMessage' | 'onMessage'>
guardrails: Guardrails
showIDESnippetActions?: boolean
}
export const Chat: React.FunctionComponent<React.PropsWithChildren<ChatboxProps>> = ({
messageInProgress,
transcript,
tokenUsage,
models,
vscodeAPI,
chatEnabled = true,
guardrails,
showIDESnippetActions = true,
}) => {
const transcriptRef = useRef(transcript)
transcriptRef.current = transcript
const userInfo = useUserAccountInfo()
const copyButtonOnSubmit = useCallback(
(text: string, eventType: 'Button' | 'Keydown' = 'Button') => {
const op = 'copy'
// remove the additional newline added by the text area at the end of the text
const code = eventType === 'Button' ? text.replace(/\n$/, '') : text
// Log the event type and text to telemetry in chat view
vscodeAPI.postMessage({
command: op,
eventType,
text: code,
})
},
[vscodeAPI]
)
const insertButtonOnSubmit = useMemo(() => {
if (showIDESnippetActions) {
return (text: string, newFile = false) => {
const op = newFile ? 'newFile' : 'insert'
// Log the event type and text to telemetry in chat view
vscodeAPI.postMessage({
command: op,
// remove the additional /n added by the text area at the end of the text
text: text.replace(/\n$/, ''),
})
}
}
return
}, [vscodeAPI, showIDESnippetActions])
const smartApply = useMemo(() => {
if (!showIDESnippetActions) {
return
}
function onSubmit({
id,
text,
instruction,
fileName,
isPrefetch,
}: {
id: string
text: string
isPrefetch?: boolean
instruction?: PromptString
fileName?: string
}) {
const command = isPrefetch ? 'smartApplyPrefetch' : 'smartApplySubmit'
const spanManager = new SpanManager('cody-webview')
const span = spanManager.startSpan(command, {
attributes: {
sampled: true,
'smartApply.id': id,
},
})
const traceparent = getTraceparentFromSpanContext(span.spanContext())
vscodeAPI.postMessage({
command,
id,
instruction: instruction?.toString(),
// remove the additional /n added by the text area at the end of the text
code: text.replace(/\n$/, ''),
fileName,
traceparent,
})
span.end()
}
return {
onSubmit,
onAccept: (id: string) => {
vscodeAPI.postMessage({
command: 'smartApplyAccept',
id,
})
},
onReject: (id: string) => {
vscodeAPI.postMessage({
command: 'smartApplyReject',
id,
})
},
}
}, [vscodeAPI, showIDESnippetActions])
const postMessage = useCallback<ApiPostMessage>(msg => vscodeAPI.postMessage(msg), [vscodeAPI])
useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
// Esc to abort the message in progress.
if (event.key === 'Escape' && messageInProgress) {
vscodeAPI.postMessage({ command: 'abort' })
}
// NOTE(sqs): I have a keybinding on my Linux machine Super+o to switch VS Code editor
// groups. This makes it so that that keybinding does not also input the letter 'o'.
// This is a workaround for (arguably) a VS Code issue.
if (event.metaKey && event.key === 'o') {
event.preventDefault()
event.stopPropagation()
}
}
window.addEventListener('keydown', handleKeyDown)
return () => {
window.removeEventListener('keydown', handleKeyDown)
}
}, [vscodeAPI, messageInProgress])
// Re-focus the input when the webview (re)gains focus if it was focused before the webview lost
// focus. This makes it so that the user can easily switch back to the Cody view and keep
// typing.
useEffect(() => {
const onFocus = (): void => {
// This works because for some reason Electron maintains the Selection but not the
// focus.
const sel = window.getSelection()
const focusNode = sel?.focusNode
const focusElement = focusNode instanceof Element ? focusNode : focusNode?.parentElement
const focusEditor = focusElement?.closest<HTMLElement>('[data-lexical-editor="true"]')
if (focusEditor) {
focusEditor.focus({ preventScroll: true })
}
}
window.addEventListener('focus', onFocus)
return () => {
window.removeEventListener('focus', onFocus)
}
}, [])
const [activeChatContext, setActiveChatContext] = useState<Context>()
return (
<>
{!chatEnabled && (
<div className={styles.chatDisabled}>
Cody chat is disabled by your Sourcegraph site administrator
</div>
)}
<Transcript
activeChatContext={activeChatContext}
setActiveChatContext={setActiveChatContext}
transcript={transcript}
tokenUsage={tokenUsage}
models={models}
messageInProgress={messageInProgress}
copyButtonOnSubmit={copyButtonOnSubmit}
insertButtonOnSubmit={insertButtonOnSubmit}
smartApply={smartApply}
userInfo={userInfo}
chatEnabled={chatEnabled}
postMessage={postMessage}
guardrails={guardrails}
/>
</>
)
}
export interface UserAccountInfo {
isDotComUser: boolean
isCodyProUser: boolean
user: Pick<
AuthenticatedAuthStatus,
'username' | 'displayName' | 'avatarURL' | 'endpoint' | 'primaryEmail' | 'organizations'
>
IDE: CodyIDE
siteHasCodyEnabled?: boolean | null
currentUserCodySubscription?: CurrentUserCodySubscription | null
}
export type ApiPostMessage = (message: any) => void