返回 CodeWhale
remote.rs
根目录 / crates / tui / src / tui / setup / remote.rs
1 //! Remote runtime setup step (#3409).
2 //!
3 //! The step answers one question — *where can this agent be reached from?* —
4 //! with four modes and no aspiration:
5 //!
6 //! | mode | what it actually is |
7 //! |------|---------------------|
8 //! | [`RemoteMode::LocalOnly`] | the default: this machine, nothing exposed |
9 //! | [`RemoteMode::RuntimeApi`] | `codewhale serve --http` on loopback, token-authenticated |
10 //! | [`RemoteMode::MobileLan`] | the same runtime reachable from a phone on the LAN |
11 //! | [`RemoteMode::ChatBridge`] | a chat bridge (Telegram, Feishu/Lark) in front of the runtime |
12 //!
13 //! Every status is derived from a fact this process can actually observe —
14 //! whether a credential *name* is set in the environment, what the shipped
15 //! runtime unit binds to, and what the bridge registry declares. Two rules are
16 //! absolute and are pinned by tests:
17 //!
18 //! 1. **Secret values are never read and never rendered.** Only the *name* of
19 //! an environment variable and whether it is set are used.
20 //! 2. **Nothing is written, applied, or provisioned.** The plan preview is
21 //! rendered in memory through the existing `remote_setup::bundle` contract
22 //! with redacted placeholders.
23
24 use crate::tui::app::App;
25 use codewhale_app_server::remote_setup::bundle;
26 use codewhale_app_server::remote_setup::registry;
27 use codewhale_localization::{Locale, MessageId, tr};
28
29 /// Env var carrying the runtime API bearer token, plus the legacy alias the
30 /// runtime still honors. Only presence is ever inspected.
31 const RUNTIME_TOKEN_VARS: [&str; 2] = ["CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN"];
32
33 /// Env var a user sets to bind the runtime somewhere other than loopback. The
34 /// shipped systemd unit hardcodes `127.0.0.1`, so without this the LAN/mobile
35 /// mode is genuinely unavailable rather than merely unconfigured.
36 const RUNTIME_HOST_VARS: [&str; 2] = ["CODEWHALE_RUNTIME_HOST", "DEEPSEEK_RUNTIME_HOST"];
37
38 /// Placeholder substituted for every secret in the generated plan preview.
39 const REDACTED: &str = "<redacted>";
40
41 /// The four ways a Codewhale runtime can be reached.
42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43 pub(super) enum RemoteMode {
44 LocalOnly,
45 RuntimeApi,
46 MobileLan,
47 ChatBridge,
48 }
49
50 impl RemoteMode {
51 /// Only the locale-parity test needs to walk every mode; the wizard renders
52 /// whatever [`observe_modes`] actually produced.
53 #[cfg(test)]
54 pub(super) const ALL: [RemoteMode; 4] = [
55 RemoteMode::LocalOnly,
56 RemoteMode::RuntimeApi,
57 RemoteMode::MobileLan,
58 RemoteMode::ChatBridge,
59 ];
60
61 /// Stable id used in the persisted step result and in tests.
62 pub(super) const fn id(self) -> &'static str {
63 match self {
64 RemoteMode::LocalOnly => "local_only",
65 RemoteMode::RuntimeApi => "runtime_api",
66 RemoteMode::MobileLan => "mobile_lan",
67 RemoteMode::ChatBridge => "chat_bridge",
68 }
69 }
70
71 pub(super) const fn label_id(self) -> MessageId {
72 match self {
73 RemoteMode::LocalOnly => MessageId::SetupRemoteModeLocalOnly,
74 RemoteMode::RuntimeApi => MessageId::SetupRemoteModeRuntimeApi,
75 RemoteMode::MobileLan => MessageId::SetupRemoteModeMobileLan,
76 RemoteMode::ChatBridge => MessageId::SetupRemoteModeChatBridge,
77 }
78 }
79 }
80
81 /// What the user can do with a mode *right now*.
82 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
83 pub(super) enum RemoteModeStatus {
84 /// Not available on this install; no user action would change it here.
85 Disabled,
86 /// Usable as configured.
87 Ready,
88 /// Available, but something is missing. Never blocks `ready`.
89 NeedsAction,
90 }
91
92 impl RemoteModeStatus {
93 pub(super) const fn id(self) -> &'static str {
94 match self {
95 RemoteModeStatus::Disabled => "disabled",
96 RemoteModeStatus::Ready => "ready",
97 RemoteModeStatus::NeedsAction => "needs_action",
98 }
99 }
100
101 pub(super) const fn label_id(self) -> MessageId {
102 match self {
103 RemoteModeStatus::Disabled => MessageId::SetupRemoteStatusDisabled,
104 RemoteModeStatus::Ready => MessageId::SetupRemoteStatusReady,
105 RemoteModeStatus::NeedsAction => MessageId::SetupRemoteStatusNeedsAction,
106 }
107 }
108 }
109
110 /// One observed mode. `detail` is a short, secret-free English fact used in the
111 /// persisted step result and the preview; the localized label is composed at
112 /// render time from `mode` and `status`.
113 #[derive(Debug, Clone, PartialEq, Eq)]
114 pub(super) struct RemoteModeFact {
115 pub(super) mode: RemoteMode,
116 pub(super) status: RemoteModeStatus,
117 pub(super) detail: String,
118 }
119
120 /// Whether any of `vars` is set to a non-empty value. **Only presence is
121 /// observed** — the value is never bound to a name, logged, or returned.
122 fn any_var_present(vars: &[&str], lookup: &dyn Fn(&str) -> Option<String>) -> bool {
123 vars.iter()
124 .any(|name| lookup(name).is_some_and(|value| !value.trim().is_empty()))
125 }
126
127 /// The first var in `vars` that is set, by name only. Used so the UI can say
128 /// *which* variable satisfied the check without revealing what it holds.
129 fn present_var_name(
130 vars: &[&'static str],
131 lookup: &dyn Fn(&str) -> Option<String>,
132 ) -> Option<&'static str> {
133 vars.iter()
134 .copied()
135 .find(|name| lookup(name).is_some_and(|value| !value.trim().is_empty()))
136 }
137
138 #[derive(Debug, Clone, PartialEq, Eq)]
139 pub(super) struct SetupRemoteFacts {
140 pub(super) modes: Vec<RemoteModeFact>,
141 pub(super) clouds_result: String,
142 pub(super) bridges_result: String,
143 pub(super) providers_result: String,
144 pub(super) mode_result: String,
145 pub(super) command_provider: String,
146 pub(super) result: String,
147 }
148
149 impl SetupRemoteFacts {
150 pub(super) fn from_app(app: &App) -> Self {
151 Self::from_app_with_env(app, &codewhale_app_server::runtime_api::runtime_env_var)
152 }
153
154 /// Test seam: the env lookup is injected so the hostile-token and
155 /// no-leak cases can be exercised without mutating the process
156 /// environment.
157 pub(super) fn from_app_with_env(app: &App, lookup: &dyn Fn(&str) -> Option<String>) -> Self {
158 let cloud_slugs = registry::CLOUD_TARGETS
159 .iter()
160 .map(|cloud| cloud.slug)
161 .collect::<Vec<_>>();
162 let bridge_slugs = registry::BRIDGES
163 .iter()
164 .map(|bridge| bridge.slug)
165 .collect::<Vec<_>>();
166 let provider_count = codewhale_config::ProviderKind::all().len();
167 // Keep the exact route identity. Named custom routes are not yet
168 // representable by the remote bundle registry, so the generated CLI
169 // command must fail explicitly for that name instead of silently
170 // substituting DeepSeek's endpoint and credential contract.
171 let command_provider = app.provider_identity_for_persistence().to_string();
172
173 let modes = observe_modes(lookup);
174 let mode_result = modes
175 .iter()
176 .map(|fact| format!("{}={}", fact.mode.id(), fact.status.id()))
177 .collect::<Vec<_>>()
178 .join(", ");
179
180 Self {
181 clouds_result: format!(
182 "{} cloud targets: {}",
183 cloud_slugs.len(),
184 cloud_slugs.join(", ")
185 ),
186 bridges_result: format!(
187 "{} chat bridges: {}",
188 bridge_slugs.len(),
189 bridge_slugs.join(", ")
190 ),
191 providers_result: format!(
192 "{provider_count} providers from the provider registry; active route {} / {}",
193 app.provider_identity_for_persistence(),
194 app.model
195 ),
196 result: format!("{mode_result}; plan=generate_only, apply=not_implemented"),
197 mode_result,
198 command_provider,
199 modes,
200 }
201 }
202
203 /// The mode the step defaults to. Local-only is always the default and is
204 /// always skippable in one key — a user who never wants remote access is
205 /// done here immediately. Asserted by test rather than branched on: the
206 /// wizard's Enter path is unconditional precisely because of this.
207 #[cfg(test)]
208 pub(super) fn default_mode(&self) -> RemoteMode {
209 RemoteMode::LocalOnly
210 }
211
212 #[cfg(test)]
213 pub(super) fn status_for(&self, mode: RemoteMode) -> RemoteModeStatus {
214 self.modes
215 .iter()
216 .find(|fact| fact.mode == mode)
217 .map_or(RemoteModeStatus::NeedsAction, |fact| fact.status)
218 }
219
220 /// True when something is missing but nothing is broken. Callers record
221 /// `NeedsAction` — which by contract never blocks the ready screen.
222 pub(super) fn needs_action(&self) -> bool {
223 self.modes
224 .iter()
225 .any(|fact| fact.status == RemoteModeStatus::NeedsAction)
226 }
227 }
228
229 /// Derive all four mode facts from observable state.
230 fn observe_modes(lookup: &dyn Fn(&str) -> Option<String>) -> Vec<RemoteModeFact> {
231 let runtime_token = present_var_name(&RUNTIME_TOKEN_VARS, lookup);
232 let lan_host = present_var_name(&RUNTIME_HOST_VARS, lookup);
233
234 let runtime_api = match runtime_token {
235 Some(name) => RemoteModeFact {
236 mode: RemoteMode::RuntimeApi,
237 status: RemoteModeStatus::Ready,
238 detail: format!(
239 "{name} is set; runtime serves 127.0.0.1:{} with token auth",
240 bundle::DEFAULT_PORT
241 ),
242 },
243 None => RemoteModeFact {
244 mode: RemoteMode::RuntimeApi,
245 status: RemoteModeStatus::NeedsAction,
246 detail: format!(
247 "no runtime token set ({}); the runtime would refuse authenticated calls",
248 RUNTIME_TOKEN_VARS[0]
249 ),
250 },
251 };
252
253 // The shipped systemd unit binds loopback. Without an explicit host
254 // override there is nothing for a phone to reach, and saying "not
255 // configured" would imply a switch the user could flip here.
256 let mobile_lan = match lan_host {
257 None => RemoteModeFact {
258 mode: RemoteMode::MobileLan,
259 status: RemoteModeStatus::Disabled,
260 detail: format!(
261 "runtime binds 127.0.0.1 only; set {} to expose it on a LAN",
262 RUNTIME_HOST_VARS[0]
263 ),
264 },
265 Some(name) => {
266 // A bound LAN address with no token is reachable *and*
267 // unauthenticated, so it is the one case that must ask for action.
268 if runtime_token.is_some() {
269 RemoteModeFact {
270 mode: RemoteMode::MobileLan,
271 status: RemoteModeStatus::Ready,
272 detail: format!("{name} is set and the runtime token is present"),
273 }
274 } else {
275 RemoteModeFact {
276 mode: RemoteMode::MobileLan,
277 status: RemoteModeStatus::NeedsAction,
278 detail: format!(
279 "{name} is set but no runtime token is; add {} before exposing a LAN port",
280 RUNTIME_TOKEN_VARS[0]
281 ),
282 }
283 }
284 }
285 };
286
287 let ready_bridges = registry::BRIDGES
288 .iter()
289 .filter(|bridge| {
290 bridge
291 .secret_keys
292 .iter()
293 .all(|key| any_var_present(&[key], lookup))
294 })
295 .map(|bridge| bridge.slug)
296 .collect::<Vec<_>>();
297 let chat_bridge = if ready_bridges.is_empty() {
298 RemoteModeFact {
299 mode: RemoteMode::ChatBridge,
300 status: RemoteModeStatus::NeedsAction,
301 detail: format!(
302 "{} bridges available ({}); none has its credentials set yet",
303 registry::BRIDGES.len(),
304 registry::BRIDGES
305 .iter()
306 .map(|bridge| bridge.slug)
307 .collect::<Vec<_>>()
308 .join(", ")
309 ),
310 }
311 } else {
312 RemoteModeFact {
313 mode: RemoteMode::ChatBridge,
314 status: RemoteModeStatus::Ready,
315 detail: format!("credentials present for: {}", ready_bridges.join(", ")),
316 }
317 };
318
319 vec![
320 RemoteModeFact {
321 mode: RemoteMode::LocalOnly,
322 status: RemoteModeStatus::Ready,
323 detail: "this machine only; nothing is exposed and nothing to configure".to_string(),
324 },
325 runtime_api,
326 mobile_lan,
327 chat_bridge,
328 ]
329 }
330
331 /// Render the plan preview **in memory**, with every secret replaced by
332 /// [`REDACTED`].
333 ///
334 /// This deliberately goes through the same `remote_setup::bundle` planning
335 /// contract the CLI uses, so the preview cannot drift from what
336 /// `codewhale remote-setup --generate-only` would produce. It calls
337 /// [`bundle::render_bundle`] (a pure function) and never
338 /// [`bundle::write_bundle`]: no file is created, no command is run, and no
339 /// cloud resource is provisioned.
340 pub(super) fn redacted_plan_preview(command_provider: &str) -> String {
341 let Some(cloud) = registry::cloud_by_slug("lighthouse") else {
342 return "No cloud target is registered; nothing to preview.".to_string();
343 };
344 let Some(bridge) = registry::bridge_by_slug("telegram") else {
345 return "No chat bridge is registered; nothing to preview.".to_string();
346 };
347 let Some(provider) = bundle::ProviderInfo::from_slug(command_provider) else {
348 return format!(
349 "Route \"{command_provider}\" is not representable as a remote bundle provider yet, \
350 so no plan can be generated for it."
351 );
352 };
353
354 let inputs = bundle::BundleInputs {
355 cloud,
356 bridge,
357 provider,
358 model: "auto".to_string(),
359 // Every secret slot is a constant placeholder. No token is generated,
360 // no environment value is read, and nothing here is usable.
361 runtime_token: REDACTED.to_string(),
362 provider_key_value: REDACTED.to_string(),
363 bridge_secret_values: bridge
364 .secret_keys
365 .iter()
366 .map(|key| ((*key).to_string(), REDACTED.to_string()))
367 .collect(),
368 allowlist: String::new(),
369 port: bundle::DEFAULT_PORT,
370 workers: bundle::DEFAULT_WORKERS,
371 workspace: "<your workspace>".to_string(),
372 };
373
374 let mut out = String::from(
375 "Preview only. Nothing below has been written, applied, or provisioned.\n\
376 Every secret is shown as <redacted>; Codewhale never reads their values here.\n\n",
377 );
378 for file in bundle::render_bundle(&inputs) {
379 out.push_str(&format!("── {} ──\n", file.relative_path));
380 out.push_str(&file.contents);
381 if !file.contents.ends_with('\n') {
382 out.push('\n');
383 }
384 out.push('\n');
385 }
386 out
387 }
388
389 pub(super) fn on_ramp_text(
390 locale: Locale,
391 clouds_result: &str,
392 bridges_result: &str,
393 providers_result: &str,
394 mode_result: &str,
395 command_provider: &str,
396 ) -> String {
397 let command = format!(
398 "codewhale remote-setup --generate-only --cloud lighthouse --bridge telegram --provider {command_provider} --out ./codewhale-deploy/lighthouse-telegram"
399 );
400 let base = tr(locale, MessageId::SetupRemoteOnRampText);
401 let mut out = base
402 .replace("{clouds_result}", clouds_result)
403 .replace("{bridges_result}", bridges_result)
404 .replace("{providers_result}", providers_result)
405 .replace("{mode_result}", mode_result)
406 .replace("{command}", &command);
407 out.push_str("\n\n");
408 out.push_str(&redacted_plan_preview(command_provider));
409 out
410 }
411
412 #[cfg(test)]
413 mod tests {
414 use super::*;
415 use std::collections::HashMap;
416
417 fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
418 let map = pairs
419 .iter()
420 .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
421 .collect::<HashMap<_, _>>();
422 move |name: &str| map.get(name).cloned()
423 }
424
425 #[test]
426 fn local_only_is_always_ready_and_needs_no_configuration() {
427 let modes = observe_modes(&env(&[]));
428 let local = modes
429 .iter()
430 .find(|fact| fact.mode == RemoteMode::LocalOnly)
431 .expect("local-only mode");
432 assert_eq!(local.status, RemoteModeStatus::Ready);
433 assert!(local.detail.contains("nothing to configure"));
434 }
435
436 #[test]
437 fn a_bare_install_reports_the_honest_mode_matrix() {
438 let modes = observe_modes(&env(&[]));
439 let by_mode = |mode| {
440 modes
441 .iter()
442 .find(|fact| fact.mode == mode)
443 .expect("mode")
444 .status
445 };
446
447 assert_eq!(by_mode(RemoteMode::LocalOnly), RemoteModeStatus::Ready);
448 // Missing token/config is NeedsAction, never Failed and never blocking.
449 assert_eq!(
450 by_mode(RemoteMode::RuntimeApi),
451 RemoteModeStatus::NeedsAction
452 );
453 // Nothing the user does on this screen can expose a loopback bind.
454 assert_eq!(by_mode(RemoteMode::MobileLan), RemoteModeStatus::Disabled);
455 assert_eq!(
456 by_mode(RemoteMode::ChatBridge),
457 RemoteModeStatus::NeedsAction
458 );
459 }
460
461 #[test]
462 fn a_lan_bind_without_a_token_asks_for_action_rather_than_claiming_ready() {
463 let modes = observe_modes(&env(&[("CODEWHALE_RUNTIME_HOST", "0.0.0.0")]));
464 let lan = modes
465 .iter()
466 .find(|fact| fact.mode == RemoteMode::MobileLan)
467 .expect("mobile mode");
468 assert_eq!(lan.status, RemoteModeStatus::NeedsAction);
469
470 let both = observe_modes(&env(&[
471 ("CODEWHALE_RUNTIME_HOST", "0.0.0.0"),
472 ("CODEWHALE_RUNTIME_TOKEN", "t-secret-value"),
473 ]));
474 assert_eq!(
475 both.iter()
476 .find(|fact| fact.mode == RemoteMode::MobileLan)
477 .expect("mobile mode")
478 .status,
479 RemoteModeStatus::Ready
480 );
481 }
482
483 #[test]
484 fn bridge_credentials_flip_the_bridge_mode_to_ready() {
485 let modes = observe_modes(&env(&[("TELEGRAM_BOT_TOKEN", "12345:AAhostile")]));
486 let bridge = modes
487 .iter()
488 .find(|fact| fact.mode == RemoteMode::ChatBridge)
489 .expect("bridge mode");
490 assert_eq!(bridge.status, RemoteModeStatus::Ready);
491 assert!(bridge.detail.contains("telegram"));
492 }
493
494 /// The single most important property of this step: it inspects
495 /// credentials without ever surfacing one.
496 #[test]
497 fn hostile_secret_values_never_reach_any_rendered_fact() {
498 let hostile_token = "t-\u{202e}AKIAIOSFODNN7EXAMPLE/../../etc/passwd";
499 let hostile_bot = "999:AAsuper-secret-bot-token";
500 let modes = observe_modes(&env(&[
501 ("CODEWHALE_RUNTIME_TOKEN", hostile_token),
502 ("CODEWHALE_RUNTIME_HOST", "10.0.0.5"),
503 ("TELEGRAM_BOT_TOKEN", hostile_bot),
504 ("FEISHU_APP_ID", "cli_hostile"),
505 ("FEISHU_APP_SECRET", "shh"),
506 ]));
507
508 let rendered = modes
509 .iter()
510 .map(|fact| fact.detail.clone())
511 .collect::<Vec<_>>()
512 .join("\n");
513 for secret in [hostile_token, hostile_bot, "cli_hostile", "shh", "AKIA"] {
514 assert!(
515 !rendered.contains(secret),
516 "secret value leaked into the step facts: {rendered}"
517 );
518 }
519 // Names are fine and are what makes the status explainable.
520 assert!(rendered.contains("CODEWHALE_RUNTIME_TOKEN"));
521 // A LAN address is host configuration the user typed, not a secret,
522 // but it is still not echoed back.
523 assert!(!rendered.contains("10.0.0.5"));
524 }
525
526 #[test]
527 fn plan_preview_is_generated_in_memory_and_fully_redacted() {
528 let preview = redacted_plan_preview("deepseek");
529
530 assert!(preview.contains("Nothing below has been written"));
531 assert!(preview.contains("RUNBOOK.md"));
532 assert!(preview.contains("runtime.env"));
533 assert!(
534 preview.contains(REDACTED),
535 "secrets must render as the redaction placeholder"
536 );
537 // The generated token slot must be the placeholder, not a real token.
538 assert!(preview.contains(&format!("CODEWHALE_RUNTIME_TOKEN={REDACTED}")));
539 }
540
541 #[test]
542 fn plan_preview_writes_nothing_to_disk() {
543 let tmp = tempfile::tempdir().expect("tempdir");
544 let before = std::fs::read_dir(tmp.path()).expect("read tempdir").count();
545
546 let _ = redacted_plan_preview("deepseek");
547
548 let after = std::fs::read_dir(tmp.path()).expect("read tempdir").count();
549 assert_eq!(before, after, "the preview must not create any file");
550 assert!(!std::path::Path::new("./codewhale-deploy").exists());
551 }
552
553 #[test]
554 fn an_unrepresentable_route_says_so_instead_of_substituting_a_provider() {
555 let preview = redacted_plan_preview("my-private-gateway");
556 assert!(preview.contains("not representable"));
557 assert!(
558 !preview.contains("DEEPSEEK_API_KEY"),
559 "must not silently substitute another provider's credential contract"
560 );
561 }
562
563 /// A user who wants none of this must be able to leave in one key: the
564 /// default mode is local-only and local-only is always usable.
565 #[test]
566 fn the_default_mode_is_local_only_and_is_never_blocking() {
567 let facts = SetupRemoteFacts {
568 modes: observe_modes(&env(&[])),
569 clouds_result: String::new(),
570 bridges_result: String::new(),
571 providers_result: String::new(),
572 mode_result: String::new(),
573 command_provider: "deepseek".to_string(),
574 result: String::new(),
575 };
576
577 assert_eq!(facts.default_mode(), RemoteMode::LocalOnly);
578 assert_eq!(
579 facts.status_for(RemoteMode::LocalOnly),
580 RemoteModeStatus::Ready
581 );
582 // Missing tokens/config are surfaced, but only ever as NeedsAction.
583 assert!(facts.needs_action());
584 assert!(
585 facts
586 .modes
587 .iter()
588 .all(|fact| fact.status != RemoteModeStatus::Disabled
589 || fact.mode == RemoteMode::MobileLan)
590 );
591 }
592
593 #[test]
594 fn mode_rows_render_in_every_complete_pack_without_placeholders() {
595 for locale in Locale::shipped_complete() {
596 for mode in RemoteMode::ALL {
597 let label = tr(*locale, mode.label_id());
598 assert!(!label.is_empty(), "{locale:?} {mode:?}");
599 assert!(!label.contains('{'), "{locale:?} {mode:?}: {label}");
600 }
601 for status in [
602 RemoteModeStatus::Disabled,
603 RemoteModeStatus::Ready,
604 RemoteModeStatus::NeedsAction,
605 ] {
606 let label = tr(*locale, status.label_id());
607 assert!(!label.is_empty(), "{locale:?} {status:?}");
608 }
609 }
610 }
611 }
612
612 lines RUST