Skip to main content

qualia_client_core/api/
qapp_launcher.rs

1//! Qapp launcher
2
3#![allow(non_snake_case)]
4
5use super::*;
6
7use crate::qapp_paths::{qapps_dir, resolve_package_manifest_path};
8use crate::qapp_registry;
9use serde::Serialize;
10use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13/// Load `qapp.json` for an installed qapp.
14pub fn load_installed_qapp_package(
15    qapp_name: &str,
16) -> Result<qapp_registry::QappPackageManifest, String> {
17    let state = crate::state::APP_STATE
18        .get()
19        .ok_or("APP_STATE not initialized")?;
20    let data_dir = state.config.lock().unwrap().storage_path.clone();
21    let qapp_dir = qapps_dir(&data_dir).join(qapp_name);
22    load_qapp_package_from_dir(&qapp_dir)
23}
24
25/// Loads qapp-package-from-dir.
26pub(crate) fn load_qapp_package_from_dir(
27    qapp_dir: &Path,
28) -> Result<qapp_registry::QappPackageManifest, String> {
29    let manifest_path = resolve_package_manifest_path(qapp_dir)
30        .ok_or_else(|| format!("qapp.json not found in {}", qapp_dir.display()))?;
31    let content = std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?;
32    serde_json::from_str::<qapp_registry::QappPackageManifest>(&content)
33        .map_err(|e| format!("Invalid qapp package manifest: {e}"))
34}
35
36fn resolve_entrypoint_path(
37    manifest: &qapp_registry::QappPackageManifest,
38    entrypoint: Option<&str>,
39) -> String {
40    let named_entrypoints = manifest.x_qualia.as_ref().map(|ext| &ext.entrypoints);
41
42    match entrypoint {
43        Some(requested) if !requested.trim().is_empty() => named_entrypoints
44            .and_then(|map| map.get(requested))
45            .cloned()
46            .unwrap_or_else(|| requested.to_string()),
47        _ => named_entrypoints
48            .and_then(|map| map.get("web"))
49            .cloned()
50            .unwrap_or_else(|| "index.html".to_string()),
51    }
52}
53
54fn split_asset_and_hash(relative_path: &str) -> (String, Option<String>) {
55    let mut parts = relative_path.splitn(2, '#');
56    let asset = parts.next().unwrap_or("").trim().trim_start_matches('/');
57    let hash = parts
58        .next()
59        .map(str::trim)
60        .filter(|value| !value.is_empty());
61    let asset_path = if asset.is_empty() {
62        "index.html".to_string()
63    } else {
64        asset.to_string()
65    };
66    (asset_path, hash.map(str::to_string))
67}
68
69fn encode_query_component(input: &str) -> String {
70    let mut encoded = String::with_capacity(input.len());
71    for byte in input.bytes() {
72        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
73            encoded.push(char::from(byte));
74        } else {
75            encoded.push('%');
76            encoded.push_str(&format!("{:02X}", byte));
77        }
78    }
79    encoded
80}
81
82fn append_launch_context(
83    mut base_url: String,
84    source: Option<String>,
85    surface: Option<String>,
86    payload_json: Option<String>,
87    qapp_name: Option<&str>,
88) -> String {
89    let mut params = Vec::new();
90
91    if let Some(source) = source.filter(|value| !value.trim().is_empty()) {
92        params.push(format!(
93            "qualia_source={}",
94            encode_query_component(source.trim())
95        ));
96    }
97
98    if let Some(surface) = surface.filter(|value| !value.trim().is_empty()) {
99        params.push(format!(
100            "qualia_surface={}",
101            encode_query_component(surface.trim())
102        ));
103    }
104
105    if let Some(payload_json) = payload_json.filter(|value| !value.trim().is_empty()) {
106        params.push(format!(
107            "qualia_payload={}",
108            encode_query_component(payload_json.trim())
109        ));
110    }
111
112    if let Some(qapp_name) = qapp_name.filter(|value| !value.trim().is_empty()) {
113        if let Ok(token) = issue_qapp_session_token(qapp_name.trim()) {
114            params.push(format!("qualia_token={}", encode_query_component(&token)));
115        }
116        let port = get_active_daemon_port();
117        if port > 0 {
118            params.push(format!("qualia_daemon_port={port}"));
119        }
120        params.push(format!(
121            "qualia_qapp={}",
122            encode_query_component(qapp_name.trim())
123        ));
124    }
125
126    if !params.is_empty() {
127        base_url.push(if base_url.contains('?') { '&' } else { '?' });
128        base_url.push_str(&params.join("&"));
129    }
130
131    base_url
132}
133
134fn append_hash_fragment(mut base_url: String, hash_fragment: Option<String>) -> String {
135    if let Some(hash_fragment) = hash_fragment {
136        base_url.push('#');
137        base_url.push_str(&hash_fragment);
138    }
139    base_url
140}
141
142#[derive(Serialize)]
143struct SparqlEndpointProbe {
144    target: String,
145    resolved_endpoint: String,
146    reachable: bool,
147    status_code: Option<u16>,
148    detail: String,
149    federation_supported: Option<bool>,
150}
151
152#[derive(Serialize)]
153struct AppRequirementCheck {
154    kind: String,
155    id: String,
156    required: bool,
157    status: String,
158    detail: String,
159}
160
161#[derive(Serialize)]
162struct QappReadinessReport {
163    qapp_name: String,
164    ready: bool,
165    summary: String,
166    blocking_issues: usize,
167    optional_warnings: usize,
168    checks: Vec<AppRequirementCheck>,
169}
170
171/// Loads workspace-catalog.
172pub fn load_workspace_catalog() -> qualia_core_db::resource_catalog::ResourceCatalog {
173    qualia_core_db::resource_catalog::load_default()
174        .unwrap_or_else(|_| qualia_core_db::resource_catalog::ResourceCatalog::empty())
175}
176
177fn catalog_has_llm(
178    catalog: &qualia_core_db::resource_catalog::ResourceCatalog,
179    model: &str,
180) -> bool {
181    if catalog.find_llm(model).is_some() {
182        return true;
183    }
184    let target = normalize_resource_key(model);
185    catalog.llms.iter().any(|entry| {
186        normalize_resource_key(&entry.id) == target
187            || entry
188                .download
189                .local_filename()
190                .map(|file| normalize_resource_key(&file) == target)
191                .unwrap_or(false)
192    })
193}
194
195fn catalog_has_ontology(
196    catalog: &qualia_core_db::resource_catalog::ResourceCatalog,
197    ontology: &str,
198) -> bool {
199    if catalog.find_ontology(ontology).is_some() {
200        return true;
201    }
202    let target = normalize_resource_key(ontology);
203    catalog
204        .ontologies
205        .iter()
206        .any(|entry| normalize_resource_key(&entry.id) == target)
207}
208
209fn normalize_resource_key(value: &str) -> String {
210    value
211        .chars()
212        .filter(|c| c.is_ascii_alphanumeric())
213        .map(|c| c.to_ascii_lowercase())
214        .collect()
215}
216
217fn directory_contains_requirement(dir: &Path, requirement: &str) -> bool {
218    let target = normalize_resource_key(requirement);
219    std::fs::read_dir(dir)
220        .ok()
221        .into_iter()
222        .flat_map(|entries| entries.filter_map(Result::ok))
223        .any(|entry| {
224            let file_name = entry.file_name();
225            let candidate = normalize_resource_key(&file_name.to_string_lossy());
226            candidate.contains(&target) || target.contains(&candidate)
227        })
228}
229
230fn collect_matching_files(dir: &Path, requirement: &str) -> Vec<PathBuf> {
231    let target = normalize_resource_key(requirement);
232    std::fs::read_dir(dir)
233        .ok()
234        .into_iter()
235        .flat_map(|entries| entries.filter_map(Result::ok))
236        .map(|entry| entry.path())
237        .filter(|path| path.is_file())
238        .filter(|path| {
239            let file_name = path
240                .file_name()
241                .map(|name| name.to_string_lossy().to_string())
242                .unwrap_or_default();
243            let candidate = normalize_resource_key(&file_name);
244            candidate.contains(&target) || target.contains(&candidate)
245        })
246        .collect()
247}
248
249fn resolve_sparql_endpoint_from_catalog(
250    endpoint_or_id: &str,
251) -> Result<(String, Option<bool>), String> {
252    if endpoint_or_id.starts_with("http://") || endpoint_or_id.starts_with("https://") {
253        return Ok((endpoint_or_id.to_string(), None));
254    }
255
256    let catalog = load_workspace_catalog();
257    catalog
258        .find_sparql(endpoint_or_id)
259        .or_else(|| {
260            let target = normalize_resource_key(endpoint_or_id);
261            catalog
262                .sparql_endpoints
263                .iter()
264                .find(|entry| normalize_resource_key(&entry.id) == target)
265        })
266        .map(|entry| (entry.endpoint.clone(), entry.federation_supported))
267        .ok_or_else(|| format!("Unknown SPARQL endpoint id: {}", endpoint_or_id))
268}
269
270fn evaluate_capability_requirement(
271    requirement: &qapp_registry::QappLaunchRequirement,
272    daemon_running: bool,
273) -> AppRequirementCheck {
274    let (status, detail) = match requirement.capability.as_str() {
275        "qualia.localDaemon.health" | "qualia.localDaemon.query" => {
276            if daemon_running {
277                ("ready", "Local Qualia daemon is running.")
278            } else {
279                ("missing", "Local Qualia daemon is not currently running.")
280            }
281        }
282        "qualia.wasm.execute_ntriples_query"
283        | "qualia.wasm.compile_query_to_json"
284        | "qualia.wasm.validate_shacl_constraint" => (
285            "declared",
286            "WASM capability is manifest-declared but not actively verified by the desktop host.",
287        ),
288        "qualia.flutter.chatRepresentationLaunch" => (
289            "ready",
290            "Flutter desktop host can launch an app with chat representation context.",
291        ),
292        _ => (
293            "declared",
294            "Capability is declared in the manifest but not yet actively checked by the desktop host.",
295        ),
296    };
297
298    AppRequirementCheck {
299        kind: "capability".to_string(),
300        id: requirement.capability.clone(),
301        required: requirement.required,
302        status: status.to_string(),
303        detail: detail.to_string(),
304    }
305}
306
307/// Inspects installed qapp readiness.
308pub fn inspect_installed_qapp_readiness(qapp_name: String) -> Result<String, String> {
309    let state = crate::state::APP_STATE.get().unwrap();
310    let data_dir = state.config.lock().unwrap().storage_path.clone();
311    let qapp_dir = qapps_dir(&data_dir).join(&qapp_name);
312    if !qapp_dir.exists() {
313        return Err(format!("Qapp directory not found: {qapp_name}"));
314    }
315
316    let manifest = load_qapp_package_from_dir(&qapp_dir)?;
317    let extension = manifest.x_qualia.clone().unwrap_or_default();
318    let daemon_running = *state.daemon_running.lock().unwrap();
319
320    let models_dir = PathBuf::from(&data_dir).join("Models");
321    let index_dir = PathBuf::from(&data_dir).join("Index");
322    let library_dir = PathBuf::from(&data_dir).join("SemanticLibrary");
323
324    let catalog = load_workspace_catalog();
325
326    let mut checks = Vec::new();
327
328    for requirement in &extension.requires {
329        checks.push(evaluate_capability_requirement(requirement, daemon_running));
330    }
331
332    if extension.local_daemon.is_some() {
333        checks.push(AppRequirementCheck {
334            kind: "daemon".to_string(),
335            id: "local-daemon".to_string(),
336            required: false,
337            status: if daemon_running { "ready" } else { "inactive" }.to_string(),
338            detail: if daemon_running {
339                "Local Qualia daemon is available for app integrations.".to_string()
340            } else {
341                "App declares local daemon integration, but the daemon is not running.".to_string()
342            },
343        });
344    }
345
346    for ontology in &extension.required_ontologies {
347        let in_catalog = catalog_has_ontology(&catalog, ontology);
348        let installed = directory_contains_requirement(&index_dir, ontology)
349            || directory_contains_requirement(&library_dir, ontology);
350        let status = if installed { "ready" } else { "missing" };
351        let detail = if installed {
352            format!(
353                "Ontology `{}` appears to be present in local Qualia storage.",
354                ontology
355            )
356        } else if in_catalog {
357            format!(
358                "Ontology `{}` is known in the bundled resource catalog but is not installed locally.",
359                ontology
360            )
361        } else {
362            format!(
363                "Ontology `{}` is required by the app but is not installed and was not found in the bundled catalog.",
364                ontology
365            )
366        };
367        checks.push(AppRequirementCheck {
368            kind: "ontology".to_string(),
369            id: ontology.clone(),
370            required: true,
371            status: status.to_string(),
372            detail,
373        });
374    }
375
376    for model in &extension.required_models {
377        let in_catalog = catalog_has_llm(&catalog, model);
378        let installed = directory_contains_requirement(&models_dir, model);
379        let status = if installed { "ready" } else { "missing" };
380        let detail = if installed {
381            format!(
382                "Model `{}` appears to be present in the local Models directory.",
383                model
384            )
385        } else if in_catalog {
386            format!(
387                "Model `{}` is known in the bundled model catalog but is not downloaded locally.",
388                model
389            )
390        } else {
391            format!(
392                "Model `{}` is required by the app but is not present and was not found in the bundled model catalog.",
393                model
394            )
395        };
396        checks.push(AppRequirementCheck {
397            kind: "model".to_string(),
398            id: model.clone(),
399            required: true,
400            status: status.to_string(),
401            detail,
402        });
403    }
404
405    for endpoint in &extension.optional_remote_endpoints {
406        let match_entry = catalog.find_sparql(endpoint).or_else(|| {
407            catalog.sparql_endpoints.iter().find(|entry| {
408                entry.endpoint == *endpoint
409                    || normalize_resource_key(&entry.id) == normalize_resource_key(endpoint)
410            })
411        });
412        let (status, detail) = if let Some(entry) = match_entry {
413            let federation_note = match entry.federation_supported {
414                Some(true) => " Federation is advertised as supported.",
415                Some(false) => " Federation is not advertised as supported.",
416                None => "",
417            };
418            (
419                "cataloged",
420                format!(
421                    "Endpoint `{}` is known to the bundled SPARQL catalog at {}.{}",
422                    endpoint, entry.endpoint, federation_note
423                ),
424            )
425        } else if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
426            (
427                "declared",
428                format!(
429                    "Endpoint `{}` is declared directly in the manifest. The desktop host does not currently verify live reachability.",
430                    endpoint
431                ),
432            )
433        } else {
434            (
435                "missing",
436                format!(
437                    "Endpoint `{}` is not present in the bundled SPARQL catalog and is not an explicit URL.",
438                    endpoint
439                ),
440            )
441        };
442        checks.push(AppRequirementCheck {
443            kind: "sparql-endpoint".to_string(),
444            id: endpoint.clone(),
445            required: false,
446            status: status.to_string(),
447            detail,
448        });
449    }
450
451    let blocking_issues = checks
452        .iter()
453        .filter(|check| check.required && check.status != "ready")
454        .count();
455    let optional_warnings = checks
456        .iter()
457        .filter(|check| {
458            !check.required && !matches!(check.status.as_str(), "ready" | "cataloged" | "declared")
459        })
460        .count();
461    let ready = blocking_issues == 0;
462    let summary = if ready {
463        format!(
464            "`{}` is ready to launch with {} optional warnings.",
465            qapp_name, optional_warnings
466        )
467    } else {
468        format!(
469            "`{}` is missing {} required resources or capabilities.",
470            qapp_name, blocking_issues
471        )
472    };
473
474    let report = QappReadinessReport {
475        qapp_name,
476        ready,
477        summary,
478        blocking_issues,
479        optional_warnings,
480        checks,
481    };
482    serde_json::to_string(&report).map_err(|e| e.to_string())
483}
484
485/// Lists installed ontology artifacts.
486pub fn list_installed_ontology_artifacts() -> Vec<String> {
487    let state = crate::state::APP_STATE.get().unwrap();
488    let data_dir = state.config.lock().unwrap().storage_path.clone();
489    let dirs = [
490        PathBuf::from(&data_dir).join("Index"),
491        PathBuf::from(&data_dir).join("SemanticLibrary"),
492    ];
493    let mut artifacts = Vec::new();
494
495    for dir in dirs {
496        if let Ok(entries) = std::fs::read_dir(dir) {
497            for entry in entries.filter_map(Result::ok) {
498                let path = entry.path();
499                if path.is_file() {
500                    artifacts.push(entry.file_name().to_string_lossy().to_string());
501                }
502            }
503        }
504    }
505
506    artifacts.sort();
507    artifacts.dedup();
508    artifacts
509}
510
511/// Removes installed-ontology.
512pub fn remove_installed_ontology(ontology_id: String) -> Result<String, String> {
513    let state = crate::state::APP_STATE.get().unwrap();
514    let data_dir = state.config.lock().unwrap().storage_path.clone();
515    let dirs = [
516        PathBuf::from(&data_dir).join("Index"),
517        PathBuf::from(&data_dir).join("SemanticLibrary"),
518    ];
519    let mut removed = 0usize;
520
521    for dir in dirs {
522        for path in collect_matching_files(&dir, &ontology_id) {
523            std::fs::remove_file(&path)
524                .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?;
525            removed += 1;
526        }
527    }
528
529    if removed == 0 {
530        return Err(format!(
531            "No installed ontology artifacts matched `{}`.",
532            ontology_id
533        ));
534    }
535
536    Ok(format!(
537        "Removed {} ontology artifact(s) for `{}`.",
538        removed, ontology_id
539    ))
540}
541
542/// Removes installed-model.
543pub fn remove_installed_model(model_id: String) -> Result<String, String> {
544    let state = crate::state::APP_STATE.get().unwrap();
545    let data_dir = state.config.lock().unwrap().storage_path.clone();
546    let models_dir = PathBuf::from(&data_dir).join("Models");
547    let matches = collect_matching_files(&models_dir, &model_id);
548    let mut removed_names = Vec::new();
549
550    for path in matches {
551        let name = path
552            .file_name()
553            .map(|n| n.to_string_lossy().to_string())
554            .unwrap_or_default();
555        let is_gguf = path
556            .extension()
557            .map(|ext| ext.to_string_lossy().eq_ignore_ascii_case("gguf"))
558            .unwrap_or(false);
559        let is_install = name.ends_with(".install.json");
560        if is_gguf || is_install {
561            std::fs::remove_file(&path)
562                .map_err(|e| format!("Failed to remove {}: {}", path.display(), e))?;
563            if is_gguf {
564                removed_names.push(name);
565            }
566        }
567    }
568
569    if removed_names.is_empty() {
570        return Err(format!("No installed model matched `{}`.", model_id));
571    }
572
573    {
574        let mut active_model = state.active_model.lock().unwrap();
575        if let Some(current) = active_model.clone() {
576            let normalized_current = normalize_resource_key(&current);
577            if removed_names
578                .iter()
579                .any(|name| normalized_current.contains(&normalize_resource_key(name)))
580            {
581                if let Some(record) = load_active_model_record_from_disk() {
582                    crate::model_lifecycle::unload_active_model(Some(record.profile_id));
583                } else {
584                    crate::model_lifecycle::unload_active_model(None);
585                }
586                *active_model = None;
587                clear_active_model_record();
588            }
589        }
590    }
591
592    Ok(format!(
593        "Removed {} model file(s): {}",
594        removed_names.len(),
595        removed_names.join(", ")
596    ))
597}
598
599/// Tests a SPARQL endpoint.
600pub fn test_sparql_endpoint(endpoint_or_id: String) -> Result<String, String> {
601    let (endpoint, federation_supported) = resolve_sparql_endpoint_from_catalog(&endpoint_or_id)?;
602    let client = reqwest::blocking::Client::builder()
603        .timeout(Duration::from_secs(8))
604        .build()
605        .map_err(|e| format!("SPARQL probe client error: {}", e))?;
606
607    let response = client
608        .get(&endpoint)
609        .header(
610            "Accept",
611            "application/sparql-results+json, application/json;q=0.9, */*;q=0.1",
612        )
613        .send();
614
615    let probe = match response {
616        Ok(response) => {
617            let status = response.status();
618            let reachable = status.is_success()
619                || status.is_redirection()
620                || matches!(status.as_u16(), 400 | 401 | 403 | 405 | 406);
621            SparqlEndpointProbe {
622                target: endpoint_or_id,
623                resolved_endpoint: endpoint,
624                reachable,
625                status_code: Some(status.as_u16()),
626                detail: format!("Endpoint responded with HTTP {}.", status.as_u16()),
627                federation_supported,
628            }
629        }
630        Err(err) => SparqlEndpointProbe {
631            target: endpoint_or_id,
632            resolved_endpoint: endpoint,
633            reachable: false,
634            status_code: None,
635            detail: format!("Endpoint probe failed: {}", err),
636            federation_supported,
637        },
638    };
639
640    serde_json::to_string(&probe).map_err(|e| e.to_string())
641}
642
643/// Returns the URL that should be opened in the system browser for a qapp.
644/// Looks up by directory name inside `{storage_path}/Qapps/`.
645pub fn launch_installed_qapp(qapp_name: String) -> Result<String, String> {
646    launch_installed_qapp_with_context(qapp_name.clone(), None, None, None, None)
647}
648
649/// Launches an installed qapp with context.
650pub fn launch_installed_qapp_with_context(
651    qapp_name: String,
652    entrypoint: Option<String>,
653    surface: Option<String>,
654    payload_json: Option<String>,
655    source: Option<String>,
656) -> Result<String, String> {
657    let state = crate::state::APP_STATE.get().unwrap();
658    let data_dir = state.config.lock().unwrap().storage_path.clone();
659    let storage_path = std::path::PathBuf::from(&data_dir);
660    if crate::qapp_install::is_package_revoked(&storage_path, &qapp_name) {
661        return Err(format!("Qapp package revoked: {qapp_name}"));
662    }
663    let qapp_dir = crate::qapp_paths::resolve_active_package_dir(&storage_path, &qapp_name);
664
665    if !qapp_dir
666        .join(crate::qapp_registry::QAPP_PACKAGE_MANIFEST)
667        .is_file()
668    {
669        return Err(format!("Qapp directory not found: {qapp_name}"));
670    }
671
672    let manifest = load_qapp_package_from_dir(&qapp_dir)?;
673    let resolved_entrypoint = resolve_entrypoint_path(&manifest, entrypoint.as_deref());
674    let (asset_path, hash_fragment) = split_asset_and_hash(&resolved_entrypoint);
675    let asset_file = qapp_dir.join(&asset_path);
676
677    let base_url = if let Some(port) = manifest.dev_port {
678        let trimmed = asset_path.trim_start_matches('/');
679        if trimmed.is_empty() || trimmed == "index.html" {
680            format!("http://localhost:{}", port)
681        } else {
682            format!("http://localhost:{}/{}", port, trimmed)
683        }
684    } else {
685        if !asset_file.exists() {
686            return Err(format!(
687                "{} not found in {}",
688                asset_path,
689                qapp_dir.display()
690            ));
691        }
692
693        if crate::qapps_protocol::qualia_protocol_port() != 0 {
694            crate::qapps_protocol::qualia_qapp_asset_url(&qapp_name, &asset_path)
695                .unwrap_or_else(|_| format!("file:///{}", asset_file.display()).replace('\\', "/"))
696        } else {
697            format!("file:///{}", asset_file.display()).replace('\\', "/")
698        }
699    };
700
701    let base_url = append_launch_context(base_url, source, surface, payload_json, Some(&qapp_name));
702    Ok(append_hash_fragment(base_url, hash_fragment))
703}