Elffuss BraidHub

kikocis/continue public

add90d1f38c6 · 6.8 KiBRawPermalink
1import * as path from "node:path";
2
3import type { ChatHistoryItem } from "core/index.js";
4import { getLastNPathParts } from "core/util/uri.js";
5import { v4 as uuidv4 } from "uuid";
6
7import { logger } from "src/util/logger.js";
8
9import { DEFAULT_SESSION_TITLE } from "../../constants/session.js";
10import { loadSession, startNewSession } from "../../session.js";
11import { posthogService } from "../../telemetry/posthogService.js";
12import { telemetryService } from "../../telemetry/telemetryService.js";
13
14import { processImagePlaceholder } from "./useChat.imageProcessing.js";
15import { SlashCommandResult } from "./useChat.types.js";
16
17/**
18 * Initialize chat history
19 */
20export async function initChatHistory(
21 resume?: boolean,
22 _additionalRules?: string[],
23): Promise<ChatHistoryItem[]> {
24 if (resume) {
25 const savedSession = loadSession();
26 if (savedSession) {
27 return savedSession.history;
28 }
29 }
30
31 // Start with empty history - system message will be injected when needed
32 return [];
33}
34
35/**
36 * Handle /config command
37 */
38export function handleConfigCommand(onShowConfigSelector: () => void): void {
39 posthogService.capture("useSlashCommand", {
40 name: "config",
41 });
42 onShowConfigSelector();
43}
44
45interface ProcessSlashCommandResultOptions {
46 result: SlashCommandResult;
47 chatHistory: ChatHistoryItem[];
48 setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
49 exit: () => void;
50 onShowConfigSelector: () => void;
51 onShowModelSelector?: () => void;
52 onShowMCPSelector?: () => void;
53 onShowSessionSelector?: () => void;
54 onClear?: () => void;
55}
56
57/**
58 * Process slash command results
59 */
60export function processSlashCommandResult({
61 result,
62 chatHistory,
63 setChatHistory,
64 exit,
65 onShowConfigSelector,
66 onShowModelSelector,
67 onShowMCPSelector,
68 onShowSessionSelector,
69 onClear,
70}: ProcessSlashCommandResultOptions): string | null {
71 if (result.exit) {
72 exit();
73 return null;
74 }
75
76 if (result.openMcpSelector) {
77 onShowMCPSelector?.();
78 return null;
79 }
80
81 if (result.openConfigSelector) {
82 onShowConfigSelector();
83 return null;
84 }
85
86 if (result.openModelSelector && onShowModelSelector) {
87 onShowModelSelector();
88 return null;
89 }
90
91 if (result.openSessionSelector && onShowSessionSelector) {
92 onShowSessionSelector();
93 return null;
94 }
95
96 if (result.clear) {
97 const systemMessage = chatHistory.find(
98 (item) => item.message.role === "system",
99 );
100 const newHistory = systemMessage ? [systemMessage] : [];
101
102 // Start a new session with a new sessionId
103 startNewSession(newHistory);
104
105 setChatHistory(newHistory);
106
107 // Reset intro message state to show it again after clearing
108 if (onClear) {
109 onClear();
110 }
111
112 if (result.output) {
113 setChatHistory([
114 {
115 message: {
116 role: "system",
117 content: result.output,
118 },
119 contextItems: [],
120 },
121 ]);
122 }
123 return null;
124 }
125
126 if (result.output) {
127 setChatHistory((prev) => [
128 ...prev,
129 {
130 message: {
131 role: "system",
132 content: result.output || "",
133 },
134 contextItems: [],
135 },
136 ]);
137 }
138
139 return result.newInput || null;
140}
141
142/**
143 * Format message with attached files and images - returns a complete ChatHistoryItem
144 */
145export async function formatMessageWithFiles(
146 message: string,
147 attachedFiles: Array<{ path: string; content: string }>,
148 imageMap?: Map<string, Buffer>,
149): Promise<import("core/index.js").ChatHistoryItem> {
150 // Convert attached files to context items
151 const contextItems = attachedFiles.map((file) => ({
152 id: {
153 providerTitle: "file",
154 itemId: uuidv4(),
155 },
156 content: file.content,
157 name: path.basename(file.path),
158 description: getLastNPathParts(file.path, 2),
159 uri: {
160 type: "file" as const,
161 value: `file://${file.path}`,
162 },
163 }));
164
165 // Process message content for images
166 let messageContent: import("core/index.js").MessageContent = message;
167
168 if (imageMap && imageMap.size > 0) {
169 const messageParts: import("core/index.js").MessagePart[] = [];
170 let textContent = message;
171
172 // Replace image placeholders with image parts
173 for (const [placeholder, originalImageBuffer] of imageMap.entries()) {
174 const result = await processImagePlaceholder(
175 placeholder,
176 originalImageBuffer,
177 textContent,
178 messageParts,
179 );
180 textContent = result.textContent;
181 }
182
183 // Add any remaining text
184 if (textContent) {
185 messageParts.push({
186 type: "text",
187 text: textContent,
188 });
189 }
190
191 // Use message parts if we have images, otherwise keep as string
192 if (messageParts.length > 0) {
193 messageContent = messageParts;
194 }
195 }
196
197 return {
198 message: {
199 role: "user",
200 content: messageContent,
201 },
202 contextItems,
203 };
204}
205
206/**
207 * Track telemetry for user message
208 */
209export function trackUserMessage(message: string, model?: any): void {
210 telemetryService.startActiveTime();
211 telemetryService.logUserPrompt(message.length, message);
212 posthogService.capture("chat", {
213 model: model?.name,
214 provider: model?.provider,
215 });
216}
217
218interface HandleSpecialCommandsOptions {
219 message: string;
220 isRemoteMode: boolean;
221 remoteUrl?: string;
222 onShowConfigSelector: () => void;
223 exit: () => void;
224}
225
226/**
227 * Handle special TUI commands
228 */
229export async function handleSpecialCommands({
230 message,
231 isRemoteMode,
232 remoteUrl,
233 onShowConfigSelector,
234 exit,
235}: HandleSpecialCommandsOptions): Promise<boolean> {
236 const trimmedMessage = message.trim();
237
238 // Special handling for /config command in TUI
239 if (trimmedMessage === "/config") {
240 handleConfigCommand(onShowConfigSelector);
241 return true;
242 }
243
244 // Handle /exit command in remote mode
245 if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") {
246 const { handleRemoteExit } = await import("./useChat.remote.helpers.js");
247 await handleRemoteExit(remoteUrl, exit);
248 return true;
249 }
250
251 return false;
252}
253
254/**
255 * Generate a title for the session based on the first assistant response
256 */
257export async function generateSessionTitle(
258 assistantResponse: string,
259 llmApi: any,
260 model: any,
261 currentSessionTitle?: string,
262): Promise<string | undefined> {
263 // Only generate title for untitled sessions
264 if (currentSessionTitle && currentSessionTitle !== DEFAULT_SESSION_TITLE) {
265 return undefined;
266 }
267
268 if (!assistantResponse || !llmApi || !model) {
269 return undefined;
270 }
271
272 try {
273 const { ChatDescriber } = await import("core/util/chatDescriber.js");
274 const generatedTitle = await ChatDescriber.describeWithBaseLlmApi(
275 llmApi,
276 model,
277 assistantResponse,
278 );
279
280 logger.debug("Generated session title", {
281 original: currentSessionTitle,
282 generated: generatedTitle,
283 });
284
285 return generatedTitle;
286 } catch (error) {
287 logger.error("Failed to generate session title:", error);
288 return undefined;
289 }
290}