From b5e1733952abc5f92b16df584e6c00483be4d7a4 Mon Sep 17 00:00:00 2001 From: Gregory Gauthier Date: Wed, 4 Mar 2026 11:15:54 +0000 Subject: [PATCH] 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. --- cmd/chat.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/cmd/chat.go b/cmd/chat.go index 3e84acb..728405b 100644 --- a/cmd/chat.go +++ b/cmd/chat.go @@ -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", "") }