fix: stream above input box

This commit is contained in:
Nate 2025-07-13 16:34:58 -07:00
parent 0c179681bc
commit c8945adb85
2 changed files with 93 additions and 40 deletions

View file

@ -50,11 +50,19 @@ export function getAllTools() {
type TODO = any; type TODO = any;
export interface StreamCallbacks {
onContent?: (content: string) => void;
onToolStart?: (toolName: string) => void;
onToolResult?: (result: string) => void;
onToolError?: (error: string) => void;
}
// Define a function to handle streaming responses with tool calling // Define a function to handle streaming responses with tool calling
export async function streamChatResponse( export async function streamChatResponse(
chatHistory: ChatCompletionMessageParam[], chatHistory: ChatCompletionMessageParam[],
assistant: ContinueClient["assistant"], assistant: ContinueClient["assistant"],
client: ContinueClient["client"] client: ContinueClient["client"],
callbacks?: StreamCallbacks
) { ) {
// Prepare tools for the API call // Prepare tools for the API call
const toolsForRequest = getAllTools(); const toolsForRequest = getAllTools();
@ -94,7 +102,11 @@ export async function streamChatResponse(
// Handle regular content // Handle regular content
if (chunk.choices[0].delta.content) { if (chunk.choices[0].delta.content) {
const content = chunk.choices[0].delta.content; const content = chunk.choices[0].delta.content;
process.stdout.write(chalk.white(content)); if (callbacks?.onContent) {
callbacks.onContent(content);
} else {
process.stdout.write(chalk.white(content));
}
aiResponse += content; aiResponse += content;
} }
@ -121,11 +133,15 @@ export async function streamChatResponse(
if (toolCall) { if (toolCall) {
if (!toolCall.name) { if (!toolCall.name) {
toolCall.name = toolCallDelta.function.name; toolCall.name = toolCallDelta.function.name;
process.stdout.write( if (callbacks?.onToolStart) {
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold( callbacks.onToolStart(toolCall.name);
toolCall.name } else {
)}${chalk.yellow("]")}` process.stdout.write(
); `\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
toolCall.name
)}${chalk.yellow("]")}`
);
}
} }
} }
} }
@ -152,7 +168,9 @@ export async function streamChatResponse(
} }
} }
console.info(); // Add a newline after the response if (!callbacks?.onContent) {
console.info(); // Add a newline after the response
}
// Add the assistant's response to chat history if there's content or tool calls // Add the assistant's response to chat history if there's content or tool calls
if (currentToolCalls.length > 0) { if (currentToolCalls.length > 0) {
@ -193,7 +211,11 @@ export async function streamChatResponse(
content: toolResult, content: toolResult,
}); });
console.info(chalk.green(toolResult) + "\n"); if (callbacks?.onToolResult) {
callbacks.onToolResult(toolResult);
} else {
console.info(chalk.green(toolResult) + "\n");
}
} catch (error) { } catch (error) {
const errorMessage = `Error executing tool ${toolCall.name}: ${ const errorMessage = `Error executing tool ${toolCall.name}: ${
error instanceof Error ? error.message : String(error) error instanceof Error ? error.message : String(error)
@ -203,11 +225,15 @@ export async function streamChatResponse(
tool_call_id: toolCall.id, tool_call_id: toolCall.id,
content: errorMessage, content: errorMessage,
}); });
console.info( if (callbacks?.onToolError) {
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red( callbacks.onToolError(errorMessage);
")" } else {
)}` console.info(
); `${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(
")"
)}`
);
}
} }
} }

View file

@ -3,7 +3,7 @@ import { Box, Text, useApp } from "ink";
import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { ChatCompletionMessageParam } from "openai/resources.mjs";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { handleSlashCommands } from "../slashCommands.js"; import { handleSlashCommands } from "../slashCommands.js";
import { streamChatResponse } from "../streamChatResponse.js"; import { streamChatResponse, StreamCallbacks } from "../streamChatResponse.js";
import UserInput from "./UserInput.js"; import UserInput from "./UserInput.js";
interface TUIChatProps { interface TUIChatProps {
@ -92,18 +92,45 @@ const TUIChat: React.FC<TUIChatProps> = ({
const newHistory = [...chatHistory, newUserMessage]; const newHistory = [...chatHistory, newUserMessage];
let assistantResponse = ""; let assistantResponse = "";
// Mock the streaming for now - you'll need to modify streamChatResponse // Create callbacks to handle streaming updates
// to accept a callback or use a different approach const streamCallbacks: StreamCallbacks = {
await streamChatResponse(newHistory, assistant, client); onContent: (content: string) => {
assistantResponse += content;
setMessages((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage.isStreaming) {
lastMessage.content += content;
}
return newMessages;
});
},
onToolStart: (toolName: string) => {
setMessages((prev) => [
...prev,
{ role: "system", content: `[Using tool: ${toolName}]` },
]);
},
onToolResult: (result: string) => {
setMessages((prev) => [
...prev,
{ role: "system", content: result },
]);
},
onToolError: (error: string) => {
setMessages((prev) => [
...prev,
{ role: "system", content: `[Tool error: ${error}]` },
]);
},
};
// For now, we'll just wait and then get the response await streamChatResponse(newHistory, assistant, client, streamCallbacks);
// In a real implementation, you'd need to modify streamChatResponse
// to provide a way to capture the streamed content
// Finalize the assistant message // Finalize the assistant message
const finalAssistantMessage: ChatCompletionMessageParam = { const finalAssistantMessage: ChatCompletionMessageParam = {
role: "assistant", role: "assistant",
content: assistantResponse || "Response received", // Fallback content: assistantResponse,
}; };
setChatHistory((prev) => [...prev, finalAssistantMessage]); setChatHistory((prev) => [...prev, finalAssistantMessage]);
@ -113,9 +140,6 @@ const TUIChat: React.FC<TUIChatProps> = ({
const lastMessage = newMessages[newMessages.length - 1]; const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage.isStreaming) { if (lastMessage.isStreaming) {
lastMessage.isStreaming = false; lastMessage.isStreaming = false;
if (!lastMessage.content) {
lastMessage.content = "Response received";
}
} }
return newMessages; return newMessages;
}); });
@ -159,24 +183,27 @@ const TUIChat: React.FC<TUIChatProps> = ({
return ( return (
<Box flexDirection="column" height="100%"> <Box flexDirection="column" height="100%">
{/* Chat history */} {/* Chat history - takes up all available space above input */}
<Box flexDirection="column" flexGrow={1} paddingX={1}> <Box flexDirection="column" flexGrow={1} paddingX={1} overflow="hidden">
{messages.map(renderMessage)} {messages.map(renderMessage)}
</Box> </Box>
{/* Input area */} {/* Fixed bottom section */}
<UserInput <Box flexDirection="column" flexShrink={0}>
onSubmit={handleUserMessage} {/* Status */}
isWaitingForResponse={isWaitingForResponse} {isWaitingForResponse && (
inputMode={inputMode} <Box paddingX={1}>
/> <Text color="yellow">Waiting for response...</Text>
</Box>
{/* Status */} )}
{isWaitingForResponse && (
<Box paddingX={1}> {/* Input area - always at bottom */}
<Text color="yellow">Waiting for response...</Text> <UserInput
</Box> onSubmit={handleUserMessage}
)} isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
/>
</Box>
</Box> </Box>
); );
}; };