feat(chat): add chat history persistence

Implement loading and saving of chat history to a JSON file. The history file path is configurable via Viper or defaults to ~/.config/grokkit/chat_history.json. Add functions to load, save, and get the history file path. Remove outdated comment in model selection.
This commit is contained in:
Gregory Gauthier 2026-03-04 11:15:54 +00:00
parent af7270967c
commit b5e1733952

View File

@ -2,16 +2,63 @@ package cmd
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gmgauthier.com/grokkit/config"
"gmgauthier.com/grokkit/internal/grok"
)
type ChatHistory struct {
Messages []map[string]string `json:"messages"`
}
func loadChatHistory() []map[string]string {
histFile := getChatHistoryFile()
data, err := os.ReadFile(histFile)
if err != nil {
return nil
}
var hist ChatHistory
if err := json.Unmarshal(data, &hist); err != nil {
return nil
}
return hist.Messages
}
func saveChatHistory(messages []map[string]string) error {
histFile := getChatHistoryFile()
hist := ChatHistory{Messages: messages}
data, err := json.MarshalIndent(hist, "", " ")
if err != nil {
return err
}
return os.WriteFile(histFile, data, 0644)
}
func getChatHistoryFile() string {
configFile := viper.GetString("chat.history_file")
if configFile != "" {
return configFile
}
home, _ := os.UserHomeDir()
if home == "" {
home = "."
}
histDir := filepath.Join(home, ".config", "grokkit")
_ = os.MkdirAll(histDir, 0755)
return filepath.Join(histDir, "chat_history.json")
}
var chatCmd = &cobra.Command{
Use: "chat",
Short: "Interactive chat with Grok (use --agent for tool-enabled mode)",
@ -37,7 +84,7 @@ func runChat(cmd *cobra.Command, args []string) {
if modelFlag != "" {
model = modelFlag
} else if agentMode {
model = config.GetModel("chat-agent", "") // we'll add this default next
model = config.GetModel("chat-agent", "")
} else {
model = config.GetModel("chat", "")
}