summaryrefslogtreecommitdiff
path: root/extension/react-app/src/tabs/chat/index.tsx
blob: a93ad4f968394b1039852d594d135f991ccf634d (plain)
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
258
259
260
261
262
263
264
265
266
267
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { selectChatMessages } from "../../redux/selectors/chatSelectors";
import MessageDiv from "./MessageDiv";
import styled from "styled-components";
import { addMessage, setIsStreaming } from "../../redux/slices/chatSlice";
import { AnyAction, Dispatch } from "@reduxjs/toolkit";
import { closeStream, streamUpdate } from "../../redux/slices/chatSlice";
import { ChatMessage, RootStore } from "../../redux/store";
import { postVscMessage, vscRequest } from "../../vscode";
import { defaultBorderRadius, Loader } from "../../components";
import { selectHighlightedCode } from "../../redux/selectors/miscSelectors";
import { readRangeInVirtualFileSystem } from "../../util";
import { selectDebugContext } from "../../redux/selectors/debugContextSelectors";

let textEntryBarHeight = "30px";

const ChatContainer = styled.div`
  display: grid;
  grid-template-rows: 1fr auto;
  height: 100%;
`;

const BottomDiv = styled.div`
  display: grid;
  grid-template-rows: auto auto;
`;

const BottomButton = styled.button(
  (props: { active: boolean }) => `
  font-size: 10px;
  border: none;
  color: white;
  margin-right: 4px;
  cursor: pointer;
  background-color: ${props.active ? "black" : "gray"};
  border-radius: ${defaultBorderRadius};
  padding: 8px;
`
);

const TextEntryBar = styled.input`
  height: ${textEntryBarHeight};
  border-bottom-left-radius: ${defaultBorderRadius};
  border-bottom-right-radius: ${defaultBorderRadius};
  padding: 8px;
  border: 1px solid white;
  background-color: black;
  color: white;
  outline: none;
`;

function ChatTab() {
  const dispatch = useDispatch();
  const chatMessages = useSelector(selectChatMessages);
  const isStreaming = useSelector((state: RootStore) => state.chat.isStreaming);
  const baseUrl = useSelector((state: RootStore) => state.config.apiUrl);
  const debugContext = useSelector(selectDebugContext);

  const [includeHighlightedCode, setIncludeHighlightedCode] = useState(true);
  const [writeToEditor, setWriteToEditor] = useState(false);
  const [waitingForResponse, setWaitingForResponse] = useState(false);

  const highlightedCode = useSelector(selectHighlightedCode);

  const streamToStateThunk = useCallback(
    (dispatch: Dispatch<AnyAction>, getResponse: () => Promise<Response>) => {
      let streamToCursor = writeToEditor;
      getResponse().then((resp) => {
        setWaitingForResponse(false);
        if (resp.body) {
          resp.body.pipeTo(
            new WritableStream({
              write(chunk) {
                let update = new TextDecoder("utf-8").decode(chunk);
                dispatch(streamUpdate(update));
                if (streamToCursor) {
                  postVscMessage("streamUpdate", { update });
                }
              },
              close() {
                dispatch(closeStream());
                if (streamToCursor) {
                  postVscMessage("closeStream", null);
                }
              },
            })
          );
        }
      });
    },
    [writeToEditor]
  );

  const compileHiddenChatMessages = useCallback(async () => {
    let messages: ChatMessage[] = [];
    if (
      includeHighlightedCode &&
      highlightedCode?.filepath !== undefined &&
      highlightedCode?.range !== undefined &&
      debugContext.filesystem[highlightedCode.filepath] !== undefined
    ) {
      let fileContents = readRangeInVirtualFileSystem(
        highlightedCode,
        debugContext.filesystem
      );
      if (fileContents) {
        messages.push({
          role: "user",
          content: fileContents,
        });
      }
    } else {
      // Similarity search over workspace
      let data = await vscRequest("queryEmbeddings", {
        query: chatMessages[chatMessages.length - 1].content,
      });
      let codeContextMessages = data.results.map(
        (result: { id: string; document: string }) => {
          let msg: ChatMessage = {
            role: "user",
            content: `File: ${result.id} \n ${result.document}`,
          };
          return msg;
        }
      );
      codeContextMessages.push({
        role: "user",
        content:
          "Use the above code to help you answer the question below. Answer in asterisk bullet points, and give the full path whenever you reference files.",
      });
      messages.push(...codeContextMessages);
    }

    let systemMsgContent = writeToEditor
      ? "Respond only with the exact code requested, no additional text."
      : "Use the above code to help you answer the question below. Respond in markdown if using bullets or other special formatting, being sure to specify language for code blocks.";

    messages.push({
      role: "system",
      content: systemMsgContent,
    });
    return messages;
  }, [highlightedCode, chatMessages, includeHighlightedCode, writeToEditor]);

  useEffect(() => {
    if (
      chatMessages.length > 0 &&
      chatMessages[chatMessages.length - 1].role === "user" &&
      !isStreaming
    ) {
      dispatch(setIsStreaming(true));
      streamToStateThunk(dispatch, async () => {
        if (chatMessages.length === 0) {
          return new Promise((resolve, _) => resolve(new Response()));
        }
        let hiddenChatMessages = await compileHiddenChatMessages();
        let augmentedMessages = [
          ...chatMessages.slice(0, -1),
          ...hiddenChatMessages,
          chatMessages[chatMessages.length - 1],
        ];
        console.log(augmentedMessages);
        // The autogenerated client can't handle streams, so have to go raw
        return fetch(`${baseUrl}/chat/complete`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            messages: augmentedMessages,
          }),
        });
      });
    }
  }, [chatMessages, dispatch, isStreaming, highlightedCode]);

  const chatMessagesDiv = useRef<HTMLDivElement>(null);
  useEffect(() => {
    // Scroll to bottom
    let interval = setInterval(() => {
      if (chatMessagesDiv.current && !waitingForResponse) {
        chatMessagesDiv.current.scrollTop += Math.max(
          4,
          0.05 * chatMessagesDiv.current.scrollHeight -
            chatMessagesDiv.current.clientHeight -
            chatMessagesDiv.current.scrollTop
        );
        if (
          chatMessagesDiv.current.scrollTop >=
          chatMessagesDiv.current.scrollHeight -
            chatMessagesDiv.current.clientHeight
        ) {
          clearInterval(interval);
        }
      }
    }, 10);
  }, [chatMessages, chatMessagesDiv, waitingForResponse]);

  return (
    <ChatContainer>
      <div className="mx-5 overflow-y-scroll" ref={chatMessagesDiv}>
        <h1>Chat</h1>
        <hr></hr>
        <div>
          {chatMessages.length > 0 ? (
            chatMessages.map((message, idx) => {
              return <MessageDiv key={idx} {...message}></MessageDiv>;
            })
          ) : (
            <p className="text-gray-400 m-auto text-center">
              You can ask questions about your codebase or ask for code written
              directly in the editor.
            </p>
          )}
          {waitingForResponse && <Loader></Loader>}
        </div>
      </div>

      <BottomDiv>
        <div className="h-12 bg-secondary-">
          <div className="flex items-center p-2">
            {/* <p className="mr-auto text-xs">
              Highlighted code is automatically included in your chat message.
            </p> */}
            <BottomButton
              className="ml-auto"
              active={writeToEditor}
              onClick={() => {
                setWriteToEditor(!writeToEditor);
              }}
            >
              {writeToEditor ? "Writing to editor" : "Write to editor"}
            </BottomButton>

            <BottomButton
              active={includeHighlightedCode}
              onClick={() => {
                setIncludeHighlightedCode(!includeHighlightedCode);
              }}
            >
              {includeHighlightedCode
                ? "Including highlighted code"
                : "Automatically finding relevant code"}
            </BottomButton>
          </div>
        </div>
        <TextEntryBar
          type="text"
          placeholder="Enter your message here"
          onKeyDown={(e) => {
            if (e.key === "Enter" && e.currentTarget.value !== "") {
              console.log("Sending message", e.currentTarget.value);
              dispatch(
                addMessage({ content: e.currentTarget.value, role: "user" })
              );
              (e.target as any).value = "";
              setWaitingForResponse(true);
            }
          }}
        ></TextEntryBar>
      </BottomDiv>
    </ChatContainer>
  );
}

export default ChatTab;