返回 CodeWhale
lsp.rs
根目录 / crates / tui / src / commands / groups / project / lsp.rs
1 //! `/lsp` command — approve, revoke and inspect language servers per folder.
2 //!
3 //! Bridges to the host LSP state through the portable project facet
4 //! (FEAT-021 D3): the handler composes byte-identical output from typed
5 //! status, approve and revoke delegates; the TUI adapter owns all host-side
6 //! LSP behavior.
7
8 use codewhale_command_contract::facets::CommandProjectContext;
9 use codewhale_command_contract::handler::{CommandContexts, CommandHandler};
10 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
11
12 use crate::commands::CommandResult;
13
14 pub(in crate::commands) const LSP_INFO: CommandInfo = CommandInfo {
15 name: "lsp",
16 aliases: &[],
17 usage: "/lsp [status|approve <name>|revoke <name>]",
18 description_key: "cmd_lsp_description",
19 };
20
21 pub(in crate::commands) struct LspCmd;
22
23 impl RegisterCommand<CommandResult> for LspCmd {
24 fn info() -> &'static CommandInfo {
25 &LSP_INFO
26 }
27
28 fn handler() -> CommandHandler<CommandResult> {
29 CommandHandler::Contextual {
30 capabilities: codewhale_command_contract::handler::CommandCapabilities::PROJECT,
31 handler: lsp_contextual,
32 }
33 }
34 }
35
36 /// Contextual `/lsp` dispatch (FEAT-021 Phase 4).
37 ///
38 /// Destructures the declared `PROJECT` facet with a safe missing-facet error;
39 /// the portable [`lsp`] handler never panics on absent capabilities.
40 fn lsp_contextual(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
41 let mut parts = contexts.into_parts();
42 let Some(project) = parts.project.as_deref_mut() else {
43 return CommandResult::error("Command capability unavailable: project");
44 };
45 lsp(project, arg)
46 }
47
48 /// Portable `/lsp` dispatch.
49 fn lsp(project: &mut dyn CommandProjectContext, arg: Option<&str>) -> CommandResult {
50 let raw = arg.map(str::trim).unwrap_or("");
51 let mut words = raw.split_whitespace();
52 let verb = words.next().unwrap_or("");
53 let names: Vec<&str> = words.collect();
54
55 match verb {
56 "" | "status" if names.is_empty() => CommandResult::message(project.lsp_status()),
57 "approve" => match project.lsp_approve(&names) {
58 Ok(message) => CommandResult::message(message),
59 Err(error) => CommandResult::error(error),
60 },
61 "revoke" => match project.lsp_revoke(&names) {
62 Ok(message) => CommandResult::message(message),
63 Err(error) => CommandResult::error(error),
64 },
65 _ => CommandResult::error(format!(
66 "Unknown /lsp argument `{raw}`. Use `/lsp status`, `/lsp approve <name>` or `/lsp revoke <name>`. `/lsp on` and `/lsp off` no longer exist: a language server starts only where you approved it."
67 )),
68 }
69 }
70
71 #[cfg(test)]
72 mod tests {
73 use super::*;
74 use codewhale_command_contract::facets::{ProjectGoalState, ProjectGoalStatus};
75
76 #[derive(Default)]
77 struct FakeProject {
78 calls: Vec<String>,
79 }
80
81 impl CommandProjectContext for FakeProject {
82 fn lsp_status(&self) -> String {
83 "status report".to_owned()
84 }
85
86 fn lsp_approve(&mut self, names: &[&str]) -> Result<String, String> {
87 self.calls.push(format!("approve {}", names.join(",")));
88 if names == ["nope"] {
89 return Err("No configured language server".to_owned());
90 }
91 Ok("approved".to_owned())
92 }
93
94 fn lsp_revoke(&mut self, names: &[&str]) -> Result<String, String> {
95 self.calls.push(format!("revoke {}", names.join(",")));
96 Ok("revoked".to_owned())
97 }
98
99 fn goal_state(&self) -> ProjectGoalState {
100 ProjectGoalState {
101 objective: None,
102 status: ProjectGoalStatus::Active,
103 pause_reason: None,
104 started_at_elapsed_seconds: None,
105 time_used_seconds: 0,
106 token_budget: None,
107 tokens_used: 0,
108 session_total_tokens: 0,
109 continuation_count: 0,
110 pending_controls: false,
111 last_known_objective: None,
112 last_known_status: None,
113 conversation_present: false,
114 is_loading: false,
115 goal_continuation_waiting: false,
116 }
117 }
118 }
119
120 #[test]
121 fn bare_and_status_report_the_real_state() {
122 for arg in [None, Some("status"), Some(" status ")] {
123 let mut project = FakeProject::default();
124 let result = lsp(&mut project, arg);
125 assert_eq!(result.message.as_deref(), Some("status report"));
126 assert!(project.calls.is_empty());
127 }
128 }
129
130 #[test]
131 fn approve_and_revoke_pass_every_named_server() {
132 let mut project = FakeProject::default();
133 assert_eq!(
134 lsp(&mut project, Some("approve rust python"))
135 .message
136 .as_deref(),
137 Some("approved")
138 );
139 assert_eq!(
140 lsp(&mut project, Some("revoke rust")).message.as_deref(),
141 Some("revoked")
142 );
143 assert_eq!(
144 lsp(&mut project, Some("approve")).message.as_deref(),
145 Some("approved")
146 );
147 assert_eq!(
148 project.calls,
149 ["approve rust,python", "revoke rust", "approve "]
150 );
151 }
152
153 #[test]
154 fn approval_failures_are_errors() {
155 let mut project = FakeProject::default();
156 let result = lsp(&mut project, Some("approve nope"));
157 assert!(result.is_error);
158 }
159
160 #[test]
161 fn on_and_off_are_gone_and_never_reach_the_host() {
162 for arg in ["on", "off", "enable", "status extra", "bogus"] {
163 let mut project = FakeProject::default();
164 let result = lsp(&mut project, Some(arg));
165 assert!(result.is_error, "{arg}");
166 let message = result.message.expect("message");
167 assert!(message.contains("`/lsp approve <name>`"), "{message}");
168 assert!(project.calls.is_empty(), "{arg}");
169 }
170 }
171
172 #[test]
173 fn missing_project_facet_fails_safely() {
174 let result = lsp_contextual(CommandContexts::empty(), Some("status"));
175 assert!(result.is_error);
176 assert!(
177 result
178 .message
179 .unwrap()
180 .contains("Command capability unavailable: project"),
181 "missing project facet must fail safely"
182 );
183 }
184 }
185
185 lines RUST