返回 CodeWhale
resume.rs
根目录 / crates / tui / src / commands / groups / session / resume.rs
1 //! `/resume` command — portable handler over the session-control facet.
2 //!
3 //! The handler owns route selection and the exact per-route messages/actions;
4 //! filesystem, manager, parser, and picker machinery stay behind the facet's
5 //! `resolve_resume_source` / `import_session_file` / `open_resume_picker`
6 //! delegates (transition blocking is checked before any picker or I/O).
7
8 use super::{CommandResult, transition_blocked_message};
9 use codewhale_command_contract::facets::{CommandSessionControlContext, ResumeSource};
10 use codewhale_command_contract::handler::{CommandContexts, CommandHandler};
11 use codewhale_command_contract::metadata::{
12 CommandInfo as ContractInfo, RegisterCommand as ContractRegisterCommand,
13 };
14
15 pub(in crate::commands) struct ResumeCmd;
16
17 pub(in crate::commands) const CONTRACT_INFO: ContractInfo = ContractInfo {
18 name: "resume",
19 aliases: &["r"],
20 usage: "/resume [session_id|path/to/export.json]",
21 description_key: "cmd_resume_description",
22 };
23
24 impl ContractRegisterCommand<CommandResult> for ResumeCmd {
25 fn info() -> &'static ContractInfo {
26 &CONTRACT_INFO
27 }
28 fn handler() -> CommandHandler<CommandResult> {
29 CommandHandler::Contextual {
30 capabilities: codewhale_command_contract::handler::CommandCapabilities::SESSION_CONTROL,
31 handler: resume_contextual,
32 }
33 }
34 }
35
36 pub(in crate::commands) fn resume_contextual(
37 contexts: CommandContexts<'_>,
38 arg: Option<&str>,
39 ) -> CommandResult {
40 let mut parts = contexts.into_parts();
41 let Some(control) = parts.control.as_deref_mut() else {
42 return CommandResult::error("Command capability unavailable: session_control".to_string());
43 };
44 resume_portable(control, arg)
45 }
46
47 pub(in crate::commands) fn resume_portable(
48 control: &mut dyn CommandSessionControlContext,
49 arg: Option<&str>,
50 ) -> CommandResult {
51 if control.transition_blocked() {
52 return CommandResult::error(transition_blocked_message(
53 "resume",
54 &control.transition_blockers(),
55 ));
56 }
57 let Some(raw) = arg.map(str::trim).filter(|s| !s.is_empty()) else {
58 control.open_resume_picker();
59 return CommandResult::ok();
60 };
61 match control.resolve_resume_source(raw) {
62 Ok(ResumeSource::File(path)) => match control.import_session_file(path) {
63 Ok(receipt) => CommandResult::with_message_and_action(
64 format!(
65 "Imported foreign session as {} ({} entries, leaf {})",
66 receipt.truncated_id, receipt.entry_count, receipt.leaf_display
67 ),
68 codewhale_command_contract::outcome::SessionAction::SyncSession(receipt.sync),
69 ),
70 Err(error) => CommandResult::error(error),
71 },
72 Ok(ResumeSource::Imported(receipt)) => CommandResult::with_message_and_action(
73 format!(
74 "Imported foreign session as {} ({} entries, leaf {})",
75 receipt.truncated_id, receipt.entry_count, receipt.leaf_display
76 ),
77 codewhale_command_contract::outcome::SessionAction::SyncSession(receipt.sync),
78 ),
79 Ok(ResumeSource::Session {
80 load_path,
81 truncated_id,
82 title,
83 }) => match load_path {
84 Some(path) => CommandResult::action(
85 codewhale_command_contract::outcome::SessionAction::LoadSession(path),
86 ),
87 None => CommandResult::message(format!("Resuming session {truncated_id} ({title})")),
88 },
89 Ok(ResumeSource::NotFound { raw, error }) => CommandResult::error(format!(
90 "Cannot resume '{raw}': {error}\nUse `/resume` without args to pick, or pass a session id, or a path to an exported session JSON."
91 )),
92 Err(error) => CommandResult::error(error),
93 }
94 }
95
96 #[cfg(test)]
97 mod tests {
98 use super::super::control_test_support::message;
99 use super::*;
100 use codewhale_command_contract::facets::ResumeImportReceipt;
101 use std::path::PathBuf;
102
103 fn control_fake() -> super::super::control_test_support::FakeControl {
104 super::super::control_test_support::FakeControl::default()
105 }
106
107 #[test]
108 fn resume_transition_blocking_wins_before_any_route() {
109 let mut fake = control_fake();
110 fake.blocked = true;
111 fake.blockers = vec!["the session is still busy with the current turn".to_string()];
112 let result = resume_portable(&mut fake, Some("anything"));
113 assert!(result.is_error);
114 assert_eq!(
115 message(&result),
116 "Cannot resume while runtime work is active:\n • the session is still busy with the current turn\n\nWait for the work to finish, or stop what you can: Ctrl+C stops a running turn, and /jobs cancel-all cancels running shell jobs."
117 );
118 assert_eq!(
119 fake.calls.borrow().as_slice(),
120 ["transition_blocked", "transition_blockers"],
121 "the gate executes exactly once before route work, then names its blockers"
122 );
123 }
124
125 #[test]
126 fn resume_bare_opens_the_picker() {
127 let mut fake = control_fake();
128 let result = resume_portable(&mut fake, None);
129 assert!(!result.is_error);
130 assert!(result.action.is_none());
131 assert!(result.message.is_none());
132 assert_eq!(
133 fake.calls.borrow().as_slice(),
134 ["transition_blocked", "open_resume_picker"]
135 );
136 }
137
138 #[test]
139 fn resume_file_and_import_routes_compose_exact_receipts() {
140 let mut fake = control_fake();
141 fake.resume = Some(Ok(ResumeSource::File(PathBuf::from("/tmp/import.json"))));
142 fake.import = Some(Ok(ResumeImportReceipt {
143 truncated_id: "imp-9".to_string(),
144 entry_count: 12,
145 leaf_display: "leaf-3".to_string(),
146 sync: super::super::lifecycle_test_support::sync_payload("imp-9"),
147 }));
148 let result = resume_portable(&mut fake, Some("/tmp/import.json"));
149 assert!(!result.is_error);
150 assert_eq!(
151 message(&result),
152 "Imported foreign session as imp-9 (12 entries, leaf leaf-3)"
153 );
154 // The engine must adopt the imported conversation; a message-only
155 // result would leave it on the previous session.
156 assert!(
157 matches!(
158 result.action,
159 Some(codewhale_command_contract::outcome::SessionAction::SyncSession(codewhale_command_contract::facets::SessionSyncPayload { ref session_id, .. }))
160 if session_id.as_deref() == Some("imp-9")
161 ),
162 "{result:?}"
163 );
164
165 let mut fake = control_fake();
166 fake.resume = Some(Ok(ResumeSource::File(PathBuf::from("/tmp/x.json"))));
167 fake.import = Some(Err(
168 "File x.json is not a recognized session export".to_string()
169 ));
170 let result = resume_portable(&mut fake, Some("/tmp/x.json"));
171 assert!(result.is_error);
172 assert_eq!(
173 message(&result),
174 "File x.json is not a recognized session export"
175 );
176
177 let mut fake = control_fake();
178 fake.resume = Some(Ok(ResumeSource::Imported(ResumeImportReceipt {
179 truncated_id: "c-1".to_string(),
180 entry_count: 0,
181 leaf_display: "(none)".to_string(),
182 sync: super::super::lifecycle_test_support::sync_payload("c-1"),
183 })));
184 let result = resume_portable(&mut fake, Some("inline-json"));
185 assert_eq!(
186 message(&result),
187 "Imported foreign session as c-1 (0 entries, leaf (none))"
188 );
189 assert!(
190 matches!(
191 result.action,
192 Some(codewhale_command_contract::outcome::SessionAction::SyncSession(codewhale_command_contract::facets::SessionSyncPayload { ref session_id, .. }))
193 if session_id.as_deref() == Some("c-1")
194 ),
195 "{result:?}"
196 );
197 }
198
199 #[test]
200 fn resume_session_and_not_found_routes_are_exact() {
201 let mut fake = control_fake();
202 fake.resume = Some(Ok(ResumeSource::Session {
203 load_path: Some(PathBuf::from("/tmp/sessions/abc123.json")),
204 truncated_id: "abc123".to_string(),
205 title: "Control Session".to_string(),
206 }));
207 let result = resume_portable(&mut fake, Some("abc123"));
208 assert!(!result.is_error);
209 assert!(matches!(
210 result.action,
211 Some(codewhale_command_contract::outcome::SessionAction::LoadSession(path)) if path == *"/tmp/sessions/abc123.json"
212 ));
213
214 let mut fake = control_fake();
215 fake.resume = Some(Ok(ResumeSource::Session {
216 load_path: None,
217 truncated_id: "abc123".to_string(),
218 title: "Control Session".to_string(),
219 }));
220 let result = resume_portable(&mut fake, Some("abc123"));
221 assert_eq!(
222 message(&result),
223 "Resuming session abc123 (Control Session)"
224 );
225
226 let mut fake = control_fake();
227 fake.resume = Some(Ok(ResumeSource::NotFound {
228 raw: "nope".to_string(),
229 error: "no such session".to_string(),
230 }));
231 let result = resume_portable(&mut fake, Some("nope"));
232 assert!(result.is_error);
233 assert_eq!(
234 message(&result),
235 "Cannot resume 'nope': no such session\nUse `/resume` without args to pick, or pass a session id, or a path to an exported session JSON."
236 );
237 }
238
239 #[test]
240 fn resume_host_lookup_errors_pass_through() {
241 let mut fake = control_fake();
242 fake.resume = Some(Err("could not open sessions directory: boom".to_string()));
243 let result = resume_portable(&mut fake, Some("abc"));
244 assert!(result.is_error);
245 assert_eq!(message(&result), "could not open sessions directory: boom");
246 }
247
248 #[test]
249 fn resume_missing_control_authority_fails_safely() {
250 let contexts = codewhale_command_contract::handler::CommandContexts::empty();
251 let result = resume_contextual(contexts, None);
252 assert!(result.is_error);
253 assert_eq!(
254 message(&result),
255 "Command capability unavailable: session_control"
256 );
257 }
258 }
259
259 lines RUST