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
305 changes: 201 additions & 104 deletions crates/wizard-core/src/agents/claude_desktop.rs

Large diffs are not rendered by default.

74 changes: 20 additions & 54 deletions crates/wizard-core/src/agents/claude_desktop/video.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Claude Desktop's local 3P profile uses native arrays for both managed extensions.
use crate::video::stdio;
use anyhow::{Context as _, Result, ensure};
use anyhow::{Context as _, Result};
use serde_json::{Map, Value, json};
use std::path::PathBuf;

Expand Down Expand Up @@ -54,49 +54,34 @@ impl Registration {
.as_str()
.is_some_and(|repo| repo.eq_ignore_ascii_case(REPO))
},
|entry| {
entry["source"] == "github"
&& entry["repo"] == REPO
&& entry["expectedName"] == MARKET
&& entry["credentialKind"] == "anonymous"
&& entry["installationPreference"] == "auto_install"
&& entry.get("path").is_none()
},
"ref",
)?;
let args = json!([stdio::ARG, self.port.to_string(), self.headers]);
reconcile(
profile,
"managedMcpServers",
enable,
json!({
"name":SERVER, "transport":"stdio", "command":self.command, "args":args,
"name":SERVER, "transport":"stdio", "command":self.command, "args":self.args(),
"toolTimeoutSec":240, "toolPolicy":{"video_models":"allow"}
}),
|entry| entry["name"] == SERVER,
|entry| entry["transport"] == "stdio" && entry["args"] == args,
"command",
)
}

/// Subscription (1p) mode: Claude Desktop reads local servers from `mcpServers` in
/// `Claude/claude_desktop_config.json`. There is no plugin marketplace or tool policy here.
fn args(&self) -> Value {
json!([stdio::ARG, self.port.to_string(), self.headers])
}

/// Claude Desktop reads local servers from `mcpServers` in its 1p configuration.
pub(super) fn update_1p_config(
&self,
config: &mut Map<String, Value>,
enable: bool,
) -> Result<()> {
let args = json!([stdio::ARG, self.port.to_string(), self.headers]);
let owned = |entry: &Value| entry["args"] == args;
if !enable {
let now_empty = match config.get_mut("mcpServers").and_then(Value::as_object_mut) {
Some(servers) if servers.get(SERVER).is_some_and(owned) => {
servers.shift_remove(SERVER);
servers.is_empty()
}
_ => false,
};
if now_empty {
if let Some(servers) = config.get_mut("mcpServers").and_then(Value::as_object_mut)
&& servers.shift_remove(SERVER).is_some()
&& servers.is_empty()
{
config.shift_remove("mcpServers");
}
return Ok(());
Expand All @@ -106,38 +91,26 @@ impl Registration {
.or_insert_with(|| json!({}))
.as_object_mut()
.context("В настройках Claude Desktop поле mcpServers должно быть объектом")?;
if let Some(entry) = servers.get_mut(SERVER) {
ensure!(
owned(entry),
"В Claude Desktop уже зарегистрирован другой MCP-сервер coreinfra_video"
);
// Refresh only the executable, which moves when Wizard is reinstalled elsewhere.
entry["command"] = json!(self.command);
} else {
servers.insert(
SERVER.into(),
json!({"command": self.command, "args": args}),
);
}
servers.insert(
SERVER.into(),
json!({"command": self.command, "args": self.args()}),
);
Ok(())
}
}

// Only refresh the pin or executable when a registration already belongs to Wizard.
// In particular, keep a user's stricter tool policies and other servers in place.
// Replace all versions of the registration at its first position in the profile.
fn reconcile(
profile: &mut Map<String, Value>,
key: &str,
enable: bool,
desired: Value,
matches: impl Fn(&Value) -> bool,
owned: impl Fn(&Value) -> bool,
refresh: &str,
) -> Result<()> {
if !enable {
if let Some(entries) = profile.get_mut(key).and_then(Value::as_array_mut) {
let previous_len = entries.len();
entries.retain(|entry| !(matches(entry) && owned(entry)));
entries.retain(|entry| !matches(entry));
if previous_len != 0 && entries.is_empty() {
profile.shift_remove(key);
}
Expand All @@ -150,15 +123,8 @@ fn reconcile(
.or_insert_with(|| json!([]))
.as_array_mut()
.with_context(|| format!("В профиле Claude Desktop поле {key} должно быть массивом"))?;
let mut existing = entries.iter_mut().filter(|entry| matches(entry));
if let Some(entry) = existing.next() {
ensure!(
owned(entry) && existing.next().is_none(),
"Конфликт регистрации CoreInfra Video в поле {key} профиля Claude Desktop"
);
entry[refresh] = desired[refresh].clone();
} else {
entries.push(desired);
}
let index = entries.iter().position(&matches).unwrap_or(entries.len());
entries.retain(|entry| !matches(entry));
entries.insert(index, desired);
Ok(())
}
4 changes: 2 additions & 2 deletions crates/wizard-core/src/prepared_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@ impl PreparedPlan {
},
PreparedStep::SetClaudeDesktop1pVideo { enabled, .. } => PreparedStepInfo {
description: if *enabled {
"Зарегистрирует MCP-сервер coreinfra_video в Claude Desktop для подписки Claude."
"Зарегистрирует локальный MCP-сервер coreinfra_video в Claude Desktop."
} else {
"Удалит MCP-сервер coreinfra_video, добавленный Wizard, из настроек Claude Desktop для подписки."
"Удалит локальный MCP-сервер coreinfra_video из настроек Claude Desktop."
}.to_owned(),
},
PreparedStep::SetCodexProxyEnabled { enabled } => PreparedStepInfo {
Expand Down
32 changes: 22 additions & 10 deletions crates/wizard-gui/src/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ pub(crate) enum AgentChange {
CodexSetRouting(RoutingMode),
ClaudeSetRouting(RoutingMode),
ClaudeDesktopSetRouting(RoutingMode),
ClaudeDesktopSetVideo(bool),
SetPiHub(HubMode),
SetOpenCodeHub(HubMode),
}
Expand All @@ -190,11 +191,13 @@ pub(crate) struct PreparedAgentChange {
}

impl AgentChange {
const fn enabled(self) -> bool {
const fn needs_agent_token(self) -> bool {
match self {
Self::CodexSetRouting(mode)
| Self::ClaudeSetRouting(mode)
| Self::ClaudeDesktopSetRouting(mode) => !matches!(mode, RoutingMode::Disabled),
Self::CodexSetRouting(mode) | Self::ClaudeSetRouting(mode) => {
!matches!(mode, RoutingMode::Disabled)
}
Self::ClaudeDesktopSetRouting(mode) => matches!(mode, RoutingMode::Hub),
Self::ClaudeDesktopSetVideo(_) => false,
Self::SetPiHub(mode) | Self::SetOpenCodeHub(mode) => !matches!(mode, HubMode::Disabled),
}
}
Expand All @@ -203,7 +206,9 @@ impl AgentChange {
match self {
Self::CodexSetRouting(_) => TokenAgent::Codex,
Self::ClaudeSetRouting(_) => TokenAgent::Claude,
Self::ClaudeDesktopSetRouting(_) => TokenAgent::ClaudeDesktop,
Self::ClaudeDesktopSetRouting(_) | Self::ClaudeDesktopSetVideo(_) => {
TokenAgent::ClaudeDesktop
}
Self::SetPiHub(_) => TokenAgent::Pi,
Self::SetOpenCodeHub(_) => TokenAgent::OpenCode,
}
Expand All @@ -225,18 +230,15 @@ pub(crate) async fn prepare_agent_change(
AgentChange::CodexSetRouting(_) => ("CodexSetRouting", "codex"),
AgentChange::ClaudeSetRouting(_) => ("ClaudeSetRouting", "claude"),
AgentChange::ClaudeDesktopSetRouting(_) => ("ClaudeDesktopSetRouting", "claude_desktop"),
AgentChange::ClaudeDesktopSetVideo(_) => ("ClaudeDesktopSetVideo", "claude_desktop"),
AgentChange::SetPiHub(_) => ("SetPiHub", "pi"),
AgentChange::SetOpenCodeHub(_) => ("SetOpenCodeHub", "opencode"),
};
log::info!("received agent change: {name}");

let settings = settings::get_state(&app).map_err(|error| format!("{error:#}"))?;

let token = if change.enabled()
&& !matches!(
change,
AgentChange::ClaudeDesktopSetRouting(RoutingMode::Sub)
) {
let token = if change.needs_agent_token() {
match token {
Some(TokenChoice::Existing { token }) if !token.is_empty() => token,
Some(TokenChoice::Create) if matches!(change, AgentChange::CodexSetRouting(_)) => {
Expand Down Expand Up @@ -272,6 +274,16 @@ pub(crate) async fn prepare_agent_change(
);
Ok(plan)
}
AgentChange::ClaudeDesktopSetVideo(enabled) => {
let mut plan = claude_desktop::prepare_video(enabled)?;
if !plan.info().is_empty() {
plan.restart_desktop(
wizard_core::agents::desktop_install::DesktopApp::Claude,
settings.last_paths.claude_desktop.as_deref(),
);
}
Ok(plan)
}
AgentChange::SetPiHub(mode) => pi::prepare_hub(mode, &token, &settings),
AgentChange::SetOpenCodeHub(mode) => opencode::prepare_hub(mode, &token, &settings),
})
Expand Down
6 changes: 5 additions & 1 deletion crates/wizard-gui/src/video.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::settings;
use crate::{agents::AgentRevisionState, revision_signal::RevisionSignal, settings};
use anyhow::{Context as _, Result};
use serde::Serialize;
use tauri::Manager as _;
Expand Down Expand Up @@ -72,5 +72,9 @@ pub(crate) async fn set_video_connection(
.await
.map_err(|_| "Не удалось настроить видео")?
.map_err(|e| format!("{e:#}"))?;
// Detection compares registrations with the saved grant. A preceding routing plan
// may already have triggered a read against the previous grant.
app.state::<RevisionSignal<AgentRevisionState>>()
.notify(AgentRevisionState);
crate::proxy::sync(&app).await.map_err(|e| format!("{e:#}"))
}
17 changes: 8 additions & 9 deletions crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ export function RoutingFieldset<M extends string>({
actionsClassName = "",
editing = false,
needsApply = false,
videoNeedsApply = false,
}: {
agent: AgentId;
modes: ModeOption<M>[];
Expand All @@ -281,6 +282,7 @@ export function RoutingFieldset<M extends string>({
actionsClassName?: string;
editing?: boolean;
needsApply?: boolean;
videoNeedsApply?: boolean;
}) {
const [draft, setDraft] = useState<M | undefined>(initialMode);
const subscriptionTokenPreview = useContext(SubscriptionTokenPreviewContext);
Expand All @@ -294,15 +296,12 @@ export function RoutingFieldset<M extends string>({
(token.selected?.kind === "create" ||
(token.selected?.kind === "existing" &&
token.selected.token !== agentToken));
const showVideo = agent === "codex" || agent === "claude" || (agent === "claude_desktop" && selected !== "disabled");
const showVideo = agent === "codex" || agent === "claude" || agent === "claude_desktop";
const video = useVideoConnection(agent, showVideo);
const videoChanged = showVideo && video.needsApply;
// Claude Desktop registers video in its configuration only through a plan that restarts it.
const desktopVideoChanged =
agent === "claude_desktop" && showVideo && !!video.status && video.enabled !== video.status.enabled;
const videoChanged = showVideo && !!video.status && (video.needsApply || videoNeedsApply);
const routingChanged =
selected !== mode || (enabled && (needsApply || tokenChanged)) || desktopVideoChanged;
const prepareRouting = !editing || routingChanged;
selected !== mode || (enabled && (needsApply || tokenChanged));
const prepareRouting = routingChanged || (!editing && (enabled || agent !== "claude_desktop"));
const systemProxy = useSystemProxy();
const [proxyPrompt, setProxyPrompt] = useState(false);

Expand All @@ -317,7 +316,7 @@ export function RoutingFieldset<M extends string>({
}

function prepare() {
const includeVideo = showVideo && (video.needsApply || (prepareRouting && video.enabled));
const includeVideo = videoChanged || (showVideo && prepareRouting && video.enabled);
onPrepare({
agent,
routing: prepareRouting ? {
Expand Down Expand Up @@ -369,7 +368,7 @@ export function RoutingFieldset<M extends string>({
disabled ||
(prepareRouting && enabled && (proxyOnly ? !hub.signedIn : !token.ready)) ||
(showVideo && !video.status && !video.error) ||
(!prepareRouting && !videoChanged)
(editing && !prepareRouting && !videoChanged)
}
onClick={prepare}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function AgentConnectionPanel({ agent, agents, account, onBack }: {
const choice = choices.find(choice => choice.id === agent)!;
const proxyAgent = agent === "claude_desktop" || (agent === "codex" && agents.codex.status === "found" && agents.codex.data.desktop.status === "found");
const needsApply = detection.status === "found" && detection.data.routing_mode !== "disabled" &&
(("video_needs_apply" in detection.data && detection.data.video_needs_apply) || ("proxy_needs_apply" in detection.data && detection.data.proxy_needs_apply) || (proxyAgent && proxy.proxy?.enabled === false));
(("proxy_needs_apply" in detection.data && detection.data.proxy_needs_apply) || (proxyAgent && proxy.proxy?.enabled === false));
const errors = detection.status === "error" ? [detection.data]
: agent === "codex" && agents.codex.status === "found" ? [agents.codex.data.cli, agents.codex.data.desktop].flatMap(part => part.status === "error" ? [part.data] : []) : [];

Expand Down Expand Up @@ -68,6 +68,7 @@ export function AgentConnectionPanel({ agent, agents, account, onBack }: {
modes={agent === "pi" || agent === "opencode" ? hubModes : routingModes(agent === "codex" ? "Codex" : "Claude")}
toChange={toChange} agentToken={detection.data.token} hub={hub}
needsApply={needsApply} disabled={busy || account.submitting} error={error}
videoNeedsApply={"video_needs_apply" in detection.data && detection.data.video_needs_apply}
note={agent === "codex" ? "Настройка общая для ChatGPT и Codex." : undefined}
actions={<Button plain disabled={busy || account.submitting} onClick={onBack}>Назад</Button>}
onPrepare={prepare}
Expand Down
3 changes: 2 additions & 1 deletion crates/wizard-gui/wizard-ui/src/agents/AgentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ export function AgentPage({
key={configurationRevision}
editing
agent="claude"
needsApply={claude.data.video_needs_apply}
videoNeedsApply={claude.data.video_needs_apply}
modes={routingModes("Claude")}
mode={claude.data.routing_mode}
toChange={(mode) => ({ ClaudeSetRouting: mode })}
Expand Down Expand Up @@ -344,6 +344,7 @@ export function AgentPage({
(!proxyStartup.starting && proxy.proxy?.enabled === false))
}
agent="claude_desktop"
videoNeedsApply={desktop.data.video_needs_apply}
modes={routingModes("Claude")}
mode={desktop.data.routing_mode}
toChange={(mode) => ({ ClaudeDesktopSetRouting: mode })}
Expand Down
13 changes: 10 additions & 3 deletions crates/wizard-gui/wizard-ui/src/agents/PreparedPlanDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,16 @@ function PlanSteps({ plan }: { plan: ConnectionPlan }) {
const steps: ReactNode[] = (plan.routing?.info ?? []).map(step => step.description);
// Keep the choice from the form visible alongside the first routing action.
if (plan.videoEnabled !== undefined) {
steps.unshift(plan.videoEnabled
? <>Установит скилл <Code>coreinfra-video</Code> для видео-моделей.</>
: <>Отключит видео-модели и удалит скилл <Code>coreinfra-video</Code>, установленный Wizard.</>);
const video = <Code>coreinfra-video</Code>;
if (plan.agent === "claude_desktop") {
steps.unshift(plan.videoEnabled
? <>Подключит инструменты {video} в Claude Desktop.</>
: <>Отключит видео-модели {video} в Claude Desktop.</>);
} else {
steps.unshift(plan.videoEnabled
? <>Установит скилл {video} для видео-моделей.</>
: <>Отключит видео-модели и удалит скилл {video}, установленный Wizard.</>);
}
}
const rows = steps.map((step, index) => <li key={index}><Text>{step}</Text></li>);
return (
Expand Down
3 changes: 2 additions & 1 deletion crates/wizard-gui/wizard-ui/src/agents/VideoConnection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ export function useVideoConnection(agent: AgentId, available: boolean) {
}, [agent, available, revision]);

const enabled = draft ?? (status && (status.enabled || status.suggested));
const needsApply = !!status && (enabled !== status.enabled || (enabled && !status.running) || !!status.error);
// The first Apply also saves an explicit decline of the default suggestion.
const needsApply = !!status && (status.suggested || enabled !== status.enabled || (enabled && !status.running) || !!status.error);
function retry() {
setError(undefined);
setRevision(value => value + 1);
Expand Down
9 changes: 7 additions & 2 deletions crates/wizard-gui/wizard-ui/src/agents/agents_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export type AgentChange =
| { CodexSetRouting: RoutingMode }
| { ClaudeSetRouting: RoutingMode }
| { ClaudeDesktopSetRouting: RoutingMode }
| { ClaudeDesktopSetVideo: boolean }
| { SetPiHub: HubMode }
| { SetOpenCodeHub: HubMode };

Expand Down Expand Up @@ -46,8 +47,11 @@ export type ConnectionPlan = {
};

export async function prepareAgentChange({ agent, routing, videoEnabled }: ConnectionDraft): Promise<ConnectionPlan> {
const prepared = routing
? await invoke<PreparedAgentChange>("prepare_agent_change", { ...routing, video: videoEnabled })
const request = routing ?? (agent === "claude_desktop" && videoEnabled !== undefined
? { change: { ClaudeDesktopSetVideo: videoEnabled }, token: null }
: undefined);
const prepared = request
? await invoke<PreparedAgentChange>("prepare_agent_change", { ...request, video: videoEnabled })
: undefined;
return { agent, routing: prepared, videoEnabled };
}
Expand Down Expand Up @@ -113,6 +117,7 @@ export type ClaudeDesktop = {
// CoreInfra token from the agent's configuration. Secret: never log or persist it.
token: string | null;
proxy_needs_apply: boolean;
video_needs_apply: boolean;
};

export type OpenCode = {
Expand Down
3 changes: 2 additions & 1 deletion crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,9 @@ function Configure({
: routingModes(choice.agent === "codex" ? "Codex" : "Claude")
}
mode={agent.data.routing_mode}
videoNeedsApply={"video_needs_apply" in agent.data && agent.data.video_needs_apply}
initialMode={
agent.data.routing_mode === "disabled" ? "hub" : undefined
hub.signedIn && agent.data.routing_mode === "disabled" ? "hub" : undefined
}
agentToken={agent.data.token}
hub={hub}
Expand Down
Loading
Loading