okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ffb3d9b31
main
1//! Strata Desktop — Tauri shell. 2//! 3//! The shell is a *carrier*, not an owner. It does exactly three things: 4//! 5//! 1. finds its bundled resources (the private Node runtime, the App Host, the built UI) and 6//! starts the App Host on a free loopback port; 7//! 2. opens one webview window on the host's own origin, so the renderer and the API share an 8//! origin exactly as the browser build does and the supplied UI's relative `/api/...` calls 9//! keep working with no rewrite; 10//! 3. stops the host when the app exits, and sees to it that nothing the app started outlives it. 11//! 12//! One app instance runs at a time (the single-instance plugin): a second launch focuses the window that is 13//! already open and starts nothing, so two apps never fight over the `app-N` engine slots. One app can still run 14//! several engines (one per GPU, say): the host gives each its own `app-N` profile under Strata Control. 15//! 16//! Closing ends the engines this app started, on every path: 17//! - a normal exit and the window's X: the host is asked to stop them through Control (drained, then ended), with a 18//! deadline after which the host is ended; 19//! - the shell is killed, crashes, or the user logs off: on Windows the shell owns a kill-on-close Job Object that 20//! contains the host, Control, the owner host, the server and the engine, so they end with it; everywhere the host 21//! watches its parent and each engine's owner is told to follow the host (`--die-with-pid`). 22//! Engines the Terminal started are not in any of this and are left alone. 23//! 24//! Ownership stays where the architecture puts it. The App Host owns the local client API and the 25//! engine lifecycle; Strata Control owns components, models, profiles and jobs; DeepSeek Harness 26//! owns the agent loop and durable sessions. There is deliberately no second supervisor, no 27//! conversation store and no agent loop in this file. 28 29#! [ cfg_attr ( not ( debug_assertions ), windows_subsystem = "windows" )] 30 31use std:: net:: TcpListener ; 32use std:: path::{ Path , PathBuf }; 33use std:: process::{ Child , Command , Stdio }; 34# [ cfg ( not ( target_os = "linux" ))] 35use std:: sync:: Mutex ; 36use std:: time::{ Duration , Instant }; 37 38use tauri::{ Manager , WebviewUrl , WebviewWindowBuilder }; 39 40mod updater; 41mod desktoplog; 42mod recovery; 43mod shell; 44// Plain std, built on every platform so its decisions are tested everywhere; only the Linux window process uses it. 45# [ cfg_attr ( not ( target_os = "linux" ), allow ( dead_code ))] 46mod fontguard; 47# [ cfg ( target_os = "linux" )] 48mod supervisor; 49 50/// The kill-on-close Job Object that holds everything this app starts (Windows). Its only handle is this process's, 51/// which the system closes however the process ends; closing the last handle ends every process in the job. 52# [ cfg ( windows )] 53mod job{ 54use std:: ffi:: c_void; 55 56type Handle =* mut c_void ; 57const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE : u32 =0x2000 ; 58/// A process may ask to start a child outside the job (CREATE_BREAKAWAY_FROM_JOB). Only the app updater does, for the 59/// installer that replaces this app: it must outlive the app, which the kill-on-close job would otherwise prevent. 60const JOB_OBJECT_LIMIT_BREAKAWAY_OK : u32 =0x0800 ; 61const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION : i32 =9 ; 62 63# [ repr ( C )] 64# [ derive ( Default )] 65struct BasicLimits { 66per_process_user_time_limit : i64 , 67per_job_user_time_limit : i64 , 68limit_flags : u32 , 69minimum_working_set_size : usize , 70maximum_working_set_size : usize , 71active_process_limit : u32 , 72affinity : usize , 73priority_class : u32 , 74scheduling_class : u32 , 75} 76 77# [ repr ( C )] 78# [ derive ( Default )] 79struct IoCounters { 80counts : [ u64 ; 6 ], 81} 82 83# [ repr ( C )] 84# [ derive ( Default )] 85struct ExtendedLimits { 86basic : BasicLimits , 87io : IoCounters , 88process_memory_limit : usize , 89job_memory_limit : usize , 90peak_process_memory_used : usize , 91peak_job_memory_used : usize , 92} 93 94# [ link ( name = "kernel32" )] 95extern "system" { 96fn CreateJobObjectW ( attributes : * mut c_void , name : * const u16 ) ->Handle ; 97fn SetInformationJobObject ( job : Handle , class : i32 , info : * mut c_void , len : u32 ) ->i32 ; 98fn AssignProcessToJobObject ( job : Handle , process : Handle ) ->i32 ; 99fn GetCurrentProcess () ->Handle ; 100fn CloseHandle ( handle : Handle ) ->i32 ; 101fn IsProcessInJob ( process : Handle , job : Handle , result : * mut i32 ) ->i32 ; 102} 103 104/// Is this process inside any job object? (The self-test asks, so an installed build proves it is contained.) 105pub fn current_process_in_a_job () ->bool { 106let mut result =0i32 ; 107unsafe { IsProcessInJob ( GetCurrentProcess (), std:: ptr:: null_mut (), & mut result) !=0 && result !=0 } 108} 109 110pub struct Job ( Handle ); 111 112// The handle is a plain kernel object handle, usable from any thread. 113unsafe impl Send for Job {} 114unsafe impl Sync for Job {} 115 116impl Job { 117/// A new job that ends all of its processes when its last handle closes. None if the system refuses. 118pub fn kill_on_close () ->Option < Job > { 119unsafe { 120let handle =CreateJobObjectW ( std:: ptr:: null_mut (), std:: ptr:: null ()); 121if handle. is_null () { 122return None ; 123} 124let mut info =ExtendedLimits :: default (); 125 info. basic . limit_flags =JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |JOB_OBJECT_LIMIT_BREAKAWAY_OK ; 126let ok =SetInformationJobObject ( 127 handle, 128JOB_OBJECT_EXTENDED_LIMIT_INFORMATION , 129& mut infoas * mut ExtendedLimits as * mut c_void , 130 std:: mem:: size_of ::< ExtendedLimits >() as u32 , 131); 132if ok ==0 { 133CloseHandle ( handle); 134return None ; 135} 136Some ( Job ( handle)) 137} 138} 139 140/// Put a process (by handle) in the job; everything it starts later joins too. 141pub fn assign_raw ( & self , process : * mut c_void ) ->bool { 142unsafe { AssignProcessToJobObject ( self . 0 , process) !=0 } 143} 144 145/// Put this very process in the job, so the host and everything below it are contained. 146pub fn assign_current ( & self ) ->bool { 147self . assign_raw ( unsafe { GetCurrentProcess () }) 148} 149} 150 151impl Drop for Job { 152fn drop ( & mut self ) { 153unsafe { 154CloseHandle ( self . 0 ); 155} 156} 157} 158} 159 160/// Held for the life of the process. The handle is deliberately never closed by us: the system closes it when the 161/// process ends, by any route, and that is the moment the job ends what is left in it. 162# [ cfg ( windows )] 163static APP_JOB : std:: sync:: OnceLock < job:: Job > = std:: sync:: OnceLock :: new (); 164 165/// Is the app inside a job object right now? Always false off Windows. 166fn app_is_contained () ->bool { 167# [ cfg ( windows )] 168{ 169 job:: current_process_in_a_job () 170} 171# [ cfg ( not ( windows ))] 172{ 173false 174} 175} 176 177/// Put this process (and so everything it starts) in a kill-on-close job. True if it is contained now. 178fn contain_app () ->bool { 179# [ cfg ( windows )] 180{ 181if let Some ( job) = job:: Job :: kill_on_close () { 182if job. assign_current () { 183let _ =APP_JOB . set ( job); 184return true ; 185} 186} 187eprintln! ( "[strata] could not put the app in a job object; engines are stopped by the host and their owners instead" ); 188false 189} 190# [ cfg ( not ( windows ))] 191{ 192false 193} 194} 195 196/// The running App Host, kept so it can be stopped on exit. 197# [ cfg ( not ( target_os = "linux" ))] 198struct HostProcess ( Mutex < Option < Child >>); 199 200/// The port the App Host bound, so the window (and the frontend) can be pointed at it. 201# [ cfg ( not ( target_os = "linux" ))] 202struct HostPort ( Mutex < Option < u16 >>); 203 204/// The secret that lets this shell (and nothing else) ask the host for a clean stop. 205# [ cfg ( not ( target_os = "linux" ))] 206struct ShutdownToken ( Mutex < Option < String >>); 207 208/// 256 random bits as hex, from the standard library's per-process random hasher keys (no extra crate). 209fn random_token () ->String { 210use std:: collections:: hash_map:: RandomState ; 211use std:: hash::{ BuildHasher , Hasher }; 212( 0 ..4 ) 213. map ( |i|{ 214let mut h =RandomState :: new (). build_hasher (); 215 h. write_u32 ( i); 216 h. write_u128 ( std:: time:: SystemTime :: now (). duration_since ( std:: time:: UNIX_EPOCH ). map ( |d| d. as_nanos ()). unwrap_or ( 0 )); 217format! ( "{:016x}" , h. finish ()) 218}) 219. collect () 220} 221 222/// The Control component that ships beside the host (`<resources>/control`): the bundled CPython, the locked 223/// wheels, strata_control and the API server. None in a development checkout. 224fn control_dir ( res : & Path ) ->Option < PathBuf > { 225let dir = res. join ( "control" ); 226let python =if cfg! ( windows) { dir. join ( "python" ). join ( "python.exe" ) } else { dir. join ( "python" ). join ( "bin" ). join ( "python3" ) }; 227if python. exists () && dir. join ( "strata.py" ). exists () { 228Some ( dir) 229} else { 230None 231} 232} 233 234/// What every host start gets, packaged or self-test: acquiring is forbidden, Control is where the bundle put it. 235fn apply_runtime_policy ( cmd : & mut Command , res : & Path ) { 236 cmd. env ( "STRATA_NO_ACQUIRE" , "1" ); 237if let Some ( dir) =control_dir ( res) { 238 cmd. env ( "STRATA_CONTROL_DIR" , dir); 239} 240} 241 242/// Ask the OS for an unused loopback port. 243/// 244/// The port is released before the host binds it, so there is a small race; the host reports a 245/// clear "port already in use" error if another process takes it first, and that surfaces in the 246/// window instead of failing silently. 247fn pick_port () ->Result < u16 , String > { 248let listener =TcpListener :: bind (( "127.0.0.1" , 0 )). map_err ( |e|format! ( "bind: {e}" )) ?; 249let port = listener. local_addr (). map_err ( |e|format! ( "addr: {e}" )) ?. port (); 250drop ( listener); 251Ok ( port) 252} 253 254/// The port the app prefers. The window's origin is `http://127.0.0.1:<port>`, and the browser storage that holds the 255/// theme, text size, language and the chat list belongs to that origin, so a port that changed on every launch lost all 256/// of it. The preferred port is fixed; only when something else holds it does the app fall back to a free one (and that 257/// launch starts with empty storage, as before). 258const PREFERRED_PORT : u16 =47831 ; 259 260/// Set when the port the person (or the app) wanted was busy: "busy:<wanted>:<used>". The host gets it as STRATA_PORT_NOTICE and tells the 261/// person (the chats and settings saved on the page belong to the port, so a different port starts empty) (#3402). 262static PORT_NOTICE : std:: sync:: Mutex < Option < String >> = std:: sync:: Mutex :: new ( None ); 263 264fn pick_stable_port () ->Result < u16 , String > { 265// The person may have chosen a port in Settings (shell-prefs.json); otherwise the app's usual one. 266let wanted = shell:: wanted_port ( & shell:: read_prefs (), PREFERRED_PORT ); 267* PORT_NOTICE . lock (). unwrap () =None ; 268match TcpListener :: bind (( "127.0.0.1" , wanted)) { 269Ok ( listener) =>{ 270drop ( listener); 271Ok ( wanted) 272} 273Err ( _) =>{ 274let used =pick_port () ?; 275* PORT_NOTICE . lock (). unwrap () =Some ( shell:: busy_notice ( wanted, used)); 276Ok ( used) 277} 278} 279} 280 281/// Locate a bundled resource. 282/// 283/// In a packaged `.app` Tauri places `bundle.resources` under `Contents/Resources`. During 284/// development they are not copied, so the repository layout is the fallback. Both are tried so 285/// `tauri dev` and the packaged bundle behave the same way. 286# [ cfg ( not ( target_os = "linux" ))] 287fn resource_dir ( app : & tauri:: AppHandle ) ->Result < PathBuf , String > { 288if let Ok ( dir) = app. path (). resource_dir () { 289if dir. join ( "host" ). join ( "server" ). join ( "index.mjs" ). exists () { 290return Ok ( plain_path ( dir)); 291} 292} 293// development: apps/desktop/src-tauri -> ../../host and ./resources 294let manifest =PathBuf :: from ( env! ( "CARGO_MANIFEST_DIR" )); 295Ok ( manifest) 296} 297 298/// Tauri returns Windows paths in the verbatim form (`\\?\C:\...`). Node cannot take such a path as 299/// its entry script (`EISDIR ... lstat 'C:'`), so the host died at once and the window sat 300/// unresponsive until the health wait gave up. Use the ordinary drive (or UNC) form. 301# [ cfg_attr ( target_os = "linux" , allow ( dead_code ))] 302fn plain_path ( p : PathBuf ) ->PathBuf { 303let text = p. to_string_lossy (). into_owned (); 304if let Some ( rest) = text. strip_prefix ( r"\\?\UNC\" ) { 305return PathBuf :: from ( format! ( r"\\{rest}" )); 306} 307match text. strip_prefix ( r"\\?\" ) { 308Some ( rest) =>PathBuf :: from ( rest), 309None => p, 310} 311} 312 313/// File name of the bundled Node runtime: `node.exe` on Windows, `node` elsewhere. 314const NODE_EXE : & str =if cfg! ( windows) { "node.exe" } else { "node" }; 315 316/// Where `tauri dev` finds a Node sidecar prepared next to the checkout (`toolchain/node`). 317fn dev_node_candidate ( res : & Path ) ->PathBuf { 318let root = res. join ( ".." ). join ( ".." ). join ( ".." ). join ( "toolchain" ). join ( "node" ); 319if cfg! ( windows) { 320// the Windows zip has node.exe at the top of the folder, not under bin/ 321 root. join ( "node-v24.12.0-win-x64" ). join ( "node.exe" ) 322} else { 323 root. join ( "node-v24.12.0-darwin-arm64" ). join ( "bin" ). join ( "node" ) 324} 325} 326 327/// The private Node runtime that ships with the bundle. 328fn node_binary ( res : & Path ) ->Result < PathBuf , String > { 329let bundled = res. join ( "node" ). join ( NODE_EXE ); 330if bundled. exists () { 331return Ok ( bundled); 332} 333// development fallback: the sidecar prepared alongside the checkout 334let dev =dev_node_candidate ( res); 335if dev. exists () { 336return Ok ( dev); 337} 338Err ( format! ( 339"the bundled Node runtime is missing (looked for {} and {})" , 340 bundled. display (), 341 dev. display () 342)) 343} 344 345/// A packaged GUI app must not flash a console window for the host process on Windows. 346# [ cfg ( windows )] 347fn hide_console ( cmd : & mut Command ) { 348use std:: os:: windows:: process:: CommandExt ; 349const CREATE_NO_WINDOW : u32 =0x0800_0000 ; 350 cmd. creation_flags ( CREATE_NO_WINDOW ); 351} 352 353# [ cfg ( not ( windows ))] 354fn hide_console ( _cmd : & mut Command ) {} 355 356/// Wait until the host answers `/api/health`, or give up. 357fn wait_for_health ( 358port : u16 , 359timeout : Duration , 360mut exited : impl FnMut () ->Option < String >, 361) ->Result <(), String > { 362let deadline =Instant :: now () + timeout; 363let url =format! ( "http://127.0.0.1:{port}/api/health" ); 364let mut last =String :: from ( "no attempt made" ); 365while Instant :: now () < deadline{ 366// A host that already died will never answer: say so now instead of after the timeout. 367if let Some ( why) =exited () { 368return Err ( format! ( "the Strata App Host stopped before it became healthy: {why}" )); 369} 370match ureq_get_ok ( & url) { 371Ok ( true ) =>return Ok (()), 372Ok ( false ) => last ="the host answered with a non-2xx status" . into (), 373Err ( e) => last = e, 374} 375 std:: thread:: sleep ( Duration :: from_millis ( 250 )); 376} 377Err ( format! ( "the Strata App Host did not become healthy at {url}: {last}" )) 378} 379 380/// A minimal blocking HTTP POST with no body (the shell's one clean-stop request). Returns the status line. 381fn http_post ( url : & str , headers : & [( & str , & str )]) ->Result < String , String > { 382http_request ( "POST" , url, headers). map ( |( status, _) | status) 383} 384 385/// GET returning the response body (the self-test reads `/api/control/status`). 386fn http_get_body ( url : & str ) ->Result <( String , String ), String > { 387http_request ( "GET" , url, & []) 388} 389 390fn http_request ( method : & str , url : & str , headers : & [( & str , & str )]) ->Result <( String , String ), String > { 391http_request_body ( method, url, headers, None ) 392} 393 394/// Like `http_request`, with an optional body (sent as given; the caller sets content-type in `headers`). 395fn http_request_body ( method : & str , url : & str , headers : & [( & str , & str )], body : Option < & str >) ->Result <( String , String ), String > { 396use std:: io::{ Read , Write }; 397let rest = url. strip_prefix ( "http://" ). ok_or ( "only http:// is supported" ) ?; 398let ( authority, path) =match rest. find ( '/' ) { 399Some ( i) =>( & rest[ ..i], & rest[ i..]), 400None =>( rest, "/" ), 401}; 402let mut stream = std:: net:: TcpStream :: connect_timeout ( 403& authority. parse (). map_err ( |e|format! ( "bad authority {authority}: {e}" )) ?, 404Duration :: from_millis ( 800 ), 405) 406. map_err ( |e| e. to_string ()) ?; 407 stream. set_read_timeout ( Some ( Duration :: from_secs ( 20 ))). map_err ( |e| e. to_string ()) ?; 408let extra: String = headers. iter (). map ( |( k, v) |format! ( "{k}: {v}\r\n" )). collect (); 409 stream 410. write_all ( format! ( "{method} {path} HTTP/1.1\r\nHost: {authority}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n{}" , body. map ( str :: len). unwrap_or ( 0 ), body. unwrap_or ( "" )). as_bytes ()) 411. map_err ( |e| e. to_string ()) ?; 412let mut buf =String :: new (); 413 stream. read_to_string ( & mut buf). map_err ( |e| e. to_string ()) ?; 414let status = buf. lines (). next (). unwrap_or_default (). to_string (); 415let response = buf. split_once ( "\r\n\r\n" ). map ( |( _, b) | b. to_string ()). unwrap_or_default (); 416Ok (( status, response)) 417} 418 419/// A minimal blocking HTTP GET, so the shell needs no async runtime for one health probe. 420fn ureq_get_ok ( url : & str ) ->Result < bool , String > { 421use std:: io::{ Read , Write }; 422let rest = url. strip_prefix ( "http://" ). ok_or ( "only http:// is supported" ) ?; 423let ( authority, path) =match rest. find ( '/' ) { 424Some ( i) =>( & rest[ ..i], & rest[ i..]), 425None =>( rest, "/" ), 426}; 427let mut stream = std:: net:: TcpStream :: connect_timeout ( 428& authority 429. parse () 430. map_err ( |e|format! ( "bad authority {authority}: {e}" )) ?, 431Duration :: from_millis ( 800 ), 432) 433. map_err ( |e| e. to_string ()) ?; 434 stream 435. set_read_timeout ( Some ( Duration :: from_millis ( 1500 ))) 436. map_err ( |e| e. to_string ()) ?; 437 stream 438. write_all ( format! ( "GET {path} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n" ). as_bytes ()) 439. map_err ( |e| e. to_string ()) ?; 440let mut buf =String :: new (); 441 stream. read_to_string ( & mut buf). map_err ( |e| e. to_string ()) ?; 442let status = buf. lines (). next (). unwrap_or_default (); 443Ok ( status. contains ( " 200" ) || status. contains ( " 204" )) 444} 445 446/// The App Host's command, ready to start: the bundled Node runs the host on `port`, serving the built UI, on 127.0.0.1 only. 447/// `shutdown_token` is the secret that lets the shell (and nothing else) ask the host for a clean stop. 448fn host_command ( res : & Path , port : u16 , shutdown_token : & str ) ->Result < Command , String > { 449let host_dir =if res. join ( "host" ). join ( "server" ). join ( "index.mjs" ). exists () { 450 res. join ( "host" ) 451} else { 452 res. join ( ".." ). join ( "host" ) 453}; 454let entry = host_dir. join ( "server" ). join ( "index.mjs" ); 455if !entry. exists () { 456return Err ( format! ( "the App Host entry is missing at {}" , entry. display ())); 457} 458let dist = host_dir. join ( "dist" ); 459if !dist. exists () { 460return Err ( format! ( 461"the built UI is missing at {}; run \"npm --prefix host run build\"" , 462 dist. display () 463)); 464} 465let node =node_binary ( res) ?; 466 467let mut cmd =Command :: new ( & node); 468 cmd. arg ( & entry) 469. current_dir ( & host_dir) 470. env ( "STRATA_PORT" , port. to_string ()) 471. env ( "STRATA_DIST" , & dist) 472. env ( "NODE_ENV" , "production" ) 473// U12: a packaged build must have no success path that uses demo responses or demo 474// metrics. `STRATA_PACKAGED` makes the host refuse to simulate; `STRATA_REAL_ENGINE` is set 475// for the same reason, so the monitor reports `none` instead of fabricated numbers. 476. env ( "STRATA_PACKAGED" , "1" ) 477. env ( "STRATA_REAL_ENGINE" , "1" ) 478// the host leaves, after stopping what this app started, when this shell is gone (killed, crashed) 479. env ( "STRATA_EXIT_WITH_PARENT" , "1" ) 480// the host listens on the loopback address only, whatever the caller's environment says 481. env ( "STRATA_BIND" , "127.0.0.1" ) 482. env ( "STRATA_SHUTDOWN_TOKEN" , shutdown_token) 483. stdin ( Stdio :: null ()) 484. stdout ( Stdio :: inherit ()) 485. stderr ( Stdio :: inherit ()); 486apply_runtime_policy ( & mut cmd, res); 487hide_console ( & mut cmd); 488if let Some ( notice) =PORT_NOTICE . lock (). unwrap (). clone () { 489 cmd. env ( "STRATA_PORT_NOTICE" , notice); 490} 491// A user with the Strata API worker on a different port sets this; unset means the worker's 492// documented loopback default. 493if let Ok ( url) = std:: env:: var ( "STRATA_SERVER_URL" ) { 494 cmd. env ( "STRATA_SERVER_URL" , url); 495} 496Ok ( cmd) 497} 498 499/// Windows and macOS: start the App Host from inside the app process and return the port it serves on. 500# [ cfg ( not ( target_os = "linux" ))] 501fn start_host ( app : & tauri:: AppHandle ) ->Result < u16 , String > { 502let res =resource_dir ( app) ?; 503let port =pick_stable_port () ?; 504let token =random_token (); 505let mut cmd =host_command ( & res, port, & token) ?; 506// The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge. 507let bridge = updater:: start ( app, random_token ()); 508 updater:: apply_env ( & mut cmd, app, bridge. as_ref ()); 509* app. state ::< ShutdownToken >(). 0 . lock (). unwrap () =Some ( token); 510 511let node =node_binary ( & res) ?; 512// The host's lines go to the run log (a packaged Windows app has no console, so they were lost before). 513let log = desktoplog:: run_log (); 514if log. is_some () { 515 cmd. stdout ( Stdio :: piped ()). stderr ( Stdio :: piped ()); 516} 517let mut child = cmd 518. spawn () 519. map_err ( |e|format! ( "could not start the App Host on {}: {e}" , node. display ())) ?; 520if let Some ( log) = log{ 521let ring = desktoplog:: Ring :: default (); 522if let Some ( out) = child. stdout . take () { 523 desktoplog:: tee ( out, "host" , false , ring. clone (), log. clone ()); 524} 525if let Some ( err) = child. stderr . take () { 526 desktoplog:: tee ( err, "host" , true , ring, log); 527} 528} 529* app. state ::< HostProcess >(). 0 . lock (). unwrap () =Some ( child); 530* app. state ::< HostPort >(). 0 . lock (). unwrap () =Some ( port); 531 532let state_app = app. clone (); 533wait_for_health ( port, Duration :: from_secs ( 60 ), move ||{ 534let state = state_app. state ::< HostProcess >(); 535let mut guard = state. 0 . lock (). unwrap (); 536match guard. as_mut (). map ( |c| c. try_wait ()) { 537Some ( Ok ( Some ( status))) =>Some ( format! ( "exit status {status}" )), 538 _ =>None , 539} 540}) ?; 541Ok ( port) 542} 543 544/// How long the host gets to stop the engines this app started (drain, then end) before it is ended. The host's own 545/// deadline is shorter; whatever is still running when the shell exits is ended by the job object / the owners. 546const HOST_STOP_SECONDS : u64 =60 ; 547 548/// Stop the App Host, and with it the engines this app started. 549/// 550/// The host stops them through Control (profiles `app-N`), then exits. Engines another client started (the 551/// Terminal's `strata runtime start`) are not touched. If the host does not finish in time it is ended, and the 552/// engines are ended by the job object (Windows) or by their owners following the host (`--die-with-pid`). 553# [ cfg ( not ( target_os = "linux" ))] 554fn stop_host ( app : & tauri:: AppHandle ) { 555let port = app. try_state ::< HostPort >(). and_then ( |s|* s. 0 . lock (). unwrap ()); 556let token = app. try_state ::< ShutdownToken >(). and_then ( |s| s. 0 . lock (). unwrap (). clone ()); 557if let Some ( state) = app. try_state ::< HostProcess >() { 558if let Some ( mut child) = state. 0 . lock (). unwrap (). take () { 559stop_host_child ( & mut child, port, token. as_deref ()); 560} 561} 562} 563 564/// End the host at once, without the clean stop (a start that failed: there is nothing to drain). 565# [ cfg ( not ( target_os = "linux" ))] 566fn kill_host ( app : & tauri:: AppHandle ) { 567if let Some ( state) = app. try_state ::< HostProcess >() { 568if let Ok ( mut guard) = state. 0 . lock () { 569if let Some ( mut child) = guard. take () { 570let _ = child. kill (); 571let _ = child. wait (); 572} 573} 574} 575} 576 577/// A clean stop first: the host stops, through Control, the engines this app started, then exits. Engines another client 578/// started (the Terminal) are not touched. If it does not finish in time the process is ended. 579fn stop_host_child ( child : & mut Child , port : Option < u16 >, token : Option < & str >) { 580if let ( Some ( port), Some ( token)) =( port, token) { 581let _ =http_post ( & format! ( "http://127.0.0.1:{port}/api/control/shutdown" ), & [( "x-strata-shutdown" , token)]); 582let deadline =Instant :: now () +Duration :: from_secs ( HOST_STOP_SECONDS ); 583while Instant :: now () < deadline{ 584if let Ok ( Some ( _)) = child. try_wait () { 585return ; 586} 587 std:: thread:: sleep ( Duration :: from_millis ( 100 )); 588} 589} 590let _ = child. kill (); 591let _ = child. wait (); 592} 593 594/// Where a packaged build keeps `bundle.resources`, found from the executable's own path. 595/// 596/// macOS `.app`: `Contents/MacOS/<exe>` -> `Contents/Resources`. Windows NSIS: next to the exe. 597/// Linux deb/AppImage: `<prefix>/bin/<exe>` -> `<prefix>/lib/<productName>`. 598fn packaged_resource_dir ( exe : & Path ) ->Option < PathBuf > { 599let dir = exe. parent () ?; 600let mut candidates =vec! [ dir. to_path_buf ()]; 601if let Some ( up) = dir. parent () { 602 candidates. push ( up. join ( "Resources" )); 603 candidates. push ( up. join ( "lib" ). join ( "Strata" )); 604 candidates. push ( up. join ( "lib" ). join ( "strata-desktop" )); 605} 606 candidates 607. into_iter () 608. find ( |p| p. join ( "host" ). join ( "server" ). join ( "index.mjs" ). exists ()) 609} 610 611/// Parse `--self-test[=path]`; returns the report path when the flag is present. 612fn self_test_path ( args : & [ String ]) ->Option < String > { 613for ain args. iter (). skip ( 1 ) { 614if a =="--self-test" { 615return Some ( 616 std:: env:: temp_dir () 617. join ( "strata-desktop-self-test.json" ) 618. to_string_lossy () 619. into_owned (), 620); 621} 622if let Some ( rest) = a. strip_prefix ( "--self-test=" ) { 623return Some ( rest. to_string ()); 624} 625} 626None 627} 628 629/// Run `strata.py --version` on the bundle's own interpreter with a scrubbed environment. 630fn control_runs ( dir : & Path ) ->( bool , String ) { 631let python =if cfg! ( windows) { dir. join ( "python" ). join ( "python.exe" ) } else { dir. join ( "python" ). join ( "bin" ). join ( "python3" ) }; 632let mut cmd =Command :: new ( & python); 633 cmd. arg ( dir. join ( "strata.py" )). arg ( "--version" ). current_dir ( dir) 634. env_remove ( "PYTHONHOME" ). env_remove ( "PYTHONPATH" ). env_remove ( "VIRTUAL_ENV" ) 635. env ( "PYTHONNOUSERSITE" , "1" ). env ( "PYTHONDONTWRITEBYTECODE" , "1" ). env ( "STRATA_NO_ACQUIRE" , "1" ); 636hide_console ( & mut cmd); 637match cmd. output () { 638Ok ( out) =>{ 639let text =String :: from_utf8_lossy ( & out. stdout ). trim (). to_string (); 640let ok = out. status . success () && text. contains ( "python 3.12" ) && text. contains ( & dir. display (). to_string ()); 641( ok, if text. is_empty () { String :: from_utf8_lossy ( & out. stderr ). trim (). to_string () } else { text}) 642} 643Err ( e) =>( false , format! ( "could not start {}: {e}" , python. display ())), 644} 645} 646 647/// With an empty component folder Control must say there is no engine and name the explicit command, exit 5, 648/// and must not create or fetch anything. 649fn control_engine_notice ( dir : & Path ) ->( bool , String ) { 650let python =if cfg! ( windows) { dir. join ( "python" ). join ( "python.exe" ) } else { dir. join ( "python" ). join ( "bin" ). join ( "python3" ) }; 651let empty = std:: env:: temp_dir (). join ( format! ( "strata-self-test-components-{}" , std:: process:: id ())); 652let _ = std:: fs:: remove_dir_all ( & empty); 653let mut cmd =Command :: new ( & python); 654 cmd. arg ( dir. join ( "strata.py" )). args ([ "components" , "engine" , "--backend" , "cuda" , "--output" , "json" ]) 655. arg ( "--components-dir" ). arg ( & empty). current_dir ( dir) 656. env_remove ( "PYTHONHOME" ). env_remove ( "PYTHONPATH" ) 657. env ( "PYTHONNOUSERSITE" , "1" ). env ( "PYTHONDONTWRITEBYTECODE" , "1" ). env ( "STRATA_NO_ACQUIRE" , "1" ); 658hide_console ( & mut cmd); 659let result =match cmd. output () { 660Ok ( out) =>{ 661let text =String :: from_utf8_lossy ( & out. stdout ). to_string (); 662let notice = text. contains ( "never downloads an engine" ); 663let created = empty. exists (); 664( out. status . code () ==Some ( 5 ) && notice && !created, format! ( "exit {:?}; notice={notice}; folder created={created}" , out. status . code ())) 665} 666Err ( e) =>( false , e. to_string ()), 667}; 668let _ = std:: fs:: remove_dir_all ( & empty); 669 result 670} 671 672/// Start the host from the packaged resources and report what actually happened. 673fn run_self_test ( report_path : & str ) ->i32 { 674let mut steps: Vec <( String , bool , String )> =Vec :: new (); 675let mut record = |name : & str , ok : bool , detail : String |{ 676 steps. push (( name. to_string (), ok, detail)); 677}; 678 679// Resolve resources the same way the real app does: `Contents/Resources` next to the 680// executable when packaged, the repository layout otherwise. 681let exe = std:: env:: current_exe (). unwrap_or_default (); 682let packaged_res =packaged_resource_dir ( & exe); 683 684let res =match packaged_res{ 685Some ( p) =>{ 686record ( "resources-packaged" , true , p. display (). to_string ()); 687 p 688} 689None =>{ 690let dev =PathBuf :: from ( env! ( "CARGO_MANIFEST_DIR" )); 691record ( 692"resources-packaged" , 693false , 694format! ( "not a packaged layout; using development root {}" , dev. display ()), 695); 696 dev 697} 698}; 699 700let host_dir =if res. join ( "host" ). join ( "server" ). join ( "index.mjs" ). exists () { 701 res. join ( "host" ) 702} else { 703 res. join ( ".." ). join ( "host" ) 704}; 705let entry = host_dir. join ( "server" ). join ( "index.mjs" ); 706let dist = host_dir. join ( "dist" ); 707record ( "host-entry-present" , entry. exists (), entry. display (). to_string ()); 708record ( "ui-dist-present" , dist. join ( "index.html" ). exists (), dist. display (). to_string ()); 709 710let node =match node_binary ( & res) { 711Ok ( n) =>{ 712let mut probe =Command :: new ( & n); 713 probe. arg ( "--version" ); 714hide_console ( & mut probe); 715let version_ok = probe 716. output () 717. map ( |o| o. status . success ()) 718. unwrap_or ( false ); 719record ( "private-node-runtime" , version_ok, n. display (). to_string ()); 720 n 721} 722Err ( e) =>{ 723record ( "private-node-runtime" , false , e. clone ()); 724return write_self_test_report ( report_path, steps, & e); 725} 726}; 727 728// Closing must always end what the app started: on Windows the shell sits in a kill-on-close job object. 729if cfg! ( windows) { 730record ( "shell-contained-in-kill-on-close-job" , app_is_contained (), "IsProcessInJob" . into ()); 731} 732 733let port =match pick_port () { 734Ok ( p) => p, 735Err ( e) =>return write_self_test_report ( report_path, steps, & e), 736}; 737 738let mut cmd =Command :: new ( & node); 739 cmd. arg ( & entry) 740. current_dir ( & host_dir) 741. env ( "STRATA_PORT" , port. to_string ()) 742. env ( "STRATA_DIST" , & dist) 743. env ( "STRATA_PACKAGED" , "1" ) 744. env ( "STRATA_REAL_ENGINE" , "1" ) 745. stdin ( Stdio :: null ()) 746. stdout ( Stdio :: null ()) 747. stderr ( Stdio :: null ()); 748apply_runtime_policy ( & mut cmd, & res); 749hide_console ( & mut cmd); 750let mut child =match cmd. spawn () { 751Ok ( c) =>{ 752record ( "host-spawned" , true , format! ( "pid {}" , c. id ())); 753 c 754} 755Err ( e) =>{ 756let msg =format! ( "spawn failed: {e}" ); 757record ( "host-spawned" , false , msg. clone ()); 758return write_self_test_report ( report_path, steps, & msg); 759} 760}; 761 762let healthy =wait_for_health ( port, Duration :: from_secs ( 45 ), ||match child. try_wait () { 763Ok ( Some ( status)) =>Some ( format! ( "exit status {status}" )), 764 _ =>None , 765}); 766record ( "host-healthy" , healthy. is_ok (), match & healthy{ 767Ok (()) =>format! ( "http://127.0.0.1:{port}/api/health answered 2xx" ), 768Err ( e) => e. clone (), 769}); 770 771// The UI must actually be served from the bundle, not merely present on disk. 772let ui_ok =ureq_get_ok ( & format! ( "http://127.0.0.1:{port}/" )). unwrap_or ( false ); 773record ( "ui-served" , ui_ok, format! ( "http://127.0.0.1:{port}/" )); 774 775// The API the renderer will call must be reachable on the same origin. 776let api_ok =ureq_get_ok ( & format! ( "http://127.0.0.1:{port}/api/health" )). unwrap_or ( false ); 777record ( "api-reachable-on-same-origin" , api_ok, "GET /api/health" . into ()); 778 779// The bundled Control component: present, runs on its own interpreter, and the host sees it with acquiring forbidden. 780match control_dir ( & res) { 781Some ( dir) =>{ 782record ( "control-component-present" , true , dir. display (). to_string ()); 783let ( ok, detail) =control_runs ( & dir); 784record ( "control-runs-on-bundled-python" , ok, detail); 785let ( ok, detail) =control_engine_notice ( & dir); 786record ( "engine-missing-is-a-notice-not-a-download" , ok, detail); 787} 788None =>record ( "control-component-present" , false , format! ( "no control component under {}" , res. display ())), 789} 790let status =http_get_body ( & format! ( "http://127.0.0.1:{port}/api/control/status" )); 791let ( status_ok, status_detail) =match & status{ 792Ok (( line, body)) =>{ 793let parsed: serde_json:: Value = serde_json:: from_str ( body). unwrap_or ( serde_json:: Value :: Null ); 794let forbidden = parsed[ "acquisition" ][ "forbidden" ] == serde_json:: Value :: Bool ( true ); 795let control = parsed[ "control" ][ "python" ]. is_string (); 796( line. contains ( " 200" ) && forbidden && control, format! ( "{line}; acquisition.forbidden={forbidden}; control={control}" )) 797} 798Err ( e) =>( false , e. clone ()), 799}; 800record ( "host-sees-control-and-forbids-acquiring" , status_ok, status_detail); 801 802let _ = child. kill (); 803let _ = child. wait (); 804 805let msg =if steps. iter (). all ( |( _, ok, _) |* ok) { 806String :: new () 807} else { 808"one or more steps failed" . into () 809}; 810write_self_test_report ( report_path, steps, & msg) 811} 812 813/// Write the JSON report and return the process exit code. 814fn write_self_test_report ( path : & str , steps : Vec <( String , bool , String )>, error : & str ) ->i32 { 815let ok = !steps. is_empty () && steps. iter (). all ( |( _, o, _) |* o); 816let steps_json: Vec < serde_json:: Value > = steps 817. iter () 818. map ( |( name, ok, detail) |{ 819 serde_json:: json!({ "name" : name, "ok" : ok, "detail" : detail}) 820}) 821. collect (); 822let report = serde_json:: json!({ 823"schemaVersion" : 1 , 824"kind" : "strata-desktop-self-test" , 825"carrier" : "tauri" , 826"ok" : ok, 827"error" : error, 828"steps" : steps_json, 829}); 830let text = serde_json:: to_string_pretty ( & report). unwrap_or_else ( |_|"{}" . into ()); 831if let Err ( e) = std:: fs:: write ( path, & text) { 832eprintln! ( "[strata] could not write the self-test report to {path}: {e}" ); 833} 834println! ( "{text}" ); 835if ok{ 8360 837} else { 8381 839} 840} 841 842fn main () { 843// ------------------------------------------------------------------ self-test 844// 845// `Strata.app/Contents/MacOS/strata-desktop --self-test[=path]` starts the App Host from the 846// *packaged resources*, waits for it to answer, checks that it serves the supplied UI, writes a 847// JSON report and exits 0/1. This is what makes the shipped artifact verifiable without a human 848// at the screen — the lesson from the Electron attempt, where a packaged app that never started 849// its host hung with no output at all. 850let args: Vec < String > = std:: env:: args (). collect (); 851// Windows and macOS: the run log and the panic hook come first, before anything that can fail. A start that goes wrong then leaves a 852// log, a crash file and a message box instead of a process that is gone with 0xc0000409 and nothing else (Linux: supervisor.rs). 853# [ cfg ( not ( target_os = "linux" ))] 854 desktoplog:: init_startup ( self_test_path ( & args). is_none ()); 855contain_app (); 856# [ cfg ( target_os = "linux" )] 857{ 858// WebKitGTK's DMA-BUF renderer shows a blank window on several NVIDIA + Wayland desktops (and some virtual GPUs); the plain 859// renderer is slower to start by a hair and always works. Anyone who set the variable themselves keeps their choice. 860if std:: env:: var_os ( "WEBKIT_DISABLE_DMABUF_RENDERER" ). is_none () { 861 std:: env:: set_var ( "WEBKIT_DISABLE_DMABUF_RENDERER" , "1" ); 862} 863} 864if let Some ( path) =self_test_path ( & args) { 865let code =run_self_test ( & path); 866 std:: process:: exit ( code); 867} 868 869// Linux: this executable is two programs. The shell (no GTK, no WebKit) owns the host and survives a crash of the window; the 870// window process (`--window-child`) only shows the page. See supervisor.rs. 871# [ cfg ( target_os = "linux" )] 872{ 873let options = supervisor:: parse_args ( & args, std:: env:: var ( "STRATA_UI" ). ok (). as_deref ()); 874if !options. window_child { 875 std:: process:: exit ( supervisor:: run ( & options)); 876} 877// A window process its shell did not start is the app updater's restart (the shell that owned the window is stopping): start Strata again normally. 878if !supervisor:: started_by_shell ( std:: env:: var ( supervisor:: SHELL_PID_ENV ). ok (). as_deref (), std:: os:: unix:: process:: parent_id ()) { 879 std:: process:: exit ( supervisor:: restart_after_update ()); 880} 881run_window_process (); 882} 883# [ cfg ( not ( target_os = "linux" ))] 884run_embedded (); 885} 886 887/// Windows and macOS: one process owns the host and the window. 888# [ cfg ( not ( target_os = "linux" ))] 889fn run_embedded () { 890let builder = tauri:: Builder :: default (); 891// macOS: WKWebView ends the page's web content process under memory pressure and leaves a blank window; the page is loaded again (#5079). 892# [ cfg ( target_os = "macos" )] 893let builder = builder. on_web_content_process_terminate ( |webview|{ 894let port = webview. app_handle (). state ::< HostPort >(). 0 . lock (). ok (). and_then ( |p|* p); 895let Some ( port) = portelse { return }; 896let failed = webview. url (). ok (). map ( |u| u. to_string ()); 897let target = webview. clone (); 898on_renderer_failure ( format! ( "http://127.0.0.1:{port}" ), recovery:: Failure :: RendererExited , "web content process terminated" . to_string (), failed, move |url|{ 899if let Ok ( url) = url. parse ::< tauri:: Url >() { let _ = target. navigate ( url); } 900}); 901}); 902 builder 903// First, as the plugin requires: a second launch ends here after telling the running app to show itself. 904. plugin ( tauri_plugin_single_instance:: init ( |app, _args, _cwd|{ 905if let Some ( window) = app. get_webview_window ( "main" ) { 906let _ = window. unminimize (); 907let _ = window. show (); 908let _ = window. set_focus (); 909} 910})) 911. plugin ( tauri_plugin_shell:: init ()) 912. plugin ( tauri_plugin_updater:: Builder :: new (). build ()) 913. plugin ( tauri_plugin_notification:: init ()) 914. manage ( HostProcess ( Mutex :: new ( None ))) 915. manage ( HostPort ( Mutex :: new ( None ))) 916. manage ( ShutdownToken ( Mutex :: new ( None ))) 917. setup ( |app|{ 918// A way to prove the safety net on a computer where the app starts fine (tests only): a panic at the place a setup error ends in. 919if std:: env:: var_os ( "STRATA_DESKTOP_TEST_PANIC" ). is_some () { 920panic! ( "STRATA_DESKTOP_TEST_PANIC is set: the app panics on purpose" ); 921} 922let handle = app. handle (). clone (); 923// A setup error would become a panic inside Tauri ("Failed to setup app"), and with panic = "abort" a crash with no message. 924// A failed start is reported (log, crash file, message box) and ends the app here instead. 925let port =match start_host ( & handle) { 926Ok ( port) => port, 927Err ( e) =>{ 928kill_host ( & handle); 929 desktoplog:: startup_failed ( & e) 930} 931}; 932let shell_token = handle. state ::< ShutdownToken >(). 0 . lock (). map ( |t| t. clone (). unwrap_or_default ()). unwrap_or_default (); 933if let Err ( e) =open_window ( app, port, & shell_token) { 934kill_host ( & handle); 935 desktoplog:: startup_failed ( & format! ( "the Strata window could not be opened: {e}" )) 936} 937Ok (()) 938}) 939. on_window_event ( |window, event|{ 940// "Minimise to tray" (Settings, off by default): closing the main window hides it and keeps Strata running in the tray; Quit in the 941// tray menu ends it (#3477). If no tray could be made the window closes as before. 942if let tauri:: WindowEvent :: CloseRequested { api, ..} = event{ 943if window. label () =="main" { 944let prefs = shell:: read_prefs (); 945if prefs. tray { 946 api. prevent_close (); 947 shell:: hide_to_tray ( & window. app_handle (). clone (), & prefs. language ); 948if !shell:: tray_exists ( & window. app_handle (). clone ()) { 949let _ = window. destroy (); 950} 951} 952} 953} 954if let tauri:: WindowEvent :: Destroyed = event{ 955stop_host ( & window. app_handle (). clone ()); 956} 957}) 958. build ( tauri:: generate_context!()) 959. unwrap_or_else ( |e| desktoplog:: startup_failed ( & format! ( "the Strata application could not be built: {e}" ))) 960. run ( |app, event|{ 961if let tauri:: RunEvent :: ExitRequested { ..} | tauri:: RunEvent :: Exit = event{ 962stop_host ( app); 963} 964}); 965} 966 967/// The one window, on the host's own origin so the page and its API share an origin exactly as the browser build does. 968# [ cfg_attr ( windows , allow ( unused_variables ))] 969fn open_window ( app : & tauri:: App , port : u16 , shell_token : & str ) ->Result <(), Box < dyn std:: error:: Error >> { 970let origin =format! ( "http://127.0.0.1:{port}" ); 971let url = origin. parse (). expect ( "a valid loopback URL" ); 972let builder =WebviewWindowBuilder :: new ( app, "main" , WebviewUrl :: External ( url)). title ( "Strata" ). inner_size ( 1440.0 , 920.0 ). min_inner_size ( 900.0 , 600.0 ); 973// Dropping pictures on the chat (QA report 1, item 4). Windows: the shell's own file-drop handler is off, because with it on the system hands 974// the dropped file to the shell and the page never sees it; with it off the page gets ordinary drag and drop events (apps/host DropZone), as 975// in a browser. Linux and macOS: the page gets the drag events but WebKit gives it no files, so the handler stays on and the shell passes the 976// drop on (see drop_script and hand_over_drop below). 977# [ cfg ( windows )] 978let builder = builder. disable_drag_drop_handler (); 979// WebKitGTK (2.50 to 2.52 at least) dereferences a null pointer in AcceleratedBackingStore::update in its UI process when a page calls 980// document.startViewTransition (the web process asks the UI process to enter accelerated compositing, and the backing store is not 981// there). The page itself does not call it on that engine (apps/host/src/lib/router.ts), and this line keeps any other script from doing 982// it either: the API is simply absent, as in older WebKit versions. 983# [ cfg ( target_os = "linux" )] 984let builder = builder. initialization_script ( 985"try { Object.defineProperty(Document.prototype, 'startViewTransition', { value: undefined, configurable: true, writable: true }); } catch (e) {}" , 986); 987# [ cfg_attr ( windows , allow ( unused_variables ))] 988let window = builder. build () ?; 989# [ cfg ( not ( windows ))] 990{ 991let target = window. clone (); 992let token = shell_token. to_string (); 993 window. on_webview_event ( move |event|{ 994if let tauri:: WebviewEvent :: DragDrop ( drag) = event{ 995match drag{ 996 tauri:: DragDropEvent :: Enter { ..} =>{ let _ = target. eval ( & drag_script ( "enter" )); } 997 tauri:: DragDropEvent :: Leave =>{ let _ = target. eval ( & drag_script ( "leave" )); } 998 tauri:: DragDropEvent :: Drop { paths, ..} =>{ 999let _ = target. eval ( & drag_script ( "leave" )); 1000let paths: Vec < String > = paths. iter (). map ( |p| p. to_string_lossy (). into_owned ()). collect (); 1001hand_over_drop ( target. clone (), port, token. clone (), paths); 1002} 1003 _ =>{} 1004} 1005} 1006}); 1007} 1008# [ cfg ( target_os = "linux" )] 1009hook_linux_drops ( & window, port, shell_token); 1010# [ cfg ( windows )] 1011hook_renderer_failures ( & window, port); 1012Ok (()) 1013} 1014 1015/// Milliseconds since the first failure report or window (a clock that only goes forward, for the recovery limit). 1016# [ cfg ( not ( target_os = "linux" ))] 1017fn uptime_ms () ->u64 { 1018static START : std:: sync:: OnceLock < Instant > = std:: sync:: OnceLock :: new (); 1019START . get_or_init ( Instant :: now). elapsed (). as_millis () as u64 1020} 1021 1022/// The page's renderer is gone (#5079). Writes it to the run log, and, when the window needs the page again, loads it again through 1023/// `navigate` after a short wait: the same screen with `?recovery=1` the first time (the page then starts with the sidebar previews 1024/// closed once), the home screen the second time, and nothing after two in two minutes. The chats are the host's and are not touched. 1025# [ cfg ( not ( target_os = "linux" ))] 1026fn on_renderer_failure ( origin : String , failure : recovery:: Failure , detail : String , failed : Option < String >, navigate : impl FnOnce ( String ) +Send +' static ) { 1027static GUARD : Mutex < recovery:: Guard > =Mutex :: new ( recovery:: Guard :: new ()); 1028let say = |text : & str |{ if let Some ( log) = desktoplog:: run_log () { log. line ( "shell" , text); } }; 1029say ( & format! ( "the page's {} ({detail}); it was showing {}" , failure. name (), failed. as_deref (). unwrap_or ( "an unknown address" ))); 1030let plan =match GUARD . lock () { 1031Ok ( mut guard) => recovery:: plan ( & mut guard, uptime_ms (), & origin, failure, failed. as_deref ()), 1032Err ( _) => recovery:: Plan :: Stop , 1033}; 1034match plan{ 1035 recovery:: Plan :: Ignore =>{} 1036 recovery:: Plan :: Stop =>say ( "the page's renderer failed again within two minutes of two recoveries; the window is left as it is (Reload in the page loads it again)" ), 1037 recovery:: Plan :: Reload { attempt, url} =>{ 1038say ( & format! ( "loading the page again (recovery {attempt}): {url}" )); 1039 std:: thread:: spawn ( move ||{ 1040 std:: thread:: sleep ( Duration :: from_millis ( recovery:: RELOAD_DELAY_MS )); 1041navigate ( url); 1042}); 1043} 1044} 1045} 1046 1047/// Windows: WebView2 tells the shell when a process of the page fails; the page's renderer dying is recovered by on_renderer_failure. 1048# [ cfg ( windows )] 1049fn hook_renderer_failures ( window : & tauri:: WebviewWindow , port : u16 ) { 1050use webview2_com:: Microsoft :: Web :: WebView2 :: Win32 ::{ ICoreWebView2ProcessFailedEventArgs2 , COREWEBVIEW2_PROCESS_FAILED_KIND }; 1051use webview2_com::{ take_pwstr, ProcessFailedEventHandler }; 1052use windows_core::{ Interface , PWSTR }; 1053let target = window. clone (); 1054let origin =format! ( "http://127.0.0.1:{port}" ); 1055let _ = window. with_webview ( move |platform|unsafe { 1056let Ok ( core) = platform. controller (). CoreWebView2 () else { return }; 1057let handler =ProcessFailedEventHandler :: create ( Box :: new ( move |sender, args|{ 1058let Some ( args) = argselse { return Ok (()) }; 1059let mut kind =COREWEBVIEW2_PROCESS_FAILED_KIND :: default (); 1060 args. ProcessFailedKind ( & mut kind) ?; 1061let mut detail =format! ( "kind {}" , kind. 0 ); 1062if let Ok ( more) = args. cast ::< ICoreWebView2ProcessFailedEventArgs2 >() { 1063let mut reason =Default :: default (); 1064let mut exit_code =0i32 ; 1065if more. Reason ( & mut reason). is_ok () { detail =format! ( "{detail}, reason {}" , recovery:: reason_name ( reason. 0 )); } 1066if more. ExitCode ( & mut exit_code). is_ok () { detail =format! ( "{detail}, exit code {exit_code:#x}" ); } 1067} 1068let failed = sender. and_then ( |view|{ 1069let mut source =PWSTR :: null (); 1070 view. Source ( & mut source). ok () ?; 1071Some ( take_pwstr ( source)) 1072}); 1073let window = target. clone (); 1074on_renderer_failure ( origin. clone (), recovery:: Failure :: from_webview2 ( kind. 0 ), detail, failed, move |url|{ 1075if let Ok ( url) = url. parse ::< tauri:: Url >() { let _ = window. navigate ( url); } 1076}); 1077Ok (()) 1078})); 1079let mut token =0i64 ; 1080let _ = core. add_ProcessFailed ( & handler, & mut token); 1081}); 1082} 1083 1084/// A file:// address from a drag, as a path (percent-escapes decoded); anything else (http, mailto, text) is not a dropped file. 1085# [ cfg_attr ( windows , allow ( dead_code ))] 1086fn file_uri_to_path ( uri : & str ) ->Option < String > { 1087let rest = uri. trim (). strip_prefix ( "file://" ) ?; 1088// file://host/path: only an empty or local host is a file on this computer 1089let rest =match rest. find ( '/' ) { Some ( 0 ) => rest, Some ( i) if rest[ ..i]. eq_ignore_ascii_case ( "localhost" ) =>& rest[ i..], _ =>return None }; 1090let bytes = rest. as_bytes (); 1091let mut out =Vec :: with_capacity ( bytes. len ()); 1092let mut i =0 ; 1093while i < bytes. len () { 1094if bytes[ i] ==b'%' && i +2 < bytes. len () { 1095if let Some ( v) = std:: str:: from_utf8 ( & bytes[ i +1 ..i +3 ]). ok (). and_then ( |h| u8:: from_str_radix ( h, 16 ). ok ()) { out. push ( v); i +=3 ; continue ; } 1096} 1097 out. push ( bytes[ i]); 1098 i +=1 ; 1099} 1100let path =String :: from_utf8 ( out). ok () ?; 1101if path. contains ( '\0' ) { None } else { Some ( path) } 1102} 1103 1104/// Linux: WebKitGTK 2.52 gives the page a file drag without the files, and the window library's own drop handler never sees one, so the 1105/// shell reads the drop itself from the GTK drag signals of the page widget: the file:// addresses arrive with the drag data, the drop hands 1106/// them to the host exactly as the other systems do (hand_over_drop), and the page shows its drop box meanwhile (QA, drop on the chat). 1107# [ cfg ( target_os = "linux" )] 1108fn hook_linux_drops ( window : & tauri:: WebviewWindow , port : u16 , token : & str ) { 1109use gtk:: prelude:: * ; 1110use std:: cell::{ Cell , RefCell }; 1111use std:: rc:: Rc ; 1112let target = window. clone (); 1113let token = token. to_string (); 1114let _ = window. with_webview ( move |platform|{ 1115let view = platform. inner (); 1116let paths: Rc < RefCell < Vec < String >>> =Rc :: new ( RefCell :: new ( Vec :: new ())); 1117let hovering =Rc :: new ( Cell :: new ( false )); 1118let generation =Rc :: new ( Cell :: new ( 0u32 )); 1119{ 1120let ( paths, hovering, generation, target) =( paths. clone (), hovering. clone (), generation. clone (), target. clone ()); 1121 view. connect_drag_data_received ( move |_, _, _, _, data, _, _|{ 1122let list: Vec < String > = data. uris (). iter (). filter_map ( |u|file_uri_to_path ( u. as_str ())). collect (); 1123if list. is_empty () { return ; } 1124* paths. borrow_mut () = list; 1125 generation. set ( generation. get () +1 ); 1126if !hovering. replace ( true ) { let _ = target. eval ( & drag_script ( "enter" )); } 1127}); 1128} 1129{ 1130// WebKit only accepts a drag when the page says so, and the page is not given the files: once the addresses of a file drag are known, 1131// the shell accepts it (as a copy) itself, so GTK goes on to deliver the drop. 1132let paths = paths. clone (); 1133 view. connect_drag_motion ( move |_, ctx, _, _, time|{ 1134if paths. borrow (). is_empty () { return false ; } 1135 ctx. drag_status ( gtk:: gdk:: DragAction :: COPY , time); 1136true 1137}); 1138} 1139{ 1140let ( paths, hovering, generation, target) =( paths. clone (), hovering. clone (), generation. clone (), target. clone ()); 1141let token = token. clone (); 1142 view. connect_drag_drop ( move |_, ctx, _, _, time|{ 1143 generation. set ( generation. get () +1 ); 1144let list = std:: mem:: take ( & mut * paths. borrow_mut ()); 1145if list. is_empty () { return false ; } // not a file: the page deals with it 1146 hovering. set ( false ); 1147 ctx. drop_finish ( true , time); 1148let _ = target. eval ( & drag_script ( "leave" )); 1149hand_over_drop ( target. clone (), port, token. clone (), list); 1150true 1151}); 1152} 1153{ 1154let ( paths, hovering, target, token) =( paths. clone (), hovering. clone (), target. clone (), token. clone ()); 1155 view. connect_drag_leave ( move |widget, _, _|{ 1156// WebKit's own handling of a drop never reaches this widget's drop signal, but GTK does say "leave" at the moment of the drop: 1157// a leave with every mouse button already up (and a file drag known) is the drop. A leave with the button still down is the 1158// pointer going out of the window. 1159if hovering. get () && !paths. borrow (). is_empty () &&pointer_buttons_up ( widget) { 1160let list = std:: mem:: take ( & mut * paths. borrow_mut ()); 1161 hovering. set ( false ); 1162let _ = target. eval ( & drag_script ( "leave" )); 1163hand_over_drop ( target. clone (), port, token. clone (), list); 1164} 1165}); 1166} 1167 view. connect_drag_leave ( move |_, _, _|{ 1168// only a leave that nothing follows ends the drag (a drop is handled above and clears the state) 1169let seen = generation. get (); 1170let ( paths, hovering, generation, target) =( paths. clone (), hovering. clone (), generation. clone (), target. clone ()); 1171 gtk:: glib:: idle_add_local_once ( move ||{ 1172if generation. get () == seen && hovering. replace ( false ) { 1173 paths. borrow_mut (). clear (); 1174let _ = target. eval ( & drag_script ( "leave" )); 1175} 1176}); 1177}); 1178}); 1179} 1180 1181/// True when no mouse button is held down (GTK drag drop: the button is already up when the drop arrives). 1182# [ cfg ( target_os = "linux" )] 1183fn pointer_buttons_up ( widget : & webkit2gtk:: WebView ) ->bool { 1184use gtk:: prelude:: * ; 1185let Some ( window) = widget. window () else { return false }; 1186let Some ( pointer) = gtk:: gdk:: Display :: default (). and_then ( |d| d. default_seat ()). and_then ( |s| s. pointer ()) else { return false }; 1187let ( _, _, _, mask) = window. device_position ( & pointer); 1188 !mask. intersects ( gtk:: gdk:: ModifierType :: BUTTON1_MASK | gtk:: gdk:: ModifierType :: BUTTON2_MASK | gtk:: gdk:: ModifierType :: BUTTON3_MASK ) 1189} 1190 1191/// The script that tells the page a file drag is over the window (`state` is "enter" or "leave"); the page shows its drop box (apps/host DropZone). 1192# [ cfg_attr ( windows , allow ( dead_code ))] 1193fn drag_script ( state : & str ) ->String { 1194format! ( "window.dispatchEvent(new CustomEvent('strata:native-drag', {{ detail: '{state}' }}));" ) 1195} 1196 1197/// The script that tells the page which dropped files the host holds for it (`files_json` is the host's own JSON array of { id, name, type, size }). 1198# [ cfg_attr ( windows , allow ( dead_code ))] 1199fn drop_script ( files_json : & str ) ->String { 1200format! ( "window.dispatchEvent(new CustomEvent('strata:native-drop', {{ detail: {files_json} }}));" ) 1201} 1202 1203/// The files of one drop, by path, to the host (which reads them and keeps each for the page to fetch once); then the page is told. 1204/// Off the window's own thread, so the window never waits for a big picture to be read. 1205# [ cfg ( not ( windows ))] 1206fn hand_over_drop ( window : tauri:: WebviewWindow , port : u16 , token : String , paths : Vec < String >) { 1207 std:: thread:: spawn ( move ||{ 1208let body = serde_json:: json!({ "paths" : paths}). to_string (); 1209let answer =http_request_body ( 1210"POST" , 1211& format! ( "http://127.0.0.1:{port}/api/app/drop" ), 1212& [( "x-strata-shutdown" , token. as_str ()), ( "content-type" , "application/json" )], 1213Some ( & body), 1214); 1215let files =match answer{ 1216Ok (( status, text)) if status. contains ( " 200" ) => serde_json:: from_str ::< serde_json:: Value >( & text). ok (). and_then ( |v| v. get ( "files" ). cloned ()), 1217Ok (( status, _)) =>{ eprintln! ( "[strata] the host did not take the dropped files: {status}" ); None } 1218Err ( e) =>{ eprintln! ( "[strata] the dropped files could not be handed to the host: {e}" ); None } 1219}; 1220let json = files. map ( |f| f. to_string ()). unwrap_or_else ( ||"[]" . to_string ()); 1221let _ = window. eval ( & drop_script ( & json)); 1222}); 1223} 1224 1225/// Linux window process: shows the page of the host the shell started and registers the app updater with it. It starts no host and 1226/// stops nothing: when the window closes it just exits, and the shell stops the host. If WebKit crashes this process, only this 1227/// process dies; the shell moves to browser mode. 1228# [ cfg ( target_os = "linux" )] 1229fn run_window_process () -> !{ 1230let port: u16 = std:: env:: var ( "STRATA_WINDOW_PORT" ). ok (). and_then ( |v| v. parse (). ok ()). unwrap_or ( PREFERRED_PORT ); 1231let token = std:: env:: var ( "STRATA_SHUTDOWN_TOKEN" ). unwrap_or_default (); 1232// A way to prove the safety net on a computer where the window works (tests only): this process dies the way a WebKit crash does. 1233if std:: env:: var_os ( "STRATA_WINDOW_TEST_CRASH" ). is_some () { 1234eprintln! ( "[strata] STRATA_WINDOW_TEST_CRASH is set: the window process aborts on purpose." ); 1235 std:: process:: abort (); 1236} 1237// WebKitGTK aborts while it draws a COLRv1 colour emoji font (fontguard.rs, #4533): this process is told to leave that font out. Only this 1238// process, and before WebKit starts its own: the host, the engine and the agent keep the fonts the person chose. 1239{ 1240let env = |k : & str | std:: env:: var ( k). ok (); 1241let dirs = fontguard:: font_dirs ( & env); 1242if let Some ( conf) = fontguard:: config_for ( & env, & desktoplog:: data_dir (). join ( "fonts" ), & dirs, Path :: new ( fontguard:: SYSTEM_CONFIG )) { 1243 std:: env:: set_var ( "FONTCONFIG_FILE" , conf); 1244} 1245} 1246// The shell is this process's parent: when it is gone (killed, crashed, logged off) the window goes too. 1247let parent = std:: os:: unix:: process:: parent_id (); 1248 std:: thread:: spawn ( move ||loop { 1249 std:: thread:: sleep ( Duration :: from_secs ( 1 )); 1250if std:: os:: unix:: process:: parent_id () != parent{ 1251 std:: process:: exit ( 0 ); 1252} 1253}); 1254 tauri:: Builder :: default () 1255// First, as the plugin requires: a second window process ends here after telling the open window to show itself. 1256. plugin ( tauri_plugin_single_instance:: init ( |app, _args, _cwd|{ 1257if let Some ( window) = tauri:: Manager :: get_webview_window ( app, "main" ) { 1258let _ = window. unminimize (); 1259let _ = window. show (); 1260let _ = window. set_focus (); 1261} 1262})) 1263. plugin ( tauri_plugin_shell:: init ()) 1264. plugin ( tauri_plugin_updater:: Builder :: new (). build ()) 1265. setup ( move |app|{ 1266// The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge; tell the host where it is. 1267let bridge_token =random_token (); 1268if let Some ( bridge) = updater:: start ( app. handle (), bridge_token) { 1269let body = serde_json:: json!({ "bridge" : { "url" : bridge. url , "token" : bridge. token } }). to_string (); 1270if let Err ( e) =http_request_body ( 1271"POST" , 1272& format! ( "http://127.0.0.1:{port}/api/control/ui" ), 1273& [( "x-strata-shutdown" , token. as_str ()), ( "content-type" , "application/json" )], 1274Some ( & body), 1275) { 1276eprintln! ( "[strata] the app updater could not be registered with the host: {e}" ); 1277} 1278} 1279open_window ( app, port, & token) 1280}) 1281. on_window_event ( |window, event|{ 1282if let tauri:: WindowEvent :: Destroyed = event{ 1283 window. app_handle (). exit ( 0 ); 1284} 1285}) 1286. build ( tauri:: generate_context!()) 1287. expect ( "error while building the Strata application" ) 1288. run ( |_app, _event|{}); 1289 std:: process:: exit ( 0 ) 1290} 1291 1292# [ cfg ( test )] 1293mod tests{ 1294use super :: * ; 1295 1296# [ test ] 1297fn dropped_file_addresses_become_paths_and_nothing_else_does () { 1298assert_eq! ( file_uri_to_path ( "file:///home/me/My%20Pictures/a%2Bb.png" ). as_deref (), Some ( "/home/me/My Pictures/a+b.png" )); 1299assert_eq! ( file_uri_to_path ( "file://localhost/tmp/x.txt" ). as_deref (), Some ( "/tmp/x.txt" )); 1300assert_eq! ( file_uri_to_path ( " file:///tmp/%C4%8C.txt\r\n" ). as_deref (), Some ( "/tmp/\u{10C}.txt" )); 1301for badin [ "http://example.com/a.png" , "file://otherhost/tmp/x" , "mailto:a@b.c" , "/tmp/plain" , "file://" , "file:///tmp/a%00b" ] { assert_eq! ( file_uri_to_path ( bad), None , "{bad}" ); } 1302assert_eq! ( file_uri_to_path ( "file:///100%" ). as_deref (), Some ( "/100%" )); 1303} 1304 1305# [ test ] 1306fn the_scripts_the_shell_sends_the_page_for_a_file_drop () { 1307assert_eq! ( drag_script ( "enter" ), "window.dispatchEvent(new CustomEvent('strata:native-drag', { detail: 'enter' }));" ); 1308let files =r#"[{"id":"a","name":"x.png","type":"image/png","size":3}]"# ; 1309let script =drop_script ( files); 1310assert! ( script. starts_with ( "window.dispatchEvent(new CustomEvent('strata:native-drop', { detail: [{" )); 1311assert! ( script. contains ( "x.png" ) && script. ends_with ( "}));" )); 1312} 1313 1314# [ test ] 1315fn the_window_origin_is_stable_unless_the_port_is_taken () { 1316// free (or already ours from a previous run): the same port every launch, so browser storage survives a restart 1317let first =pick_stable_port (). unwrap (); 1318let second =pick_stable_port (). unwrap (); 1319if first ==PREFERRED_PORT { 1320// (when another program already holds the preferred port, as an installed Strata does on a dev PC, every call falls back to a fresh port) 1321assert_eq! ( first, second); 1322} 1323// held by another program: a different free port, not a failure 1324if first ==PREFERRED_PORT { 1325let held =TcpListener :: bind (( "127.0.0.1" , PREFERRED_PORT )). unwrap (); 1326let fallback =pick_stable_port (). unwrap (); 1327assert_ne! ( fallback, PREFERRED_PORT ); 1328drop ( held); 1329} 1330} 1331 1332fn scratch ( name : & str ) ->PathBuf { 1333let dir = std:: env:: temp_dir (). join ( format! ( "strata-desktop-{name}-{}" , std:: process:: id ())); 1334let _ = std:: fs:: remove_dir_all ( & dir); 1335 std:: fs:: create_dir_all ( & dir). unwrap (); 1336 dir 1337} 1338 1339# [ test ] 1340fn bundled_node_uses_the_platform_file_name () { 1341let res =scratch ( "node" ); 1342assert! ( node_binary ( & res). is_err ()); 1343let dir = res. join ( "node" ); 1344 std:: fs:: create_dir_all ( & dir). unwrap (); 1345 std:: fs:: write ( dir. join ( NODE_EXE ), b"" ). unwrap (); 1346assert_eq! ( node_binary ( & res). unwrap (), dir. join ( NODE_EXE )); 1347assert_eq! ( NODE_EXE , if cfg! ( windows) { "node.exe" } else { "node" }); 1348let _ = std:: fs:: remove_dir_all ( & res); 1349} 1350 1351# [ test ] 1352fn verbatim_windows_paths_are_made_plain () { 1353assert_eq! ( plain_path ( PathBuf :: from ( r"\\?\C:\a\b" )), PathBuf :: from ( r"C:\a\b" )); 1354assert_eq! ( 1355plain_path ( PathBuf :: from ( r"\\?\UNC\srv\share\x" )), 1356PathBuf :: from ( r"\\srv\share\x" ) 1357); 1358assert_eq! ( plain_path ( PathBuf :: from ( "/usr/lib/Strata" )), PathBuf :: from ( "/usr/lib/Strata" )); 1359} 1360 1361# [ test ] 1362fn control_is_found_only_when_whole () { 1363let res =scratch ( "control" ); 1364assert! ( control_dir ( & res). is_none ()); 1365let dir = res. join ( "control" ); 1366let py =if cfg! ( windows) { dir. join ( "python" ). join ( "python.exe" ) } else { dir. join ( "python" ). join ( "bin" ). join ( "python3" ) }; 1367 std:: fs:: create_dir_all ( py. parent (). unwrap ()). unwrap (); 1368 std:: fs:: write ( & py, b"" ). unwrap (); 1369assert! ( control_dir ( & res). is_none (), "no strata.py yet" ); 1370 std:: fs:: write ( dir. join ( "strata.py" ), b"" ). unwrap (); 1371assert_eq! ( control_dir ( & res), Some ( dir)); 1372let _ = std:: fs:: remove_dir_all ( & res); 1373} 1374 1375# [ cfg ( windows )] 1376# [ test ] 1377fn a_process_in_the_job_ends_when_the_job_is_closed () { 1378use std:: os:: windows:: io:: AsRawHandle ; 1379let job = job:: Job :: kill_on_close (). expect ( "a job object" ); 1380let mut child =Command :: new ( "ping" ). args ([ "-n" , "120" , "127.0.0.1" ]). stdout ( Stdio :: null ()). spawn (). expect ( "ping" ); 1381assert! ( job. assign_raw ( child. as_raw_handle () as * mut std:: ffi:: c_void ), "the child joins the job" ); 1382assert! ( child. try_wait (). unwrap (). is_none (), "it runs while the job is open" ); 1383drop ( job); // what the system does when the app ends, by any route 1384let deadline =Instant :: now () +Duration :: from_secs ( 10 ); 1385while child. try_wait (). unwrap (). is_none () &&Instant :: now () < deadline{ 1386 std:: thread:: sleep ( Duration :: from_millis ( 50 )); 1387} 1388let ended = child. try_wait (). unwrap (). is_some (); 1389if !ended{ 1390let _ = child. kill (); 1391} 1392assert! ( ended, "closing the job must end its processes" ); 1393} 1394 1395# [ test ] 1396fn the_shells_wait_for_the_host_exceeds_the_hosts_own_deadline_and_stays_bounded () { 1397// the host ends itself after 45 s (server/index.mjs); the shell must wait longer than that, but not for ever 1398assert! ( HOST_STOP_SECONDS >45 &&HOST_STOP_SECONDS <=90 ); 1399} 1400 1401# [ test ] 1402fn shutdown_tokens_are_long_and_different () { 1403let ( a, b) =( random_token (), random_token ()); 1404assert_eq! ( a. len (), 64 ); 1405assert_ne! ( a, b); 1406assert! ( a. chars (). all ( |c| c. is_ascii_hexdigit ())); 1407} 1408 1409# [ test ] 1410fn a_bare_node_is_not_taken_for_the_windows_runtime () { 1411if !cfg! ( windows) { 1412return ; 1413} 1414let res =scratch ( "bare" ); 1415let dir = res. join ( "node" ); 1416 std:: fs:: create_dir_all ( & dir). unwrap (); 1417 std:: fs:: write ( dir. join ( "node" ), b"" ). unwrap (); 1418assert! ( node_binary ( & res). is_err ()); 1419let _ = std:: fs:: remove_dir_all ( & res); 1420} 1421 1422# [ test ] 1423fn packaged_resources_are_found_for_each_platform_layout () { 1424let root =scratch ( "layout" ); 1425for ( exe_rel, res_rel) in [ 1426( "Contents/MacOS/strata-desktop" , "Contents/Resources" ), 1427( "install/strata-desktop.exe" , "install" ), 1428( "usr/bin/strata-desktop" , "usr/lib/Strata" ), 1429] { 1430let exe = root. join ( exe_rel); 1431let res = root. join ( res_rel); 1432assert! ( packaged_resource_dir ( & exe). is_none (), "{exe_rel}" ); 1433let server = res. join ( "host" ). join ( "server" ); 1434 std:: fs:: create_dir_all ( & server). unwrap (); 1435 std:: fs:: write ( server. join ( "index.mjs" ), b"" ). unwrap (); 1436assert_eq! ( packaged_resource_dir ( & exe), Some ( res), "{exe_rel}" ); 1437} 1438let _ = std:: fs:: remove_dir_all ( & root); 1439} 1440 1441# [ test ] 1442fn the_host_command_listens_on_loopback_only_and_carries_the_shutdown_secret () { 1443let res =scratch ( "hostcmd" ); 1444let server = res. join ( "host" ). join ( "server" ); 1445 std:: fs:: create_dir_all ( & server). unwrap (); 1446 std:: fs:: write ( server. join ( "index.mjs" ), b"" ). unwrap (); 1447 std:: fs:: create_dir_all ( res. join ( "host" ). join ( "dist" )). unwrap (); 1448 std:: fs:: create_dir_all ( res. join ( "node" )). unwrap (); 1449 std:: fs:: write ( res. join ( "node" ). join ( NODE_EXE ), b"" ). unwrap (); 1450// a caller's environment must not widen the bind address: the command sets it itself 1451 std:: env:: set_var ( "STRATA_BIND" , "0.0.0.0" ); 1452let cmd =host_command ( & res, 47831 , "s3cret" ). expect ( "a host command" ); 1453 std:: env:: remove_var ( "STRATA_BIND" ); 1454let env: std:: collections:: HashMap < String , String > = cmd 1455. get_envs () 1456. filter_map ( |( k, v) |Some (( k. to_string_lossy (). into_owned (), v?. to_string_lossy (). into_owned ()))) 1457. collect (); 1458assert_eq! ( env. get ( "STRATA_BIND" ). map ( String :: as_str), Some ( "127.0.0.1" )); 1459assert_eq! ( env. get ( "STRATA_PORT" ). map ( String :: as_str), Some ( "47831" )); 1460assert_eq! ( env. get ( "STRATA_SHUTDOWN_TOKEN" ). map ( String :: as_str), Some ( "s3cret" )); 1461assert_eq! ( env. get ( "STRATA_PACKAGED" ). map ( String :: as_str), Some ( "1" )); 1462assert_eq! ( env. get ( "STRATA_NO_ACQUIRE" ). map ( String :: as_str), Some ( "1" )); 1463assert! ( env. get ( "STRATA_DIST" ). unwrap (). ends_with ( "dist" )); 1464// a layout without the built UI or the host is refused in plain words 1465assert! ( host_command ( & scratch ( "empty" ), 1 , "x" ). unwrap_err (). contains ( "App Host entry is missing" )); 1466let _ = std:: fs:: remove_dir_all ( & res); 1467} 1468}