Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions internal/repl/repl.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ func Run(ag *agent.Agent, cliAgent agent.CLIAgent, quietMode bool, version strin
}
tracker.CompleteCurrent(ag.Cfg.Context.API, ag.Usage.TotalTokens(), ag.History)
}
stopCloudSession := func() {
tracker.Stop()
}
reconcileCloudSession := func() {
cfg := ag.AppConfig
if cfg != nil && cfg.CloudSync != nil && !*cfg.CloudSync {
stopCloudSession()
return
}
startCloudSession()
}
switchCloudProject := func(projectID int) bool {
cfg := ag.AppConfig
if cfg == nil || cfg.CloudSync == nil || !*cfg.CloudSync {
Expand Down Expand Up @@ -540,11 +551,11 @@ func Run(ag *agent.Agent, cliAgent agent.CLIAgent, quietMode bool, version strin
continue
case input == "/set":
handleSetCommand(input, ag, term)
startCloudSession()
reconcileCloudSession()
continue
case input == "/settings" || strings.HasPrefix(input, "/settings "):
runSettingsPicker(ag, term)
startCloudSession()
reconcileCloudSession()
continue

case input == "/queue":
Expand Down Expand Up @@ -856,6 +867,12 @@ func Run(ag *agent.Agent, cliAgent agent.CLIAgent, quietMode bool, version strin
}
v := enabled
cfg.CloudSync = &v
if !enabled {
// Withdraw consent before persisting the preference. If saving fails,
// the in-memory opt-out still prevents the active session from ever
// uploading pending history later in this run.
stopCloudSession()
}
if err := cfg.Save(); err != nil {
term.PrintError(fmt.Sprintf("Failed to save config: %v", err))
continue
Expand Down Expand Up @@ -1166,7 +1183,7 @@ func Run(ag *agent.Agent, cliAgent agent.CLIAgent, quietMode bool, version strin
continue
case strings.HasPrefix(input, "/set "):
handleSetCommand(input, ag, term)
startCloudSession()
reconcileCloudSession()
continue
case input == "/keys":
handleKeys(ag, term)
Expand Down
23 changes: 20 additions & 3 deletions internal/session/cloud_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ func PromptCloudSyncConsent(cfg *api.Config, readLine func() (string, error)) bo
fmt.Println()
fmt.Print(" Enable cloud session sync? [Y/n]: ")

line, _ := readLine()
line, err := readLine()
if err != nil {
fmt.Println(" Cloud session sync unchanged.")
fmt.Println()
return false
}

enabled := ApplyCloudSyncChoice(cfg, line)
if enabled {
Expand Down Expand Up @@ -104,12 +109,24 @@ func (t *CloudSessionTracker) SwitchProject(
}

t.CompleteCurrent(client, totalTokens, messages)
t.reset()
t.StartWithHistory(client, projectID, model, len(messages), totalTokens)
return true
}

// Stop forgets the active cloud session without making a network request. Call
// this when the user opts out so a later opt-in starts a new history boundary
// and cannot upload messages entered while syncing was disabled. Opt-out does
// not finalize or upload pending history: consent has already been withdrawn.
func (t *CloudSessionTracker) Stop() {
t.reset()
}

func (t *CloudSessionTracker) reset() {
t.cloudID = ""
t.projectID = 0
t.historyStart = 0
t.tokenStart = 0
t.StartWithHistory(client, projectID, model, len(messages), totalTokens)
return true
}

// CompleteCurrent finalizes the active cloud session using only the portion
Expand Down
78 changes: 78 additions & 0 deletions internal/session/cloud_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"

"github.com/Quality-Max/qmax-code/internal/api"
Expand Down Expand Up @@ -75,6 +78,21 @@
}
}

func TestPromptCloudSyncConsent_ReadErrorDoesNotOptInOrPersist(t *testing.T) {
withTempHome(t)
cfg := api.DefaultConfig()

if PromptCloudSyncConsent(cfg, func() (string, error) { return "", errors.New("interrupted") }) {
t.Fatal("read error opted in")
}
if cfg.CloudSync != nil {
t.Fatalf("read error persisted cloud sync choice: %v", *cfg.CloudSync)
}
if loaded := api.LoadQMaxCodeConfig(); loaded.CloudSync != nil {
t.Fatalf("read error wrote cloud sync preference: %v", *loaded.CloudSync)
}
}

// ---- Config.CloudSync JSON round-trip ----

func TestConfigCloudSync_NilOmittedFromJSON(t *testing.T) {
Expand Down Expand Up @@ -343,6 +361,66 @@
}
}

func TestCloudTracker_StopThenRestart_ExcludesMessagesTypedWhileSyncWasDisabled(t *testing.T) {
var created int
uploaded := map[string][]string{}
requests := map[string]int{}
client, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
requests[r.Method+" "+r.URL.Path]++
switch {
case r.Method == http.MethodPost && r.URL.Path == "/api/agent-sessions":
created++
_, _ = w.Write([]byte(fmt.Sprintf(`{"session_id":"cloud-%d"}`, created)))

Check failure on line 373 in internal/session/cloud_session_test.go

View workflow job for this annotation

GitHub Actions / build-and-test

QF1012: Use fmt.Fprintf(...) instead of Write([]byte(fmt.Sprintf(...))) (staticcheck)
case r.Method == http.MethodPatch:
_, _ = w.Write([]byte(`{}`))
case r.Method == http.MethodPost:
var body struct {
Events []struct {
Payload api.Message `json:"payload"`
} `json:"events"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode events request: %v", err)
}
for _, event := range body.Events {
content, ok := event.Payload.Content.(string)
if !ok {
t.Fatalf("event payload content = %T, want string", event.Payload.Content)
}
uploaded[r.URL.Path] = append(uploaded[r.URL.Path], content)
}
_, _ = w.Write([]byte(`{}`))
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
})

var tracker CloudSessionTracker
tracker.StartWithHistory(client, 1, "model", 0, 0)
tracker.Stop() // /cloudsync off

if tracker.cloudID != "" || tracker.projectID != 0 {
t.Fatalf("stopped tracker retained session state: %+v", tracker)
}

// These messages are kept locally while sync is off. Re-enabling after a
// project switch must start a new session after this history boundary.
history := []api.Message{{Role: "user", Content: "private while sync off"}}
tracker.StartWithHistory(client, 2, "model", len(history), 10) // /cloudsync on after /project 2
history = append(history, api.Message{Role: "user", Content: "newly consented prompt"})
tracker.CompleteCurrent(client, 20, history)

if got := uploaded["/api/agent-sessions/cloud-1/events"]; len(got) != 0 {
t.Errorf("opt-out uploaded private history = %q", got)
}
if got := requests[http.MethodPatch+" /api/agent-sessions/cloud-1"]; got != 0 {
t.Errorf("opt-out finalized cloud session with %d PATCH requests", got)
}
if got, want := uploaded["/api/agent-sessions/cloud-2/events"], []string{"newly consented prompt"}; !reflect.DeepEqual(got, want) {
t.Errorf("re-enabled upload = %q, want %q", got, want)
}
}

func TestCloudTracker_SwitchProject_FinalizesOldSessionAndScopesNewHistory(t *testing.T) {
var createdProjects []int
var patchedIDs []string
Expand Down
Loading