Elffuss BraidHub

kikocis/continue public

e31fcddb0dec · 6.8 KiBRawPermalink
1import {
2 LLMInteractionCancel,
3 LLMInteractionChunk,
4 LLMInteractionError,
5 LLMInteractionItem,
6 LLMInteractionMessage,
7 LLMInteractionStartChat,
8 LLMInteractionStartComplete,
9 LLMInteractionStartFim,
10 LLMInteractionSuccess,
11} from "core";
12import { useEffect, useReducer } from "react";
13
14declare const vscode: any;
15
16export type LLMResult = LLMInteractionMessage | LLMInteractionChunk;
17
18const MAX_GROUP_LENGTH = 32;
19
20interface ToConsoleViewInit {
21 type: "init";
22 uuid: string;
23 items: LLMInteractionItem[];
24}
25
26interface ToConsoleViewItem {
27 type: "item";
28 uuid: string;
29 item: LLMInteractionItem;
30}
31
32interface ToConsoleViewRemove {
33 type: "remove";
34 uuid: string;
35 interactionId: string;
36}
37
38interface ToConsoleViewClear {
39 type: "clear";
40 uuid: string;
41}
42
43type ToConsoleView =
44 | ToConsoleViewInit
45 | ToConsoleViewItem
46 | ToConsoleViewRemove
47 | ToConsoleViewClear;
48
49/**
50 * Represents a linear list of LLMInteractionItem, transformed into
51 * a form that is more convenient for rendering.
52 */
53export interface LLMInteraction {
54 start?:
55 | LLMInteractionStartChat
56 | LLMInteractionStartComplete
57 | LLMInteractionStartFim;
58
59 // We use an array-of-arrays for efficiency when rendering a streamed result
60 // with lots and lots of separate tokens; instead of having a linear list
61 // of 1024 Result components, we have 32 ResultGroup components each rendering
62 // 32 Results.
63 //
64 // Inline content can split between one group and the next - we'll let the
65 // browser engine sort that out.
66 results: LLMResult[][];
67
68 end?: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel;
69}
70
71export interface LLMLog {
72 loading: boolean;
73 interactions: Map<string, LLMInteraction>;
74 order: string[];
75}
76
77/**
78 * Appends a new result item (chunk or message) to an interaction,
79 * existing iteractions must already have been copied with
80 * copyInteractionForMutation().
81 */
82function appendItemToInteractionResult(
83 interaction: LLMInteraction,
84 item: LLMInteractionMessage | LLMInteractionChunk,
85) {
86 let lastGroup = interaction.results[interaction.results.length - 1];
87
88 if (lastGroup == undefined || lastGroup.length == MAX_GROUP_LENGTH) {
89 interaction.results.push([item]);
90 } else {
91 lastGroup.push(item);
92 }
93}
94
95/**
96 * Makes a copy of an interaction that can be mutated without changing
97 * any objects/arrays that are part of the old state. We always make
98 * a copy of the last (open) result group, so that we can simply append
99 * to it; this is very slightly inefficient for the case where we're
100 * handling a single end item with no results, but makes things simpler.
101 */
102function copyInteractionForMutation(oldInteraction: LLMInteraction) {
103 const oldResults = oldInteraction.results;
104 let oldLastGroup = oldInteraction.results[oldInteraction.results.length - 1];
105 let newResults;
106
107 if (oldLastGroup == undefined || oldLastGroup.length == MAX_GROUP_LENGTH) {
108 newResults = [...oldInteraction.results];
109 } else {
110 newResults = oldInteraction.results.slice(0, -1);
111 newResults.push([...oldLastGroup]);
112 }
113
114 return { ...oldInteraction, results: newResults };
115}
116
117function appendItemsToLLMLog(
118 oldLog: LLMLog,
119 items: LLMInteractionItem[],
120): LLMLog {
121 const oldInteractions = oldLog.interactions;
122 const newInteractions: Map<string, LLMInteraction> = new Map();
123 let order = oldLog.order;
124 let interactionsAdded = false;
125
126 // Add the new items to the log, making mutable copies of old
127 // LLMInteraction as necessary
128 for (const item of items) {
129 let interaction = newInteractions.get(item.interactionId);
130 if (interaction === undefined) {
131 const oldInteraction = oldInteractions.get(item.interactionId);
132 if (oldInteraction) {
133 interaction = copyInteractionForMutation(oldInteraction);
134 } else {
135 interaction = {
136 results: [],
137 };
138
139 if (interactionsAdded) {
140 order.push(item.interactionId);
141 } else {
142 order = [...order, item.interactionId];
143 interactionsAdded = true;
144 }
145 }
146 newInteractions.set(item.interactionId, interaction);
147 }
148
149 switch (item.kind) {
150 case "startChat":
151 case "startComplete":
152 case "startFim":
153 interaction.start = item;
154 break;
155 case "chunk":
156 case "message":
157 appendItemToInteractionResult(interaction, item);
158 break;
159 case "success":
160 case "error":
161 case "cancel":
162 interaction.end = item;
163 break;
164 }
165 }
166
167 // Copy over unchanged interactions
168 for (const interactionId of oldInteractions.keys()) {
169 if (!newInteractions.has(interactionId)) {
170 newInteractions.set(interactionId, oldInteractions.get(interactionId)!);
171 }
172 }
173
174 return {
175 loading: false,
176 interactions: newInteractions,
177 order,
178 };
179}
180
181function removeInteractionFromLLMLog(
182 llmLog: LLMLog,
183 interactionId: string,
184): LLMLog {
185 const newInteractions = new Map(llmLog.interactions);
186 newInteractions.delete(interactionId);
187 const newOrder = llmLog.order.filter((id) => id !== interactionId);
188
189 return {
190 loading: false,
191 interactions: newInteractions,
192 order: newOrder,
193 };
194}
195
196/**
197 * Hook to accumulate log data structures based on messages passed
198 * from the core. Note that each call site will create an independent
199 * data structure, so this should be only used once at a toplevel
200 * component.
201 * @returns currently log datastructure.
202 */
203export default function useLLMLog() {
204 const [llmLog, dispatchLlmLog] = useReducer(
205 (llmLog: LLMLog, message: ToConsoleView) => {
206 switch (message.type) {
207 case "init":
208 return appendItemsToLLMLog(llmLog, message.items);
209 case "item":
210 return appendItemsToLLMLog(llmLog, [message.item]);
211 case "remove":
212 return removeInteractionFromLLMLog(llmLog, message.interactionId);
213 case "clear":
214 return {
215 loading: false,
216 interactions: new Map(),
217 order: [],
218 };
219 }
220 },
221 {
222 loading: true,
223 interactions: new Map(),
224 order: [],
225 },
226 );
227
228 useEffect(function () {
229 // The uuid here marks the "generation" when the webview is
230 // reloaded, so we don't get confused if there are inflight
231 // messages from the previous generation. In particular, this
232 // avoids problems when React.StrictMode runs this effect
233 // twice - we don't want to process two "init" messages.
234 const uuid = crypto.randomUUID();
235 const onMessage = (event: MessageEvent<ToConsoleView>) => {
236 if (event.data.uuid !== uuid) {
237 return;
238 }
239
240 dispatchLlmLog(event.data);
241 };
242 window.addEventListener("message", onMessage);
243 vscode.postMessage({ type: "start", uuid });
244
245 return () => {
246 vscode.postMessage({ type: "stop", uuid });
247 window.removeEventListener("message", onMessage);
248 };
249 }, []);
250
251 return llmLog;
252}