Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

make the anthropic warning fire once per session lifecycle (#3228)

kt55b4f89ae39b
diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rs
index a98a46b0dc..dbbebadb82 100644
--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs
+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs
@@ -5035,6 +5035,210 @@ async fn tui_attach_to_idle_session_renders_without_input() {
drop(supervisor);
}
+/// The Anthropic subscription ban-risk warning's detection text: the fake
+/// auth resolves it for the e2e (the product text the login-completed arm
+/// draws is the `ANTHROPIC_SUBSCRIPTION_AUTH_WARNING` constant; the two
+/// stay distinguishable).
+const E2E_SUBSCRIPTION_WARNING: &str = "E2E anthropic subscription ban-risk warning";
+
+/// The e2e's fake auth surface: the credential-detection arm resolves a
+/// subscription warning (the product's `getAnthropicSubscriptionAuthWarning`
+/// seam — a stored OAuth credential answers the warning text).
+struct E2ESubscriptionAuth;
+
+impl pa_tui::provider_auth::ProviderAuthCommands for E2ESubscriptionAuth {
+ fn login_options(&self) -> pa_tui::provider_auth::ProviderRowsFuture {
+ Box::pin(async move { Vec::new() })
+ }
+
+ fn logout_options(&self) -> pa_tui::provider_auth::ProviderRowsFuture {
+ Box::pin(async move { Vec::new() })
+ }
+
+ fn login(
+ &self,
+ _provider: &pa_tui::provider_auth::ProviderRow,
+ _api_key: Option<&str>,
+ ) -> pa_tui::provider_auth::ProviderAuthFuture {
+ Box::pin(async move { pa_tui::provider_auth::ProviderAuthOutcome::Cancelled })
+ }
+
+ fn login_on_panel(
+ &self,
+ _provider: &pa_tui::provider_auth::ProviderRow,
+ _panel: pa_tui::auth_panel::AuthPanelHandle,
+ ) -> pa_tui::provider_auth::ProviderAuthFuture {
+ Box::pin(async move { pa_tui::provider_auth::ProviderAuthOutcome::Cancelled })
+ }
+
+ fn logout(
+ &self,
+ _provider: &pa_tui::provider_auth::ProviderRow,
+ ) -> pa_tui::provider_auth::ProviderAuthFuture {
+ Box::pin(async move { pa_tui::provider_auth::ProviderAuthOutcome::Cancelled })
+ }
+
+ fn anthropic_subscription_warning(&self) -> pa_tui::provider_auth::ProviderWarningFuture {
+ Box::pin(async move { Some(E2E_SUBSCRIPTION_WARNING) })
+ }
+}
+
+/// The interactive options for a session on an Anthropic model with the
+/// fake subscription credential surface (the detection arm's two inputs).
+fn subscription_options(
+ supervisor: &Supervisor,
+ dir: &Path,
+ session_dir: &Path,
+ session: pa_tui::interactive::SessionSelection,
+) -> pa_tui::interactive::InteractiveOptions {
+ let mut options = base_options(supervisor, dir, session_dir);
+ options.model_selection = pa_tui::interactive::ModelSelection {
+ provider: Some("anthropic".to_string()),
+ model: Some("claude-test".to_string()),
+ api_key: None,
+ thinking: None,
+ };
+ options.provider_auth = Some(pa_tui::provider_auth::ProviderAuthCommandsHandle(
+ std::sync::Arc::new(E2ESubscriptionAuth),
+ ));
+ options.session = session;
+ options
+}
+
+/// The Anthropic subscription warning fires once per session LIFECYCLE,
+/// not on every open (operator directive 2026-09-29): a new session on an
+/// Anthropic subscription credential draws the ban-risk warning once and
+/// marks the session's persisted gate with the daemon — the marker row is
+/// durable in the session file and `get_state` serves it — and a FRESH
+/// TUI process attaching to that session draws NO warning: the reattach
+/// reads the gate. This is the end-to-end composition of the client gate
+/// and the daemon's marker (the supervisor routes the new
+/// `mark_anthropic_warning_shown` frame to the worker).
+#[tokio::test]
+async fn tui_anthropic_warning_warns_once_then_a_fresh_process_reattaches_silently() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let supervisor = spawn_supervisor(dir.path());
+
+ // The scripted model fixture (the harness's opt-in `model` knob): the
+ // session reports an Anthropic model, so the startup detection arm's
+ // provider gate passes and the fake credential resolves the warning.
+ let script = serde_json::json!({
+ "responses": [],
+ "model": { "id": "claude-test", "provider": "anthropic", "reasoning": false },
+ });
+ std::fs::write(
+ dir.path().join("script.json"),
+ serde_json::to_string(&script).expect("script json"),
+ )
+ .expect("script.json");
+
+ // Run one: the fresh session warns once and marks the gate.
+ let options = subscription_options(
+ &supervisor,
+ dir.path(),
+ &session_dir,
+ pa_tui::interactive::SessionSelection::New,
+ );
+ let plan = pa_tui::interactive::HeadlessPlan {
+ // The exit gate holds the run until the fire-and-forget mark's
+ // write resolves (the worker persists the marker row before its
+ // ack), so the durable-row assertions below read completed state —
+ // no timing window guards them.
+ steps: vec![pa_tui::interactive::HeadlessStep::WaitRender {
+ needle: E2E_SUBSCRIPTION_WARNING.to_string(),
+ timeout_ms: 15_000,
+ }],
+ width: 100,
+ height: 30,
+ };
+ let outcome = run_headless_bounded(options, plan)
+ .await
+ .expect("interactive run one");
+ let rendered = outcome.frames.join("\n");
+ assert!(
+ rendered.contains(E2E_SUBSCRIPTION_WARNING),
+ "the new session drew the ban-risk warning:\n{rendered}"
+ );
+ let session = outcome.active_session_id.clone();
+
+ // The gate is durable: the marker row landed in the session file, and
+ // the daemon's `get_state` serves it open.
+ let file = session_dir.join(format!("{}.jsonl", outcome.session_id));
+ let persisted = std::fs::read_to_string(&file).unwrap_or_else(|_| {
+ let listing = std::fs::read_dir(&session_dir).map_or_else(
+ |error| format!("unreadable: {error}"),
+ |entries| {
+ entries
+ .filter_map(std::result::Result::ok)
+ .map(|entry| entry.file_name().to_string_lossy().to_string())
+ .collect::<Vec<_>>()
+ .join(", ")
+ },
+ );
+ panic!("the session file {} ({listing})", file.display())
+ });
+ assert!(
+ persisted.contains("anthropic_subscription_warning_shown"),
+ "the marker row reached the session file:\n{persisted}"
+ );
+ let (client, _events) = pa_tui::daemon_client::DaemonClient::connect(&supervisor.socket)
+ .await
+ .expect("connect supervisor");
+ let state = client
+ .request_ok(DaemonCommand::GetState {
+ id: None,
+ active_session_id: session.clone(),
+ rest: serde_json::Map::default(),
+ })
+ .await
+ .expect("get_state");
+ client.close();
+ assert_eq!(
+ state.get("anthropicWarningShown"),
+ Some(&serde_json::json!(true)),
+ "the daemon serves the open gate: {state}"
+ );
+
+ // Run two: a FRESH TUI process attaches to the same session — the
+ // gate holds, no warning renders anywhere in the run.
+ let options = subscription_options(
+ &supervisor,
+ dir.path(),
+ &session_dir,
+ pa_tui::interactive::SessionSelection::Attach(session.clone()),
+ );
+ let plan = pa_tui::interactive::HeadlessPlan {
+ // The detection arm is awaited at open, so the first dock frame
+ // proves its decision baked in — the reattach's negative reads
+ // completed state, not a timing window (a late warning cannot
+ // miss the window: the open either warned or skipped before the
+ // frame painted).
+ steps: vec![pa_tui::interactive::HeadlessStep::WaitRender {
+ needle: "subagents".to_string(),
+ timeout_ms: 15_000,
+ }],
+ width: 100,
+ height: 30,
+ };
+ let outcome = run_headless_bounded(options, plan)
+ .await
+ .expect("interactive run two");
+ let rendered = outcome.frames.join("\n");
+ assert!(
+ !rendered.contains(E2E_SUBSCRIPTION_WARNING),
+ "the reattaching process did not re-render the warning:\n{rendered}"
+ );
+ assert!(
+ !rendered.contains("Anthropic subscription auth is active"),
+ "neither arm re-warned on the reattach:\n{rendered}"
+ );
+ assert_eq!(outcome.active_session_id, session, "run two attached by id");
+ drop(supervisor);
+}
+
/// The idle-session event repaint regression: a daemon event that lands on
/// an attached, idle TUI (a `session_info_changed` rename from a second
/// wire client) must repaint the frame on its own — TS `handleEvent`'s
diff --git a/crates/pa-core/src/session/mod.rs b/crates/pa-core/src/session/mod.rs
index 07becfb297..2bc756e563 100644
--- a/crates/pa-core/src/session/mod.rs
+++ b/crates/pa-core/src/session/mod.rs
@@ -18,6 +18,16 @@ use pa_types::JsonMap;
/// Current on-disk session format version.
pub const CURRENT_SESSION_VERSION: u32 = 3;
+/// `custom` entry `customType` marking that this session has already drawn
+/// the Anthropic subscription ban-risk warning (operator directive
+/// 2026-09-29: the warning fires once per session LIFECYCLE, not once per
+/// TUI instance — the shown-state persists in the session's own durable
+/// store, exactly like `thread_goal_state`, so a reattach or a resume of
+/// the same session reads the row and skips the warning; a genuinely new
+/// session, or a fresh auth landing, shows it once). The row's `data` is
+/// `{ "shown": true }`.
+pub const ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE: &str = "anthropic_subscription_warning_shown";
+
/// Entry types that can represent user intent (vs. daemon bookkeeping).
pub const CONTENT_ENTRY_TYPES: [&str; 10] = [
"message",
diff --git a/crates/pa-core/src/session/window.rs b/crates/pa-core/src/session/window.rs
index 1f0d965afe..b5448161e1 100644
--- a/crates/pa-core/src/session/window.rs
+++ b/crates/pa-core/src/session/window.rs
@@ -271,6 +271,10 @@ impl WindowedSessionStore {
let mut compaction_count = 0;
let mut non_bootstrap = false;
let mut goal = None;
+ // The Anthropic subscription warning's once-per-session-lifecycle
+ // gate: set when the walk meets the marked-shown custom row (any
+ // position on the active branch hydrates it, exactly like `goal`).
+ let mut anthropic_warning_shown = false;
let mut window_done = false;
let mut seen = HashSet::new();
let mut thinking = None;
@@ -437,7 +441,10 @@ impl WindowedSessionStore {
"model_change" | "thinking_level_change" | "service_tier_change"
) || (goal.is_none()
&& meta.custom_type.as_deref()
- == Some(crate::goals::GOAL_STATE_CUSTOM_TYPE))))
+ == Some(crate::goals::GOAL_STATE_CUSTOM_TYPE))
+ || (!anthropic_warning_shown
+ && meta.custom_type.as_deref()
+ == Some(crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE))))
{
match serde_json::from_slice::<FileEntry>(&line) {
Ok(entry) => Some(entry),
@@ -450,6 +457,9 @@ impl WindowedSessionStore {
if goal.is_none() {
goal = entry.as_ref().and_then(valid_goal);
}
+ if !anthropic_warning_shown {
+ anthropic_warning_shown = entry.as_ref().is_some_and(valid_warning_shown);
+ }
match entry.as_ref() {
Some(FileEntry::ThinkingLevelChange { payload, .. }) if thinking.is_none() => {
thinking = Some(payload.thinking_level.clone());
@@ -582,6 +592,7 @@ impl WindowedSessionStore {
stats: older_path_stats.clone(),
first_user: first_user_message.clone(),
goal,
+ anthropic_warning_shown,
non_bootstrap,
retained_whole_file: !window_done,
};
@@ -764,6 +775,13 @@ impl WindowedSessionStore {
pub fn goal_state(&self) -> Option<&crate::goals::GoalState> {
self.snapshot.goal.as_ref()
}
+ /// Whether the active branch already carries the Anthropic subscription
+ /// warning's shown marker (the once-per-session-lifecycle gate's
+ /// hydrated read; [`crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE`]).
+ #[must_use]
+ pub fn anthropic_warning_shown(&self) -> bool {
+ self.snapshot.anthropic_warning_shown
+ }
#[must_use]
pub fn has_thinking_level(&self) -> bool {
self.snapshot.thinking_present
@@ -926,6 +944,23 @@ impl WindowedSessionStore {
}
}
+/// Whether `entry` is the session's Anthropic subscription warning shown
+/// marker (the once-per-lifecycle gate's persisted row,
+/// [`crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE`] with
+/// `data.shown == true`).
+fn valid_warning_shown(entry: &FileEntry) -> bool {
+ let FileEntry::Custom { payload, .. } = entry else {
+ return false;
+ };
+ payload.custom_type == crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE
+ && payload
+ .data
+ .as_ref()
+ .and_then(|data| data.get("shown"))
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false)
+}
+
fn valid_goal(entry: &FileEntry) -> Option<crate::goals::GoalState> {
let FileEntry::Custom { payload, .. } = entry else {
return None;
@@ -970,6 +1005,12 @@ pub(super) fn update_snapshot(snapshot: &mut Snapshot, entry: &FileEntry) {
if let Some(goal) = valid_goal(entry) {
snapshot.goal = Some(goal);
}
+ // A live append of the warning marker folds into the retained window's
+ // snapshot the same way, so the sidecar the next reload serves stays
+ // current without a re-walk.
+ if valid_warning_shown(entry) {
+ snapshot.anthropic_warning_shown = true;
+ }
match entry {
FileEntry::ThinkingLevelChange { payload, .. } => {
snapshot.thinking.clone_from(&payload.thinking_level);
diff --git a/crates/pa-core/src/session/window_cache.rs b/crates/pa-core/src/session/window_cache.rs
index e77cd07e41..d8143109f8 100644
--- a/crates/pa-core/src/session/window_cache.rs
+++ b/crates/pa-core/src/session/window_cache.rs
@@ -85,6 +85,14 @@ pub(super) struct Snapshot {
pub stats: WindowStats,
pub first_user: Option<serde_json::Value>,
pub goal: Option<crate::goals::GoalState>,
+ /// Whether the active branch already carries an
+ /// [`crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE`] row: the
+ /// subscription warning's once-per-session-lifecycle gate, hydrated
+ /// from the walk like `goal`. Older sidecars deserialize this as
+ /// `false` (the conservative default: the warning shows again rather
+ /// than being suppressed by a cache that predates the flag).
+ #[serde(default)]
+ pub anthropic_warning_shown: bool,
pub non_bootstrap: bool,
/// The open's walk retained every file row (no compaction boundary
/// was found): the retained window covers the whole session file, so
diff --git a/crates/pa-core/src/session/window_tests.rs b/crates/pa-core/src/session/window_tests.rs
index 9cdfa84610..cbbc4c5f2d 100644
--- a/crates/pa-core/src/session/window_tests.rs
+++ b/crates/pa-core/src/session/window_tests.rs
@@ -297,6 +297,70 @@ fn valid_goal_and_physical_metadata_survive_invalid_newer_branch_goal() {
}
}
+/// The Anthropic subscription warning's once-per-session-lifecycle marker
+/// hydrates from the discarded prefix exactly like the goal row (operator
+/// directive 2026-09-29): the walk parses on-path custom rows beyond the
+/// retained window, so a resume of a long session reads the marker without
+/// paying a full-file parse — and the cached sidecar serves it warm. The
+/// matcher is honest about the payload: a row with `data.shown` false is
+/// not a marker.
+#[test]
+fn anthropic_warning_marker_hydrates_from_before_the_boundary() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("warning.jsonl");
+ let mut rows: Vec<serde_json::Value> = fixture()
+ .lines()
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect();
+ // Put the marker deep in the discarded prefix, on the active chain
+ // (the same rewiring the goal fixture uses: u0 parents to the marker,
+ // the marker parents to the settings row).
+ rows[2]["parentId"] = json!("marked");
+ rows.insert(
+ 2,
+ json!({"type":"custom","id":"marked","parentId":"settings","customType":crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE,"data":{"shown":true}}),
+ );
+ let body: String = rows.into_iter().map(|row| row.to_string() + "\n").collect();
+ std::fs::write(&path, body).unwrap();
+ // Twice: the cold walk, then the warm sidecar reload — both must
+ // serve the hydrated gate.
+ for _ in 0..2 {
+ let store = WindowedSessionStore::open(&path).unwrap().unwrap();
+ assert!(
+ store.anthropic_warning_shown(),
+ "the marker beyond the retained window hydrates the gate"
+ );
+ assert_eq!(store.compaction_count(), 2);
+ }
+ // The plain fixture never hydrates the gate.
+ let plain = dir.path().join("plain.jsonl");
+ std::fs::write(&plain, fixture()).unwrap();
+ let store = WindowedSessionStore::open(&plain).unwrap().unwrap();
+ assert!(!store.anthropic_warning_shown());
+}
+
+/// A `custom` row with the marker's type but `data.shown` false is not the
+/// marker: the gate's payload check keeps a future un-show payload (or a
+/// foreign row borrowing the type) from suppressing the warning.
+#[test]
+fn an_unshown_marker_row_never_hydrates_the_gate() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("unshown.jsonl");
+ let mut rows: Vec<serde_json::Value> = fixture()
+ .lines()
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect();
+ rows[2]["parentId"] = json!("unshown");
+ rows.insert(
+ 2,
+ json!({"type":"custom","id":"unshown","parentId":"settings","customType":crate::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE,"data":{"shown":false}}),
+ );
+ let body: String = rows.into_iter().map(|row| row.to_string() + "\n").collect();
+ std::fs::write(&path, body).unwrap();
+ let store = WindowedSessionStore::open(&path).unwrap().unwrap();
+ assert!(!store.anthropic_warning_shown());
+}
+
#[test]
fn unleased_append_invalidates_without_certification() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/pa-daemon/src/engine/scripted.rs b/crates/pa-daemon/src/engine/scripted.rs
index b6c0af4f79..3b15ce7128 100644
--- a/crates/pa-daemon/src/engine/scripted.rs
+++ b/crates/pa-daemon/src/engine/scripted.rs
@@ -43,6 +43,14 @@ pub struct ScriptedEngine {
compaction: CompactionScript,
branch_summary: CompactionScript,
goal: Option<ScriptedGoal>,
+ /// The script's resolved-model fixture (`{"model": {"id": ...,
+ /// "provider": ..., "reasoning": ...}}`, the connection-state wire
+ /// shape `model_metadata` serves): the harness reports NO model
+ /// unless the script scripts one, so the roster/list surfaces stay
+ /// empty for plain scripts exactly like before (an e2e that needs a
+ /// model-dependent client behavior — the Anthropic subscription
+ /// warning's provider gate — opts in).
+ model: Option<Value>,
}
/// A scripted thread goal (the post-compaction goal-continue fixture):
@@ -169,12 +177,17 @@ impl ScriptedEngine {
.and_then(Value::as_bool)
.unwrap_or(false),
});
+ let model = script
+ .get("model")
+ .filter(|model| !model.is_null())
+ .cloned();
Ok(ScriptedEngine {
responses,
side_question,
compaction,
branch_summary,
goal,
+ model,
})
}
@@ -222,13 +235,16 @@ fn scripted_usage() -> Value {
}
impl SessionEngine for ScriptedEngine {
- /// No model metadata: the TS scripted harness reports no resolved
- /// model on the session summary (`summaryForActiveSession` reads the
- /// agent's model, unset in the harness), so the roster summary and the
- /// CLI `list` table stay empty for scripted sessions — the `faux-1`
- /// id rides on the message rows only.
+ /// The script's model fixture, when one is scripted (`{"model":
+ /// {"id": ..., "provider": ..., "reasoning": ...}}`): absent (the
+ /// plain harness scripts), no model is reported — the TS scripted
+ /// harness reports no resolved model on the session summary
+ /// (`summaryForActiveSession` reads the agent's model, unset in the
+ /// harness), so the roster summary and the CLI `list` table stay
+ /// empty for scripted sessions and the `faux-1` id rides on the
+ /// message rows only.
fn model_metadata(&self) -> Option<Value> {
- None
+ self.model.clone()
}
/// The scripted thread goal's state, or the empty state (no goal
diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rs
index 41981c3587..fe138ec163 100644
--- a/crates/pa-daemon/src/protocol.rs
+++ b/crates/pa-daemon/src/protocol.rs
@@ -147,6 +147,7 @@ pub const KNOWN_COMMAND_TYPES: &[&str] = &[
"get_mcp_connections",
"set_mcp_static_token",
"remove_mcp_connection",
+ "mark_anthropic_warning_shown",
];
/// Parsed client command envelope.
@@ -867,6 +868,9 @@ pub fn command_active_session_id(command: &DaemonCommand) -> Option<&str> {
| DaemonCommand::SetSessionEntryLabel {
active_session_id, ..
}
+ | DaemonCommand::MarkAnthropicWarningShown {
+ active_session_id, ..
+ }
| DaemonCommand::RetryWorker {
active_session_id, ..
}
@@ -1035,6 +1039,7 @@ pub fn command_type_name(command: &DaemonCommand) -> &'static str {
DaemonCommand::GetSystemPrompt { .. } => "get_system_prompt",
DaemonCommand::GetToolDefinition { .. } => "get_tool_definition",
DaemonCommand::SetSessionEntryLabel { .. } => "set_session_entry_label",
+ DaemonCommand::MarkAnthropicWarningShown { .. } => "mark_anthropic_warning_shown",
DaemonCommand::AckResult { .. } => "ack_result",
DaemonCommand::PrepareUpdateRestart { .. } => "prepare_update_restart",
DaemonCommand::CommitUpdateRestart { .. } => "commit_update_restart",
diff --git a/crates/pa-daemon/src/session_store.rs b/crates/pa-daemon/src/session_store.rs
index c4058c7a64..a3a137c7aa 100644
--- a/crates/pa-daemon/src/session_store.rs
+++ b/crates/pa-daemon/src/session_store.rs
@@ -156,6 +156,15 @@ pub struct SessionFile {
pub(crate) leaf_id: Option<String>,
pub(crate) window: Option<SessionWindow>,
pub(crate) lease: Option<std::sync::Arc<crate::lease::SessionLease>>,
+ /// Whether this session has already drawn the Anthropic subscription
+ /// ban-risk warning (the once-per-session-lifecycle gate, operator
+ /// directive 2026-09-29): hydrated from the persisted
+ /// [`pa_core::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE`] row at open
+ /// (full or windowed), flipped by
+ /// [`SessionFile::mark_anthropic_warning_shown`]. Client-facing reads
+ /// serve it through `get_state`
+ /// (`SessionSummary::anthropic_warning_shown`).
+ pub(crate) anthropic_warning_shown: bool,
}
#[derive(Debug, Clone)]
diff --git a/crates/pa-daemon/src/session_store/read.rs b/crates/pa-daemon/src/session_store/read.rs
index 76c6d4fd7b..8ae2804206 100644
--- a/crates/pa-daemon/src/session_store/read.rs
+++ b/crates/pa-daemon/src/session_store/read.rs
@@ -2,6 +2,7 @@
//! streamed and windowed opens, the bounded header-only readers, the
//! file-layout helpers, and the in-memory create.
+use super::view::is_warning_shown_row;
use super::{
anyhow, fold_child_usage_attributions, fs, message_text, BufRead, Context, HashMap, Map, Path,
PathBuf, Read, Result, SessionEntry, SessionFile, SessionHeader, SessionWindow, Value,
@@ -168,6 +169,7 @@ impl SessionFile {
leaf_id: None,
window: None,
lease: None,
+ anthropic_warning_shown: false,
};
for line in lines {
let line = line.with_context(read_context)?;
@@ -181,6 +183,12 @@ impl SessionFile {
}
}
fold_child_usage_attributions(&mut file.entries);
+ // The once-per-lifecycle gate rides the ACTIVE branch, exactly
+ // like the windowed walk below: a marker on an abandoned or
+ // sibling branch never suppresses the warning for the open leaf
+ // (fail-open — an off-path marker must not hide the warning on a
+ // branch that never showed it).
+ file.anthropic_warning_shown = file.branch().iter().copied().any(is_warning_shown_row);
Ok(file)
}
@@ -203,6 +211,10 @@ impl SessionFile {
_ => None,
})
.ok_or_else(|| anyhow!("window has no session header"))?;
+ // The window's walk already hydrated the once-per-session-lifecycle
+ // warning gate from the whole active branch (the row may sit in the
+ // discarded prefix, far outside this store's retained rows).
+ let anthropic_warning_shown = window.anthropic_warning_shown();
let mut file = Self {
path: path.to_owned(),
header,
@@ -211,6 +223,7 @@ impl SessionFile {
leaf_id: None,
window: None,
lease: None,
+ anthropic_warning_shown,
};
// The raw rows are consumed in place: each line String drops as
// soon as its parsed entry joins the store, instead of keeping the
@@ -281,6 +294,11 @@ impl SessionFile {
}
full.leaf_id.clone_from(&self.leaf_id);
full.lease.clone_from(&self.lease);
+ // The merged store's leaf is the window's leaf: re-derive the gate
+ // from the merged ACTIVE branch — the full open's own-leaf answer
+ // can disagree, a post-snapshot marker must hydrate, and an
+ // off-path one must not (the full scan never wins here).
+ full.anthropic_warning_shown = full.branch().iter().copied().any(is_warning_shown_row);
*self = full;
}
@@ -304,6 +322,7 @@ impl SessionFile {
leaf_id: None,
window: None,
lease: None,
+ anthropic_warning_shown: false,
}
}
}
diff --git a/crates/pa-daemon/src/session_store/tests.rs b/crates/pa-daemon/src/session_store/tests.rs
index 229417cd68..f3ede33e6a 100644
--- a/crates/pa-daemon/src/session_store/tests.rs
+++ b/crates/pa-daemon/src/session_store/tests.rs
@@ -257,6 +257,145 @@ fn the_depth_two_chain_reports_the_folded_aggregate() {
assert_eq!(spawn.1.cost.total, pa_types::JsNumber(0.15));
}
+/// The Anthropic subscription warning's once-per-session-lifecycle gate
+/// (operator directive 2026-09-29): [`SessionFile::mark_anthropic_warning_shown`]
+/// persists the marker row durably, the live flag flips, and BOTH reopen
+/// paths (the full [`SessionFile::open`] and the windowed
+/// [`SessionFile::open_windowed`]) hydrate the gate from the file — the
+/// reattach/resume contract: a session that warned once never warns again
+/// however it reopens. A fresh session serves the gate closed.
+#[test]
+fn marking_the_warning_persists_and_both_reopens_hydrate_it() {
+ let dir = temp_dir();
+ let mut session = SessionFile::create("/repo", None, 0);
+ session.append_message(&json!({"role": "user", "content": "hi", "timestamp": 1u64}));
+ let path = dir.join(session_file_name(session.session_id()));
+ session.set_path(path.clone());
+ session.rewrite().unwrap();
+ assert!(
+ !session.anthropic_warning_shown(),
+ "an unmarked session serves the gate closed"
+ );
+
+ session.mark_anthropic_warning_shown().unwrap();
+ assert!(
+ session.anthropic_warning_shown(),
+ "the live flag flipped with the mark"
+ );
+
+ // The durable row: the exact custom entry the lifecycle reads back.
+ let text = fs::read_to_string(&path).unwrap();
+ assert!(
+ text.contains("\"customType\":\"anthropic_subscription_warning_shown\""),
+ "the marker row reached the session file: {text}"
+ );
+
+ // The full reopen (a plain resume) and the windowed reopen (the
+ // create-over-file replay of a long session) both hydrate the gate.
+ let reopened = SessionFile::open(&path).unwrap();
+ assert!(reopened.anthropic_warning_shown());
+ let windowed = SessionFile::open_windowed(&path).unwrap();
+ assert!(windowed.anthropic_warning_shown());
+
+ // A session that never warned stays closed through both opens.
+ let mut fresh = SessionFile::create("/repo", None, 0);
+ let fresh_path = dir.join(session_file_name(fresh.session_id()));
+ fresh.set_path(fresh_path.clone());
+ fresh.rewrite().unwrap();
+ assert!(!SessionFile::open(&fresh_path)
+ .unwrap()
+ .anthropic_warning_shown());
+ assert!(!SessionFile::open_windowed(&fresh_path)
+ .unwrap()
+ .anthropic_warning_shown());
+}
+
+/// The bots' round on the full open (the PR's Medium): the gate rides
+/// the ACTIVE branch — a marker on an abandoned or sibling branch must
+/// never suppress the warning for the open leaf. The windowed walk
+/// already followed the active chain; the full open's all-entries scan
+/// disagreed, so the two reopen paths answered differently on the same
+/// file (and `install_full_history` could overwrite the windowed
+/// answer with the full scan's).
+#[test]
+fn an_off_branch_marker_never_hydrates_the_full_open_gate() {
+ let dir = temp_dir();
+ let row = |id: &str, parent: Option<&str>, message: Value| {
+ json!({
+ "type": "message", "id": id, "parentId": parent,
+ "timestamp": "2026-09-30T00:00:00.000Z",
+ "message": message,
+ })
+ .to_string()
+ };
+ let marker = |id: &str, parent: &str| {
+ json!({
+ "type": "custom", "id": id, "parentId": parent,
+ "timestamp": "2026-09-30T00:00:01.000Z",
+ "customType": "anthropic_subscription_warning_shown",
+ "data": { "shown": true },
+ })
+ .to_string()
+ };
+ let header = |id: &str| {
+ json!({"type": "session", "version": 3, "id": id, "timestamp": "2026-09-30T00:00:00.000Z", "cwd": "/tmp"}).to_string()
+ };
+
+ // The marker hangs off u1 as a SIBLING of the live branch: the open
+ // leaf (the last row, b1) walks u1 -> header and never meets it.
+ let path = dir.join("off-branch-marker.jsonl");
+ std::fs::write(
+ &path,
+ [
+ header("off-1"),
+ row("u1", None, json!({"role": "user", "content": "hi"})),
+ marker("m1", "u1"),
+ row(
+ "b1",
+ Some("u1"),
+ json!({"role": "user", "content": "the sibling turn"}),
+ ),
+ ]
+ .join("\n"),
+ )
+ .unwrap();
+ assert!(
+ !SessionFile::open(&path).unwrap().anthropic_warning_shown(),
+ "an off-branch marker never hydrates the full open's gate"
+ );
+ assert!(
+ !SessionFile::open_windowed(&path)
+ .unwrap()
+ .anthropic_warning_shown(),
+ "the windowed walk agrees: the active chain carries no marker"
+ );
+
+ // The same marker ON the active branch answers open — the sibling
+ // branch's rows stay irrelevant.
+ let path_on = dir.join("on-branch-marker.jsonl");
+ std::fs::write(
+ &path_on,
+ [
+ header("on-1"),
+ row("u1", None, json!({"role": "user", "content": "hi"})),
+ marker("m1", "u1"),
+ row(
+ "b1",
+ Some("m1"),
+ json!({"role": "user", "content": "after the marker"}),
+ ),
+ ]
+ .join("\n"),
+ )
+ .unwrap();
+ assert!(SessionFile::open(&path_on)
+ .unwrap()
+ .anthropic_warning_shown());
+ assert!(SessionFile::open_windowed(&path_on)
+ .unwrap()
+ .anthropic_warning_shown());
+}
+
#[test]
fn creates_and_loads_a_session() {
let dir = temp_dir();
diff --git a/crates/pa-daemon/src/session_store/view.rs b/crates/pa-daemon/src/session_store/view.rs
index f9cb0721e5..cbc2acf60f 100644
--- a/crates/pa-daemon/src/session_store/view.rs
+++ b/crates/pa-daemon/src/session_store/view.rs
@@ -18,7 +18,45 @@ const CONTENT_ENTRY_TYPES: &[&str] = &[
"branch_summary",
];
+/// Whether `entry` is the session's Anthropic subscription warning shown
+/// marker: a `custom` row carrying
+/// [`pa_core::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE`] with
+/// `data.shown == true` (the once-per-session-lifecycle gate's persisted
+/// state, written by [`SessionFile::mark_anthropic_warning_shown`]).
+pub(crate) fn is_warning_shown_row(entry: &SessionEntry) -> bool {
+ entry.type_ == "custom"
+ && entry.fields.get("customType").and_then(Value::as_str)
+ == Some(pa_core::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE)
+ && entry
+ .fields
+ .get("data")
+ .and_then(|data| data.get("shown"))
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+}
+
impl SessionFile {
+ /// Whether this session has already drawn the Anthropic subscription
+ /// ban-risk warning (the once-per-session-lifecycle gate): hydrated from
+ /// the persisted marker row at open, flipped by
+ /// [`SessionFile::mark_anthropic_warning_shown`]; `get_state` serves it
+ /// as `SessionSummary::anthropic_warning_shown`.
+ #[must_use]
+ pub fn anthropic_warning_shown(&self) -> bool {
+ self.anthropic_warning_shown
+ }
+
+ /// Re-hydrate the warning gate from the in-memory entries: the fork
+ /// arms build their stores by ADOPTING copied rows (no file reopen),
+ /// so the gate must agree with the rows the new store itself carries —
+ /// a fork of a warned session answers its own file (the marker row
+ /// rides the copied branch), not the source's live flag.
+ pub(crate) fn hydrate_anthropic_warning_flag(&mut self) {
+ // The active branch, exactly like the reopen paths: a marker on a
+ // sibling row never flips the gate.
+ self.anthropic_warning_shown = self.branch().iter().copied().any(is_warning_shown_row);
+ }
+
#[must_use]
pub fn entries(&self) -> &[SessionEntry] {
&self.entries
diff --git a/crates/pa-daemon/src/session_store/write.rs b/crates/pa-daemon/src/session_store/write.rs
index d94aebcbc5..7224e9b70b 100644
--- a/crates/pa-daemon/src/session_store/write.rs
+++ b/crates/pa-daemon/src/session_store/write.rs
@@ -154,6 +154,30 @@ impl SessionFile {
self.persist_entry_at(entry_type, fields, &crate::util::now_iso())
}
+ /// Durably mark that this session has drawn the Anthropic subscription
+ /// ban-risk warning (the once-per-session-lifecycle gate, operator
+ /// directive 2026-09-29): append the
+ /// [`pa_core::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE`] custom row
+ /// and arm the in-memory flag, so a reattach, a resume, or a worker
+ /// replacement rebuild reads the row and the gate holds.
+ ///
+ /// # Errors
+ ///
+ /// Returns the underlying I/O error when the durable append fails; the
+ /// in-memory flag stays unset then, so the next open re-warns (a lost
+ /// marker costs one repeated warning, never a suppressed one).
+ pub fn mark_anthropic_warning_shown(&mut self) -> Result<()> {
+ self.persist_entry(
+ "custom",
+ json!({
+ "customType": pa_core::session::ANTHROPIC_WARNING_SHOWN_CUSTOM_TYPE,
+ "data": { "shown": true },
+ }),
+ )?;
+ self.anthropic_warning_shown = true;
+ Ok(())
+ }
+
/// Append one entry stamped with the given time. The interrupted-
/// compaction replay re-stamps the supervisor's declaration, so the
/// entry's timestamp is the row's stable identity: a replacement that
diff --git a/crates/pa-daemon/src/session_tree.rs b/crates/pa-daemon/src/session_tree.rs
index 456a0be3fe..07012c989b 100644
--- a/crates/pa-daemon/src/session_tree.rs
+++ b/crates/pa-daemon/src/session_tree.rs
@@ -291,6 +291,7 @@ impl SessionFile {
forked.adopt_entry(entry);
}
}
+ forked.hydrate_anthropic_warning_flag();
forked.rewrite().context("write forked session file")?;
Ok(forked)
}
@@ -371,6 +372,9 @@ impl SessionFile {
self.adopt_entry(entry);
}
}
+ // The kept path decides the gate from here on (the in-memory fork
+ // IS the new session; its entries are the new session's rows).
+ self.hydrate_anthropic_warning_flag();
Ok(())
}
}
@@ -578,6 +582,53 @@ mod tests {
let _ = a;
}
+ /// The Anthropic subscription warning's gate on the fork arms
+ /// (operator directive 2026-09-29): a fork builds its store by
+ /// ADOPTING the copied rows, so its live gate must agree with its own
+ /// file — a fork whose kept path carries the marker answers open (its
+ /// first open draws no second warning), and a fork cut ABOVE the
+ /// marker (the genuinely-new-session case) answers closed.
+ #[test]
+ fn forked_stores_hydrate_the_warning_gate_from_their_own_rows() {
+ let (dir, mut store) = temp_store();
+ let a = message_entry(&mut store, "user", "first");
+ let _ = a;
+ // The marker row, on the session's chain.
+ store.mark_anthropic_warning_shown().expect("mark the gate");
+ let b = message_entry(&mut store, "assistant", "after the marker");
+ assert!(
+ store.anthropic_warning_shown(),
+ "the live store serves its marked gate"
+ );
+
+ // The file-backed fork BELOW the marker: the marker rides the kept
+ // path, so the fork's own file answers open.
+ let forked = store.create_branched_file(&b, dir.path()).unwrap();
+ assert!(
+ forked.anthropic_warning_shown(),
+ "the fork of a marked path serves the gate its rows carry"
+ );
+ let text = std::fs::read_to_string(&forked.path).unwrap();
+ assert!(
+ text.contains("anthropic_subscription_warning_shown"),
+ "the forked file carries the marker row: {text}"
+ );
+
+ // The in-memory fork below the marker serves the same answer.
+ let mut in_memory = store.clone();
+ in_memory.replace_with_branch(Some(&b)).unwrap();
+ assert!(in_memory.anthropic_warning_shown());
+
+ // The fork cut ABOVE the marker is a genuinely new session: the
+ // kept path carries no marker row, and the gate closes.
+ let a = store.entries()[0].id.clone();
+ let forked_above = store.create_branched_file(&a, dir.path()).unwrap();
+ assert!(
+ !forked_above.anthropic_warning_shown(),
+ "a fork cut above the marker answers closed"
+ );
+ }
+
#[test]
fn file_entries_round_trip() {
let (_dir, mut store) = temp_store();
diff --git a/crates/pa-daemon/src/types.rs b/crates/pa-daemon/src/types.rs
index f7319c0010..6dd7b7bde1 100644
--- a/crates/pa-daemon/src/types.rs
+++ b/crates/pa-daemon/src/types.rs
@@ -142,6 +142,14 @@ pub struct SessionSummary {
pub runtime_kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unfinished_action_count: Option<u32>,
+ /// Whether this session has already drawn the Anthropic subscription
+ /// ban-risk warning (Rust-native, operator directive 2026-09-29): the
+ /// once-per-session-lifecycle gate the interactive client reads from
+ /// `get_state` before warning — a reattach or a resume of the same
+ /// session skips, a genuinely new session warns once. Absent when the
+ /// session is still initializing (older workers never emit it).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub anthropic_warning_shown: Option<bool>,
}
/// Port of `SessionActionSnapshot` (core/session-action-store.ts).
diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs
index 2b33edb461..ad8a752243 100644
--- a/crates/pa-daemon/src/worker/commands.rs
+++ b/crates/pa-daemon/src/worker/commands.rs
@@ -121,6 +121,7 @@ impl Worker {
"shutdown" => self.handle_shutdown().await,
"rename" => self.handle_rename("rename", payload),
"set_session_name" => self.handle_rename("set_session_name", payload),
+ "mark_anthropic_warning_shown" => self.handle_mark_anthropic_warning_shown(),
"rename_saved_session" => self.handle_rename_saved_session(payload),
"delete_saved_session" => self.handle_delete_saved_session(payload).await,
"replace_acp_mcp_servers" => self.handle_replace_acp_mcp_servers(payload),
@@ -747,6 +748,31 @@ impl Worker {
response_success(None, "kill", None)
}
+ /// `mark_anthropic_warning_shown` (Rust-native, operator directive
+ /// 2026-09-29): the interactive client reports that it just drew the
+ /// Anthropic subscription ban-risk warning; the worker persists the
+ /// once-per-session-lifecycle marker row (the gate a reattach, a resume,
+ /// or a worker replacement reads). Idempotent — a session already marked
+ /// (or an in-memory session with no file) answers success without a
+ /// second row.
+ fn handle_mark_anthropic_warning_shown(&self) -> DaemonResponse {
+ const NAME: &str = "mark_anthropic_warning_shown";
+ if let Err(response) = self.require_created(NAME) {
+ return response;
+ }
+ let mut core = self.core.lock().unwrap();
+ let Some(store) = core.store.as_mut() else {
+ return response_failure(None, NAME, "Session is still initializing", None);
+ };
+ if store.anthropic_warning_shown() {
+ return response_success(None, NAME, None);
+ }
+ match store.mark_anthropic_warning_shown() {
+ Ok(()) => response_success(None, NAME, None),
+ Err(error) => response_failure(None, NAME, &error.to_string(), None),
+ }
+ }
+
pub(crate) fn handle_rename(&self, command: &str, payload: &Value) -> DaemonResponse {
if let Err(response) = self.require_created(command) {
return response;
diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rs
index 82902dabe8..7fff3f280c 100644
--- a/crates/pa-daemon/src/worker/summary.rs
+++ b/crates/pa-daemon/src/worker/summary.rs
@@ -452,6 +452,8 @@ pub(crate) fn session_summary(
model_fallback_message,
runtime_kind: Some(core.runtime_kind.clone()),
unfinished_action_count: Some(0),
+ anthropic_warning_shown: store
+ .map(crate::session_store::SessionFile::anthropic_warning_shown),
}
}
diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rs
index bcd37a8116..39f614c16b 100644
--- a/crates/pa-daemon/src/worker/tests.rs
+++ b/crates/pa-daemon/src/worker/tests.rs
@@ -51,3 +51,4 @@ mod goal_tests;
mod kill_broadcast_tests;
mod queue_tests;
mod summary_tests;
+mod warning_marker_tests;
diff --git a/crates/pa-daemon/src/worker/tests/warning_marker_tests.rs b/crates/pa-daemon/src/worker/tests/warning_marker_tests.rs
new file mode 100644
index 0000000000..e38c922000
--- /dev/null
+++ b/crates/pa-daemon/src/worker/tests/warning_marker_tests.rs
@@ -0,0 +1,143 @@
+//! The Anthropic subscription warning's once-per-session-lifecycle gate at
+//! the worker surface (operator directive 2026-09-29): the
+//! `mark_anthropic_warning_shown` command persists the marker row through
+//! the session file, `get_state` serves the hydrated flag, a repeated mark
+//! is idempotent, and a fresh worker's open of the same file reads the same
+//! gate — the reattach/resume contract.
+use super::*;
+use crate::engine::{EngineEvent, PromptRequest};
+use crate::worker::WorkerConfig;
+
+/// The scripted harness engine (the create-path seams keep their trait
+/// defaults; the run seams stay inert — this suite drives no turn).
+struct QuietEngine;
+impl SessionEngine for QuietEngine {
+ fn run_prompt(
+ &self,
+ _: usize,
+ _: PromptRequest,
+ _: &dyn Fn() -> bool,
+ _: &mut dyn FnMut(EngineEvent) -> bool,
+ ) {
+ }
+ fn run_side_question(
+ &self,
+ request: crate::engine::SideQuestionRequest,
+ signal: &pa_agent::abort::AbortSignal,
+ sink: &pa_core::session_engine::side_question::SideQuestionSink,
+ ) -> crate::engine::SideQuestionOutcome {
+ crate::engine::ScriptedEngine::default().run_side_question(request, signal, sink)
+ }
+ fn run_compaction(
+ &self,
+ request: crate::engine::CompactionRequest,
+ signal: &pa_agent::abort::AbortSignal,
+ ) -> crate::engine::CompactionOutcome {
+ crate::engine::ScriptedEngine::default().run_compaction(request, signal)
+ }
+ fn run_branch_summary(
+ &self,
+ request: crate::engine::BranchSummaryRequest,
+ signal: &pa_agent::abort::AbortSignal,
+ ) -> crate::engine::BranchSummaryOutcome {
+ crate::engine::ScriptedEngine::default().run_branch_summary(request, signal)
+ }
+ fn rebuild_session_context(
+ &self,
+ _: Vec<pa_types::session::FileEntry>,
+ _: pa_core::session_engine::goal_driver::GoalBranchReload,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+fn worker_in(dir: &std::path::Path, session_id: &str) -> Worker {
+ let mut worker = Worker::new(
+ WorkerConfig {
+ socket_path: dir.join("worker.sock"),
+ supervisor_socket_path: PathBuf::new(),
+ token: "warning-marker-test".into(),
+ worker_instance_id: String::new(),
+ active_session_id: session_id.into(),
+ agent_dir: dir.join("agent"),
+ recovery_journal_path: dir.join("recovery.jsonl"),
+ telemetry_disabled: Some(true),
+ script: Some(json!({"responses":[]})),
+ },
+ None,
+ );
+ worker.engine = std::sync::Arc::new(QuietEngine);
+ worker
+}
+
+#[tokio::test]
+async fn the_mark_command_persists_and_serves_the_gate() {
+ let dir = tempfile::tempdir().unwrap();
+ let session_dir = dir.path().join("sessions");
+ std::fs::create_dir_all(&session_dir).unwrap();
+ let worker = worker_in(dir.path(), "warning-mark");
+
+ let created = worker
+ .dispatch(
+ "create",
+ &json!({"cwd": "/tmp", "sessionDir": session_dir, "name": "gate"}),
+ )
+ .await;
+ assert!(created.success, "create failed: {created:?}");
+
+ // Before the mark the gate is closed: `get_state` carries the flag a
+ // reattach reads.
+ let state = worker.dispatch("get_state", &json!({})).await;
+ assert!(state.success, "{state:?}");
+ assert_eq!(
+ state.data.as_ref().unwrap().get("anthropicWarningShown"),
+ Some(&json!(false)),
+ "an unmarked session reports the gate closed"
+ );
+
+ // The mark: persisted through the session file.
+ let marked = worker
+ .dispatch("mark_anthropic_warning_shown", &json!({}))
+ .await;
+ assert!(marked.success, "the mark failed: {marked:?}");
+ let file = {
+ let core = worker.core.lock().unwrap();
+ core.store.as_ref().expect("created store").path.clone()
+ };
+ let text = std::fs::read_to_string(&file).unwrap();
+ assert!(
+ text.contains("anthropic_subscription_warning_shown"),
+ "the marker row reached the session file: {text}"
+ );
+
+ // `get_state` serves the gate open.
+ let state = worker.dispatch("get_state", &json!({})).await;
+ assert_eq!(
+ state.data.as_ref().unwrap().get("anthropicWarningShown"),
+ Some(&json!(true)),
+ "the marked session reports the gate open"
+ );
+
+ // A repeated mark is idempotent: one marker row, not one per client.
+ let again = worker
+ .dispatch("mark_anthropic_warning_shown", &json!({}))
+ .await;
+ assert!(again.success, "{again:?}");
+ let text = std::fs::read_to_string(&file).unwrap();
+ assert_eq!(
+ text.matches("anthropic_subscription_warning_shown").count(),
+ 1,
+ "the idempotent mark appended no second row"
+ );
+
+ // The reattach/resume contract: a fresh worker's session file opens
+ // with the gate hydrated (the replacement/replay read).
+ let reopened = crate::session_store::SessionFile::open(&file).unwrap();
+ assert!(
+ reopened.anthropic_warning_shown(),
+ "the persisted marker hydrates a fresh open"
+ );
+
+ let killed = worker.dispatch("kill", &json!({})).await;
+ assert!(killed.success, "{killed:?}");
+}
diff --git a/crates/pa-daemon/tests/command_breadth.rs b/crates/pa-daemon/tests/command_breadth.rs
index 6bf83e21d3..7d0fe2090e 100644
--- a/crates/pa-daemon/tests/command_breadth.rs
+++ b/crates/pa-daemon/tests/command_breadth.rs
@@ -522,6 +522,10 @@ const WIRE_FIXTURES: &[(&str, &str)] = &[
"get_mcp_connections",
r#"{"type": "get_mcp_connections", "activeSessionId": "sess"}"#,
),
+ (
+ "mark_anthropic_warning_shown",
+ r#"{"type": "mark_anthropic_warning_shown", "activeSessionId": "sess"}"#,
+ ),
];
/// The accept list is the TS list, in TS order, followed by the Rust-native
@@ -550,6 +554,7 @@ fn known_command_types_match_the_ts_list() {
| "list_kernel_bash"
| "tail_kernel_bash"
| "kill_kernel_bash"
+ | "mark_anthropic_warning_shown"
),
"unexpected non-TS command type: {extra}"
);
diff --git a/crates/pa-tui/src/interactive/headless.rs b/crates/pa-tui/src/interactive/headless.rs
index 6a8bd9a0e6..bd81758977 100644
--- a/crates/pa-tui/src/interactive/headless.rs
+++ b/crates/pa-tui/src/interactive/headless.rs
@@ -98,6 +98,11 @@ pub(super) struct HeadlessSettle {
pub(super) traces_login_pending: bool,
/// An MCP auth flow is pending.
pub(super) mcp_auth_pending: bool,
+ /// The Anthropic subscription warning's `mark_anthropic_warning_shown`
+ /// write is still in flight (fire-and-forget in the product — the run
+ /// must still not end with the durable write un-acked; a lost mark
+ /// costs a repeated warning on the session's next open).
+ pub(super) anthropic_warning_mark_pending: bool,
}
impl HeadlessSettle {
@@ -122,6 +127,7 @@ impl HeadlessSettle {
auth_panel_open: view.auth_panel.is_some(),
traces_login_pending: session.pending_traces_login(),
mcp_auth_pending: session.pending_mcp_auth(),
+ anthropic_warning_mark_pending: session.anthropic_warning_mark_pending(),
}
}
@@ -176,6 +182,9 @@ impl HeadlessSettle {
if self.mcp_auth_pending {
blockers.push("a pending MCP auth flow".to_string());
}
+ if self.anthropic_warning_mark_pending {
+ blockers.push("the Anthropic warning's mark write in flight".to_string());
+ }
blockers
}
}
diff --git a/crates/pa-tui/src/interactive/tests.rs b/crates/pa-tui/src/interactive/tests.rs
index 880a93f192..9b2e68ee28 100644
--- a/crates/pa-tui/src/interactive/tests.rs
+++ b/crates/pa-tui/src/interactive/tests.rs
@@ -248,6 +248,10 @@ fn the_headless_settle_names_every_stuck_member() {
mcp_auth_pending: true,
..Default::default()
},
+ HeadlessSettle {
+ anthropic_warning_mark_pending: true,
+ ..Default::default()
+ },
] {
assert!(!stuck.settled(), "one stuck member holds the gate shut");
assert_eq!(
@@ -280,8 +284,9 @@ fn the_headless_settle_names_every_stuck_member() {
auth_panel_open: true,
traces_login_pending: true,
mcp_auth_pending: true,
+ anthropic_warning_mark_pending: true,
};
- assert_eq!(all.blockers().len(), 12);
+ assert_eq!(all.blockers().len(), 13);
assert!(
all.blockers()
.iter()
diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rs
index 76054cba1c..b6ca9a8ffc 100644
--- a/crates/pa-tui/src/session_ui.rs
+++ b/crates/pa-tui/src/session_ui.rs
@@ -220,9 +220,19 @@ pub(crate) struct SessionUi {
/// The client-process settings seam (`/settings`, `/fullscreen`);
/// the composition root supplies it.
client_settings: Option<std::sync::Arc<dyn crate::client_settings::ClientSettings>>,
- /// The ban-risk warning's once-per-session gate (TS
- /// `anthropicSubscriptionWarningShown`).
+ /// The ban-risk warning's view-local dedup (TS
+ /// `anthropicSubscriptionWarningShown`): this VIEW's own
+ /// once-per-instance gate. The once-per-SESSION-lifecycle gate (the
+ /// operator 2026-09-29 fix for the every-open re-warn) is the
+ /// daemon-side marker read through `get_state` — see
+ /// [`Self::anthropic_warning_already_shown`] and
+ /// [`Self::mark_anthropic_warning_shown`].
anthropic_subscription_warning_shown: bool,
+ /// The in-flight `mark_anthropic_warning_shown` fire-and-forget: set
+ /// when the mark task is spawned, cleared by the task itself at its
+ /// end (ack, error, or bound) — the headless exit gate reads it so a
+ /// scripted run never ends with the durable write still in flight.
+ anthropic_warning_mark_pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// The side-question run currently streaming (TS `activeSideQuestionId`):
/// at most one run per client, exactly like the daemon enforces.
active_side_question_id: Option<String>,
diff --git a/crates/pa-tui/src/session_ui/lifecycle.rs b/crates/pa-tui/src/session_ui/lifecycle.rs
index 80e6e788e7..d36789d9e3 100644
--- a/crates/pa-tui/src/session_ui/lifecycle.rs
+++ b/crates/pa-tui/src/session_ui/lifecycle.rs
@@ -78,6 +78,7 @@ impl SessionUi {
speed_stats: None,
client_settings: options.client_settings.clone(),
anthropic_subscription_warning_shown: false,
+ anthropic_warning_mark_pending: std::sync::Arc::default(),
active_side_question_id: None,
side_question_counter: 0,
share: None,
diff --git a/crates/pa-tui/src/session_ui/notes.rs b/crates/pa-tui/src/session_ui/notes.rs
index 46dee96850..6b6d07024e 100644
--- a/crates/pa-tui/src/session_ui/notes.rs
+++ b/crates/pa-tui/src/session_ui/notes.rs
@@ -2,8 +2,8 @@
//! (TS `showStatus`/`showError`), the tray rebuild, the goal-tray
//! glue, and the anthropic-subscription warning pair that rides it.
use super::{
- format_goal_status, terminal_columns, AgentView, ChatEntry, SessionUi, StatusKind, Value,
- ANTHROPIC_SUBSCRIPTION_AUTH_WARNING,
+ format_goal_status, terminal_columns, AgentView, ChatEntry, DaemonCommand, Duration, Map,
+ SessionUi, StatusKind, Value, ANTHROPIC_SUBSCRIPTION_AUTH_WARNING, UI_REQUEST_TIMEOUT_MS,
};
impl SessionUi {
@@ -117,9 +117,18 @@ impl SessionUi {
/// TS `maybeWarnAboutAnthropicSubscriptionAuth`'s login-completed
/// slice (`onLoginCompleted`): a COMPLETED Anthropic subscription
- /// login draws the ban-risk warning once per session, gated by the
- /// settings toggle (`warnings.anthropicExtraUsage`, TS default
- /// true — an absent settings seam keeps the warning ENABLED).
+ /// login draws the ban-risk warning, gated by the settings toggle
+ /// (`warnings.anthropicExtraUsage`, TS default true — an absent
+ /// settings seam keeps the warning ENABLED).
+ ///
+ /// Operator directive 2026-09-29 (the TS delta this arm carries): a
+ /// fresh auth landing RE-WARNS — the login-completed slice is NOT
+ /// gated by the once-per-session-lifecycle marker (each completed
+ /// subscription login is its own landing, the user just re-proved the
+ /// credential shape), so the per-instance dedup flag drops out of this
+ /// arm's gate. The marker is still marked
+ /// ([`Self::mark_anthropic_warning_shown`]), so a later open of this
+ /// session does not draw a second copy.
/// The warning STACKS — `note_as` would rewrite the just-shown
/// login-success row in place — and carries the same `⚠` prefix as
/// the credential-detection arm.
@@ -129,7 +138,6 @@ impl SessionUi {
view: &mut AgentView,
) {
if provider != crate::provider_auth::ANTHROPIC_PROVIDER_ID
- || self.anthropic_subscription_warning_shown
|| !self
.client_settings
.as_ref()
@@ -138,6 +146,7 @@ impl SessionUi {
return;
}
self.anthropic_subscription_warning_shown = true;
+ self.mark_anthropic_warning_shown();
view.push_entry(ChatEntry::Status {
text: format!("\u{26a0} {ANTHROPIC_SUBSCRIPTION_AUTH_WARNING}"),
kind: StatusKind::Warning,
@@ -156,7 +165,21 @@ impl SessionUi {
/// slice — where the just-settled subscription OAuth login itself
/// proves the shape — lives in
/// [`Self::maybe_warn_anthropic_subscription_auth`]. Both share the
- /// once-per-run gate and the `warnings.anthropicExtraUsage` setting.
+ /// `warnings.anthropicExtraUsage` setting.
+ ///
+ /// Operator directive 2026-09-29 (the TS delta this arm carries): the
+ /// warning fires once per SESSION LIFECYCLE, not once per TUI
+ /// instance — the per-instance flag stays as this view's own dedup,
+ /// but the real gate is the session's persisted marker read from the
+ /// daemon ([`Self::anthropic_warning_already_shown`]): a reattach or
+ /// a resume of a session that already drew the warning skips it, a
+ /// genuinely new session draws it once (and marks it shown). The
+ /// check runs LAST — after the settings toggle, the provider, and
+ /// the credential shape resolved an actual pending warning — so the
+ /// extra `get_state` round trip never happens for sessions that
+ /// would not warn anyway, and it fails OPEN (an absent field from an
+ /// older daemon, or an unreadable state, draws the warning rather
+ /// than suppressing it).
pub(crate) async fn maybe_warn_anthropic_subscription_auth_if_subscribed(
&mut self,
provider: Option<&str>,
@@ -176,7 +199,16 @@ impl SessionUi {
return;
};
if let Some(warning) = auth.0.anthropic_subscription_warning().await {
+ if self.anthropic_warning_already_shown().await {
+ // This session already drew the warning somewhere (this
+ // view attaches to, or resumes, a session that warned
+ // before): hold the view-local gate too, so a later
+ // model switch in THIS instance costs no further reads.
+ self.anthropic_subscription_warning_shown = true;
+ return;
+ }
self.anthropic_subscription_warning_shown = true;
+ self.mark_anthropic_warning_shown();
// The warning STACKS, never rewrites: `note_as` would replace
// the just-shown `Model: ...` or login-success confirmation
// row in place (TS `showStatus`'s back-to-back rewrite); a
@@ -191,6 +223,67 @@ impl SessionUi {
}
}
+ /// The session's persisted once-per-lifecycle gate (operator
+ /// directive 2026-09-29): whether THIS session has already drawn the
+ /// Anthropic subscription ban-risk warning — the daemon's `get_state`
+ /// carries `anthropicWarningShown`, hydrated from the session file's
+ /// marker row, so every view of the session (a reattach, a resume, a
+ /// fresh process) reads the same truth. Best-effort and fail-open: an
+ /// unreadable state, or a field an older daemon never emits, answers
+ /// `false` — the warning shows rather than being suppressed by a
+ /// failed read.
+ async fn anthropic_warning_already_shown(&mut self) -> bool {
+ self.bounded_request(
+ Duration::from_millis(UI_REQUEST_TIMEOUT_MS),
+ DaemonCommand::GetState {
+ id: None,
+ active_session_id: self.active_session_id.clone(),
+ rest: Map::default(),
+ },
+ )
+ .await
+ .ok()
+ .and_then(|state| {
+ state
+ .get("anthropicWarningShown")
+ .and_then(serde_json::Value::as_bool)
+ })
+ .unwrap_or(false)
+ }
+
+ /// Persist the session's once-per-lifecycle marker with the daemon
+ /// (`mark_anthropic_warning_shown`): fire-and-forget and bounded — the
+ /// durable row is never a render dependency; a failed or
+ /// unacknowledged mark costs one repeated warning on this session's
+ /// next open, never a suppressed one.
+ fn mark_anthropic_warning_shown(&self) {
+ let client = self.client.clone();
+ let active_session_id = self.active_session_id.clone();
+ let pending = self.anthropic_warning_mark_pending.clone();
+ pending.store(true, std::sync::atomic::Ordering::Release);
+ tokio::spawn(async move {
+ let _ = tokio::time::timeout(
+ Duration::from_millis(UI_REQUEST_TIMEOUT_MS),
+ client.request_ok(DaemonCommand::MarkAnthropicWarningShown {
+ id: None,
+ active_session_id,
+ rest: Map::default(),
+ }),
+ )
+ .await;
+ pending.store(false, std::sync::atomic::Ordering::Release);
+ });
+ }
+
+ /// Whether the session's `mark_anthropic_warning_shown` write is still
+ /// in flight (the headless exit gate holds the run until the durable
+ /// write resolves — the mark is never a render dependency, but a
+ /// scripted run must not end with it un-acked).
+ pub(crate) fn anthropic_warning_mark_pending(&self) -> bool {
+ self.anthropic_warning_mark_pending
+ .load(std::sync::atomic::Ordering::Acquire)
+ }
+
/// The TS `showError` row: `⚠ Error: <message>` in the error color.
pub(crate) fn error_row(&mut self, message: &str, view: &mut AgentView) {
view.push_entry(ChatEntry::Status {
diff --git a/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs b/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs
new file mode 100644
index 0000000000..a0c14e64e9
--- /dev/null
+++ b/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs
@@ -0,0 +1,659 @@
+//! Headless e2e for the Anthropic subscription warning's once-per-session
+//! LIFECYCLE gate (operator directive 2026-09-29): the warning fired on
+//! every session open because its shown-flag lived on the TUI instance;
+//! the fix persists the shown-state with the session (the daemon's
+//! `anthropicWarningShown` served through `get_state`, marked through
+//! `mark_anthropic_warning_shown`), so a genuinely new session warns once,
+//! a reattach or a resume of a marked session never re-renders it, the
+//! `warnings.anthropicExtraUsage` toggle stays first, and a FRESH auth
+//! landing (a completed subscription login) still re-warns — each landing
+//! is its own event. The daemon half (the marker row, the hydration, the
+//! idempotent handler) is covered by the pa-daemon suites; these runs
+//! verify the client gate over a scripted daemon socket.
+#![cfg(unix)]
+
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+
+use anyhow::Result;
+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+use pa_tui::interactive::{
+ run_interactive, HeadlessPlan, HeadlessStep, InteractiveOptions, ModelSelection,
+ SessionSelection, UiMode,
+};
+use serde_json::{json, Value};
+
+/// The detection arm's warning text (the fake auth's
+/// `anthropic_subscription_warning`): distinguishable from the
+/// login-completed arm's product warning below, so each arm's row is
+/// provably its own.
+const DETECTION_WARNING: &str = "TEST anthropic subscription ban-risk warning";
+
+/// The login-completed arm's row rides the product constant's text (the
+/// `ANTHROPIC_SUBSCRIPTION_AUTH_WARNING` body); the arm renders it with the
+/// same `\u{26a0}` prefix.
+const LOGIN_WARNING_NEEDLE: &str = "Anthropic subscription auth is active";
+
+/// The session gate the scripted daemon serves: `None` answers `get_state`
+/// WITHOUT the field (an older daemon — the client must fail open), the
+/// booleans answer the hydrated gate.
+struct MockSession {
+ active: &'static str,
+ wire: &'static str,
+ name: &'static str,
+ warning_shown: Option<bool>,
+}
+
+impl MockSession {
+ fn new(active: &'static str, warning_shown: Option<bool>) -> Self {
+ Self {
+ active,
+ wire: "sess-1",
+ name: "warning lifecycle session",
+ warning_shown,
+ }
+ }
+}
+
+struct MockSupervisor {
+ listener: UnixListener,
+ session: MockSession,
+ /// The commands the client sent, in arrival order (the mark assertion).
+ commands: Arc<Mutex<Vec<String>>>,
+}
+
+impl MockSupervisor {
+ fn bind(socket: &std::path::Path, session: MockSession) -> Self {
+ MockSupervisor {
+ listener: UnixListener::bind(socket).expect("bind mock socket"),
+ session,
+ commands: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ /// Serve one connection: attach the session, answer the loop's requests.
+ /// `get_state` serves the model's provider plus the lifecycle gate;
+ /// `mark_anthropic_warning_shown` answers success and lands in the
+ /// command log.
+ fn serve(self) {
+ let (stream, _) = self.listener.accept().expect("accept");
+ let write_stream = stream.try_clone().expect("clone mock socket");
+ let mut writer = write_stream;
+ let mut reader = BufReader::new(stream);
+
+ let hello = json!({
+ "type": "daemon_hello",
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "serverCapabilities": [],
+ "clientId": "mock",
+ });
+ write_json(&mut writer, &hello);
+
+ let mut line = String::new();
+ loop {
+ line.clear();
+ match reader.read_line(&mut line) {
+ Ok(0) | Err(_) => break,
+ Ok(_) => {}
+ }
+ let Ok(envelope) = serde_json::from_str::<Value>(line.trim()) else {
+ continue;
+ };
+ let id = envelope.get("id").and_then(Value::as_str).unwrap_or("");
+ let command = envelope.get("command").cloned().unwrap_or(Value::Null);
+ let command_type = command
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ self.commands.lock().unwrap().push(command_type.clone());
+ match command_type.as_str() {
+ "create" => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": "create",
+ "success": true,
+ "data": {
+ "activeSessionId": self.session.active,
+ "id": self.session.active,
+ "sessionId": self.session.wire,
+ "sessionFile": format!("/tmp/{}.jsonl", self.session.wire),
+ },
+ }),
+ );
+ }
+ "attach" => {
+ write_json(&mut writer, &attach_data(id, &self.session));
+ }
+ "get_state" => {
+ // The summary the worker serves: the model's provider
+ // (the detection arm's provider gate) plus the
+ // lifecycle gate the fix reads. `None` models a daemon
+ // that never emits the field (the fail-open degrade).
+ let mut data = json!({
+ "activeSessionId": self.session.active,
+ "sessionId": self.session.wire,
+ "model": { "provider": "anthropic", "modelId": "claude-test" },
+ "isStreaming": false,
+ "isCompacting": false,
+ });
+ if let Some(shown) = self.session.warning_shown {
+ data["anthropicWarningShown"] = json!(shown);
+ }
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": "get_state",
+ "success": true,
+ "data": data,
+ }),
+ );
+ }
+ "mark_anthropic_warning_shown" => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": "mark_anthropic_warning_shown",
+ "success": true,
+ "data": {},
+ }),
+ );
+ }
+ _ => {
+ write_json(
+ &mut writer,
+ &json!({
+ "type": "response",
+ "id": id,
+ "command": command_type,
+ "success": true,
+ "data": {},
+ }),
+ );
+ }
+ }
+ }
+ }
+}
+
+fn write_json(writer: &mut UnixStream, value: &Value) {
+ let mut line = serde_json::to_string(value).expect("serialize mock frame");
+ line.push('\n');
+ writer.write_all(line.as_bytes()).expect("write mock frame");
+ writer.flush().expect("flush mock frame");
+}
+
+/// The slim attach result: one empty session.
+fn attach_data(id: &str, session: &MockSession) -> Value {
+ json!({
+ "type": "response",
+ "id": id,
+ "command": "attach",
+ "success": true,
+ "data": {
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "activeSessionId": session.active,
+ "snapshot": {
+ "activeSessionId": session.active,
+ "summary": { "id": session.active, "cwd": "/tmp" },
+ "state": {
+ "activeSessionId": session.active,
+ "cwd": "/tmp",
+ "sessionId": session.wire,
+ "sessionName": session.name,
+ "model": null,
+ "isStreaming": false,
+ "isCompacting": false,
+ "sessionActions": { "queuedCount": 0, "steering": [], "followUps": [] },
+ },
+ "messages": [],
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ },
+ "client": { "id": "mock", "capabilities": [] },
+ "lastEventSequence": 0,
+ "lastEventCursor": null,
+ },
+ })
+}
+
+/// A minimal settings seam for the harness: every getter returns its TS
+/// default except `warnings.anthropicExtraUsage`, which the store models
+/// (the toggle test flips it).
+#[derive(Default)]
+struct StubSettings {
+ anthropic_extra_usage: bool,
+}
+
+impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn theme(&self) -> Option<String> {
+ None
+ }
+ fn image_model(&self) -> Option<String> {
+ None
+ }
+ fn default_service_tier(&self) -> String {
+ "default".to_string()
+ }
+ fn set_default_service_tier(&self, _tier: &str) -> Result<()> {
+ Ok(())
+ }
+ fn set_theme(&self, _theme: &str) -> Result<()> {
+ Ok(())
+ }
+ fn show_images(&self) -> bool {
+ true
+ }
+ fn set_show_images(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn clear_on_shrink(&self) -> bool {
+ false
+ }
+ fn set_clear_on_shrink(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn show_terminal_progress(&self) -> bool {
+ false
+ }
+ fn set_show_terminal_progress(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn image_auto_resize(&self) -> bool {
+ true
+ }
+ fn set_image_auto_resize(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn block_images(&self) -> bool {
+ false
+ }
+ fn set_block_images(&self, _blocked: bool) -> Result<()> {
+ Ok(())
+ }
+ fn enable_skill_commands(&self) -> bool {
+ true
+ }
+ fn set_enable_skill_commands(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn enable_builtin_skills(&self) -> bool {
+ true
+ }
+ fn set_enable_builtin_skills(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn show_hardware_cursor(&self) -> bool {
+ false
+ }
+ fn set_show_hardware_cursor(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn editor_padding_x(&self) -> u64 {
+ 0
+ }
+ fn set_editor_padding_x(&self, _padding: u64) -> Result<()> {
+ Ok(())
+ }
+ fn autocomplete_max_visible(&self) -> u64 {
+ 5
+ }
+ fn set_autocomplete_max_visible(&self, _max: u64) -> Result<()> {
+ Ok(())
+ }
+ fn quiet_startup(&self) -> bool {
+ false
+ }
+ fn set_quiet_startup(&self, _quiet: bool) -> Result<()> {
+ Ok(())
+ }
+ fn idle_eviction_minutes(&self) -> String {
+ "90".to_string()
+ }
+ fn set_idle_eviction_minutes(&self, _value: &str) -> Result<()> {
+ Ok(())
+ }
+ fn mermaid_rendering_mode(&self) -> String {
+ "streaming".to_string()
+ }
+ fn set_mermaid_rendering_mode(&self, _mode: &str) -> Result<()> {
+ Ok(())
+ }
+ fn tree_filter_mode(&self) -> String {
+ "user-only".to_string()
+ }
+ fn set_tree_filter_mode(&self, _mode: &str) -> Result<()> {
+ Ok(())
+ }
+ fn chat_detail(&self) -> String {
+ "overview".to_string()
+ }
+ fn set_chat_detail(&self, _detail: &str) -> Result<()> {
+ Ok(())
+ }
+ fn warnings_anthropic_extra_usage(&self) -> bool {
+ self.anthropic_extra_usage
+ }
+ fn set_warnings_anthropic_extra_usage(&self, _enabled: bool) -> Result<()> {
+ Ok(())
+ }
+ fn update_channel(&self) -> Option<String> {
+ None
+ }
+ fn set_update_channel(&self, _channel: &str) -> Result<()> {
+ Ok(())
+ }
+ fn effective_update_channel(&self, version: &str) -> String {
+ if version.contains("-beta") {
+ "nightly".to_string()
+ } else {
+ "stable".to_string()
+ }
+ }
+}
+
+/// The fake auth surface: one Anthropic subscription row (the panel
+/// login), and a subscription warning the detection arm resolves.
+struct SubscriptionAuth;
+
+impl pa_tui::provider_auth::ProviderAuthCommands for SubscriptionAuth {
+ fn login_options(&self) -> pa_tui::provider_auth::ProviderRowsFuture {
+ Box::pin(async move {
+ vec![pa_tui::provider_auth::ProviderRow {
+ id: "anthropic".to_string(),
+ name: "Anthropic".to_string(),
+ auth_type: pa_tui::provider_auth::AuthType::Oauth,
+ status: None,
+ flow: pa_tui::provider_auth::AuthFlow::TerminalFlow,
+ configured: false,
+ available: true,
+ }]
+ })
+ }
+
+ fn logout_options(&self) -> pa_tui::provider_auth::ProviderRowsFuture {
+ Box::pin(async move { Vec::new() })
+ }
+
+ fn login(
+ &self,
+ _provider: &pa_tui::provider_auth::ProviderRow,
+ _api_key: Option<&str>,
+ ) -> pa_tui::provider_auth::ProviderAuthFuture {
+ Box::pin(async move { pa_tui::provider_auth::ProviderAuthOutcome::Cancelled })
+ }
+
+ fn login_on_panel(
+ &self,
+ _provider: &pa_tui::provider_auth::ProviderRow,
+ _panel: pa_tui::auth_panel::AuthPanelHandle,
+ ) -> pa_tui::provider_auth::ProviderAuthFuture {
+ Box::pin(async move {
+ pa_tui::provider_auth::ProviderAuthOutcome::Status("Connected to Anthropic".to_string())
+ })
+ }
+
+ fn logout(
+ &self,
+ _provider: &pa_tui::provider_auth::ProviderRow,
+ ) -> pa_tui::provider_auth::ProviderAuthFuture {
+ Box::pin(async move { pa_tui::provider_auth::ProviderAuthOutcome::Cancelled })
+ }
+
+ fn anthropic_subscription_warning(&self) -> pa_tui::provider_auth::ProviderWarningFuture {
+ Box::pin(async move { Some(DETECTION_WARNING) })
+ }
+}
+
+fn options(
+ socket: PathBuf,
+ settings: Arc<StubSettings>,
+ auth: Option<pa_tui::provider_auth::ProviderAuthCommandsHandle>,
+) -> InteractiveOptions {
+ InteractiveOptions {
+ socket_path: socket,
+ cwd: PathBuf::from("/tmp"),
+ session_dir: None,
+ script_path: None,
+ model_selection: ModelSelection::default(),
+ model_catalog: Vec::new(),
+ model_configured_providers: std::collections::HashSet::default(),
+ model_recent_models: Vec::new(),
+ default_thinking_level: None,
+ models: None,
+ no_session: false,
+ session: SessionSelection::New,
+ initial_message: None,
+ show_images: true,
+ fullscreen_mouse: true,
+ theme: "prime".to_string(),
+ code_block_indent: " ".to_string(),
+ tree_filter_mode: String::new(),
+ branch_summary_skip_prompt: false,
+ version: "0.0.0".to_string(),
+ onboarding: None,
+ telemetry_disabled: None,
+ client_auth: None,
+ traces: None,
+ provider_auth: auth,
+ update_commands: None,
+ telemetry: None,
+ keybindings: pa_tui::keybindings::KeybindingsManager::new(),
+ session_rlm_depth: None,
+ prompt_stash: std::sync::Arc::default(),
+ session_has_children: false,
+ restore_dock_focus: false,
+ client_settings: Some(settings),
+ }
+}
+
+/// One headless run against the scripted daemon: the rendered frames plus
+/// every command the client sent.
+fn run_plan(
+ settings: Arc<StubSettings>,
+ session: MockSession,
+ steps: Vec<HeadlessStep>,
+) -> (Vec<String>, Vec<String>) {
+ std::env::remove_var("TMUX");
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("tui.sock");
+ let supervisor = MockSupervisor::bind(&socket, session);
+ let commands = supervisor.commands.clone();
+ let handle = std::thread::spawn(move || supervisor.serve());
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("tokio runtime");
+ let plan = HeadlessPlan {
+ steps,
+ width: 100,
+ height: 30,
+ };
+ let auth = Some(pa_tui::provider_auth::ProviderAuthCommandsHandle(Arc::new(
+ SubscriptionAuth,
+ )));
+ let outcome = runtime
+ .block_on(run_interactive(
+ options(socket, settings, auth),
+ UiMode::Headless(plan),
+ ))
+ .expect("interactive run");
+ handle.join().expect("mock supervisor finished");
+ let sent = commands.lock().unwrap().clone();
+ (outcome.frames, sent)
+}
+
+fn wait_render(needle: &str) -> HeadlessStep {
+ HeadlessStep::WaitRender {
+ needle: needle.to_string(),
+ timeout_ms: 10_000,
+ }
+}
+
+fn enter() -> HeadlessStep {
+ HeadlessStep::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
+}
+
+fn warning_settings() -> Arc<StubSettings> {
+ Arc::new(StubSettings {
+ anthropic_extra_usage: true,
+ })
+}
+
+/// The genuinely-new session (the daemon reports the gate closed): the
+/// startup detection arm draws the warning once and marks the gate with
+/// the daemon — exactly one mark leaves the client.
+#[test]
+fn a_new_session_warns_once_and_marks_the_gate() {
+ let (frames, commands) = run_plan(
+ warning_settings(),
+ MockSession::new("s1", Some(false)),
+ // The exit gate holds the run until the fire-and-forget mark's
+ // write resolves, so the mark count reads completed state — no
+ // timing window guards the assertion.
+ vec![wait_render(DETECTION_WARNING)],
+ );
+ let all = frames.join("\n");
+ assert!(
+ all.contains(DETECTION_WARNING),
+ "the new session drew the ban-risk warning:\n{all}"
+ );
+ let marks = commands
+ .iter()
+ .filter(|command| *command == "mark_anthropic_warning_shown")
+ .count();
+ assert_eq!(
+ marks, 1,
+ "the warned session marked the gate exactly once: {commands:?}"
+ );
+}
+
+/// The reattach/resume read (a fresh TUI instance over a session whose
+/// gate the daemon reports OPEN): no warning renders, and the client never
+/// re-marks. This is the every-open re-warn the directive fixes.
+#[test]
+fn a_marked_session_reattach_never_rewarns() {
+ let (frames, commands) = run_plan(
+ warning_settings(),
+ MockSession::new("s1", Some(true)),
+ // The detection arm is awaited at open, so the first dock frame
+ // proves its decision baked in — the negative reads completed
+ // state, not a timing window.
+ vec![wait_render("subagents")],
+ );
+ let all = frames.join("\n");
+ assert!(
+ !all.contains(DETECTION_WARNING),
+ "the reattached session did not re-render the warning:\n{all}"
+ );
+ assert!(
+ !commands
+ .iter()
+ .any(|command| command == "mark_anthropic_warning_shown"),
+ "the skipped warning never marked: {commands:?}"
+ );
+}
+
+/// The settings toggle stays FIRST: with `warnings.anthropicExtraUsage`
+/// off, a genuinely new session on a subscription credential never warns
+/// and never marks (the daemon-side gate is never asked).
+#[test]
+fn the_settings_toggle_off_never_warns() {
+ let settings = Arc::new(StubSettings {
+ anthropic_extra_usage: false,
+ });
+ let (frames, commands) = run_plan(
+ settings,
+ MockSession::new("s1", Some(false)),
+ vec![wait_render("subagents")],
+ );
+ let all = frames.join("\n");
+ assert!(
+ !all.contains(DETECTION_WARNING),
+ "the disabled toggle kept the warning down:\n{all}"
+ );
+ assert!(
+ !commands
+ .iter()
+ .any(|command| command == "mark_anthropic_warning_shown"),
+ "a suppressed warning never marked: {commands:?}"
+ );
+}
+
+/// The fresh auth landing re-warns: on a session whose gate is OPEN (its
+/// open drew no warning), a COMPLETED Anthropic subscription login still
+/// draws the product warning — the login-completed arm is not gated by
+/// the lifecycle marker, each landing is its own event — and it marks the
+/// gate too.
+#[test]
+fn a_fresh_login_rewarns_on_a_marked_session() {
+ let (frames, commands) = run_plan(
+ warning_settings(),
+ MockSession::new("s1", Some(true)),
+ vec![
+ // The detection arm is awaited at open: the first dock frame
+ // proves it read the open gate and drew nothing.
+ wait_render("subagents"),
+ // The login: the selector mounts, Enter runs the panel flow,
+ // the fake settles it, the login-completed arm draws the
+ // product warning.
+ HeadlessStep::Submit("/login".to_string()),
+ wait_render("Anthropic"),
+ enter(),
+ wait_render(LOGIN_WARNING_NEEDLE),
+ ],
+ );
+ let all = frames.join("\n");
+ assert!(
+ !all.contains(DETECTION_WARNING),
+ "the open's detection arm stayed gated by the session's marker:\n{all}"
+ );
+ assert!(
+ all.contains(LOGIN_WARNING_NEEDLE),
+ "the completed login re-warned with the product warning:\n{all}"
+ );
+ assert!(
+ all.contains("Connected to Anthropic"),
+ "the login outcome's status row rendered:\n{all}"
+ );
+ assert!(
+ commands
+ .iter()
+ .any(|command| command == "mark_anthropic_warning_shown"),
+ "the login arm marked the gate too: {commands:?}"
+ );
+}
+
+/// The degrade: a daemon whose `get_state` carries no
+/// `anthropicWarningShown` field (the pre-fix build) keeps the warning
+/// working — the gate fails OPEN, so an unreadable lifecycle state shows
+/// the warning rather than suppressing it.
+#[test]
+fn a_daemon_without_the_gate_field_fails_open_and_warns() {
+ let (frames, commands) = run_plan(
+ warning_settings(),
+ MockSession::new("s1", None),
+ vec![wait_render(DETECTION_WARNING)],
+ );
+ let all = frames.join("\n");
+ assert!(
+ all.contains(DETECTION_WARNING),
+ "the absent field failed open and the warning showed:\n{all}"
+ );
+ assert!(
+ commands
+ .iter()
+ .any(|command| command == "mark_anthropic_warning_shown"),
+ "the client still marks (the new daemon persists it): {commands:?}"
+ );
+}
diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs
index 78e98b0279..aa5e3f834a 100644
--- a/crates/pa-types/src/daemon/command.rs
+++ b/crates/pa-types/src/daemon/command.rs
@@ -1140,6 +1140,21 @@ pub enum DaemonCommand {
#[serde(flatten)]
rest: JsonMap,
},
+ /// Rust-native client command (operator directive 2026-09-29): the
+ /// interactive client's report that it just drew the Anthropic
+ /// subscription ban-risk warning — the worker persists the session's
+ /// once-per-lifecycle marker row so a reattach, a resume, or a worker
+ /// replacement of the same session skips the warning (the TS gate is
+ /// per interactive-mode instance, so the TS protocol has no
+ /// counterpart; an older daemon rejects the frame and the client
+ /// degrades to its per-instance gate).
+ MarkAnthropicWarningShown {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ id: Option<String>,
+ active_session_id: String,
+ #[serde(flatten)]
+ rest: JsonMap,
+ },
AckResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
@@ -1256,4 +1271,9 @@ mod tests {
r#"{"type":"worker_register","activeSessionId":"abc123def456","sessionId":"s-uuid","socketPath":"/tmp/w.sock","workerInstanceId":"inst-1","token":"tok","pid":4242}"#,
);
}
+
+ #[test]
+ fn mark_anthropic_warning_shown_roundtrip() {
+ rt::<DaemonCommand>(r#"{"type":"mark_anthropic_warning_shown","activeSessionId":"s1"}"#);
+ }
}