diff --git a/README.md b/README.md index 570a904..d0b7c4e 100644 --- a/README.md +++ b/README.md @@ -1665,6 +1665,11 @@ the word starts with C; otherwise they retain a separate `(C)` before the label. Copy exports the complete sanitized text available in the bounded session preview, not an unlimited transcript: it cannot recover text omitted by observation limits. Clipboard contents then follow your terminal and operating system's retention behaviour. +When Codex marks an answer as hidden, blocked, or requiring a native display +that Codexometer cannot provide, Sessions shows **View this reply in Codex.** +The terminal, history, Copy, and read-only web view use that notice in the +configured language instead of the original text. This applies once Codex supplies the decision; it cannot +recall text already shown or copied while an answer was streaming. `Left` / `Right` move along **graph ↔ split ↔ expanded ↔ full detail** without wrapping. Each row retains its own presentation; adjusting one does not resize @@ -4034,11 +4039,11 @@ go test -race -cover -timeout 10m -run '^TestLocalisedScreens$' ./internal/ui ``` An optional Unix integration check verifies the installed Codex against the -0.164.0 baseline, 0.166.0, 0.167.0, 0.167.1, 0.167.2, 0.168.0 or 0.169.0, including negotiated +0.164.0 baseline, 0.166.0, 0.167.0, 0.167.1, 0.167.2, 0.168.0, 0.169.0 or 0.170.0, including negotiated compressed WebSocket RPC: ```sh -CODEXOMETER_TEST_CODEX_VERSION=0.169.0 go test ./internal/codex -run '^TestNativeCodexCompression$' -count=1 +CODEXOMETER_TEST_CODEX_VERSION=0.170.0 go test ./internal/codex -run '^TestNativeCodexCompression$' -count=1 ``` Use `0.164.0` when that version is on `PATH`; the existing diff --git a/docs/slash-command-support.md b/docs/slash-command-support.md index c26a426..21fa102 100644 --- a/docs/slash-command-support.md +++ b/docs/slash-command-support.md @@ -1,6 +1,6 @@ # Slash-command support audit -Codexometer behaviour updated for [v0.31.0](https://github.com/merefield/codexometer/releases/tag/v0.31.0) on **2026-11-18**. The upstream inventory remains pinned to **Codex CLI 0.169.0** (`rust-v0.169.0`): [command registry](https://github.com/openai/codex/blob/rust-v0.169.0/codex-rs/tui/src/slash_command.rs), [native command dispatch](https://github.com/openai/codex/blob/rust-v0.169.0/codex-rs/tui/src/chatwidget/slash_dispatch.rs), [app-server method registry](https://github.com/openai/codex/blob/rust-v0.169.0/codex-rs/app-server-protocol/src/protocol/common.rs), [thread settings types](https://github.com/openai/codex/blob/rust-v0.169.0/codex-rs/app-server-protocol/src/protocol/v2/thread.rs), and [native directory-change workflow](https://github.com/openai/codex/blob/rust-v0.169.0/codex-rs/tui/src/app/working_directory.rs). This is not a claim of compatibility with every newer Codex release. +Upstream inventory checked against **Codex CLI 0.170.0** on **2026-11-19**: [command registry](https://github.com/openai/codex/blob/rust-v0.170.0/codex-rs/tui/src/slash_command.rs), [native command dispatch](https://github.com/openai/codex/blob/rust-v0.170.0/codex-rs/tui/src/chatwidget/slash_dispatch.rs), [app-server method registry](https://github.com/openai/codex/blob/rust-v0.170.0/codex-rs/app-server-protocol/src/protocol/common.rs), [thread settings types](https://github.com/openai/codex/blob/rust-v0.170.0/codex-rs/app-server-protocol/src/protocol/v2/thread.rs), and [native directory-change workflow](https://github.com/openai/codex/blob/rust-v0.170.0/codex-rs/tui/src/app/working_directory.rs). This is not a claim of compatibility with every newer Codex release. The tables cover all **65 registered command variants** and the three additional accepted aliases `/cwd`, `/pet` and `/clean`: **68 upstream command names** in total. `/presets` and `/config` were absent from the earlier inventory and are now included as gaps, not newly implemented features. Codexometer’s local `/help` and terminal `/commands` entries, and model-advertised speed aliases, are outside that count. Platform, feature and debug-build filters affect actual visibility. The [published reference](https://learn.chatgpt.com/docs/developer-commands#built-in-slash-commands) is supplementary; the pinned registry determines this inventory. Codexometer has explicit adapters/local UI implementations; it does not send slash commands as model prompts. There is no generic server endpoint to discover or execute the CLI's slash commands. diff --git a/internal/codex/answer_display.go b/internal/codex/answer_display.go new file mode 100644 index 0000000..4e3237c --- /dev/null +++ b/internal/codex/answer_display.go @@ -0,0 +1,117 @@ +package codex + +import ( + "encoding/json" + "slices" +) + +type answerItem struct { + ID, Type, Text, Phase string + Moderation json.RawMessage +} + +// The companion cannot implement native replacements, annotations or trusted +// contact checks. Only an explicit plain show (or no restriction) is renderable. +func restrictedAnswer(raw json.RawMessage) bool { + if len(raw) == 0 || string(raw) == "null" { + return false + } + var m struct { + Moderated *bool + Display *struct { + Version int + Mode string + TrustedContacts string + Annotation json.RawMessage + } + } + if json.Unmarshal(raw, &m) != nil || m.Moderated == nil { + return true + } + d := m.Display + if d == nil { + return *m.Moderated + } + return d.Version != 1 || d.Mode != "show" || d.TrustedContacts != "skip" || + (len(d.Annotation) != 0 && string(d.Annotation) != "null") +} + +// Scoped to one thread. Keep identities, never message contents. Copy on +// append so a daemon snapshot can be read after releasing the provider lock. +type answerID struct{ turn, item string } +type answerGuards []answerID + +func (g *answerGuards) note(turn, item string) { + key := answerID{turn, item} + if slices.Contains(*g, key) { + return + } + const limit = 4 * SessionHistoryLimit + start := max(0, len(*g)-limit+1) + *g = append(slices.Clone((*g)[start:]), key) +} + +func (g answerGuards) covers(turn, item string) bool { + for _, k := range g { + // Completion mirrors omit item IDs. Only use that fallback within + // the same turn; a positive item identity also works without a turn. + if k.turn == turn && (item == "" || k.item == "" || k.item == item) || + k.item != "" && k.item == item && (k.turn == "" || turn == "") { + return true + } + } + return false +} + +func (g answerGuards) protect(c *SessionContext) { + if c.Kind == SessionContextReply && g.covers(c.TurnID, c.ItemID) { + c.withholdAnswer() + } +} + +func (c *rolloutCursor) inheritAnswerGuards(guards answerGuards) { + for _, k := range guards { + c.answers.note(k.turn, k.item) + } + c.answers.protect(&c.preview) +} + +// SameHistoryTurn compares observations, not their displayed text. Legacy +// mirrors can lack a turn ID: use a shared item ID, or as a last resort +// the same nonzero observation time. Never match conflicting known IDs. +func (a SessionContext) SameHistoryTurn(b SessionContext) bool { + if a.ThreadID != b.ThreadID { + return false + } + if a.TurnID != "" && b.TurnID != "" { + return a.TurnID == b.TurnID + } + if a.ItemID != "" && b.ItemID != "" { + return a.ItemID == b.ItemID + } + return !a.At.IsZero() && a.At.Equal(b.At) +} + +// ProtectReply updates an already-delivered excerpt when a matching decision +// arrives via another source. It never matches another thread or a command. +func (decision SessionContext) ProtectReply(c *SessionContext) { + if decision.ReplyRestricted && c.Kind == SessionContextReply && decision.SameHistoryTurn(*c) && + (decision.ItemID == "" || c.ItemID == "" || decision.ItemID == c.ItemID) { + c.withholdAnswer() + if c.TurnID == "" { + c.TurnID = decision.TurnID + } + if c.ItemID == "" { + c.ItemID = decision.ItemID + } + } +} + +func (c *SessionContext) withholdAnswer() { + c.Text, c.ReplyRestricted, c.Streaming = "", true, false + c.Activity = SessionActivity{} +} + +// HasDisplayText includes restricted answers: observers carry only the flag; +// presenters supply the localised notice instead of assistant-authored text. +func (c SessionContext) HasDisplayText() bool { return c.ReplyRestricted || c.Text != "" } diff --git a/internal/codex/answer_display_test.go b/internal/codex/answer_display_test.go new file mode 100644 index 0000000..0b3eafc --- /dev/null +++ b/internal/codex/answer_display_test.go @@ -0,0 +1,134 @@ +package codex + +import ( + "context" + "encoding/json" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestAnswerDisplayContract(t *testing.T) { + for _, tc := range []struct { + raw string + restrict bool + }{ + {"", false}, {"null", false}, {`{"moderated":false}`, false}, + {`{"moderated":true,"display":{"version":1,"mode":"show","trustedContacts":"skip","extra":42}}`, false}, + {`{"moderated":true,"display":null}`, true}, + {`{"moderated":false,"display":{"version":1,"mode":"hide","replacement":{"kind":"wellbeingPromptHelpline"}}}`, true}, + {`{"moderated":true,"display":{"version":1,"mode":"block","reason":{"kind":"protection","protectionType":"fixture"}}}`, true}, + {`{"moderated":true,"display":{"version":1,"mode":"show","trustedContacts":"check"}}`, true}, + {`{"moderated":true,"display":{"version":1,"mode":"show","trustedContacts":"skip","annotation":{"kind":"wellbeingHelpline","subject":"answer"}}}`, true}, + {`{"moderated":false,"display":{"version":2,"mode":"show","trustedContacts":"skip"}}`, true}, + {`{"moderated":false,"display":{"action":"legacy"}}`, true}, + {`{"moderated":true,"display":{"version":1,"mode":"show"}}`, true}, + {`{"display":null}`, true}, {`"malformed"`, true}, + } { + if got := restrictedAnswer(json.RawMessage(tc.raw)); got != tc.restrict { + t.Errorf("%s: restricted = %t, want %t", tc.raw, got, tc.restrict) + } + } +} + +func TestRestrictedLiveAnswerStopsStreamingAndCannotReplay(t *testing.T) { + states := map[string]*daemonContextState{} + emit := func(method, raw string) { + daemonContextEvent(states, method, nil, json.RawMessage(raw), time.Now()) + } + emit("turn/started", `{"threadId":"s","turn":{"id":"t"}}`) + item := `{"threadId":"s","turnId":"t","item":{"id":"a","type":"agentMessage","phase":"final_answer","text":"fixture plaintext"%s}}` + plain := strings.Replace(item, "%s", "", 1) + blocked := strings.Replace(item, "%s", `,"moderation":{"moderated":true}`, 1) + delta := `{"threadId":"s","turnId":"t","itemId":"a","delta":"partial"}` + emit("item/started", plain) + emit("item/agentMessage/delta", delta) + if !states["s"].latest.Streaming { + t.Fatal("ordinary stream was buffered") + } + for _, e := range [][2]string{{"item/completed", blocked}, {"item/started", blocked}, {"item/agentMessage/delta", delta}, {"item/completed", plain}} { + emit(e[0], e[1]) + got := states["s"].latest + if !got.ReplyRestricted || got.Text != "" || got.Streaming || states["s"].streamText != "" { + t.Fatalf("%s retained restricted text: %+v", e[0], got) + } + } + emit("item/completed", strings.Replace(plain, `"id":"a"`, `"id":"b"`, 1)) + if got := states["s"].latest; got.ReplyRestricted || got.Text != "fixture plaintext" { + t.Fatal("restriction was applied to an unrelated item", got) + } +} + +func TestRestrictedRolloutMirrorsAndRestart(t *testing.T) { + for _, decision := range []string{ + `{"type":"agent_message","phase":"final_answer","message":"fixture plaintext","moderation":{"item_id":"a","moderated":true}}`, + `{"type":"item_completed","turn_id":"t","item":{"type":"AgentMessage","id":"a","content":[{"type":"Text","text":"fixture plaintext"}],"moderation":{"moderated":true}}}`, + } { + now, home := time.Now(), t.TempDir() + path := testRolloutPath(t, home, now, "s") + event := func(p string) string { return `{"type":"event_msg","payload":` + p + "}\n" } + writeRollout(t, path, sessionMetaLine("s", `"cli"`, "/example", nil)+"\n"+event(`{"type":"task_started","turn_id":"t"}`)+event(decision)+ + `{"type":"response_item","payload":{"type":"message","role":"assistant","phase":"final_answer","content":[{"type":"output_text","text":"fixture plaintext"}]}}`+"\n"+ + event(`{"type":"task_complete","turn_id":"t","last_agent_message":"fixture plaintext"}`)) + for _, compressed := range []bool{false, true} { + if compressed { + compressTestRollout(t, path, true) + } + r, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + r.statusProvider = nil + u, err := r.FetchTokenUsage(context.Background()) + if err != nil || len(u.Sessions) != 1 { + t.Fatal(u, err) + } + c := u.Sessions[0].Context + if c.Text != "" || !c.ReplyRestricted || c.TurnID != "t" { + t.Fatal("restart exposed mirrored text", c) + } + for _, cursor := range r.files { + cursor.currentTurnID = "next" + c, ok := rolloutContextRecord([]byte(event(`{"type":"task_complete","turn_id":"next","last_agent_message":"safe"}`)), cursor) + if !ok || c.Text != "safe" || c.ReplyRestricted { + t.Fatal("unrelated turn hidden", c) + } + } + } + } +} + +func TestTurnSummaryRestrictsAlreadyStreamedAnswer(t *testing.T) { + states := map[string]*daemonContextState{} + for _, e := range [][2]string{ + {"item/started", `{"threadId":"s","turnId":"t","item":{"type":"agentMessage","phase":"final_answer","id":"a"}}`}, + {"item/agentMessage/delta", `{"threadId":"s","turnId":"t","itemId":"a","delta":"fixture plaintext"}`}, + {"turn/completed", `{"threadId":"s","turn":{"id":"t","status":"completed","items":[{"type":"agentMessage","id":"a","text":"fixture plaintext","moderation":{"moderated":true}}]}}`}, + } { + daemonContextEvent(states, e[0], nil, json.RawMessage(e[1]), time.Now()) + } + c := daemonContextSnapshot(states, []string{"s"}, nil)["s"] + if !c.ReplyRestricted || c.Text != "" || c.Streaming || states["s"].streamText != "" { + t.Fatal(c) + } +} + +func TestTruncatedTailDoesNotPublishOrphanedAnswerMirror(t *testing.T) { + path := filepath.Join(t.TempDir(), "rollout.jsonl") + final := `{"type":"event_msg","payload":{"type":"task_complete","turn_id":"t","last_agent_message":"unverified mirror"}}` + "\n" + writeRollout(t, path, strings.Repeat("x", 256*1024)+"\n"+final) + cursor := &rolloutCursor{threadID: "s", currentTurnID: "t"} + if c := latestSessionContext(path, cursor); c.Text != "" { + t.Fatal(c) + } + c, ok := rolloutContextRecord([]byte(final), cursor) + if !ok || c.Text != "" { + t.Fatal("subsequent mirror exposed truncated history", c) + } + rolloutContextRecord([]byte(`{"type":"event_msg","payload":{"type":"task_started","turn_id":"next"}}`), cursor) + cursor.currentTurnID = "next" + if c, ok := rolloutContextRecord([]byte(strings.ReplaceAll(final, `"t"`, `"next"`)), cursor); !ok || c.Text != "unverified mirror" { + t.Fatal("new turn lost ordinary reply", c) + } +} diff --git a/internal/codex/daemon_native_unix_test.go b/internal/codex/daemon_native_unix_test.go index 8af962a..edc31d6 100644 --- a/internal/codex/daemon_native_unix_test.go +++ b/internal/codex/daemon_native_unix_test.go @@ -20,7 +20,7 @@ func TestNativeCodexCompression(t *testing.T) { if expected == "" && os.Getenv("CODEXOMETER_TEST_CODEX_164") == "1" { expected = "0.164.0" // Retain the existing baseline test invocation. } - versions := []string{"0.164.0", "0.166.0", "0.167.0", "0.167.1", "0.167.2", "0.168.0", "0.169.0"} + versions := []string{"0.164.0", "0.166.0", "0.167.0", "0.167.1", "0.167.2", "0.168.0", "0.169.0", "0.170.0"} if expected == "" { t.Skip("set CODEXOMETER_TEST_CODEX_VERSION to one of " + strings.Join(versions, ", ") + " with that Codex installed") } @@ -93,7 +93,7 @@ func TestNativeCodexCompression(t *testing.T) { if err != nil || len(loaded) != 0 { t.Fatal("isolated server unexpectedly has loaded threads", loaded, err) } - if expected == "0.169.0" { + if slices.Index(versions, expected) >= slices.Index(versions, "0.169.0") { // 0.169 adds explicit provider selection. An unknown provider must // fail rather than silently returning the default catalogue. if _, err := p.commandModels(context.Background(), "codexometer-unknown-provider"); err == nil { diff --git a/internal/codex/daemon_status.go b/internal/codex/daemon_status.go index 7e3eefd..614ce8e 100644 --- a/internal/codex/daemon_status.go +++ b/internal/codex/daemon_status.go @@ -24,6 +24,7 @@ type sessionDaemonSnapshot struct { Goals map[string]*SessionGoal UsageCoverage map[string]string Contexts map[string]SessionContext + AnswerGuards map[string]answerGuards WorkingDirectories map[string]string Statuses map[string]sessionRuntimeStatus ModelObservations []resolvedModelObservation diff --git a/internal/codex/daemon_status_unix.go b/internal/codex/daemon_status_unix.go index 2357524..c98ba58 100644 --- a/internal/codex/daemon_status_unix.go +++ b/internal/codex/daemon_status_unix.go @@ -237,8 +237,15 @@ func (p *daemonStatusProvider) statusSnapshotLocked(threadIDs []string) sessionD if contexts == nil { contexts = map[string]SessionContext{} } + var guards map[string]answerGuards for _, id := range threadIDs { c := contexts[id] + if s := p.contexts[id]; s != nil && len(s.answers) != 0 { + if guards == nil { + guards = make(map[string]answerGuards) + } + guards[id] = s.answers + } if pending := p.pendingModels[id]; pending != nil { c.PendingModel = pending.display } @@ -254,6 +261,7 @@ func (p *daemonStatusProvider) statusSnapshotLocked(threadIDs []string) sessionD Goals: goals, UsageCoverage: coverage, Contexts: contexts, + AnswerGuards: guards, WorkingDirectories: directories, Statuses: statuses, ModelObservations: append([]resolvedModelObservation(nil), p.observations...), diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index c39ea38..939ea10 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -181,6 +181,8 @@ type LiveUsageReader struct { } type rolloutCursor struct { + answers answerGuards + partialAnswerHistory bool activity sessionActivityState preview SessionContext offset int64 @@ -446,6 +448,11 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover appServerUp = true exactStatuses = daemonSnapshot.Statuses r.daemonContexts = daemonSnapshot.Contexts + if len(daemonSnapshot.AnswerGuards) != 0 { + for _, cursor := range r.files { + cursor.inheritAnswerGuards(daemonSnapshot.AnswerGuards[cursor.threadID]) + } + } daemonCoverage = daemonSnapshot.UsageCoverage r.daemonDirectories = daemonSnapshot.WorkingDirectories r.daemonAttachments = daemonSnapshot.AttachedThreads @@ -725,6 +732,7 @@ func (r *LiveUsageReader) addFile(ctx context.Context, path string, info os.File // Replacing this path changes the historical baseline, not the activity // already observed by this process. Keep it only for the same thread. if previous := r.files[path]; previous != nil && cursor.threadID != "" && previous.threadID == cursor.threadID { + cursor.inheritAnswerGuards(previous.answers) cursor.observedTokens, cursor.modelCalls, cursor.turnTimings = previous.observedTokens, previous.modelCalls, previous.turnTimings cursor.lastGrowthAt = previous.lastGrowthAt } @@ -1575,6 +1583,7 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string preview.CompletedSteerIDs, preview.TurnID = live.CompletedSteerIDs, live.TurnID } } + cursor.answers.protect(&preview) if cursor.guardianReviewer && !preview.pending() { // A private reviewer's reply (streaming or final) is not the // conversation. Its tokens above still belong to this group; the diff --git a/internal/codex/live_usage_compressed.go b/internal/codex/live_usage_compressed.go index 63fdc43..e36b64b 100644 --- a/internal/codex/live_usage_compressed.go +++ b/internal/codex/live_usage_compressed.go @@ -42,6 +42,7 @@ func (r *LiveUsageReader) addCompressedFile(ctx context.Context, path string, in return fmt.Errorf("read compressed rollout: %w", err) } if old != nil && old.threadID == cursor.threadID { + cursor.inheritAnswerGuards(old.answers) cursor.observedTokens, cursor.modelCalls, cursor.turnTimings = old.observedTokens, old.modelCalls, old.turnTimings cursor.lastGrowthAt = old.lastGrowthAt if old.offset != cursor.offset { @@ -104,6 +105,11 @@ func compressedRolloutBaseline(ctx context.Context, path string, info os.FileInf cursor.compressedTail = append(cursor.compressedTail[:0], tail...) if !oversized { baselineRolloutRecord(cursor, line) + } else { + cursor.partialAnswerHistory = true + if cursor.preview.Kind == SessionContextReply { + cursor.preview = SessionContext{} + } } line = line[:0] oversized = false diff --git a/internal/codex/live_usage_guardian_test.go b/internal/codex/live_usage_guardian_test.go index df00264..f5b22fe 100644 --- a/internal/codex/live_usage_guardian_test.go +++ b/internal/codex/live_usage_guardian_test.go @@ -71,16 +71,14 @@ func TestGuardianPlanQuotaAccounting(t *testing.T) { } } if tc.limits != "" { - checkpoint := richTokenCountLine(now, 110, 100, 20, 0, 10) + cached := int64(20) if tc.otherTurn { appendRollout(t, path, turnContextWithTurnIDLine(now, "other", autoReviewModel)+"\n") } if tc.mismatchedUsage { - checkpoint = richTokenCountLine(now, 110, 100, 19, 0, 10) + cached-- } - checkpoint = strings.Replace(checkpoint, `"info":`, `"rate_limits":`+tc.limits+`,"info":`, 1) - checkpoint = strings.Replace(checkpoint, `"output_tokens":`, `"reasoning_output_tokens":0,"output_tokens":`, 1) - appendRollout(t, path, fmt.Sprintf(`{"ordinal":%d,`, tc.ordinal)+checkpoint[1:]+"\n") + appendRollout(t, path, guardianCheckpoint(now, tc.ordinal, 110, cached, tc.limits)) } first := fetch() if tc.reroute != "" { @@ -120,3 +118,50 @@ func TestGuardianPlanQuotaAccounting(t *testing.T) { t.Fatal("quota exemption must not publish a zero-dollar benchmark/API price") } } + +func guardianCheckpoint(now time.Time, ordinal int, total, cached int64, limits string) string { + s := richTokenCountLine(now, total, 100, cached, 0, 10) + s = strings.Replace(s, `"info":`, `"rate_limits":`+limits+`,"info":`, 1) + s = strings.Replace(s, `"output_tokens":`, `"reasoning_output_tokens":0,"output_tokens":`, 1) + return fmt.Sprintf(`{"ordinal":%d,`, ordinal) + s[1:] + "\n" +} + +func TestReusedGuardianThreadAcrossReconnect(t *testing.T) { + now, home := time.Now(), t.TempDir() + path := testRolloutPath(t, home, now, "review") + meta := sessionMetaLine("review", `{"subagent":{"other":"guardian"}}`, "/synthetic", nil) + writeRollout(t, path, strings.Replace(meta, `"source":`, `"model_provider":"openai","source":`, 1)+"\n") + r, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + connected := stubSessionStatusProvider{subscribed: map[string]struct{}{"review": {}}} + r.statusProvider = connected + check := func(want int64) { + t.Helper() + s, err := r.FetchTokenUsage(context.Background()) + if err != nil || s.TotalTokens != want*110 || s.APIEqUSD != 0 || s.APIEqPricedCalls+s.APIEqUnpricedCalls+s.APIEqPendingCalls != 0 || int64(len(r.files[path].modelCalls)) != want { + t.Fatalf("want %d distinct, accounted plan reviews: %+v %v", want, s, err) + } + for _, row := range s.Sessions { + if row.Context.Text != "" { + t.Fatal("private Guardian prose became a session reply", row.Context) + } + } + } + check(0) + for i, turn := range []string{"first", "second"} { + u := BenchmarkUsage{InputTokens: 100, CachedInputTokens: 20, OutputTokens: 10, TotalTokens: 110} + exact := exactLine(t, now, "review", turn, "response-"+turn, u) + ordinal := 10 + i*3 + record := fmt.Sprintf(`{"ordinal":%d,`, ordinal) + exact[1:] + "\n" + checkpoint := guardianCheckpoint(now, ordinal+1, int64(i+1)*110, 20, `{"limit_id":"codex","plan_type":"pro"}`) + appendRollout(t, path, turnContextWithTurnIDLine(now, turn, autoReviewModel)+"\n"+record+checkpoint+ + `{"type":"event_msg","payload":{"type":"agent_message","phase":"final_answer","message":"private reviewer prose"}}`+"\n") + r.statusProvider = nil + check(int64(i + 1)) + r.statusProvider = connected + appendRollout(t, path, record+checkpoint) + check(int64(i + 1)) + } +} diff --git a/internal/codex/session_context.go b/internal/codex/session_context.go index f439e36..c4ea0be 100644 --- a/internal/codex/session_context.go +++ b/internal/codex/session_context.go @@ -41,6 +41,7 @@ type SessionContext struct { // not that the model followed an instruction. No message text is retained. CompletedSteerIDs string Streaming bool + ReplyRestricted bool // original answer must not be displayed, exported or restored from a mirror Activity SessionActivity // ApprovalContext is preceding same-thread/turn prose captured when the // request arrived. Display-only: never part of the authorised action. @@ -165,7 +166,7 @@ func (c SessionContext) pending() bool { } func preferSessionContext(a, b SessionContext) SessionContext { - if b.Text == "" && b.CurrentTask == "" && b.LatestGuidance == "" { + if !b.HasDisplayText() && b.CurrentTask == "" && b.LatestGuidance == "" { return a } priority := func(c SessionContext) int { @@ -188,7 +189,7 @@ func preferSessionContext(a, b SessionContext) SessionContext { tie = b.At.Equal(a.At) && (b.ThreadID < a.ThreadID || b.ThreadID == a.ThreadID && b.RequestID < a.RequestID) } - if a.Text == "" && a.CurrentTask == "" && a.LatestGuidance == "" || pb > pa || pb == pa && (newer || tie) { + if !a.HasDisplayText() && a.CurrentTask == "" && a.LatestGuidance == "" || pb > pa || pb == pa && (newer || tie) { return b } return a @@ -241,6 +242,9 @@ func rolloutContextRecord(line []byte, cursor *rolloutCursor) (SessionContext, b Timestamp time.Time `json:"timestamp"` Ordinal *uint64 `json:"ordinal"` Payload struct { + ID string + Moderation json.RawMessage + Item answerItem Error json.RawMessage `json:"error"` Code json.RawMessage `json:"codex_error_info"` WillRetry *bool `json:"will_retry"` @@ -267,6 +271,9 @@ func rolloutContextRecord(line []byte, cursor *rolloutCursor) (SessionContext, b } c := SessionContext{At: event.Timestamp, ThreadID: cursor.threadID, TurnID: event.Payload.TurnID, Source: "LOCAL"} p := event.Payload + if c.TurnID == "" { + c.TurnID = cursor.currentTurnID + } if (p.Type == "error" || p.Type == "task_complete" || p.Type == "turn_complete") && p.TurnID != "" && cursor.currentTurnID != "" && p.TurnID != cursor.currentTurnID { return c, false } @@ -274,7 +281,7 @@ func rolloutContextRecord(line []byte, cursor *rolloutCursor) (SessionContext, b if p.Phase != "commentary" && p.Phase != "final_answer" { return c, false } - c.Kind = SessionContextActivity + c.ItemID, c.Kind = p.ID, SessionContextActivity if p.Phase == "final_answer" { c.Kind = SessionContextReply } @@ -285,8 +292,24 @@ func rolloutContextRecord(line []byte, cursor *rolloutCursor) (SessionContext, b } } else if event.Type == "event_msg" { switch p.Type { + case "item_started", "item_completed": + if p.Item.Type != "AgentMessage" { + return c, false + } + if p.Type == "item_completed" && p.Item.Phase == "final_answer" { + cursor.partialAnswerHistory = false + } + if !restrictedAnswer(p.Item.Moderation) { + return c, false + } + c.ItemID = p.Item.ID + cursor.answers.note(c.TurnID, c.ItemID) + c.Kind = SessionContextReply case "task_started", "turn_started", "user_message": cursor.activity = sessionActivityState{} + if p.Type != "user_message" { + cursor.partialAnswerHistory = false + } return SessionContext{}, true case "task_complete", "turn_complete": cursor.activity = sessionActivityState{} @@ -311,8 +334,20 @@ func rolloutContextRecord(line []byte, cursor *rolloutCursor) (SessionContext, b failure := sessionFailureContext(c, raw) return failure, failureAffectsTurn(failure) case "agent_message": - c.Kind, c.Text = SessionContextActivity, p.Message if p.Phase == "final_answer" { + cursor.partialAnswerHistory = false + } + restricted := restrictedAnswer(p.Moderation) + if restricted { + var target struct { + ID string `json:"item_id"` + } + _ = json.Unmarshal(p.Moderation, &target) + c.ItemID = target.ID + cursor.answers.note(c.TurnID, c.ItemID) + } + c.Kind, c.Text = SessionContextActivity, p.Message + if restricted || p.Phase == "final_answer" || p.Phase == "" && cursor.answers.covers(c.TurnID, c.ItemID) { c.Kind = SessionContextReply } case "request_user_input": @@ -357,6 +392,13 @@ func rolloutContextRecord(line []byte, cursor *rolloutCursor) (SessionContext, b } if c.Kind == SessionContextReply { cursor.activity = sessionActivityState{} + cursor.answers.protect(&c) + // A truncated bootstrap can start after the authoritative item but + // before a raw response/completion mirror. That mirror alone cannot + // establish that the omitted decision permitted display. + if cursor.partialAnswerHistory && !c.ReplyRestricted { + c = SessionContext{} + } } if c.Kind == SessionContextActivity && cursor.preview.pending() && p.Type != "exec_command_begin" { return cursor.preview, true @@ -394,14 +436,20 @@ func latestSessionContext(path string, cursor *rolloutCursor) SessionContext { } var latest SessionContext copyCursor := *cursor + copyCursor.partialAnswerHistory = start > 0 copyCursor.preview = SessionContext{} copyCursor.activity = sessionActivityState{} for _, line := range lines[:max(len(lines)-1, 0)] { + if turn, ordinal, at, ok := rolloutTurnIDRecord(line); ok && tokenRecordIsOwned(ordinal, copyCursor.subagentHistoryStartOrdinal, at, copyCursor.nonRoot, copyCursor.startedAt) { + copyCursor.currentTurnID = turn + } if c, ok := rolloutContextRecord(line, ©Cursor); ok { latest = c copyCursor.preview = c } } cursor.activity = copyCursor.activity + cursor.answers = copyCursor.answers + cursor.partialAnswerHistory = copyCursor.partialAnswerHistory return latest } diff --git a/internal/codex/session_context_daemon.go b/internal/codex/session_context_daemon.go index 8e10b0a..be664fb 100644 --- a/internal/codex/session_context_daemon.go +++ b/internal/codex/session_context_daemon.go @@ -13,6 +13,7 @@ import ( // Pending requests are keyed by JSON-RPC request id, so resolving one request // cannot clear a different outstanding question/approval for the same thread. type daemonContextState struct { + answers answerGuards completedSteers []string steerMessageID string turnObserved bool @@ -43,6 +44,7 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id var p struct { approvalRequestScope Turn struct { + Items []answerItem ID string `json:"id"` Status string `json:"status"` Error json.RawMessage `json:"error"` @@ -65,15 +67,13 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id Questions []contextQuestion `json:"questions"` IsBlocking *bool `json:"isBlocking"` Item struct { + answerItem Content []struct { Type string `json:"type"` Text string `json:"text"` } `json:"content"` - ID, ClientID string + ClientID string CWD string `json:"cwd"` - Type string `json:"type"` - Text string `json:"text"` - Phase string `json:"phase"` Command string `json:"command"` Status string `json:"status"` ExitCode *int `json:"exitCode"` @@ -93,6 +93,12 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id state = &daemonContextState{requests: map[string]SessionContext{}, commands: map[string]contextCommandItem{}} states[p.ThreadID] = state } + agentItem := p.Item.Type == "agentMessage" && (method == "item/completed" || method == "item/started") + restricted := agentItem && restrictedAnswer(p.Item.Moderation) + if restricted { + state.answers.note(p.TurnID, p.Item.ID) + state.answers.protect(&state.latest) + } if (method == "item/started" || method == "item/completed" || method == "item/agentMessage/delta") && (state.ended || state.activeTurn != "" && p.TurnID != state.activeTurn) { return @@ -104,7 +110,7 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id } switch method { case "turn/started": - states[p.ThreadID] = &daemonContextState{activeTurn: p.Turn.ID, turnObserved: true, requests: map[string]SessionContext{}, commands: map[string]contextCommandItem{}} + states[p.ThreadID] = &daemonContextState{answers: state.answers, activeTurn: p.Turn.ID, turnObserved: true, requests: map[string]SessionContext{}, commands: map[string]contextCommandItem{}} return case "thread/closed": delete(states, p.ThreadID) @@ -113,6 +119,16 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id if !state.acceptTurn(p.Turn.ID) { return } + // Native turn/completed may itself carry the final agent item. The + // last delta/item notification isn't guaranteed to have the decision. + for _, item := range p.Turn.Items { + if item.Type == "agentMessage" && restrictedAnswer(item.Moderation) { + state.answers.note(p.Turn.ID, item.ID) + c.Kind, c.TurnID, c.ItemID = SessionContextReply, p.Turn.ID, item.ID + c.withholdAnswer() + state.latest = c + } + } state.finishedTurn = p.Turn.ID // Keep the observed task alongside its reply until the next turn. state.ended = true @@ -289,7 +305,7 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id } } } - if state.observeUserMessage(p.Item.ID, p.TurnID, userMessageText(p.Item.Content)) && state.latest.Text == "" { + if state.observeUserMessage(p.Item.ID, p.TurnID, userMessageText(p.Item.Content)) && !state.latest.HasDisplayText() { c.Kind = SessionContextActivity state.latest = c } @@ -328,6 +344,13 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id if state.streamItem == p.Item.ID { state.streamItem, state.streamText = "", "" } + c.ItemID = p.Item.ID + if state.answers.covers(p.TurnID, p.Item.ID) { + c.Kind = SessionContextReply + c.withholdAnswer() + state.activity = sessionActivityState{} + break + } c.Kind, c.Text = SessionContextActivity, p.Item.Text if p.Item.Phase == "final_answer" { c.Kind = SessionContextReply @@ -353,6 +376,12 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id if state.activeTurn != "" && p.TurnID != state.activeTurn { return } + if state.answers.covers(p.TurnID, p.Item.ID) { + state.streamItem, state.streamText = "", "" + c.ItemID, c.Kind = p.Item.ID, SessionContextReply + c.withholdAnswer() + break + } state.streamItem, state.streamTurn, state.streamPhase = p.Item.ID, p.TurnID, p.Item.Phase state.streamText = boundedStreamText(p.Item.Text) return @@ -402,7 +431,7 @@ func daemonContextEvent(states map[string]*daemonContextState, method string, id } else { c.Text = SanitizeSessionContext(c.Text) } - if c.Text == "" { + if !c.HasDisplayText() { return } if c.pending() { @@ -496,7 +525,7 @@ func daemonContextSnapshot(states map[string]*daemonContextState, ids []string, c.ThreadID, c.TurnID, c.Source = id, state.activeTurn, "LIVE" } c.PendingApprovalsLimited = state.approvalsLimited && statuses[id] == sessionRuntimeApproval - if c.Text != "" || c.CurrentTask != "" || c.LatestGuidance != "" || c.CompletedSteerIDs != "" || c.PendingApprovalsLimited { + if c.HasDisplayText() || c.CurrentTask != "" || c.LatestGuidance != "" || c.CompletedSteerIDs != "" || c.PendingApprovalsLimited { out[id] = c } } diff --git a/internal/codex/session_history.go b/internal/codex/session_history.go index 7c935b0..a0d9773 100644 --- a/internal/codex/session_history.go +++ b/internal/codex/session_history.go @@ -17,7 +17,23 @@ var ErrSessionHistory = errors.New("session history unavailable") func (c Client) SessionHistory(ctx context.Context, id string) ([]SessionContext, error) { if c.LiveUsage != nil { if p, ok := c.LiveUsage.statusProvider.(SessionHistoryClient); ok { - return p.SessionHistory(ctx, id) + turns, err := p.SessionHistory(ctx, id) + if err == nil { + c.LiveUsage.mu.Lock() + for _, cursor := range c.LiveUsage.files { + if cursor.threadID == id { + for i := range turns { + if turns[i].ReplyRestricted { + cursor.answers.note(turns[i].TurnID, turns[i].ItemID) + } + cursor.answers.protect(&turns[i]) + } + cursor.answers.protect(&cursor.preview) + } + } + c.LiveUsage.mu.Unlock() + } + return turns, err } } return nil, ErrSessionHistory @@ -25,9 +41,12 @@ func (c Client) SessionHistory(ctx context.Context, id string) ([]SessionContext // Restrict excerpts to display fields even when supplied by another reader. func HistoryExcerpt(c SessionContext) SessionContext { + if c.ReplyRestricted { + c.withholdAnswer() + } return SessionContext{ ThreadID: c.ThreadID, TurnID: c.TurnID, ItemID: c.ItemID, - Kind: SessionContextReply, Source: c.Source, At: c.At, + Kind: SessionContextReply, Source: c.Source, At: c.At, ReplyRestricted: c.ReplyRestricted, Text: SanitizeSessionContext(c.Text), CurrentTask: SanitizeSessionContext(c.CurrentTask), LatestGuidance: SanitizeSessionContext(c.LatestGuidance), } diff --git a/internal/codex/session_history_unix.go b/internal/codex/session_history_unix.go index 3fe0991..bb0a406 100644 --- a/internal/codex/session_history_unix.go +++ b/internal/codex/session_history_unix.go @@ -12,8 +12,8 @@ type historyTurn struct { ID, Status string CompletedAt *int64 Items []struct { - ID, Type, Text, Phase string - Content []struct{ Type, Text string } + answerItem + Content []struct{ Type, Text string } } } @@ -58,11 +58,12 @@ func (p *daemonStatusProvider) SessionHistory(ctx context.Context, id string) ([ case "agentMessage": if item.Phase == "final_answer" || item.Phase == "" { c.Text, c.ItemID = item.Text, item.ID + c.ReplyRestricted = restrictedAnswer(item.Moderation) } } } c = HistoryExcerpt(c) - if c.Text != "" { + if c.HasDisplayText() { result = append(result, c) } if len(result) == SessionHistoryLimit { diff --git a/internal/codex/session_history_unix_test.go b/internal/codex/session_history_unix_test.go index 9fd10b0..6fe3a87 100644 --- a/internal/codex/session_history_unix_test.go +++ b/internal/codex/session_history_unix_test.go @@ -9,6 +9,24 @@ import ( "testing" ) +func TestHistoryDecisionProtectsLocalMirrorAfterDisconnect(t *testing.T) { + p, f := newQuotaDaemon(t) + f.catalogues = map[string]map[string]any{"thread/turns/list": {"data": []any{map[string]any{"id": "turn", "status": "completed", "items": []any{ + map[string]any{"id": "a", "type": "agentMessage", "phase": "final_answer", "text": "fixture plaintext", "moderation": map[string]any{"moderated": true}}, + }}}}} + cursor := &rolloutCursor{threadID: "one", currentTurnID: "turn", preview: SessionContext{Kind: SessionContextReply, ThreadID: "one", TurnID: "turn", Text: "fixture plaintext"}} + r := &LiveUsageReader{statusProvider: p, files: map[string]*rolloutCursor{"path": cursor}} + turns, err := (Client{LiveUsage: r}).SessionHistory(context.Background(), "one") + if err != nil || len(turns) != 1 || !turns[0].ReplyRestricted || turns[0].Text != "" || !cursor.preview.ReplyRestricted || cursor.preview.Text != "" { + t.Fatal(turns, cursor.preview, err) + } + r.statusProvider = nil + c, ok := rolloutContextRecord([]byte(`{"type":"event_msg","payload":{"type":"task_complete","turn_id":"turn","last_agent_message":"fixture plaintext"}}`), cursor) + if !ok || !c.ReplyRestricted || c.Text != "" { + t.Fatal("disconnect revived text", c) + } +} + func TestSessionHistoryBoundedReadOnlyCompletedTurns(t *testing.T) { p, f := newQuotaDaemon(t) rows := []any{map[string]any{"id": "active", "status": "inProgress", "items": []any{map[string]any{"type": "agentMessage", "text": "Not finished"}}}} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index 474cde2..e953a6b 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -71,6 +71,14 @@ func (t *Translator) Format(key string, args ...any) string { func Text(key string) string { return current.Text(key) } func Format(key string, args ...any) string { return current.Format(key, args...) } +// SessionText translates only the application's notice, never user or model prose. +func SessionText(text string, restricted bool) string { + if restricted { + return Text("View this reply in Codex.") + } + return text +} + // WindowName translates only the app's canonical quota-window names, not // arbitrary server-provided model names or identifiers. func WindowName(name string) string { return current.WindowName(name) } diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 2d89260..5714115 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -19,6 +19,22 @@ import ( "golang.org/x/text/language" ) +func TestRestrictedReplyNoticeInEveryLocale(t *testing.T) { + const key = "View this reply in Codex." + if got := SessionText(key, false); got != key { + t.Fatalf("translated ordinary assistant text %q", got) + } + for _, code := range codes { + got := New(code).Text(key) + if got == "" || (got == key) != (code == "en-GB") { + t.Errorf("%s: missing or unexpected translation %q", code, got) + } + } + if got := New("fr").Text(key); got != "Voir cette réponse dans Codex." { + t.Fatal(got) + } +} + func TestPresentationKeysHaveCatalogueEntries(t *testing.T) { data, err := files.ReadFile("locales/en-GB.json") if err != nil { diff --git a/internal/i18n/locales/da.json b/internal/i18n/locales/da.json index 44924f5..31b0e42 100644 --- a/internal/i18n/locales/da.json +++ b/internal/i18n/locales/da.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Se dette svar i Codex.", "%s ago": "for %s siden", "COMMAND REVIEW": "KOMMANDOVURDERING", "PROCESS REVIEW": "PROCESVURDERING", diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 7d584ea..054ee6f 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Diese Antwort in Codex ansehen.", "%s ago": "vor %s", "COMMAND REVIEW": "BEFEHLSPRÜFUNG", "PROCESS REVIEW": "PROZESSPRÜFUNG", diff --git a/internal/i18n/locales/en-GB.json b/internal/i18n/locales/en-GB.json index 0fd8670..f5bbf3e 100644 --- a/internal/i18n/locales/en-GB.json +++ b/internal/i18n/locales/en-GB.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "View this reply in Codex.", "%s ago": "%s ago", "COMMAND REVIEW": "COMMAND REVIEW", "PROCESS REVIEW": "PROCESS REVIEW", diff --git a/internal/i18n/locales/es.json b/internal/i18n/locales/es.json index d5411db..55ffc06 100644 --- a/internal/i18n/locales/es.json +++ b/internal/i18n/locales/es.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Ver esta respuesta en Codex.", "%s ago": "hace %s", "COMMAND REVIEW": "REVISIÓN DEL COMANDO", "PROCESS REVIEW": "REVISIÓN DEL PROCESO", diff --git a/internal/i18n/locales/et.json b/internal/i18n/locales/et.json index 4ed91a5..57ced53 100644 --- a/internal/i18n/locales/et.json +++ b/internal/i18n/locales/et.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Vaata seda vastust Codexis.", "%s ago": "%s tagasi", "COMMAND REVIEW": "KÄSU HINDAMINE", "PROCESS REVIEW": "PROTSESSI HINDAMINE", diff --git a/internal/i18n/locales/fi.json b/internal/i18n/locales/fi.json index dd9e48c..7f62291 100644 --- a/internal/i18n/locales/fi.json +++ b/internal/i18n/locales/fi.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Katso tämä vastaus Codexissa.", "%s ago": "%s sitten", "COMMAND REVIEW": "KOMENNON ARVIOINTI", "PROCESS REVIEW": "PROSESSIN ARVIOINTI", diff --git a/internal/i18n/locales/fr.json b/internal/i18n/locales/fr.json index 39f219e..368c95f 100644 --- a/internal/i18n/locales/fr.json +++ b/internal/i18n/locales/fr.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Voir cette réponse dans Codex.", "%s ago": "il y a %s", "COMMAND REVIEW": "EXAMEN DE LA COMMANDE", "PROCESS REVIEW": "EXAMEN DU PROCESSUS", diff --git a/internal/i18n/locales/it.json b/internal/i18n/locales/it.json index 313a21a..a44536e 100644 --- a/internal/i18n/locales/it.json +++ b/internal/i18n/locales/it.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Visualizza questa risposta in Codex.", "%s ago": "%s fa", "COMMAND REVIEW": "VERIFICA COMANDO", "PROCESS REVIEW": "VERIFICA PROCESSO", diff --git a/internal/i18n/locales/ja.json b/internal/i18n/locales/ja.json index 8bab3e2..7c9e30c 100644 --- a/internal/i18n/locales/ja.json +++ b/internal/i18n/locales/ja.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "この返信は Codex で確認してください。", "%s ago": "%s前", "COMMAND REVIEW": "コマンド審査", "PROCESS REVIEW": "プロセス審査", diff --git a/internal/i18n/locales/nb.json b/internal/i18n/locales/nb.json index 9708d35..08c6f82 100644 --- a/internal/i18n/locales/nb.json +++ b/internal/i18n/locales/nb.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Se dette svaret i Codex.", "%s ago": "for %s siden", "COMMAND REVIEW": "KOMMANDOVURDERING", "PROCESS REVIEW": "PROSESSVURDERING", diff --git a/internal/i18n/locales/nl.json b/internal/i18n/locales/nl.json index edc03cf..67814b9 100644 --- a/internal/i18n/locales/nl.json +++ b/internal/i18n/locales/nl.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Bekijk dit antwoord in Codex.", "%s ago": "%s geleden", "COMMAND REVIEW": "COMMANDOCONTROLE", "PROCESS REVIEW": "PROCESCONTROLE", diff --git a/internal/i18n/locales/pt-BR.json b/internal/i18n/locales/pt-BR.json index f6d3e23..0f773f0 100644 --- a/internal/i18n/locales/pt-BR.json +++ b/internal/i18n/locales/pt-BR.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Veja esta resposta no Codex.", "%s ago": "há %s", "COMMAND REVIEW": "REVISÃO DO COMANDO", "PROCESS REVIEW": "REVISÃO DO PROCESSO", diff --git a/internal/i18n/locales/pt-PT.json b/internal/i18n/locales/pt-PT.json index a952e61..d5ff323 100644 --- a/internal/i18n/locales/pt-PT.json +++ b/internal/i18n/locales/pt-PT.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Consulte esta resposta no Codex.", "%s ago": "há %s", "COMMAND REVIEW": "REVISÃO DO COMANDO", "PROCESS REVIEW": "REVISÃO DO PROCESSO", diff --git a/internal/i18n/locales/ru.json b/internal/i18n/locales/ru.json index bdaf9be..4e26d61 100644 --- a/internal/i18n/locales/ru.json +++ b/internal/i18n/locales/ru.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Посмотрите этот ответ в Codex.", "%s ago": "%s назад", "COMMAND REVIEW": "ПРОВЕРКА КОМАНДЫ", "PROCESS REVIEW": "ПРОВЕРКА ПРОЦЕССА", diff --git a/internal/i18n/locales/sv.json b/internal/i18n/locales/sv.json index 96331de..83ca064 100644 --- a/internal/i18n/locales/sv.json +++ b/internal/i18n/locales/sv.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Visa det här svaret i Codex.", "%s ago": "för %s sedan", "COMMAND REVIEW": "KOMMANDOGRANSKNING", "PROCESS REVIEW": "PROCESSGRANSKNING", diff --git a/internal/i18n/locales/tr.json b/internal/i18n/locales/tr.json index 801c22d..02bf654 100644 --- a/internal/i18n/locales/tr.json +++ b/internal/i18n/locales/tr.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "Bu yanıtı Codex’te görüntüleyin.", "%s ago": "%s önce", "COMMAND REVIEW": "KOMUT İNCELEMESİ", "PROCESS REVIEW": "SÜREÇ İNCELEMESİ", diff --git a/internal/i18n/locales/zh-Hans.json b/internal/i18n/locales/zh-Hans.json index 51e56de..533f49f 100644 --- a/internal/i18n/locales/zh-Hans.json +++ b/internal/i18n/locales/zh-Hans.json @@ -1,4 +1,5 @@ { + "View this reply in Codex.": "请在 Codex 中查看此回复。", "%s ago": "%s前", "COMMAND REVIEW": "命令审查", "PROCESS REVIEW": "进程审查", diff --git a/internal/ui/model.go b/internal/ui/model.go index da8f780..874cef6 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -2938,10 +2938,16 @@ func refreshTick(after time.Duration) tea.Cmd { return tea.Tick(after, func(now time.Time) tea.Msg { return refreshMsg(now) }) } +func projectMonitorReply(previous, current codex.SessionContext) codex.SessionContext { + previous.ProtectReply(¤t) + current.Text = i18n.SessionText(current.Text, current.ReplyRestricted) + return current +} + func applyMonitorSessionObservation(row *monitorSession, observed codex.LiveUsageSession) { row.name = observed.Name row.modelSettings = observed.ModelSettings - row.preview = observed.Context + row.preview = projectMonitorReply(row.preview, observed.Context) row.steerProgress = append([]codex.SessionSteerProgress(nil), observed.SteerProgress...) row.goal = observed.Goal.Clone() row.readState = observed.ReadState diff --git a/internal/ui/monitor_history.go b/internal/ui/monitor_history.go index 95fb3d5..1ff8009 100644 --- a/internal/ui/monitor_history.go +++ b/internal/ui/monitor_history.go @@ -36,16 +36,6 @@ type monitorHistoryResult struct { err error } -func sameHistoryTurn(a, b codex.SessionContext) bool { - if a.ThreadID != b.ThreadID { - return false - } - if a.TurnID != "" && b.TurnID != "" { - return a.TurnID == b.TurnID - } - return a.ItemID == b.ItemID && a.At.Equal(b.At) && a.Text == b.Text -} - func (m *Model) saveMonitorHistory(id string, h monitorTurnHistory) { m.monitorHistory = maps.Clone(m.monitorHistory) if m.monitorHistory == nil { @@ -54,13 +44,24 @@ func (m *Model) saveMonitorHistory(id string, h monitorTurnHistory) { m.monitorHistory[id] = h } +func (h *monitorTurnHistory) protectPinned(c codex.SessionContext) { + if h.selected != nil && c.ReplyRestricted { + pinned := projectMonitorReply(c, *h.selected) + if pinned != *h.selected { + h.selected = &pinned + } + } +} + func addHistoryTurn(h monitorTurnHistory, c codex.SessionContext) monitorTurnHistory { - if c.Kind != codex.SessionContextReply || c.Streaming || strings.TrimSpace(c.Text) == "" { + if c.Kind != codex.SessionContextReply || c.Streaming || !c.ReplyRestricted && strings.TrimSpace(c.Text) == "" { return h } - c = codex.HistoryExcerpt(c) + c = projectMonitorReply(codex.SessionContext{}, codex.HistoryExcerpt(c)) + h.protectPinned(c) for i, old := range h.turns { - if sameHistoryTurn(old, c) { + if old.SameHistoryTurn(c) { + c = projectMonitorReply(old, c) if old == c { return h } @@ -80,14 +81,18 @@ func addHistoryTurn(h monitorTurnHistory, c codex.SessionContext) monitorTurnHis func (m *Model) observeMonitorHistory() { cloned := false for _, s := range m.monitorSessionData { - if s.preview.Kind == codex.SessionContextReply && !s.preview.Streaming && s.preview.Text != "" { + if s.preview.Kind == codex.SessionContextReply && !s.preview.Streaming && s.preview.HasDisplayText() { h := m.monitorHistory[s.id] + next := h if !h.observedThrough.IsZero() && !s.preview.At.After(h.observedThrough) && - !slices.ContainsFunc(h.turns, func(c codex.SessionContext) bool { return sameHistoryTurn(c, s.preview) }) { - continue + !slices.ContainsFunc(h.turns, func(c codex.SessionContext) bool { return c.SameHistoryTurn(s.preview) }) { + // The selected excerpt can outlive the page it came from. + // Revoke it without putting a stale turn back on that page. + next.protectPinned(s.preview) + } else { + next = addHistoryTurn(h, s.preview) } - next := addHistoryTurn(h, s.preview) - if slices.Equal(h.turns, next.turns) { + if slices.Equal(h.turns, next.turns) && h.selected == next.selected { continue } if !cloned { @@ -124,12 +129,12 @@ func (m *Model) moveMonitorHistory(delta int) { if h.selected != nil { index = -1 // pinned entry may already have fallen outside the cache for i, c := range h.turns { - if sameHistoryTurn(c, *h.selected) { + if c.SameHistoryTurn(*h.selected) { index = i break } } - } else if s, ok := m.contextDetailSession(); ok && len(h.turns) > 0 && sameHistoryTurn(h.turns[len(h.turns)-1], s.preview) { + } else if s, ok := m.contextDetailSession(); ok && len(h.turns) > 0 && h.turns[len(h.turns)-1].SameHistoryTurn(s.preview) { // Live already displays this completed answer; Previous means the // answer before it, not a duplicate of the current screen. index-- @@ -194,17 +199,27 @@ func (m Model) updateMonitorHistory(msg tea.Msg) (Model, tea.Cmd, bool) { h.turns = nil for _, c := range result.turns { for _, previous := range old { - if sameHistoryTurn(c, previous) && c.LatestGuidance == "" { - c.LatestGuidance = previous.LatestGuidance + if c.SameHistoryTurn(previous) { + previous.ProtectReply(&c) + if c.LatestGuidance == "" { + c.LatestGuidance = previous.LatestGuidance + } break } } + if c.ReplyRestricted { + if i := m.monitorSessionIndex(result.id); i >= 0 { + m.monitorSessionData = slices.Clone(m.monitorSessionData) + row := &m.monitorSessionData[i] + row.preview = projectMonitorReply(c, row.preview) + } + } h = addHistoryTurn(h, c) } for _, c := range old { found := false for _, v := range h.turns { - if sameHistoryTurn(c, v) { + if c.SameHistoryTurn(v) { found = true break } @@ -260,12 +275,12 @@ func (m Model) historyButtonsForRows(width, textRows int) []monitorNavigationBut if h.selected != nil { older = false for i, c := range h.turns { - if sameHistoryTurn(c, *h.selected) { + if c.SameHistoryTurn(*h.selected) { older = i > 0 break } } - } else if s, ok := m.contextDetailSession(); ok && len(h.turns) == 1 && sameHistoryTurn(h.turns[0], s.preview) { + } else if s, ok := m.contextDetailSession(); ok && len(h.turns) == 1 && h.turns[0].SameHistoryTurn(s.preview) { older = false } if !older && h.selected == nil { @@ -369,7 +384,7 @@ func (m Model) historyDocument(width int, s monitorSession, c codex.SessionConte h := m.monitorHistory[s.id] heading := i18n.Text("PREVIOUS TURN") for i, v := range h.turns { - if sameHistoryTurn(c, v) { + if c.SameHistoryTurn(v) { heading += i18n.Format(" // %d OF %d", i+1, len(h.turns)) break } @@ -391,7 +406,7 @@ func (m Model) historyDocument(width int, s monitorSession, c codex.SessionConte appendSection(i18n.Text("TASK"), c.CurrentTask, "body") appendSection(i18n.Text("LATEST GUIDANCE"), c.LatestGuidance, "body") replyKind := "prose" - if c.Kind == codex.SessionContextReply && sameHistoryTurn(c, s.preview) && c.Text == s.preview.Text { + if c.Kind == codex.SessionContextReply && c.SameHistoryTurn(s.preview) && c.Text == s.preview.Text { replyKind = "reply" } appendSection(i18n.Text("LAST REPLY"), c.Text, replyKind) diff --git a/internal/ui/monitor_history_test.go b/internal/ui/monitor_history_test.go index b3a9945..254f744 100644 --- a/internal/ui/monitor_history_test.go +++ b/internal/ui/monitor_history_test.go @@ -31,6 +31,71 @@ func historyTestModel() Model { return m } +func TestRestrictedHistoryRevokesPinnedCopyAndLiveMirror(t *testing.T) { + m := historyTestModel() + m.moveMonitorHistory(-1) + c, ok := m.historicalContext() + if !ok || c.Text == "" { + t.Fatal("missing pinned reply") + } + restricted := c + restricted.ReplyRestricted = true + m.monitorSessionData[0].preview = c + m, _, _ = m.updateMonitorHistory(monitorHistoryResult{id: "root-one", turns: []codex.SessionContext{restricted}}) + check := func() { + t.Helper() + if got := m.monitorCopyText("root-one"); got != i18n.Text("View this reply in Codex.") { + t.Fatal("clipboard exposed original", got) + } + } + check() + m.showLiveMonitorHistory() + check() + applyMonitorSessionObservation(&m.monitorSessionData[0], codex.LiveUsageSession{Context: c}) + check() +} + +func TestLegacyHistoryRestrictionReplacesPlaintext(t *testing.T) { + for _, item := range []string{"item", ""} { + for _, source := range []string{"live", "history page"} { + t.Run(source+"/"+item, func(t *testing.T) { + m := historyTestModel() + old := historyContext(7) + old.TurnID, old.ItemID = "", item + decision := old + decision.TurnID, decision.ItemID, decision.Text, decision.ReplyRestricted = "turn", "item", "", true + if item != "" { + decision.At = old.At.Add(time.Second) + } + other := codex.HistoryExcerpt(historyContext(6)) + h := monitorTurnHistory{turns: []codex.SessionContext{other, old}, selected: &old} + m.saveMonitorHistory("root-one", h) + m.monitorSessionData[0].preview = old + if source == "live" { + applyMonitorSessionObservation(&m.monitorSessionData[0], codex.LiveUsageSession{Context: decision}) + m.observeMonitorHistory() + } else { + m, _, _ = m.updateMonitorHistory(monitorHistoryResult{id: "root-one", turns: []codex.SessionContext{other, decision}}) + } + // A lagging local observation must not restore a cached copy. + applyMonitorSessionObservation(&m.monitorSessionData[0], codex.LiveUsageSession{Context: old}) + m.observeMonitorHistory() + h = m.monitorHistory["root-one"] + notice := i18n.Text("View this reply in Codex.") + if len(h.turns) != 2 || h.turns[0].Text != other.Text || !h.turns[1].ReplyRestricted || h.turns[1].Text != notice || + h.selected == nil || !h.selected.ReplyRestricted || m.monitorCopyText("root-one") != notice || + !strings.Contains(ansi.Strip(strings.Join(m.contextDetailLines(100), "\n")), notice) { + t.Fatal("legacy reply still accessible or unrelated turn lost", h) + } + m.showLiveMonitorHistory() + if m.monitorCopyText("root-one") != notice { + t.Fatal("live mirror restored plaintext") + } + }) + } + } +} + func TestMonitorHistoryNavigationPinningAndCopy(t *testing.T) { m := historyTestModel() next, _ := m.Update(tea.KeyPressMsg{Code: tea.KeyLeft, Mod: tea.ModAlt}) @@ -71,6 +136,23 @@ func TestMonitorHistoryNavigationPinningAndCopy(t *testing.T) { } } +func TestEvictedLegacyPinStillHonoursRestriction(t *testing.T) { + m := historyTestModel() + id := "root-one" + pin := historyContext(1) + pin.TurnID, pin.ItemID = "", "item" + h := m.monitorHistory[id] + h.selected, h.turns, h.observedThrough = &pin, h.turns[1:], pin.At.Add(time.Hour) + m.saveMonitorHistory(id, h) + c := pin + c.TurnID, c.ReplyRestricted, c.Text = "1", true, "" + applyMonitorSessionObservation(&m.monitorSessionData[0], codex.LiveUsageSession{Context: c}) + m.observeMonitorHistory() + if got := m.monitorHistory[id]; len(got.turns) != 2 || !got.selected.ReplyRestricted || m.monitorCopyText(id) != i18n.Text("View this reply in Codex.") { + t.Fatal("evicted plaintext still pinned, or stale turn reappeared") + } +} + func TestMonitorHistoryRejectsStreamingAndRemovesCapabilities(t *testing.T) { m := historyTestModel() c := historyContext(4) diff --git a/internal/ui/monitor_read.go b/internal/ui/monitor_read.go index 17b89fd..69ae64d 100644 --- a/internal/ui/monitor_read.go +++ b/internal/ui/monitor_read.go @@ -116,7 +116,7 @@ func (m Model) monitorUnreadResult(id string) (monitorSession, bool) { return monitorSession{}, false } } - if h := m.monitorHistory[id]; h.selected != nil && !sameHistoryTurn(*h.selected, c) { + if h := m.monitorHistory[id]; h.selected != nil && !h.selected.SameHistoryTurn(c) { return monitorSession{}, false } return row, true diff --git a/internal/web/control_test.go b/internal/web/control_test.go index 6d444b1..eef07c7 100644 --- a/internal/web/control_test.go +++ b/internal/web/control_test.go @@ -6,12 +6,15 @@ import ( "errors" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "sync" "testing" "time" "github.com/merefield/codexometer/internal/codex" + "github.com/merefield/codexometer/internal/i18n" ) type actionSource struct { @@ -390,6 +393,36 @@ func TestReplyIsNotHiddenByPreviousApprovalJustification(t *testing.T) { } } +func TestRestrictedRolloutAbsentFromReadOnlyBrowserPayload(t *testing.T) { + home, now := t.TempDir(), time.Now() + dir := filepath.Join(home, "sessions", now.Format("2006/01/02")) + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + log := `{"type":"session_meta","payload":{"id":"session","source":"cli","cwd":"/example"}} +{"type":"event_msg","payload":{"type":"task_started","turn_id":"t"}} +{"type":"event_msg","payload":{"type":"agent_message","phase":"final_answer","message":"fixture plaintext","moderation":{"item_id":"a","moderated":true}}} +{"type":"event_msg","payload":{"type":"task_complete","turn_id":"t","last_agent_message":"fixture plaintext"}} +` + if err := os.WriteFile(filepath.Join(dir, "rollout-"+now.Format("2006-01-02T15-04-05")+"-session.jsonl"), []byte(log), 0600); err != nil { + t.Fatal(err) + } + r, err := codex.NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + live, err := r.FetchTokenUsage(context.Background()) + if err != nil { + t.Fatal(err) + } + s := newStore() + s.live(live, nil, now) + raw, _ := s.snapshot() + if !strings.Contains(string(raw), i18n.Text("View this reply in Codex.")) || strings.Contains(string(raw), "fixture plaintext") { + t.Fatalf("unsafe or empty browser state: %s", raw) + } +} + func TestLiveTaskAndStreamProjection(t *testing.T) { s := newStore() row := codex.LiveUsageSession{ID: "session", Context: codex.SessionContext{Kind: codex.SessionContextReply, Text: "Partial", CurrentTask: "Build\u001b[31m it\u001b[0m", LatestGuidance: "Use Go", Streaming: true}} diff --git a/internal/web/state.go b/internal/web/state.go index 3039542..a367292 100644 --- a/internal/web/state.go +++ b/internal/web/state.go @@ -10,6 +10,7 @@ import ( "github.com/merefield/codexometer/internal/codex" "github.com/merefield/codexometer/internal/confirmation" + "github.com/merefield/codexometer/internal/i18n" "github.com/merefield/codexometer/internal/prose" "github.com/merefield/codexometer/internal/quotagraph" "github.com/merefield/codexometer/internal/statusline" @@ -329,6 +330,7 @@ func (s *store) live(l codex.LiveUsageSnapshot, err error, now time.Time) { s.samples[row.ID] = codex.CaptureUsageSample(s.samples[row.ID], row.TotalTokens, before, now, now, 120) s.previous[row.ID] = row.TotalTokens } + row.Context.Text = i18n.SessionText(row.Context.Text, row.Context.ReplyRestricted) text := row.Context.Text approvalContext := "" if row.Context.Kind == codex.SessionContextApproval {