Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

20.1 KB
Raw Blame
//! Upgrade-path compatibility: data written by past releases must stay
//! readable by current code.
//!
//! Everything under `tests/fixtures/upgrade/` is real bytes written by the
//! named release (0.8.3 stable on Windows for `store.json` and
//! `mcp_config.json`, 0.8.3 stable on macOS for the thread files, and 0.8.5
//! stable on macOS for its `store.json`), committed
//! so a schema drift that would silently eat user data fails here instead of
//! on a user machine. Threads are plain per-thread JSON/JSONL files; the store
//! marks the MCP schema version (3 on 0.8.3, 4 from 0.8.4, 5 from the release
//! that removes the default Exa entry) that
//! `core/setup.rs migrate_mcp_servers` migrates against.
//!
//! When a release intentionally changes one of these schemas, commit the old
//! release's output as a new fixture directory under
//! `tests/fixtures/upgrade/<release>/` and add assertions for it (pass that
//! directory to `fixture_root`); update an existing fixture only when the
//! current schema itself is being pinned, never to make a test pass.

// `core::setup` is desktop-only -- `core/mod.rs` gates it out of
// `--features cli`, which builds this test target too. The fixtures are
// desktop data folders, so the suite belongs to the desktop build.
#![cfg(not(feature = "cli"))]

use app_lib::core::mcp::models::McpSettings;
use app_lib::core::setup::{
    is_default_exa_server, is_hosted_default_exa_server, mcp_migration_start,
    remove_default_exa_from_config, schema_after_exa_cutover, CURRENT_MCP_SCHEMA_VERSION,
};
use app_lib::core::threads::helpers::read_messages_from_file;
use app_lib::core::threads::utils::{get_messages_path, get_thread_dir, get_thread_metadata_path};
use serde_json::Value;
use std::path::PathBuf;

/// Root of a committed release data-folder fixture. Mirrors the layout of
/// `~/Library/Application Support/Jan/data` (macOS) / `%APPDATA%\Jan\data`
/// (Windows): `threads/<id>/{thread.json,messages.jsonl}`, `store.json`,
/// `mcp_config.json`.
fn fixture_root(release: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/upgrade")
        .join(release)
}

/// Every committed release fixture, oldest first. Discovered rather than
/// listed because the tripwire below exists to demand a new fixture on a
/// schema bump -- if it also demanded an edit here, the edit is the thing that
/// would get forgotten.
fn fixture_releases() -> Vec<String> {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/upgrade");
    let mut releases: Vec<(Vec<u64>, String)> = std::fs::read_dir(&root)
        .unwrap_or_else(|e| panic!("upgrade fixture root {root:?} unreadable: {e}"))
        .map(|entry| entry.expect("fixture directory entry must be readable"))
        .filter(|entry| entry.path().is_dir())
        .map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            // Sort on the parsed components, not the string: "0.8.10" must
            // come after "0.8.9", which it does not lexicographically.
            let parts = name
                .split('.')
                .map(|part| {
                    part.parse().unwrap_or_else(|_| {
                        panic!("fixture directory {name:?} is not a dotted release version")
                    })
                })
                .collect();
            (parts, name)
        })
        .collect();
    assert!(
        !releases.is_empty(),
        "no release fixtures under {root:?} -- this suite would pass vacuously"
    );
    releases.sort();
    releases.into_iter().map(|(_, name)| name).collect()
}

/// `mcp_version` from a release fixture's `store.json`, checking on the way
/// that the directory name and the release the store records agree.
fn fixture_mcp_version(release: &str) -> i64 {
    let path = fixture_root(release).join("store.json");
    let raw = std::fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("{release} store.json fixture missing at {path:?}: {e}"));
    let store: Value = serde_json::from_str(&raw)
        .unwrap_or_else(|e| panic!("{release} store.json must parse: {e}"));
    assert_eq!(
        store["version"].as_str(),
        Some(release),
        "fixture directory {release} holds a store.json written by a different release"
    );
    store["mcp_version"].as_i64().unwrap_or(0)
}

fn read_thread_metadata(release: &str, thread_id: &str) -> Value {
    let path = get_thread_metadata_path(&fixture_root(release), thread_id).unwrap();
    let raw = std::fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("{release} thread metadata {path:?} unreadable: {e}"));
    serde_json::from_str(&raw).expect("thread.json must parse as JSON")
}

fn read_all_messages(release: &str, thread_id: &str) -> Vec<Value> {
    // The reader returns Ok(vec![]) for a missing file, which would turn a
    // layout-constant drift into a confusing downstream length failure —
    // assert the resolved path exists first so the cause is named.
    let path = get_messages_path(&fixture_root(release), thread_id).unwrap();
    assert!(
        path.exists(),
        "{release} messages file missing at {path:?} — layout constant drifted"
    );
    read_messages_from_file(&fixture_root(release), thread_id)
        .unwrap_or_else(|e| panic!("{release} messages for {thread_id} failed to parse: {e}"))
}

#[test]
fn threads_written_by_0_8_3_resolve_and_parse() {
    let thread_ids = [
        "1fa772e9-47e5-4a8c-a664-4b1cef37c5aa",
        "784952d3-dc72-474e-ab24-0d78e7035280",
    ];
    for id in thread_ids {
        let dir = get_thread_dir(&fixture_root("0.8.3"), id).unwrap();
        assert!(dir.is_dir(), "0.8.3 thread dir {id} missing from fixtures");
        let metadata = read_thread_metadata("0.8.3", id);
        assert_eq!(
            metadata["object"], "thread",
            "0.8.3 thread.json lost its `object` discriminator"
        );
        assert!(
            metadata["title"].is_string(),
            "0.8.3 thread.json lost its `title`"
        );
        assert!(
            !metadata["assistants"]
                .as_array()
                .expect("assistants")
                .is_empty(),
            "0.8.3 thread.json carried a default assistant; schema must keep parsing it"
        );
    }
}

#[test]
fn messages_written_by_0_8_3_round_trip_through_the_current_reader() {
    // Seeded during the 0.8.3 QA run: user message plus the mock provider's
    // reply. Both turns must survive the current JSONL reader.
    let messages = read_all_messages("0.8.3", "784952d3-dc72-474e-ab24-0d78e7035280");
    assert!(
        messages.len() >= 2,
        "0.8.3 thread should have at least a user and an assistant turn"
    );
    assert_eq!(messages[0]["role"], "user");
    assert_eq!(messages[1]["role"], "assistant");
    // 0.8.3 content shape: content[0] = {type: "text", text: {value: "..."}}.
    let user_text = messages[0]["content"][0]["text"]["value"]
        .as_str()
        .expect("0.8.3 user message text must be readable");
    assert!(
        user_text.contains("QA thread 1"),
        "0.8.3 message content drifted: {user_text}"
    );
}

#[test]
fn thread_dir_layout_matches_current_path_resolution() {
    // get_thread_dir/get_messages_path are what every reader resolves through;
    // if the layout constants drift (e.g. `threads` renamed), this fails.
    let id = "1fa772e9-47e5-4a8c-a664-4b1cef37c5aa";
    assert!(get_thread_dir(&fixture_root("0.8.3"), id).unwrap().is_dir());
    let messages = read_all_messages("0.8.3", id);
    assert!(
        !messages.is_empty(),
        "0.8.3 messages must not read as empty"
    );
}

#[test]
fn every_store_fixture_sits_inside_the_migration_range() {
    let releases = fixture_releases();

    // `migrate_mcp_servers` (core/setup.rs) only walks stores *below*
    // CURRENT_MCP_SCHEMA_VERSION through the gates, so a fixture at or above it
    // would sit outside the migration path this suite exists to cover and
    // assert nothing.
    for release in &releases {
        let mcp_version = fixture_mcp_version(release);
        assert!(
            mcp_version < CURRENT_MCP_SCHEMA_VERSION,
            "{release} fixture carries mcp_version {mcp_version}, which the current schema \
             ({CURRENT_MCP_SCHEMA_VERSION}) no longer migrates"
        );
    }

    // The newest fixture is pinned at exactly CURRENT - 1, and that is the
    // whole point of this test. `<` is satisfied by 3 < 5 just as well as by
    // 3 < 4, so it would stay green through a schema bump and guard nothing --
    // it only ever fired if the constant were *lowered*. Pinning the gap at
    // exactly one release means bumping the constant fails here until the
    // newly-superseded release's store output is committed as a fixture, which
    // is the coverage this file exists to keep.
    let newest = releases
        .last()
        .expect("fixture_releases rejects an empty set");
    let newest_version = fixture_mcp_version(newest);
    assert_eq!(
        newest_version,
        CURRENT_MCP_SCHEMA_VERSION - 1,
        "the newest upgrade fixture ({newest}) carries mcp_version {newest_version}, but the \
         current schema is {CURRENT_MCP_SCHEMA_VERSION}. If you just bumped \
         CURRENT_MCP_SCHEMA_VERSION, commit the store.json written by the release that shipped \
         schema {} as a new fixture directory under tests/fixtures/upgrade/.",
        CURRENT_MCP_SCHEMA_VERSION - 1
    );
}

#[test]
fn mcp_config_written_by_0_8_3_parses_with_current_settings_schema() {
    let raw = std::fs::read_to_string(fixture_root("0.8.3").join("mcp_config.json"))
        .expect("0.8.3 mcp_config.json fixture missing");
    let config: Value = serde_json::from_str(&raw).expect("0.8.3 mcp_config.json must parse");

    // `mcpSettings` (0.8.3) deserializes into the current typed settings.
    let settings: McpSettings = serde_json::from_value(config["mcpSettings"].clone())
        .expect("0.8.3 mcpSettings must deserialize into the current McpSettings schema");
    assert_eq!(settings.tool_call_timeout_seconds, 30);
    assert_eq!(settings.backoff_multiplier, 2.0);

    // Those two asserts cannot catch a renamed key, which is what makes the
    // synthetic case below necessary rather than belt-and-braces. 0.8.3 stored
    // the shipped defaults, and every McpSettings field carries
    // `#[serde(default)]`, so a rename degrades to a value identical to the one
    // the fixture holds and both asserts above stay green.
    //
    // Non-default values keyed by the same names do bite: if
    // `toolCallTimeoutSeconds` or `backoffMultiplier` is renamed, these fall
    // back to 30 and 2.0 and fail.
    let renamed_probe: McpSettings = serde_json::from_value(serde_json::json!({
        "toolCallTimeoutSeconds": 90,
        "backoffMultiplier": 3.5,
    }))
    .expect("the current McpSettings schema must accept 0.8.3's camelCase keys");
    assert_eq!(
        renamed_probe.tool_call_timeout_seconds, 90,
        "toolCallTimeoutSeconds no longer maps onto tool_call_timeout_seconds"
    );
    assert_eq!(
        renamed_probe.backoff_multiplier, 3.5,
        "backoffMultiplier no longer maps onto backoff_multiplier"
    );

    // Migration 4 removes only an exa entry that is inactive *and* keyless.
    //
    // What the fixture actually is, stated carefully because the obvious
    // reading is wrong: 0.8.3's own `migrate_exa_to_http` wrote this entry with
    // `active: true` (`git show v0.8.3:src-tauri/src/core/setup.rs`), so it is
    // byte-for-byte 0.8.3's *default*, not evidence that a user activated
    // anything. Migration 4 therefore leaves it alone, and it ran once for
    // everyone on 0.8.4 or later; migration 5 is the step that removes it (see
    // `the_exa_default_0_8_3_wrote_is_removed_by_migration_5` below).
    let servers = config["mcpServers"].as_object().expect("mcpServers object");
    let fixture_exa = servers
        .get("exa")
        .expect("0.8.3 config carried an exa entry");
    assert!(
        !is_default_exa_server(fixture_exa),
        "migration 4 must keep leaving an exa entry as 0.8.3 wrote it alone"
    );
    let untouched_default = serde_json::json!({
        "type": "http",
        "url": "https://mcp.exa.ai/mcp",
        "command": "",
        "args": [],
        "env": {},
        "active": false
    });
    assert!(
        is_default_exa_server(&untouched_default),
        "the never-activated default exa entry is what migration 4 removes"
    );
}

/// Migration 5 (#9010): the hosted Exa default 0.8.3 wrote for everyone is
/// removed, and only that. These rows decide who loses configuration.
#[test]
fn the_exa_default_0_8_3_wrote_is_removed_by_migration_5() {
    let hosted = |active: bool| {
        serde_json::json!({
            "type": "http",
            "url": "https://mcp.exa.ai/mcp",
            "command": "",
            "args": [],
            "env": {},
            "active": active
        })
    };
    // 0.8.3's migration 3, and the same entry deactivated by the user.
    assert!(is_hosted_default_exa_server(&hosted(true)));
    assert!(is_hosted_default_exa_server(&hosted(false)));

    // A key keeps it, whatever else it looks like.
    let mut keyed = hosted(true);
    keyed["env"] = serde_json::json!({ "EXA_API_KEY": "sk-real" });
    assert!(!is_hosted_default_exa_server(&keyed));

    // Authentication headers are credentials: an entry that carries any is the
    // user's, even when it is the hosted url, active, and has no env.
    let mut headers = hosted(true);
    headers["headers"] = serde_json::json!({ "Authorization": "Bearer sk-real" });
    assert!(!is_hosted_default_exa_server(&headers));
    // An empty headers map is what the default looks like with none set.
    let mut no_headers = hosted(true);
    no_headers["headers"] = serde_json::json!({});
    assert!(is_hosted_default_exa_server(&no_headers));
    // A field this migration does not know is the user's too.
    let mut unknown = hosted(true);
    unknown["timeout"] = serde_json::json!(60);
    assert!(!is_hosted_default_exa_server(&unknown));

    // Another url, transport, command or args is not the default.
    let mut proxy = hosted(false);
    proxy["url"] = serde_json::json!("https://exa.proxy.internal/mcp");
    assert!(!is_hosted_default_exa_server(&proxy));
    let mut stdio = hosted(true);
    stdio["type"] = serde_json::json!("stdio");
    assert!(!is_hosted_default_exa_server(&stdio));
    let mut command = hosted(true);
    command["command"] = serde_json::json!("npx");
    command["args"] = serde_json::json!(["-y", "exa-mcp-server"]);
    assert!(!is_hosted_default_exa_server(&command));

    // A malformed entry is not something to delete.
    for malformed in [
        serde_json::json!("exa"),
        serde_json::json!(null),
        serde_json::json!(7),
    ] {
        assert!(!is_hosted_default_exa_server(&malformed));
    }
}

#[test]
fn migration_5_removes_the_exa_entry_from_a_real_0_8_3_config_and_nothing_else() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("mcp_config.json");
    std::fs::copy(fixture_root("0.8.3").join("mcp_config.json"), &path).unwrap();
    let before: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();

    assert!(remove_default_exa_from_config(&path).unwrap());

    let after: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert!(after["mcpServers"].get("exa").is_none());
    // Every other server, and the settings, are byte-for-byte what they were.
    let mut expected = before["mcpServers"].as_object().unwrap().clone();
    expected.remove("exa");
    assert_eq!(after["mcpServers"], Value::Object(expected));
    assert_eq!(after["mcpSettings"], before["mcpSettings"]);

    // Once it is gone there is nothing left for a second run to do.
    assert!(!remove_default_exa_from_config(&path).unwrap());
}

#[test]
fn migration_5_leaves_a_config_it_does_not_recognise_alone() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("mcp_config.json");

    // No file yet: nothing to do, and nothing created.
    assert!(!remove_default_exa_from_config(&path).unwrap());
    assert!(!path.exists());

    for config in [
        // A keyed entry.
        serde_json::json!({ "mcpServers": { "exa": {
            "type": "http", "url": "https://mcp.exa.ai/mcp", "command": "", "args": [],
            "env": { "EXA_API_KEY": "sk-real" }, "active": true } } }),
        // The hosted url, active, with authentication headers.
        serde_json::json!({ "mcpServers": { "exa": {
            "type": "http", "url": "https://mcp.exa.ai/mcp", "command": "", "args": [],
            "env": {}, "headers": { "Authorization": "Bearer sk-real" }, "active": true } } }),
        // The hosted url with a field this migration does not know.
        serde_json::json!({ "mcpServers": { "exa": {
            "type": "http", "url": "https://mcp.exa.ai/mcp", "command": "", "args": [],
            "env": {}, "timeout": 60, "active": true } } }),
        // A custom endpoint, inactive and keyless.
        serde_json::json!({ "mcpServers": { "exa": {
            "type": "http", "url": "https://exa.proxy.internal/mcp", "command": "", "args": [],
            "env": {}, "active": false } } }),
        // A malformed entry.
        serde_json::json!({ "mcpServers": { "exa": "oops" } }),
        // No exa at all.
        serde_json::json!({ "mcpServers": { "fetch": { "command": "uvx", "args": [], "env": {} } } }),
        // No servers object.
        serde_json::json!({ "mcpSettings": {} }),
    ] {
        std::fs::write(&path, serde_json::to_string_pretty(&config).unwrap()).unwrap();
        let bytes = std::fs::read(&path).unwrap();
        assert!(!remove_default_exa_from_config(&path).unwrap(), "{config}");
        assert_eq!(std::fs::read(&path).unwrap(), bytes, "{config}");
    }
}

/// A cutover that could not read or write the config just then must not be
/// recorded as done: the next startup has to try it again, or the entry stays for
/// good even after the problem is gone.
#[test]
fn a_failed_exa_cutover_is_retried_at_the_next_startup() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("mcp_config.json");

    // A config that cannot be read right now (a directory stands in for it).
    std::fs::create_dir(&path).unwrap();
    let failed = remove_default_exa_from_config(&path).map(|_| ());
    assert!(failed.is_err());
    let recorded = schema_after_exa_cutover(&failed);
    assert!(
        recorded < CURRENT_MCP_SCHEMA_VERSION,
        "a failed cutover recorded as schema {recorded} would never run again"
    );

    // The next startup: the config is readable again, so the cutover runs.
    std::fs::remove_dir(&path).unwrap();
    std::fs::copy(fixture_root("0.8.3").join("mcp_config.json"), &path).unwrap();
    let retried = remove_default_exa_from_config(&path).map(|_| ());
    assert!(retried.is_ok());
    assert_eq!(
        schema_after_exa_cutover(&retried),
        CURRENT_MCP_SCHEMA_VERSION
    );
    let config: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert!(config["mcpServers"].get("exa").is_none());

    // Nothing to remove is a success too: no reason to keep retrying.
    let nothing = remove_default_exa_from_config(&path).map(|_| ());
    assert_eq!(
        schema_after_exa_cutover(&nothing),
        CURRENT_MCP_SCHEMA_VERSION
    );
}

/// A first start has no `mcp_config.json` and an empty store. Every migration
/// step edits an entry of an existing config, so each would fail on the missing
/// file and log an error (#9469); such a profile has nothing to migrate and
/// starts at the current schema, which `setup_mcp` then writes the default for.
#[test]
fn a_profile_without_an_mcp_config_has_nothing_to_migrate() {
    assert_eq!(mcp_migration_start(0, false), CURRENT_MCP_SCHEMA_VERSION);
    // A deleted config on an old store is the same: there is nothing to edit.
    assert_eq!(mcp_migration_start(3, false), CURRENT_MCP_SCHEMA_VERSION);

    // An existing config keeps the gates it has not passed yet, so a real
    // upgrade still walks them.
    assert_eq!(mcp_migration_start(0, true), 0);
    assert_eq!(mcp_migration_start(3, true), 3);
    assert_eq!(
        mcp_migration_start(CURRENT_MCP_SCHEMA_VERSION, true),
        CURRENT_MCP_SCHEMA_VERSION
    );
}