From 431b9c0a41dc36f92c856196c9b4cc85509ea436 Mon Sep 17 00:00:00 2001 From: Ruslan Strazhnyk Date: Fri, 27 Nov 2026 00:43:12 +0100 Subject: [PATCH] Reset cloud session tracking on consent changes --- internal/repl/repl.go | 23 +++++++- internal/session/cloud_session.go | 23 +++++++- internal/session/cloud_session_test.go | 78 ++++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 6 deletions(-) diff --git a/internal/repl/repl.go b/internal/repl/repl.go index 6ae4c58..fe522c7 100644 --- a/internal/repl/repl.go +++ b/internal/repl/repl.go @@ -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 { @@ -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": @@ -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 @@ -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) diff --git a/internal/session/cloud_session.go b/internal/session/cloud_session.go index 39d91b1..066ffbf 100644 --- a/internal/session/cloud_session.go +++ b/internal/session/cloud_session.go @@ -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 { @@ -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 diff --git a/internal/session/cloud_session_test.go b/internal/session/cloud_session_test.go index 06ff9c4..f5976bd 100644 --- a/internal/session/cloud_session_test.go +++ b/internal/session/cloud_session_test.go @@ -2,8 +2,11 @@ package session import ( "encoding/json" + "errors" + "fmt" "net/http" "net/http/httptest" + "reflect" "testing" "github.com/Quality-Max/qmax-code/internal/api" @@ -75,6 +78,21 @@ func TestApplyCloudSyncChoice_PersistsToDisk(t *testing.T) { } } +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) { @@ -343,6 +361,66 @@ func TestCloudTracker_CompleteCurrent_SkipsHistoryBeforeTruncatedSession(t *test } } +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))) + 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