Skip to main content

agentmux_srv/server/app_api/
session.rs

1use super::*;
2use crate::ambient;
3use crate::backend::rpc_types::RpcContext;
4
5pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
6    register_session_activity_summary(engine, state);
7    register_session_next_prompt_suggestion(engine, state);
8    register_session_resume_preflight_handler(engine, state);
9    register_session_archive_handler(engine, state);
10    register_session_restore_handler(engine, state);
11    register_session_export_handler(engine, state);
12}
13
14fn register_session_resume_preflight_handler(engine: &Arc<WshRpcEngine>, state: &AppState) {
15    let state = state.clone();
16    engine.register_typed(COMMAND_SESSION_RESUME_PREFLIGHT, move |cmd: CommandSessionResumePreflightData, _ctx| {
17        let state = state.clone();
18        async move { resume_preflight(&state, cmd).await }
19    });
20}
21
22/// `session:resume_preflight` — read-only, mutates nothing, spawns nothing.
23///
24/// The pane calls this on mount so it can say whether the conversation it's
25/// displaying will actually be continued, instead of the user finding out by
26/// typing and watching the transcript clear
27/// (`crate::backend::resume_preflight`'s module doc).
28pub(crate) async fn resume_preflight(
29    state: &AppState,
30    cmd: CommandSessionResumePreflightData,
31) -> Result<SessionResumePreflightResult, String> {
32    let mstore = state.mstore.clone();
33    // Needed to resolve an identity-bound pane's REAL config dir — see
34    // `preflight_input_from_meta`.
35    let id_store = state.id_store.clone();
36    let identity_store = state.identity_store.clone();
37    // The pane's own transcript, for the session its rendered history belongs to.
38    let filestore = state.filestore.clone();
39
40    let block = mstore
41        .must_get::<Block>(&cmd.block_id)
42        .map_err(|e| format!("session:resume_preflight: {e}"))?;
43
44    let bound_config_dir = crate::identity::resolver::resolve_bound_oauth_config_dir(
45        &mstore,
46        &id_store,
47        &identity_store,
48        &cmd.block_id,
49    );
50    let mut input = preflight_input_from_meta(&block.meta, bound_config_dir);
51    let session_id_field = obj::meta_get_string(&block.meta, "agent:session_id_field", "session_id");
52    let block_id = cmd.block_id.clone();
53
54    // Blocking I/O (a transcript tail read, one `is_file`, at most
55    // one `read_dir` of a single directory) off the async runtime's
56    // worker threads — small, but a pane open shouldn't be able to
57    // stall the reactor on a cold or network-backed home directory.
58    let result = tokio::task::spawn_blocking(move || {
59        if input.session_id.is_empty() {
60            input.history_session_id =
61                crate::backend::blockcontroller::persistent::pane_history_session_id(
62                    Some(&filestore),
63                    Some(&mstore),
64                    &block_id,
65                    &session_id_field,
66                )
67                .unwrap_or_default();
68        }
69        // The head of the agent's chain, for the spawn's resume
70        // gate. The UID comes from the pane's agent row, as the
71        // spawn env's does (`persisted_agent_identity`).
72        let uid = mstore
73            .instance_get_active_for_block(&block_id)
74            .ok()
75            .flatten()
76            .map(|instance| instance.id)
77            .filter(|uid| !uid.trim().is_empty());
78        let gfs = crate::backend::agent_session::global_transcript_store();
79        if let (Some(uid), Some(gfs)) = (uid.as_deref().map(str::trim), gfs) {
80            input.chain_head = crate::backend::continuity_segments::chain_head(gfs, uid)
81                .map(crate::backend::continuity_segments::with_legacy_identity);
82            // As the spawn's gate does: a fork with no chain of its
83            // own starts from the agent it was forked from.
84            if input.chain_head.is_none() {
85                input.fork_source = crate::backend::continuity_segments::fork_source_head(&mstore, gfs, uid);
86            }
87        }
88        input.identity_key =
89            crate::identity::account_email::identity_key_from_oauth_dir("claude", &input.config_dir);
90        crate::backend::resume_preflight::preflight(&input)
91    })
92    .await
93    .map_err(|e| format!("session:resume_preflight: {e}"))?;
94
95    tracing::info!(
96        block_id = %cmd.block_id,
97        verdict = %result.verdict.as_str(),
98        duration_ms = result.duration_ms,
99        "session:resume_preflight"
100    );
101
102    Ok(SessionResumePreflightResult {
103        block_id: cmd.block_id,
104        verdict: result.verdict.as_str().to_string(),
105        session_id: result.session_id,
106        recoverable_session_id: result.recoverable_session_id,
107        steps: result
108            .steps
109            .into_iter()
110            .map(|s| ResumePreflightStep {
111                id: s.id.to_string(),
112                label: s.label,
113                ok: s.ok,
114                detail: s.detail,
115                duration_ms: s.duration_ms,
116            })
117            .collect(),
118        duration_ms: result.duration_ms,
119    })
120}
121
122
123/// Lift a block's meta into a [`resume_preflight::PreflightInput`].
124///
125/// **Every default here must match what the real spawn path uses for the
126/// same key**, or the preflight predicts something the spawn won't do —
127/// which is worse than not predicting at all, since the pane then states a
128/// falsehood confidently.
129///
130/// `agent:resume_flag` defaulting to `"--resume"` is that rule doing real
131/// work (#2833): it was `""` here while all five real spawn-path readers
132/// default to `"--resume"` (the persistent and subprocess branches of
133/// `agent_handlers/input.rs`'s `run_agent_turn` and of
134/// `app_api/agent_io.rs`'s `register_agent_send`, plus the eager-resume path
135/// in `eager_resume.rs` — the persistent branch of `run_agent_turn` is the
136/// one that builds `PersistentSpawnConfig` for a pane's message send).
137/// `agent_open.rs` only started writing the key recently, so any Claude pane
138/// created before that and not respawned since has no `agent:resume_flag`
139/// at all: the spawn still attaches `--resume`, but the preflight was
140/// reporting `Unknown` and silently suppressing the notice for exactly the
141/// long-lived panes this feature exists for.
142/// `bound_config_dir` is `identity::resolver::resolve_bound_oauth_config_dir`'s
143/// answer for this block, and **takes precedence over `cmd:env`** whenever
144/// it's `Some` (reagent P1, second pass on PR #2833).
145///
146/// For an agent bound to an OAuth account, the `cmd:env` snapshot is
147/// simply not where the CLI will look: the real spawn resolves the isolated
148/// dir dynamically through `inject_identity_env_async` (via
149/// `agent_handlers/input.rs`'s `build_persistent_spawn_env`, which
150/// `app_api/agent_io.rs`'s `agent_send_spawn_env` also calls), and
151/// `reactive.rs` already documents that "identity-bound agents' real
152/// `CLAUDE_CONFIG_DIR` is never the stale `cmd:env` snapshot"
153/// (`SPEC_SUBAGENT_WATCHER_IDENTITY_BOUND_CONFIG_DIR_2026_08_22.md`).
154/// Checking reachability against the wrong directory is worse than not
155/// checking: it can warn "fresh" at a pane that will resume perfectly well,
156/// or stay quiet at one that's about to lose its conversation.
157///
158/// `None` — not identity-bound, or a non-OAuth provider — keeps the
159/// `cmd:env` read, which is correct for those. Same helper and same
160/// precedence order `subagent_watcher` already uses for this exact
161/// pre-spawn question.
162fn preflight_input_from_meta(
163    meta: &crate::backend::obj::MetaMapType,
164    bound_config_dir: Option<std::path::PathBuf>,
165) -> crate::backend::resume_preflight::PreflightInput {
166    // `CLAUDE_CONFIG_DIR` from the block's own `cmd:env` map — the fallback
167    // when this pane isn't identity-bound.
168    let config_dir = match bound_config_dir {
169        Some(dir) => dir.to_string_lossy().to_string(),
170        None => crate::backend::blockcontroller::cmd_env_of(meta)
171            .remove("CLAUDE_CONFIG_DIR")
172            .unwrap_or_default(),
173    };
174
175    crate::backend::resume_preflight::PreflightInput {
176        resume_flag: obj::meta_get_string(meta, "agent:resume_flag", "--resume"),
177        session_id: obj::meta_get_string(meta, "agent:sessionid", ""),
178        working_dir: obj::meta_get_string(meta, "cmd:cwd", ""),
179        config_dir,
180        history_session_id: String::new(),
181        chain_head: None,
182        identity_key: None,
183        fork_source: None,
184    }
185}
186
187fn register_session_archive_handler(engine: &Arc<WshRpcEngine>, state: &AppState) {
188    let state = state.clone();
189    engine.register_typed(COMMAND_SESSION_ARCHIVE, move |cmd: CommandSessionArchiveData, ctx| {
190        let state = state.clone();
191        async move { archive_session(&state, &ctx, cmd).await }
192    });
193}
194
195pub(crate) async fn archive_session(state: &AppState, ctx: &RpcContext, cmd: CommandSessionArchiveData) -> Result<SessionArchiveResult, String> {
196    let mstore = state.mstore.clone();
197    let filestore = state.filestore.clone();
198    let broker = state.broker.clone();
199
200    crate::server::actor::require_own_block_transcript(ctx, &mstore, &cmd.block_id, "a pane's transcript")?;
201
202    tracing::info!(block_id = %cmd.block_id, "session:archive");
203
204    let archive_dir = session_archive::default_archive_dir()
205        .ok_or_else(|| "cannot determine home directory".to_string())?;
206
207    // The delete and its announcement under the block's
208    // transcript order lock, so no in-flight append's write and
209    // event can interleave with them (review of #3636).
210    let (archived_bytes, archived_at) =
211        crate::backend::transcript::append::with_transcript_order(&cmd.block_id, || {
212            let archived = session_archive::archive_session_output(
213                &mstore,
214                &filestore,
215                &cmd.block_id,
216                &archive_dir,
217            )?;
218            // The block's transcript is gone: open panes resync now.
219            crate::backend::transcript::append::publish_transcript_changed(
220                &broker,
221                &cmd.block_id,
222                crate::backend::mps::FILE_OP_DELETE,
223                &filestore,
224                &mstore,
225            );
226            Ok::<_, String>(archived)
227        })?;
228
229    Ok(SessionArchiveResult { block_id: cmd.block_id, archived_bytes, archived_at })
230}
231
232fn register_session_restore_handler(engine: &Arc<WshRpcEngine>, state: &AppState) {
233    let state = state.clone();
234    engine.register_typed(COMMAND_SESSION_RESTORE, move |cmd: CommandSessionRestoreData, ctx| {
235        let state = state.clone();
236        async move { restore_session(&state, &ctx, cmd).await }
237    });
238}
239
240pub(crate) async fn restore_session(state: &AppState, ctx: &RpcContext, cmd: CommandSessionRestoreData) -> Result<SessionRestoreResult, String> {
241    let mstore = state.mstore.clone();
242    let filestore = state.filestore.clone();
243    let broker = state.broker.clone();
244
245    crate::server::actor::require_own_block_transcript(ctx, &mstore, &cmd.block_id, "a pane's transcript")?;
246
247    tracing::info!(block_id = %cmd.block_id, "session:restore");
248
249    // The replace and its announcement under the block's
250    // transcript order lock (review of #3636): no append's write
251    // and event can land between them, so a pane sees every
252    // event of the old generation, then the replace, then the
253    // new generation's.
254    let restored_bytes =
255        crate::backend::transcript::append::with_transcript_order(&cmd.block_id, || {
256            let restored = session_archive::restore_session_output(
257                &mstore,
258                &filestore,
259                &cmd.block_id,
260            )?;
261            // Replaced content, a new generation: open panes resync now.
262            crate::backend::transcript::append::publish_transcript_changed(
263                &broker,
264                &cmd.block_id,
265                crate::backend::mps::FILE_OP_REPLACE,
266                &filestore,
267                &mstore,
268            );
269            Ok::<_, String>(restored)
270        })?;
271
272    Ok(SessionRestoreResult { block_id: cmd.block_id, restored_bytes })
273}
274
275fn register_session_export_handler(engine: &Arc<WshRpcEngine>, state: &AppState) {
276    let state = state.clone();
277    engine.register_typed(COMMAND_SESSION_EXPORT, move |cmd: CommandSessionExportData, _ctx| {
278        let state = state.clone();
279        async move { export_session(&state, cmd).await }
280    });
281}
282
283pub(crate) async fn export_session(state: &AppState, cmd: CommandSessionExportData) -> Result<SessionExportResult, String> {
284    let mstore = state.mstore.clone();
285    let filestore = state.filestore.clone();
286
287    tracing::info!(block_id = %cmd.block_id, "session:export");
288
289    let (raw_bytes, line_count) = session_archive::read_session_output(
290        &mstore,
291        &filestore,
292        &cmd.block_id,
293    )?;
294
295    let byte_count = raw_bytes.len() as u64;
296    let content = base64::engine::general_purpose::STANDARD.encode(&raw_bytes);
297
298    Ok(SessionExportResult { content, line_count, byte_count })
299}
300
301fn empty_summary_result() -> ActivitySummaryResult {
302    ActivitySummaryResult { summary: String::new(), tokens: None }
303}
304
305fn register_session_activity_summary(engine: &Arc<WshRpcEngine>, state: &AppState) {
306    let state = state.clone();
307    engine.register_typed(COMMAND_SESSION_ACTIVITY_SUMMARY, move |cmd: CommandActivitySummaryData, _ctx| {
308        let state = state.clone();
309        async move { activity_summary(&state, cmd).await }
310    });
311}
312
313pub(crate) async fn activity_summary(state: &AppState, cmd: CommandActivitySummaryData) -> Result<ActivitySummaryResult, String> {
314    let mstore = state.mstore.clone();
315    let filestore = state.filestore.clone();
316
317    // Admit through the Ambient Model Call gateway BEFORE doing any
318    // work: a stale (superseded) request does zero FileStore reads
319    // or prompt building, not just skips the CLI spawn. `admit` queues
320    // the call in the interactive class (`ambient::limits`), raced
321    // against cancellation, so a request superseded while queued for
322    // a permit never spawns the CLI at all. See
323    // docs/specs/SPEC_AMBIENT_MODEL_CALLS_FRAMEWORK_2026_07_03.md.
324    let Some(mut slot) = ambient::call::admit(
325        &ambient::purpose::ACTIVITY_SUMMARY,
326        cmd.block_id.clone(),
327        cmd.generation,
328    )
329    .await
330    else {
331        return Ok(empty_summary_result());
332    };
333
334    let word_target = cmd.word_target.unwrap_or(7).max(3).min(20);
335
336    let block: Block = mstore
337        .get(&cmd.block_id)
338        .map_err(|e| format!("session:activity_summary: {e}"))?
339        .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", cmd.block_id))?;
340
341    // The user's newest message, verbatim — the frontend passes this
342    // directly from the just-submitted TurnStart content, so the
343    // common case needs no FileStore read at all. Without one, the
344    // session's recent activity is read instead, and shown to the
345    // model as activity: it used to be passed off as "The user just
346    // said". See
347    // docs/specs/SPEC_AMBIENT_PANE_TITLE_OVERALL_GOAL_TRACKING_2026_08_17.md.
348    let user_message = cmd
349        .user_message
350        .as_deref()
351        .map(str::trim)
352        .filter(|s| !s.is_empty())
353        .map(str::to_string);
354    let activity = summary_activity(&filestore, &mstore, &cmd.block_id, cmd.activity);
355
356    // A stored value that is not a real title (a placeholder an older build
357    // accepted, such as `(none yet)`) counts as NO title: it is never fed
358    // back into the prompt, so it cannot sustain itself. The first draft
359    // fed it back as the "current title" and told the model to repeat it.
360    let stored_title = obj::meta_get_string(&block.meta, ambient::title::META_TITLE, "");
361    let current_title = if ambient::validate::is_usable_title(&stored_title) {
362        stored_title
363    } else {
364        String::new()
365    };
366
367    // Nothing to anchor a title on AND nothing new to evaluate —
368    // matches the old digest-empty early return.
369    if user_message.is_none() && activity.is_none() && current_title.is_empty() {
370        slot.abandon(ambient::outcome::Outcome::EmptyDigest);
371        return Ok(empty_summary_result());
372    }
373
374    let Some(target) = ambient::call::CliTarget::from_meta(&block.meta) else {
375        tracing::debug!(block_id = %cmd.block_id, "session:activity_summary: no CLI path in meta");
376        return Ok(empty_summary_result());
377    };
378
379    let refresh = cmd.refresh.unwrap_or(false);
380    let prompt = ambient::prompt::build_session_title_prompt(
381        prompt_anchor(&current_title, refresh),
382        user_message.as_deref(),
383        activity.as_deref(),
384        word_target,
385    );
386    let limits = ambient::validate::title_limits(word_target);
387    let reply = slot
388        .run_held(&target, &prompt, |raw| {
389            ambient::reply::judge_line(raw, |t| ambient::validate::accept_line(t, &limits))
390        })
391        .await;
392
393    let stored = store_summary_title(state, &slot, &cmd.block_id, &reply.text, cmd.turn, refresh);
394    Ok(ActivitySummaryResult { summary: if stored { reply.text } else { String::new() }, tokens: reply.tokens })
395}
396
397/// Stored here, not by the pane: one writer with the recovery sweep,
398/// in one transaction, so a rewording never replaces the title and
399/// neither writer overwrites what the other stored while its call ran
400/// (`ambient::title`). The slot is held until the write, so a newer
401/// message's request, admitted while this one ran, supersedes it and
402/// this older title is not stored after the newer one.
403fn store_summary_title(
404    state: &AppState,
405    slot: &ambient::call::Slot,
406    block_id: &str,
407    title: &str,
408    turn: Option<u32>,
409    refresh: bool,
410) -> bool {
411    if title.is_empty() {
412        return false;
413    }
414    let still_current = || !slot.is_superseded();
415    match ambient::title::store_title(&state.mstore, block_id, title, ambient::title::Replace::IfNews, turn, still_current) {
416        Ok(true) => {
417            crate::backend::blockcontroller::core::broadcast_block_update(&state.mstore, &state.event_bus, block_id);
418            true
419        }
420        // A refresh judged the session afresh and found the same goal: the title
421        // is confirmed as still right, so it stops being asked about at every message.
422        // The pane reads the renewed stamp from its block meta, which only a broadcast updates.
423        Ok(false) if refresh => {
424            match ambient::title::confirm_title(&state.mstore, block_id, title, turn, still_current) {
425                Ok(true) => crate::backend::blockcontroller::core::broadcast_block_update(&state.mstore, &state.event_bus, block_id),
426                Ok(false) => {}
427                Err(e) => tracing::warn!(block_id = %block_id, error = %e, "session:activity_summary: could not confirm the title"),
428            }
429            false
430        }
431        Ok(false) => false,
432        Err(e) => {
433            tracing::warn!(block_id = %block_id, error = %e, "session:activity_summary: could not store the title");
434            false
435        }
436    }
437}
438
439/// The session's recent activity for a title call: what the pane sent from its
440/// document (any provider), else the output file's tail (Claude-shaped streams
441/// only). Read with the user's message too, not only when there is none: a short
442/// status question in the middle of new work says nothing about that work, and a
443/// title built on the message alone stays on the old topic.
444fn summary_activity(
445    filestore: &crate::backend::storage::filestore::FileStore,
446    mstore: &crate::backend::storage::store::Store,
447    block_id: &str,
448    pane_entries: Option<Vec<String>>,
449) -> Option<String> {
450    pane_entries
451        .filter(|entries| !entries.is_empty())
452        .and_then(|entries| ambient::digest::activity_from_entries(block_id, entries))
453        .map(|activity| activity.text)
454        .or_else(|| ambient::digest::read_recent_activity_digest(filestore, mstore, block_id))
455}
456
457/// The title the model is shown as current. None on a refresh: with nothing to
458/// anchor on, "the current title still fits, SKIP" is not the easy answer
459/// (`build_session_title_prompt` writes the create form for an empty one).
460fn prompt_anchor(current_title: &str, refresh: bool) -> &str {
461    if refresh {
462        ""
463    } else {
464        current_title
465    }
466}
467
468fn empty_suggestion_result() -> NextPromptSuggestionResult {
469    NextPromptSuggestionResult { suggestion: String::new(), tokens: None }
470}
471
472fn register_session_next_prompt_suggestion(engine: &Arc<WshRpcEngine>, state: &AppState) {
473    let state = state.clone();
474    engine.register_typed(COMMAND_SESSION_NEXT_PROMPT_SUGGESTION, move |cmd: CommandNextPromptSuggestionData, _ctx| {
475        let state = state.clone();
476        async move { next_prompt_suggestion(&state, cmd).await }
477    });
478}
479
480pub(crate) async fn next_prompt_suggestion(state: &AppState, cmd: CommandNextPromptSuggestionData) -> Result<NextPromptSuggestionResult, String> {
481    let mstore = state.mstore.clone();
482    let filestore = state.filestore.clone();
483
484    // Same admission discipline and interactive class as activity_summary.
485    // Ghost text has a sharper failure mode than the read-only summary
486    // (a stale suggestion can put words in the user's mouth), so
487    // admitting before any work matters just as much here.
488    let Some(slot) = ambient::call::admit(
489        &ambient::purpose::NEXT_PROMPT_SUGGESTION,
490        cmd.block_id.clone(),
491        cmd.generation,
492    )
493    .await
494    else {
495        return Ok(empty_suggestion_result());
496    };
497
498    let block: Block = mstore
499        .get(&cmd.block_id)
500        .map_err(|e| format!("session:next_prompt_suggestion: {e}"))?
501        .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", cmd.block_id))?;
502
503    // The pane's own translated conversation when it sent one (any
504    // provider); otherwise the output file, which only Claude-shaped
505    // streams can be read from.
506    // Pane activity that ends at the user's message was taken before the
507    // reply reached the pane's document (the turn-end edge can lead the
508    // last nodes); the file may already hold the reply.
509    let activity = match cmd.activity.filter(|entries| !entries.is_empty()) {
510        Some(entries) => ambient::digest::activity_from_entries(&cmd.block_id, entries)
511            .filter(|a| a.ending != ambient::digest::TurnEnding::UserLast)
512            .or_else(|| ambient::digest::read_recent_activity(&filestore, &mstore, &cmd.block_id)),
513        None => ambient::digest::read_recent_activity(&filestore, &mstore, &cmd.block_id),
514    };
515    let Some(activity) = activity else {
516        slot.abandon(ambient::outcome::Outcome::EmptyDigest);
517        return Ok(empty_suggestion_result());
518    };
519    // The turn ended waiting for the user (a question, a tool that asks
520    // them) or before the assistant answered: there is no next
521    // instruction to predict, so no call. Asked to judge this itself,
522    // the model wrote prose about declining, and it reached the composer.
523    if activity.ending != ambient::digest::TurnEnding::Statement {
524        slot.abandon(ambient::outcome::Outcome::Gated);
525        return Ok(empty_suggestion_result());
526    }
527
528    let Some(target) = ambient::call::CliTarget::from_meta(&block.meta) else {
529        tracing::debug!(block_id = %cmd.block_id, "session:next_prompt_suggestion: no CLI path in meta");
530        return Ok(empty_suggestion_result());
531    };
532
533    let prompt = ambient::prompt::build_next_prompt_prompt(&activity.text);
534    let reply = slot
535        .run(&target, &prompt, |raw| ambient::reply::judge_line(raw, ambient::validate::accept_next_prompt))
536        .await;
537
538    // The tokens were spent either way, so they are still reported;
539    // only the text is withheld when it is not a usable next prompt.
540    Ok(NextPromptSuggestionResult { suggestion: reply.text, tokens: reply.tokens })
541}
542
543
544#[cfg(test)]
545mod preflight_input_tests {
546    use super::preflight_input_from_meta;
547
548    // ── resume-preflight meta extraction (reagent P1 on PR #2833) ────────
549    //
550    // The divergence these guard: the preflight must read every meta key with
551    // the SAME default the real spawn path uses, or it predicts a spawn that
552    // won't happen. Unit-testing `preflight` itself (as the rest of the suite
553    // does) can't catch that — it takes an explicit `PreflightInput`, so the
554    // extraction defaults are exactly the part those tests skip.
555
556    fn meta_of(pairs: &[(&str, serde_json::Value)]) -> crate::backend::obj::MetaMapType {
557        let mut m = crate::backend::obj::MetaMapType::new();
558        for (k, v) in pairs {
559            m.insert(k.to_string(), v.clone());
560        }
561        m
562    }
563
564    /// The regression itself: a Claude pane predating `agent_open.rs` writing
565    /// `agent:resume_flag`. The spawn attaches `--resume` via its own default,
566    /// so the preflight must not read this as "provider can't resume" and go
567    /// silent.
568    #[test]
569    fn absent_resume_flag_defaults_to_the_same_value_the_spawn_path_uses() {
570        let input = preflight_input_from_meta(&meta_of(&[]), None);
571        assert_eq!(
572            input.resume_flag, "--resume",
573            "must match agent_handlers/input.rs:400's default, or the preflight              reports Unknown for panes whose spawn really will --resume",
574        );
575    }
576
577    /// A provider that genuinely has no resume flag writes an explicit empty
578    /// string; that must survive as empty rather than being back-filled with
579    /// the default, or the preflight would claim resume support that isn't there.
580    #[test]
581    fn an_explicitly_empty_resume_flag_is_preserved_not_defaulted() {
582        let input = preflight_input_from_meta(&meta_of(&[("agent:resume_flag", serde_json::json!(""))]), None);
583        assert_eq!(input.resume_flag, "");
584    }
585
586    #[test]
587    fn an_explicit_resume_flag_is_read_verbatim() {
588        let input = preflight_input_from_meta(&meta_of(&[("agent:resume_flag", serde_json::json!("-r"))]), None);
589        assert_eq!(input.resume_flag, "-r");
590    }
591
592    #[test]
593    fn config_dir_is_read_out_of_the_cmd_env_map() {
594        let input = preflight_input_from_meta(&meta_of(&[(
595            "cmd:env",
596            serde_json::json!({ "CLAUDE_CONFIG_DIR": "/home/dev/.claude", "OTHER": "x" }),
597        )]), None);
598        assert_eq!(input.config_dir, "/home/dev/.claude");
599    }
600
601    /// No `cmd:env` at all, or no `CLAUDE_CONFIG_DIR` within it, must yield an
602    /// empty config dir — `preflight` turns that into `Unknown` and stays
603    /// silent, which is the correct posture when there's nowhere to look.
604    #[test]
605    fn a_missing_config_dir_is_empty_rather_than_a_guess() {
606        assert_eq!(preflight_input_from_meta(&meta_of(&[]), None).config_dir, "");
607        assert_eq!(
608            preflight_input_from_meta(&meta_of(&[("cmd:env", serde_json::json!({ "PATH": "/usr/bin" }))]), None)
609                .config_dir,
610            ""
611        );
612        assert_eq!(
613            preflight_input_from_meta(&meta_of(&[("cmd:env", serde_json::json!("not-an-object"))]), None).config_dir,
614            ""
615        );
616    }
617
618    #[test]
619    fn session_id_and_working_dir_default_to_empty() {
620        let input = preflight_input_from_meta(&meta_of(&[]), None);
621        assert_eq!(input.session_id, "");
622        assert_eq!(input.working_dir, "");
623
624        let input = preflight_input_from_meta(&meta_of(&[
625            ("agent:sessionid", serde_json::json!("sid-1")),
626            ("cmd:cwd", serde_json::json!("/work/dir")),
627        ]), None);
628        assert_eq!(input.session_id, "sid-1");
629        assert_eq!(input.working_dir, "/work/dir");
630    }
631
632    /// reagent P1 (second pass): an identity-bound pane's real config dir
633    /// comes from the identity resolver, never the `cmd:env` snapshot, so a
634    /// resolved dir must win outright — including when `cmd:env` disagrees.
635    #[test]
636    fn a_bound_identity_config_dir_overrides_the_cmd_env_snapshot() {
637        let meta = meta_of(&[(
638            "cmd:env",
639            serde_json::json!({ "CLAUDE_CONFIG_DIR": "/stale/from/spawn/snapshot" }),
640        )]);
641        let input = preflight_input_from_meta(
642            &meta,
643            Some(std::path::PathBuf::from("/identities/acct-7/claude")),
644        );
645        assert_eq!(
646            input.config_dir, "/identities/acct-7/claude",
647            "the identity-resolved dir is where the CLI will actually look",
648        );
649    }
650
651    /// …and a resolved dir must still win when there's no `cmd:env` at all.
652    #[test]
653    fn a_bound_identity_config_dir_is_used_with_no_cmd_env_present() {
654        let input = preflight_input_from_meta(
655            &meta_of(&[]),
656            Some(std::path::PathBuf::from("/identities/acct-9/claude")),
657        );
658        assert_eq!(input.config_dir, "/identities/acct-9/claude");
659    }
660
661    /// `None` means "not identity-bound, or not an OAuth provider" — for
662    /// those the `cmd:env` snapshot IS what the spawn uses, so it must still
663    /// be read rather than dropped.
664    #[test]
665    fn an_unbound_pane_still_falls_back_to_cmd_env() {
666        let meta = meta_of(&[("cmd:env", serde_json::json!({ "CLAUDE_CONFIG_DIR": "/home/dev/.claude" }))]);
667        assert_eq!(preflight_input_from_meta(&meta, None).config_dir, "/home/dev/.claude");
668    }
669}
670
671#[cfg(test)]
672#[path = "session_tests.rs"]
673mod tests;