Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

log command, finish context update

Dane Schneider9c811082d214
diff --git a/cli/api/methods.go b/cli/api/methods.go
index e4282756..9302ec15 100644
--- a/cli/api/methods.go
+++ b/cli/api/methods.go
@@ -620,3 +620,27 @@ func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, error) {
return convos, nil
}
+
+func (a *Api) ListLogs(planId string) (*shared.LogResponse, error) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/logs", apiHost, planId)
+
+ resp, err := http.Get(serverUrl)
+ if err != nil {
+ return nil, fmt.Errorf("error sending request: %v", err)
+ }
+
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("error listing logs: %d - %s", resp.StatusCode, string(errorBody))
+ }
+
+ var logs shared.LogResponse
+ err = json.NewDecoder(resp.Body).Decode(&logs)
+ if err != nil {
+ return nil, fmt.Errorf("error decoding response: %v", err)
+ }
+
+ return &logs, nil
+}
diff --git a/cli/api/types.go b/cli/api/types.go
index 07958739..fbabaef8 100644
--- a/cli/api/types.go
+++ b/cli/api/types.go
@@ -47,4 +47,5 @@ type ApiClient interface {
ListContext(planId string) ([]*shared.Context, error)
ListConvo(planId string) ([]*shared.ConvoMessage, error)
+ ListLogs(planId string) (*shared.LogResponse, error)
}
diff --git a/cli/cmd/log.go b/cli/cmd/log.go
index 9bebbff3..126944c3 100644
--- a/cli/cmd/log.go
+++ b/cli/cmd/log.go
@@ -2,7 +2,7 @@ package cmd
import (
"fmt"
- "os"
+ "plandex/api"
"plandex/lib"
"plandex/term"
@@ -14,8 +14,8 @@ var logCmd = &cobra.Command{
Use: "log [scope]",
Aliases: []string{"history"},
Short: "Show plan history",
- Long: `Show plan history. Pass an optional scope to log only a specific part of the plan. Valid scopes are "convo", "context", and "draft". If no scope is passed, the history of the entire plan will be output.`,
- Args: cobra.MaximumNArgs(1),
+ Long: `Show plan history.`,
+ Args: cobra.NoArgs,
Run: runLog,
}
@@ -25,26 +25,18 @@ func init() {
}
func runLog(cmd *cobra.Command, args []string) {
- var dir string
- switch {
- case len(args) == 0:
- dir = lib.CurrentPlanDir
- case args[0] == "convo":
- dir = lib.ConversationSubdir
- case args[0] == "context":
- dir = lib.ContextSubdir
- case args[0] == "draft":
- dir = lib.ResultsSubdir
- default:
- fmt.Fprint(os.Stderr, "Invalid scope. Valid scopes are 'convo', 'context', and 'draft'")
- os.Exit(1)
+ lib.MustResolveProject()
+
+ if lib.CurrentPlanId == "" {
+ fmt.Println("No current plan")
+ return
}
- history, err := lib.GetGitCommitHistory(dir)
+ res, err := api.Client.ListLogs(lib.CurrentPlanId)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
- term.PageOutput(history)
+ term.PageOutput(res.Body)
}
diff --git a/server/db/git.go b/server/db/git.go
index 00f6ae2a..42528def 100644
--- a/server/db/git.go
+++ b/server/db/git.go
@@ -46,25 +46,40 @@ func GitAddAndCommit(orgId, planId, message string) error {
return nil
}
-func gitAdd(repoDir, path string) error {
- res, err := exec.Command("git", "-C", repoDir, "add", path).CombinedOutput()
+func GitRewindToSHA(orgId, planId, sha string) error {
+ dir := getPlanDir(orgId, planId)
+
+ err := gitRewindToSHA(dir, sha)
if err != nil {
- return fmt.Errorf("error adding files to git repository for dir: %s, err: %v, output: %s", repoDir, err, string(res))
+ return fmt.Errorf("error rewinding git repository for dir: %s, err: %v", dir, err)
}
return nil
}
-func gitCommit(repoDir, commitMsg string) error {
- res, err := exec.Command("git", "-C", repoDir, "commit", "-m", commitMsg).CombinedOutput()
+func GetGitCommitHistory(orgId, planId string) (string, error) {
+ dir := getPlanDir(orgId, planId)
+
+ history, err := getGitCommitHistory(dir)
if err != nil {
- return fmt.Errorf("error committing files to git repository for dir: %s, err: %v, output: %s", repoDir, err, string(res))
+ return "", fmt.Errorf("error getting git history for dir: %s, err: %v", dir, err)
}
- return nil
+ return history, nil
}
-func GitRewindToSHA(repoDir, sha string) error {
+func GetLatestCommit(orgId, planId string) (string, string, error) {
+ dir := getPlanDir(orgId, planId)
+
+ sha, timestamp, err := getLatestCommit(dir)
+ if err != nil {
+ return "", "", fmt.Errorf("error getting latest commit for dir: %s, err: %v", dir, err)
+ }
+
+ return sha, timestamp, nil
+}
+
+func gitRewindToSHA(repoDir, sha string) error {
res, err := exec.Command("git", "-C", repoDir, "reset", "--hard",
sha).CombinedOutput()
@@ -75,7 +90,7 @@ func GitRewindToSHA(repoDir, sha string) error {
return nil
}
-func GetLatestCommit(dir string) (string, string, error) {
+func getLatestCommit(dir string) (string, string, error) {
var out bytes.Buffer
cmd := exec.Command("git", "log", "--pretty=%h@@|@@%at@@|@@%B@>>>@")
cmd.Dir = dir
@@ -94,8 +109,7 @@ func GetLatestCommit(dir string) (string, string, error) {
return first[0], first[1], nil
}
-func GetGitCommitHistory(dir string) (string, error) {
-
+func getGitCommitHistory(dir string) (string, error) {
var out bytes.Buffer
cmd := exec.Command("git", "log", "--pretty=%h@@|@@%at@@|@@%B@>>>@")
cmd.Dir = dir
@@ -166,3 +180,21 @@ func processGitHistoryOutput(raw string) [][2]string {
return history
}
+
+func gitAdd(repoDir, path string) error {
+ res, err := exec.Command("git", "-C", repoDir, "add", path).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("error adding files to git repository for dir: %s, err: %v, output: %s", repoDir, err, string(res))
+ }
+
+ return nil
+}
+
+func gitCommit(repoDir, commitMsg string) error {
+ res, err := exec.Command("git", "-C", repoDir, "commit", "-m", commitMsg).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("error committing files to git repository for dir: %s, err: %v, output: %s", repoDir, err, string(res))
+ }
+
+ return nil
+}
diff --git a/server/handlers/plans_context.go b/server/handlers/plans_context.go
index fd2aa19e..beca1d47 100644
--- a/server/handlers/plans_context.go
+++ b/server/handlers/plans_context.go
@@ -255,10 +255,15 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
}
maxTokens := shared.MaxContextTokens
- tokensAdded := 0
+ tokensDiff := 0
totalTokens := plan.ContextTokens
- updateNumTokensById := make(map[string]int)
+ tokensDiffById := make(map[string]int)
contextsById := make(map[string]*db.Context)
+ var updatedContexts []*shared.Context
+
+ numFiles := 0
+ numUrls := 0
+ numTrees := 0
var mu sync.Mutex
errCh := make(chan error)
@@ -276,9 +281,8 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
}
contextsById[id] = context
-
+ updatedContexts = append(updatedContexts, context.ToApi())
updateNumTokens, err := shared.GetNumTokens(params.Body)
-
tokenDiff := updateNumTokens - context.NumTokens
if err != nil {
@@ -286,16 +290,25 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- updateNumTokensById[id] = updateNumTokens
- tokensAdded += tokenDiff
+ tokensDiffById[id] = updateNumTokens
+ tokensDiff += tokenDiff
totalTokens += tokenDiff
+
+ switch context.ContextType {
+ case shared.ContextFileType:
+ numFiles++
+ case shared.ContextURLType:
+ numUrls++
+ case shared.ContextDirectoryTreeType:
+ numTrees++
+ }
}(id, params)
}
if totalTokens > maxTokens {
log.Printf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
res := shared.LoadContextResponse{
- TokensAdded: tokensAdded,
+ TokensAdded: tokensDiff,
TotalTokens: totalTokens,
MaxTokensExceeded: true,
}
@@ -312,7 +325,6 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- updatedContextsCh := make(chan *db.Context)
errCh = make(chan error)
for id, params := range requestBody {
go func(id string, params *shared.UpdateContextParams) {
@@ -323,35 +335,32 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
context.Body = params.Body
context.Sha = sha
- context.NumTokens = updateNumTokensById[id]
-
- err = db.StoreContext(context)
-
- if err != nil {
- errCh <- err
- return
- }
-
- updatedContextsCh <- context
+ context.NumTokens = tokensDiffById[id]
+ errCh <- db.StoreContext(context)
}(id, params)
}
- var apiContexts []*shared.Context
for i := 0; i < len(requestBody); i++ {
- select {
- case err := <-errCh:
+ err := <-errCh
+ if err != nil {
log.Printf("Error creating context: %v\n", err)
http.Error(w, "Error creating context: "+err.Error(), http.StatusInternalServerError)
return
- case dbContext := <-updatedContextsCh:
- apiContext := dbContext.ToApi()
- apiContext.Body = ""
- apiContexts = append(apiContexts, apiContext)
}
}
- commitMsg := shared.SummaryForUpdateContext(apiContexts) + "\n\n" + shared.TableForContextUpdate(apiContexts)
+ updateRes := &shared.ContextUpdateResult{
+ UpdatedContexts: updatedContexts,
+ TokenDiffsById: tokensDiffById,
+ TokensDiff: tokensDiff,
+ TotalTokens: totalTokens,
+ NumFiles: numFiles,
+ NumUrls: numUrls,
+ NumTrees: numTrees,
+ }
+
+ commitMsg := shared.SummaryForUpdateContext(updateRes) + "\n\n" + shared.TableForContextUpdate(updateRes)
err = db.GitAddAndCommit(currentOrgId, planId, commitMsg)
if err != nil {
@@ -360,7 +369,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- err = db.AddPlanContextTokens(planId, tokensAdded)
+ err = db.AddPlanContextTokens(planId, tokensDiff)
if err != nil {
log.Printf("Error updating plan tokens: %v\n", err)
http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
@@ -368,7 +377,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
}
res := shared.UpdateContextResponse{
- TokensAdded: tokensAdded,
+ TokensAdded: tokensDiff,
TotalTokens: totalTokens,
Msg: commitMsg,
}
diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.go
index c2101a47..4d642fa4 100644
--- a/server/handlers/plans_versions.go
+++ b/server/handlers/plans_versions.go
@@ -1,20 +1,49 @@
package handlers
import (
+ "encoding/json"
"log"
"net/http"
+ "plandex-server/db"
"github.com/gorilla/mux"
+ "github.com/plandex/plandex/shared"
)
func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListLogsHandler")
+ // TODO: get from auth when implemented
+ currentOrgId := "org1"
+
vars := mux.Vars(r)
planId := vars["planId"]
log.Println("planId: ", planId)
+ body, err := db.GetGitCommitHistory(currentOrgId, planId)
+
+ if err != nil {
+ log.Println("Error getting logs: ", err)
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+
+ res := shared.LogResponse{
+ Body: body,
+ }
+
+ bytes, err := json.Marshal(res)
+
+ if err != nil {
+ log.Println("Error marshalling logs: ", err)
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+
+ w.Write(bytes)
+
+ log.Println("Successfully processed request for ListLogsHandler")
}
func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
diff --git a/shared/context.go b/shared/context.go
index a2c46c08..a686c00b 100644
--- a/shared/context.go
+++ b/shared/context.go
@@ -10,14 +10,13 @@ import (
)
type ContextUpdateResult struct {
- UpdatedContexts []Context
- TokenDiffsByName map[string]int
- TokensDiff int
- TotalTokens int
- MaxExceeded bool
- NumFiles int
- NumUrls int
- NumTrees int
+ UpdatedContexts []*Context
+ TokenDiffsById map[string]int
+ TokensDiff int
+ TotalTokens int
+ NumFiles int
+ NumUrls int
+ NumTrees int
}
func (c *Context) TypeAndIcon() (string, string) {
@@ -246,7 +245,7 @@ func SummaryForUpdateContext(updateRes *ContextUpdateResult) string {
func TableForContextUpdate(updateRes *ContextUpdateResult) string {
contexts := updateRes.UpdatedContexts
- tokenDiffsByName := updateRes.TokenDiffsByName
+ tokenDiffsById := updateRes.TokenDiffsById
if len(contexts) == 0 {
return ""
@@ -259,7 +258,7 @@ func TableForContextUpdate(updateRes *ContextUpdateResult) string {
for _, context := range contexts {
t, icon := context.TypeAndIcon()
- diff := tokenDiffsByName[context.Name]
+ diff := tokenDiffsById[context.Id]
diffStr := "+" + strconv.Itoa(diff)
tableColor := tablewriter.FgHiGreenColor
diff --git a/shared/req_res.go b/shared/req_res.go
index 7cdd1f5f..de40ca61 100644
--- a/shared/req_res.go
+++ b/shared/req_res.go
@@ -69,9 +69,8 @@ type RewindPlanRequest struct {
Sha string `json:"sha"`
}
-type ListPlanChangesResponse struct {
- Results []*PlanFileResult `json:"planResults"`
- Replacements []*Replacement `json:"planReplacements"`
+type LogResponse struct {
+ Body string `json:"body"`
}
type PlanTokenCount struct {