Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,16 @@ and plan confirmation; multiple installed agents always show a selection first.
The final action launches the configured desktop app or CLI.

Connection options are ordered API access, subscription, then without CoreInfra.
Token selection is automatic: reuse the configured token if it belongs to the
The default token is selected automatically: reuse the configured token if it belongs to the
selected Hub, otherwise reuse the oldest token named for the agent, or create one
on confirmation. A note shows its name instead of a selector. Claude Desktop's
subscription uses the existing Wizard proxy-token flow. «Завершить настройку»
opens the change plan and confirms it before the launch step.
on confirmation. The note's «Изменить» link opens a menu of tokens in the selected
Hub. The choice is shared by API configuration and downloads. Claude Desktop's
subscription uses Wizard's shared proxy token and needs no separate agent token.
The local proxy has exactly two listeners: `127.0.0.1:33787` for Claude Desktop and
the system proxy, and `127.0.0.1:33788` for ChatGPT. Both use the same Wizard token;
changing an agent's API token does not change either listener's credential.
«Завершить настройку» opens the change plan before the launch step. Regular agent
pages use «Применить», enabled for pending mode/token changes or a stopped proxy.

Downloads run in the backend and preserve explicit pauses across dialog closes.
Installing requires a separate «Установить» confirmation; «Отмена» retains the
Expand Down
132 changes: 123 additions & 9 deletions crates/wizard-core/src/agents/claude_desktop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use std::{
use wizard_settings::Settings;

const HUB_URL: &str = "https://hub.coreinfra.ai/anthropic/api";
// Read-only compatibility with an unreleased configuration. Never bind this port.
const RETIRED_PROXY_URL: &str = "http://127.0.0.1:33789";
pub(crate) static CONFIG_LOCK: Mutex<()> = Mutex::new(());

#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
Expand All @@ -28,6 +30,7 @@ pub(crate) struct ClaudeDesktop {
pub info: AgentInfo,
pub routing_mode: RoutingMode,
pub token: Option<AgentToken>,
pub proxy_needs_apply: bool,
}

pub(super) fn detect(settings: &Settings) -> AgentDetection<ClaudeDesktop> {
Expand All @@ -40,14 +43,15 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection<ClaudeDesktop> {
AgentDetection::Error(error) => return AgentDetection::Error(error),
};

let (routing_mode, token) = match read_routing() {
let (routing_mode, token, proxy_needs_apply) = match read_routing() {
Ok(routing) => routing,
Err(error) => return AgentDetection::Error(format!("{error:#}")),
};
AgentDetection::Found(ClaudeDesktop {
info,
routing_mode,
token,
proxy_needs_apply,
})
}

Expand Down Expand Up @@ -118,6 +122,18 @@ pub fn prepare_restore_backup(id: u32) -> Result<PreparedPlan> {

fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result<PreparedPlan> {
let mut changes = manager.restore_changes(id)?;
// An old backup must not point Claude at a listener that no longer exists.
for change in &mut changes {
if change.path().parent() == Some(dir)
&& let Ok(profile) = json::parse(&change.after)
&& profile["egressProxyUrl"] == RETIRED_PROXY_URL
{
json::update(&mut change.after, |profile| {
profile["egressProxyUrl"] = json!(format!("http://{}", wizard_proxy::ADDRESS));
Ok(())
})?;
}
}
// A restore also backs up the state it replaces. If the user has selected another
// profile since this backup, include that profile so the new backup is restorable.
let meta_path = dir.join("_meta.json");
Expand Down Expand Up @@ -162,34 +178,35 @@ fn prepare_restore_at(dir: &Path, manager: &BackupManager, id: u32) -> Result<Pr
}

/// Hub reads the profile's key. Sub has no agent key; Wizard owns proxy credentials.
fn read_routing() -> Result<(RoutingMode, Option<AgentToken>)> {
fn read_routing() -> Result<(RoutingMode, Option<AgentToken>, bool)> {
let _guard = PreparedAgent::ClaudeDesktop.lock()?;

read_routing_at(&config_library()?)
}

fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option<AgentToken>)> {
fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option<AgentToken>, bool)> {
let meta = json::read(&dir.join("_meta.json"))?;
let Some(id) = applied_id(&meta)? else {
return Ok((RoutingMode::Disabled, None));
return Ok((RoutingMode::Disabled, None, false));
};

let config = json::read(&dir.join(format!("{id}.json")))?;
let preferences = json::read(&dir.with_file_name("claude_desktop_config.json"))?;
let proxy_url = format!("http://{}", wizard_proxy::ADDRESS);
let proxy_needs_apply = config["egressProxyUrl"] == RETIRED_PROXY_URL;

if preferences["deploymentMode"] == "1p"
&& config["egressProxyUrl"] == proxy_url
&& (config["egressProxyUrl"] == proxy_url || proxy_needs_apply)
&& config.get("egressProxyPacUrl").is_none()
{
Ok((RoutingMode::Sub, None))
Ok((RoutingMode::Sub, None, proxy_needs_apply))
} else if preferences["deploymentMode"] != "1p" && has_hub_connection(&config) {
let token = config["inferenceGatewayApiKey"]
.as_str()
.and_then(|token| AgentToken::new(token.to_owned()));
Ok((RoutingMode::Hub, token))
Ok((RoutingMode::Hub, token, proxy_needs_apply))
} else {
Ok((RoutingMode::Disabled, None))
Ok((RoutingMode::Disabled, None, false))
}
}

Expand Down Expand Up @@ -300,6 +317,57 @@ mod tests {
use super::*;
use crate::config_files::changes::FileSnapshot;

#[test]
fn first_launch_needs_only_precreated_configuration() -> Result<()> {
for mode in [RoutingMode::Hub, RoutingMode::Sub] {
let root = tempfile::tempdir()?;
let dir = root.path().join("Claude-3p/configLibrary");
let plan = prepare_routing_at(&dir, mode, "test-agent-token")?;
assert!(!dir.parent().expect("profile directory").exists());
let mut activated = false;
plan.apply_with_backup(
None,
|enabled| {
assert!(enabled);
// All files must be present before starting the proxy or the desktop app.
let meta = json::read(&dir.join("_meta.json"))?;
let id = applied_id(&meta)?.expect("selected profile");
assert_eq!(meta["entries"], json!([{ "id": id, "name": "CoreInfra" }]));
let profile = json::read(&dir.join(format!("{id}.json")))?;
assert_eq!(profile["egressProxyUrl"], "http://127.0.0.1:33787");
let preferences =
json::read(&dir.with_file_name("claude_desktop_config.json"))?;
assert_eq!(
preferences["deploymentMode"],
if mode == RoutingMode::Hub { "3p" } else { "1p" }
);
if mode == RoutingMode::Sub {
assert!(profile.get("inferenceGatewayApiKey").is_none());
}
activated = true;
Ok(())
},
|_| panic!("unexpected ChatGPT proxy"),
)?;
assert!(activated);
let (detected, token, needs_apply) = read_routing_at(&dir)?;
assert_eq!(detected, mode);
assert!(!needs_apply);
assert_eq!(
token.map(AgentToken::into_secret).as_deref(),
(mode == RoutingMode::Hub).then_some("test-agent-token")
);

let repeated = prepare_routing_at(&dir, mode, "test-agent-token")?;
assert!(repeated.steps().iter().all(|step| match step {
PreparedStep::ChangeFile { change } => !change.is_changed(),
_ => true,
}));
assert_eq!(std::fs::read_dir(&dir)?.count(), 2);
}
Ok(())
}

struct Fixture {
root: tempfile::TempDir,
dir: PathBuf,
Expand Down Expand Up @@ -434,6 +502,51 @@ mod tests {
Ok(())
}

#[test]
fn retired_proxy_configuration_is_repaired_on_apply_and_backup_restore() -> Result<()> {
for mode in [RoutingMode::Hub, RoutingMode::Sub] {
let fixture = Fixture::new("gateway")?;
let token = if mode == RoutingMode::Hub {
"api-token"
} else {
""
};
fixture.apply(prepare_routing_at(&fixture.dir, mode, token)?, true)?;

let mut profile = json::read(&fixture.files[0])?;
profile["egressProxyUrl"] = json!(RETIRED_PROXY_URL);
std::fs::write(&fixture.files[0], profile.to_string())?;
let (detected, agent_token, needs_apply) = read_routing_at(&fixture.dir)?;
assert_eq!(detected, mode);
assert!(needs_apply);
assert_eq!(agent_token.is_some(), mode == RoutingMode::Hub);
// Detection leaves the user's profile unchanged; Apply confirms the repair.
assert_eq!(json::read(&fixture.files[0])?, profile);

fixture.apply(prepare_routing_at(&fixture.dir, mode, token)?, true)?;
assert_eq!(fixture.manager().get_backups()?.len(), 2);
assert!(!read_routing_at(&fixture.dir)?.2);

// Restoring the backup of the retired configuration keeps the two-port layout.
fixture.apply(
prepare_restore_at(&fixture.dir, &fixture.manager(), 2)?,
true,
)?;
assert_eq!(
json::read(&fixture.files[0])?["egressProxyUrl"],
"http://127.0.0.1:33787"
);
let (restored_mode, restored_token, needs_apply) = read_routing_at(&fixture.dir)?;
assert_eq!(restored_mode, mode);
assert!(!needs_apply);
assert_eq!(
restored_token.map(AgentToken::into_secret).as_deref(),
(mode == RoutingMode::Hub).then_some("api-token")
);
}
Ok(())
}

#[test]
fn backup_failure_prevents_configuration_and_proxy_changes() -> Result<()> {
let fixture = Fixture::new("gateway")?;
Expand Down Expand Up @@ -602,8 +715,9 @@ mod tests {
std::fs::write(&profile_path, original.to_string())?;
std::fs::write(&preferences_path, r#"{"deploymentMode":"3p"}"#)?;

let (detected, token) = read_routing_at(&dir)?;
let (detected, token, proxy_needs_apply) = read_routing_at(&dir)?;
assert_eq!(detected, RoutingMode::Hub);
assert!(!proxy_needs_apply);
assert_eq!(
token.map(AgentToken::into_secret).as_deref(),
Some("manual-token")
Expand Down
Loading
Loading