дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 13:52:36 +02:00
Порівняти коміти
28
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
43163e3fd6 | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 |
No files matched your search
@@ -3,7 +3,8 @@ name: Homebrew
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -27,17 +28,17 @@ jobs:
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
@@ -47,7 +48,7 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
|
||||
@@ -179,7 +179,7 @@ jobs:
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
|
||||
Створено
@@ -4440,7 +4440,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tracing",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
|
||||
pub use skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
@@ -53,6 +54,49 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Resolves agent `id`'s interactive sign-in command without an open project.
|
||||
pub fn login_launch_without_project(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
id: &str,
|
||||
) -> IdeResult<LoginLaunch> {
|
||||
let spec = provider::load(custom_agents_dir, secrets)
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
spec.login_launch(cwd, None)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status_with(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
) -> CopilotAuthStatus {
|
||||
let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot");
|
||||
let cwd_buf = cwd.to_path_buf();
|
||||
let cli_fut = async move {
|
||||
let spec = copilot_spec?;
|
||||
native::copilot::probe_auth_status(spec, cwd_buf).await
|
||||
};
|
||||
let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts);
|
||||
let (cli, gh) = tokio::join!(cli_fut, gh_fut);
|
||||
let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new()));
|
||||
match cli {
|
||||
Some(cli) => CopilotAuthStatus {
|
||||
authenticated: cli.authenticated,
|
||||
login: cli.login,
|
||||
auth_type: cli.auth_type,
|
||||
status_message: cli.status_message,
|
||||
gh_installed,
|
||||
gh_accounts,
|
||||
},
|
||||
None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
@@ -201,6 +245,8 @@ struct Shared {
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
probes: Mutex<HashMap<String, AgentProbe>>,
|
||||
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
|
||||
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
|
||||
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
|
||||
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
|
||||
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
|
||||
@@ -706,6 +752,7 @@ impl AgentManager {
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
terminal_auth_args: RwLock::new(HashMap::new()),
|
||||
copilot_acp_fallback: Mutex::new(HashSet::new()),
|
||||
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
|
||||
mcp_servers_hook: RwLock::new(None),
|
||||
@@ -785,16 +832,24 @@ impl AgentManager {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Directory holding linked Git worktrees created for agent tasks of this project.
|
||||
pub fn worktrees_dir(&self) -> &Path {
|
||||
&self.shared.paths.worktrees_dir
|
||||
}
|
||||
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let in_use: std::collections::HashSet<String> =
|
||||
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
|
||||
let terminal_auth = self.shared.terminal_auth_args.read();
|
||||
let list = specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
let mut info = provider::describe(p);
|
||||
info.can_sign_in =
|
||||
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
@@ -802,6 +857,7 @@ impl AgentManager {
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
@@ -815,6 +871,35 @@ impl AgentManager {
|
||||
list
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let spec = specs
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
|
||||
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
|
||||
})?;
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
|
||||
let status = copilot_auth_status_with(
|
||||
self.shared.paths.custom_agents_dir.as_deref(),
|
||||
self.shared.env_secrets(),
|
||||
&self.shared.paths.project_root,
|
||||
)
|
||||
.await;
|
||||
if status.authenticated || !status.gh_accounts.is_empty() {
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
|
||||
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
|
||||
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
|
||||
@@ -837,7 +922,9 @@ impl AgentManager {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?;
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
@@ -3509,6 +3596,14 @@ impl Task {
|
||||
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
|
||||
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
|
||||
})?;
|
||||
if let Some(args) = init.auth_methods.iter().find_map(|method| {
|
||||
if method.get("type").and_then(Value::as_str) != Some("terminal") {
|
||||
return None;
|
||||
}
|
||||
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
|
||||
}) {
|
||||
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
|
||||
}
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
|
||||
@@ -623,6 +623,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -647,6 +650,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -73,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -151,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -166,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -176,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -194,16 +285,15 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -229,6 +319,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -237,18 +461,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -259,9 +482,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -389,6 +613,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -901,6 +1126,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1160,12 +1401,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1174,7 +1415,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1458,4 +1699,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -1212,7 +1212,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
|
||||
@@ -486,6 +486,16 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +157,10 @@ pub struct ColumnInfo {
|
||||
pub nullable: bool,
|
||||
pub default: Option<String>,
|
||||
pub primary_key: bool,
|
||||
/// `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -172,6 +176,10 @@ pub struct IndexInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
/// The table's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
@@ -1119,11 +1127,18 @@ impl DbManager {
|
||||
let nullable = flag(&it.next().flatten());
|
||||
let default = it.next().flatten();
|
||||
let primary_key = flag(&it.next().flatten());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1175,7 +1190,17 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
|
||||
@@ -132,6 +132,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
nullable: yes(r.get("null?")),
|
||||
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
|
||||
primary_key: yes(r.get("primary key")),
|
||||
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -140,7 +141,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
Ok(keys) => foreign_keys(&keys),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
// `LIKE` matches without case and with wildcards: the exact name picks the row.
|
||||
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
|
||||
let comment = match show(pool, &like).await {
|
||||
Ok(shown) => shown
|
||||
.records()
|
||||
.find(|r| r.get("name") == Some(table))
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
|
||||
@@ -145,7 +145,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
|
||||
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
|
||||
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
|
||||
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
|
||||
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
|
||||
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
@@ -153,7 +154,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
|
||||
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
|
||||
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -166,13 +167,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT column_name, column_type, is_nullable, column_default, \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
@@ -192,8 +194,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
AND kc.constraint_name = con.constraint_name \
|
||||
@@ -204,6 +208,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
|
||||
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
|
||||
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
|
||||
)),
|
||||
// A view's `table_comment` is the word `VIEW`.
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
|
||||
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
|
||||
)),
|
||||
DbDriver::Oracle => {
|
||||
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
|
||||
}
|
||||
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
|
||||
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
|
||||
@@ -956,6 +982,22 @@ mod tests {
|
||||
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_read_where_the_engine_keeps_them() {
|
||||
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
|
||||
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
|
||||
assert_eq!(table_comment(driver, "s", "t"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_escapes_backslashes_and_delimiters() {
|
||||
let driver = DbDriver::Clickhouse;
|
||||
|
||||
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
|
||||
raw VARBINARY(4)) COMMENT = '用户表'"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
@@ -59,6 +60,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert_eq!(d.comment.as_deref(), Some("用户表"));
|
||||
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, Some("名字"), None]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
|
||||
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
|
||||
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
|
||||
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
|
||||
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
|
||||
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
|
||||
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
@@ -350,6 +352,10 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
|
||||
assert_eq!(key.columns, ["region", "id"]);
|
||||
|
||||
|
||||
@@ -12,4 +12,3 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// API calls normally answer within a few seconds.
|
||||
const QUICK: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
|
||||
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
|
||||
/// install or remove a managed copy in its tools directory at runtime).
|
||||
pub fn gh_executable() -> Option<PathBuf> {
|
||||
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
GH.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("gh") {
|
||||
return Some(found);
|
||||
}
|
||||
let candidates: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
|
||||
@@ -386,3 +371,37 @@ pub fn prepare_diff(
|
||||
let files = repo.diff_files(&base, head_oid)?;
|
||||
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let search = std::env::join_paths([&dir]).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
|
||||
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
|
||||
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
|
||||
|
||||
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
|
||||
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
|
||||
|
||||
std::fs::remove_file(&gh).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
|
||||
//!
|
||||
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
|
||||
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
|
||||
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
|
||||
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
|
||||
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
|
||||
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
|
||||
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
|
||||
|
||||
use crate::Project;
|
||||
use ide_agent::GhAuthAccount;
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// GitHub CLI accounts available on this machine and which one applies to the project.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhProjectAccountStatus {
|
||||
pub gh_installed: bool,
|
||||
pub accounts: Vec<GhAuthAccount>,
|
||||
/// Value of `vcs.github.account` (`""` = Automatic).
|
||||
pub configured_account: String,
|
||||
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
|
||||
pub effective_account: Option<String>,
|
||||
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
|
||||
pub suggested_account: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedAutoAccount {
|
||||
login: Option<String>,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
|
||||
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) fn is_valid_github_login(login: &str) -> bool {
|
||||
let bytes = login.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.current_dir(std::env::temp_dir())
|
||||
.args(args)
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1")
|
||||
.env("CLICOLOR", "0");
|
||||
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
|
||||
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
|
||||
for key in AMBIENT_GH_VARS {
|
||||
cmd.env_remove(key);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
|
||||
if !is_valid_github_login(login) {
|
||||
return None;
|
||||
}
|
||||
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
|
||||
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
|
||||
let token = out.stdout.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// Access level of an account for a specific `owner/repo` on `github.com`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum RepoAccess {
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Push = 2,
|
||||
}
|
||||
|
||||
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
|
||||
let endpoint = format!("repos/{owner}/{name}");
|
||||
let mut cmd =
|
||||
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
|
||||
cmd.env("GH_TOKEN", token);
|
||||
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
|
||||
return RepoAccess::None;
|
||||
};
|
||||
if !out.success {
|
||||
return RepoAccess::None;
|
||||
}
|
||||
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
|
||||
}
|
||||
|
||||
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
|
||||
let active_access =
|
||||
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
|
||||
// Prefer higher RepoAccess; break ties in favor of the globally active account.
|
||||
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
|
||||
if *best_access == RepoAccess::None {
|
||||
// Nobody could reach the repo (offline or SSO required): keep the active account.
|
||||
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
|
||||
}
|
||||
let auto_detected = !best.active && *best_access > active_access;
|
||||
Some((best, auto_detected))
|
||||
}
|
||||
|
||||
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
|
||||
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim();
|
||||
let path = if let Some(rest) =
|
||||
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
|
||||
{
|
||||
rest
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
|
||||
} else {
|
||||
url.strip_prefix("[email protected]:")?
|
||||
};
|
||||
let path = path.trim_matches('/');
|
||||
let (owner, rest) = path.split_once('/')?;
|
||||
let repo = rest.split('/').next()?;
|
||||
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((owner.to_owned(), repo.to_owned()))
|
||||
}
|
||||
|
||||
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
|
||||
let repos = project.repos();
|
||||
let mut ordered = Vec::new();
|
||||
if let Some(primary) = repos.primary() {
|
||||
ordered.push(primary);
|
||||
}
|
||||
for repo in repos.all() {
|
||||
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
|
||||
ordered.push(repo);
|
||||
}
|
||||
}
|
||||
for repo in ordered {
|
||||
let Ok(mut remotes) = repo.remotes() else { continue };
|
||||
remotes.sort_by_key(|r| r.name != "origin");
|
||||
for remote in remotes {
|
||||
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
|
||||
if let Some(coords) = parse_github_owner_repo(url) {
|
||||
return Some(coords);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
|
||||
// Fast path: the repository owner matches one of the signed-in accounts directly.
|
||||
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
|
||||
return Some((matched.login.clone(), !matched.active));
|
||||
}
|
||||
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
|
||||
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
|
||||
let cache_key = (key_repo, key_logins);
|
||||
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
|
||||
&& cached.at.elapsed() < CACHE_TTL
|
||||
{
|
||||
if let Some(login) = cached.login {
|
||||
let is_active = accounts.iter().any(|a| a.login == login && a.active);
|
||||
return Some((login, !is_active));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let tokens: Vec<(GhAuthAccount, Option<String>)> =
|
||||
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
|
||||
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = tokens
|
||||
.into_iter()
|
||||
.map(|(acc, token)| {
|
||||
s.spawn(move || {
|
||||
let access = match token {
|
||||
Some(tok) => probe_repo_access(program, &tok, owner, repo),
|
||||
None => RepoAccess::None,
|
||||
};
|
||||
(acc, access)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok()).collect()
|
||||
});
|
||||
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
|
||||
AUTO_CACHE
|
||||
.lock()
|
||||
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
|
||||
picked
|
||||
}
|
||||
|
||||
/// Resolves global status when no project is open.
|
||||
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
|
||||
let configured_account = configured_account.trim().to_owned();
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
|
||||
};
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
|
||||
}
|
||||
|
||||
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
|
||||
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
|
||||
/// processes use `gh`'s own behaviour.
|
||||
pub fn apply_to_project(project: &Project) {
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return;
|
||||
}
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if configured_account.is_empty() {
|
||||
set_project_token(project, None);
|
||||
return;
|
||||
}
|
||||
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
|
||||
set_project_token(project, token);
|
||||
}
|
||||
|
||||
/// Applies the project's explicit account setting and returns the full account status,
|
||||
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
|
||||
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
|
||||
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
}
|
||||
apply_to_project(project);
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
};
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
|
||||
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
active_login
|
||||
};
|
||||
|
||||
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
|
||||
primary_github_repo(project)
|
||||
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
|
||||
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
|
||||
}
|
||||
|
||||
fn set_project_token(project: &Project, token: Option<String>) {
|
||||
let os_tok = token.map(std::ffi::OsString::from);
|
||||
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
|
||||
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
|
||||
if changed_root || changed_wt {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_project_env(project: &Project) {
|
||||
ide_core::project_env::remove_all(&project.root);
|
||||
ide_core::project_env::remove_all(project.agents.worktrees_dir());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
|
||||
Some(("l0ng-ai".into(), "openidea".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
|
||||
Some(("acme-corp".into(), "payments".into()))
|
||||
);
|
||||
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
|
||||
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_github_logins_against_flag_injection() {
|
||||
assert!(is_valid_github_login("alice"));
|
||||
assert!(is_valid_github_login("alice-work"));
|
||||
assert!(is_valid_github_login("l0ng-ai"));
|
||||
assert!(!is_valid_github_login(""));
|
||||
assert!(!is_valid_github_login("--hostname"));
|
||||
assert!(!is_valid_github_login("bad space"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
|
||||
let personal = GhAuthAccount { login: "alice".into(), active: true };
|
||||
let work = GhAuthAccount { login: "alice-work".into(), active: false };
|
||||
|
||||
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
|
||||
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&private_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
|
||||
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&public_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
|
||||
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
|
||||
let (picked, auto) = pick_best_account(&oss).unwrap();
|
||||
assert_eq!(picked.login, "alice");
|
||||
assert!(!auto);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
mod formatter;
|
||||
pub mod github_auth;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
@@ -419,6 +420,7 @@ impl Host {
|
||||
self.environment.project_closed();
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
}
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
|
||||
@@ -6,11 +6,11 @@ use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SkillsPolicy,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -108,6 +108,106 @@ pub fn agent_set_env(
|
||||
host.project(window)?.agents.set_builtin_env(&id, env)
|
||||
}
|
||||
|
||||
/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<CopilotAuthStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
match host.project(window) {
|
||||
Ok(project) => Ok(project.agents.copilot_auth_status().await),
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: std::path::PathBuf,
|
||||
launch: LoginLaunch,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
crate::ops::term::apply_output_rate(host, window);
|
||||
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
let options = ide_terminal::TerminalOptions {
|
||||
cwd: cwd.into(),
|
||||
shell: Some(launch.program.to_string_lossy().into_owned()),
|
||||
args: launch.args,
|
||||
env: launch.env,
|
||||
cols: if cols == 0 { 80 } else { cols },
|
||||
rows: if rows == 0 { 20 } else { rows },
|
||||
shell_integration: false,
|
||||
};
|
||||
let exit_channel = on_event.clone();
|
||||
host.terminals.spawn_program(
|
||||
options,
|
||||
format!("agent-login:{window}"),
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| {
|
||||
let _ = on_event.send(AgentLoginEvent::Output { data });
|
||||
}),
|
||||
Some(std::sync::Arc::new(move |code| {
|
||||
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&id)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
|
||||
/// variables cleared) and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_gh_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cwd = host
|
||||
.project(window)
|
||||
.map(|p| p.root.clone())
|
||||
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
|
||||
let launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -1463,15 +1563,18 @@ ide_command::domain!(
|
||||
agent_cli_update,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
agent_fork_session,
|
||||
agent_gh_login_spawn,
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
|
||||
@@ -448,6 +448,14 @@ pub fn set_settings(
|
||||
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
|
||||
host.apply_git_executable();
|
||||
}
|
||||
if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
crate::github_auth::apply_to_project(&project);
|
||||
}
|
||||
});
|
||||
}
|
||||
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
|
||||
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
|
||||
for project in affected() {
|
||||
@@ -524,11 +532,56 @@ pub fn set_settings(
|
||||
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
|
||||
}
|
||||
|
||||
/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_project_account_status(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
|
||||
/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_set_project_account(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
account: String,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let trimmed = account.trim().to_owned();
|
||||
if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) {
|
||||
return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}")));
|
||||
}
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global };
|
||||
let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
set_settings(host, window, scope, "vcs.github.account", &json)?;
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() });
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
project:
|
||||
cancel_request,
|
||||
cancel_task,
|
||||
close_project,
|
||||
gh_project_account_status,
|
||||
gh_set_project_account,
|
||||
open_project,
|
||||
project_current,
|
||||
project_roots,
|
||||
|
||||
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
&root,
|
||||
&settings,
|
||||
));
|
||||
// Godot is usually an app bundle / Flatpak outside the search path.
|
||||
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
|
||||
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
|
||||
let mut found: std::collections::BTreeMap<_, _> =
|
||||
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
|
||||
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
|
||||
found.insert("gh".to_owned(), gh);
|
||||
}
|
||||
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
|
||||
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
|
||||
Ok(Tools::new(&data)
|
||||
.with_downloads(settings.tool_downloads.clone())
|
||||
.with_runtime(runtime.commands, runtime.env)
|
||||
.with_custom_paths(custom)
|
||||
.with_found_paths(found.into_iter().collect())
|
||||
.with_found_paths(found)
|
||||
.with_work_dir(work_dir))
|
||||
}
|
||||
|
||||
|
||||
@@ -217,6 +217,61 @@ impl SecretStore for FileSecretStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugin secrets in the OS credential store (Secret Service, Windows Credential
|
||||
/// Manager), like saved SSH and agent values. Without a credential store a value
|
||||
/// stays in the owner-only [`FileSecretStore`] file, which also still answers for
|
||||
/// values saved there by an older version until they are set again.
|
||||
pub struct CredentialSecretStore {
|
||||
store: ide_ssh::secrets::SecretFile,
|
||||
fallback: FileSecretStore,
|
||||
}
|
||||
|
||||
impl CredentialSecretStore {
|
||||
/// `dir`: the plugins' data directory (the index file and the fallback files live there).
|
||||
pub fn new(dir: PathBuf) -> Self {
|
||||
Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir)
|
||||
}
|
||||
|
||||
fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self {
|
||||
Self { store, fallback: FileSecretStore { dir } }
|
||||
}
|
||||
|
||||
fn key(plugin: &str, name: &str) -> String {
|
||||
format!("{plugin}/{name}")
|
||||
}
|
||||
|
||||
/// Drops a value from the fallback file, writing it only when it held one.
|
||||
fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> {
|
||||
if self.fallback.get(plugin, name).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
self.fallback.set(plugin, name, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretStore for CredentialSecretStore {
|
||||
fn get(&self, plugin: &str, name: &str) -> Option<String> {
|
||||
self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name))
|
||||
}
|
||||
|
||||
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
|
||||
let key = Self::key(plugin, name);
|
||||
match value {
|
||||
Some(v) => match self.store.set(&key, v) {
|
||||
Ok(()) => self.forget_fallback(plugin, name),
|
||||
Err(e) => {
|
||||
tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message);
|
||||
self.fallback.set(plugin, name, Some(v))
|
||||
}
|
||||
},
|
||||
None => {
|
||||
self.store.delete(&key);
|
||||
self.forget_fallback(plugin, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest response body a plugin receives.
|
||||
const MAX_RESPONSE: usize = 16 << 20;
|
||||
/// Largest stdout / stderr kept from a process by default.
|
||||
@@ -4210,6 +4265,67 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged");
|
||||
}
|
||||
|
||||
/// Plugin secrets go to the credential store; a value an older version left in
|
||||
/// the owner-only file keeps working until it is set again, and then leaves the file.
|
||||
#[test]
|
||||
fn plugin_secrets_go_to_the_credential_store() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap();
|
||||
let secrets = CredentialSecretStore::new(dir.clone());
|
||||
assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a"));
|
||||
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap();
|
||||
let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e");
|
||||
assert_eq!(on_disk, Vec::<PathBuf>::new());
|
||||
assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::<PathBuf>::new());
|
||||
let again = CredentialSecretStore::new(dir);
|
||||
assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b"));
|
||||
assert_eq!(again.get("other.plugin", "token"), None);
|
||||
|
||||
again.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(again.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
/// Without a credential store a value stays in the owner-only file.
|
||||
#[test]
|
||||
fn plugin_secrets_without_a_credential_store_stay_in_the_file() {
|
||||
struct NoStore;
|
||||
impl ide_ssh::secrets::Vault for NoStore {
|
||||
fn available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<String> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
let store = ide_ssh::secrets::SecretFile::with_vault(
|
||||
dir.join("plugin-secrets.json"),
|
||||
|v| serde_json::from_value(v).ok(),
|
||||
Arc::new(NoStore),
|
||||
);
|
||||
let secrets = CredentialSecretStore::with_store(store, dir.clone());
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
assert_eq!(
|
||||
ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"),
|
||||
[dir.join("acme.lint").join("secrets.json")]
|
||||
);
|
||||
assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
secrets.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(secrets.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn storage_and_secrets_refuse_symlinked_private_directories() {
|
||||
|
||||
@@ -63,7 +63,7 @@ pub mod views;
|
||||
pub mod web;
|
||||
mod websocket;
|
||||
|
||||
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
@@ -1949,6 +1949,12 @@ impl PluginHost {
|
||||
*self.shared.secrets.write() = store;
|
||||
}
|
||||
|
||||
/// Keeps plugin secrets in the OS credential store, with the owner-only
|
||||
/// files under the plugins directory as the fallback.
|
||||
pub fn use_credential_store(&self) {
|
||||
self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone())));
|
||||
}
|
||||
|
||||
/// Stores (or, with `None`, deletes) a secret the plugin declares under
|
||||
/// `[[contributes.secrets]]`.
|
||||
pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> {
|
||||
|
||||
@@ -762,6 +762,12 @@ impl Host {
|
||||
if let Some(cmd) = post_start {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
if project.is_trusted() {
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
crate::ops::sdk::container_python::ensure(self, &project);
|
||||
Ok(project)
|
||||
}
|
||||
@@ -2015,7 +2021,9 @@ fn independent_eclipse_projects(root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
/// The detected roots with the last Gradle sync's source sets first: Gradle evaluated what
|
||||
/// static detection guesses. Folders outside the project keep their absolute path, which
|
||||
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`).
|
||||
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`);
|
||||
/// their `detected_from` owner keeps its leading `/` or drive (`<project>/Gradle`) so
|
||||
/// module lists still address them as absolute paths.
|
||||
fn with_gradle_roots(
|
||||
root: &Path,
|
||||
build_cache: &Path,
|
||||
@@ -2039,12 +2047,22 @@ fn with_gradle_roots(
|
||||
};
|
||||
if !out.iter().any(|f| f.path == path) {
|
||||
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
|
||||
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
|
||||
// the UI reads the folder as project-relative.
|
||||
// UI still finds the module after a sync. Projects outside the root keep their
|
||||
// absolute owner (without `normalize`, which strips a leading `/`), except an ancestor
|
||||
// of the root (opened from a subproject) or a filesystem/drive root, which stay
|
||||
// `Gradle` so they cannot shadow in-project modules or collapse to a bare drive `D:`.
|
||||
let project = dunce::canonicalize(&project).unwrap_or(project);
|
||||
let detected_from = match project.strip_prefix(root) {
|
||||
Ok(rel) if !rel.as_os_str().is_empty() => {
|
||||
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
|
||||
}
|
||||
Err(_) if !root.starts_with(&project) && project.parent().is_some() => {
|
||||
let raw = project.to_string_lossy().replace('\\', "/");
|
||||
let owner = raw.trim_end_matches('/');
|
||||
let drive_root =
|
||||
owner.len() == 2 && owner.as_bytes()[0].is_ascii_alphabetic() && owner.as_bytes()[1] == b':';
|
||||
if owner.is_empty() || drive_root { "Gradle".into() } else { format!("{owner}/Gradle") }
|
||||
}
|
||||
_ => "Gradle".into(),
|
||||
};
|
||||
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
|
||||
@@ -2492,18 +2510,109 @@ mod gradle_roots_tests {
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let owner = format!("{}/Gradle", svc.to_string_lossy().replace('\\', "/"));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
|
||||
// A project outside the root is not a module the UI could address.
|
||||
// A project outside the root keeps its absolute owner so module lists still address it.
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/it/java".into(), RootKind::Test, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some(owner.as_str())),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some(owner.as_str())),
|
||||
("web".into(), RootKind::Source, None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_keep_plain_gradle_for_ancestors_and_fs_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let composite = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let app = composite.join("app");
|
||||
let lib = app.join("lib");
|
||||
let cache = composite.join("cache");
|
||||
let ext_posix = composite.join("ext-posix/src/main/java");
|
||||
let ext_win = composite.join("ext-win/src/main/java");
|
||||
for d in [
|
||||
composite.join("src/main/java"),
|
||||
app.join("src/main/java"),
|
||||
lib.join("src/main/java"),
|
||||
ext_posix.clone(),
|
||||
ext_win.clone(),
|
||||
cache.clone(),
|
||||
] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
// Opened at `composite/app` while Gradle discovers parent `composite/settings.gradle`
|
||||
// (so `composite` is an ancestor of `root`), plus external roots owned by `/` or `D:/`.
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(composite.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(composite.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app", "dir": s(app.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app:lib", "dir": s(lib.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":posix-root", "dir": "/", "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(ext_posix.clone())], "res": [] } ] },
|
||||
{ "path": ":win-drive", "dir": "D:/", "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(ext_win.clone())], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
std::fs::write(app.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(abs(composite.join("src/main/java")), Some("Gradle")),
|
||||
("src/main/java".into(), Some("Gradle")),
|
||||
("lib/src/main/java".into(), Some("lib/Gradle")),
|
||||
(abs(ext_posix), Some("Gradle")),
|
||||
(abs(ext_win), Some("Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gradle_sync_roots_canonicalize_symlinked_project_dirs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let real = ws.join("real");
|
||||
let link = ws.join("link");
|
||||
let app = real.join("app");
|
||||
let lib = app.join("lib");
|
||||
let cache = ws.join("cache");
|
||||
for d in [real.join("src/main/java"), app.join("src/main/java"), lib.join("src/main/java"), cache.clone()] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
// Opened at canonical `real/app`, while Gradle reports projects through the symlink `link`.
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(link.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(real.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app", "dir": s(link.join("app")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app:lib", "dir": s(link.join("app/lib")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
std::fs::write(app.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(abs(real.join("src/main/java")), Some("Gradle")),
|
||||
("src/main/java".into(), Some("Gradle")),
|
||||
("lib/src/main/java".into(), Some("lib/Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -282,11 +282,18 @@ impl crate::Host {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
self.environment.direnv_opened(&project.root, &project.sink);
|
||||
{
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
project.lsp.set_execution_allowed(true);
|
||||
project.lsp.prewarm_java_configuration();
|
||||
} else {
|
||||
self.environment.project_closed();
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
project.agents.shutdown();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
|
||||
@@ -697,6 +697,7 @@ async fn typescript() {
|
||||
}
|
||||
|
||||
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
|
||||
#[cfg(unix)]
|
||||
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
|
||||
events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
|
||||
|
||||
@@ -6,7 +6,6 @@ use ide_host::{Host, HostConfig};
|
||||
use ide_plugin::TextQuery;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
struct Harness {
|
||||
host: Arc<Host>,
|
||||
@@ -510,6 +509,7 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
|
||||
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let f = Harness::new();
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
|
||||
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
|
||||
Some(settings)
|
||||
}
|
||||
|
||||
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
|
||||
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
|
||||
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
|
||||
/// A threshold the server configuration sets explicitly is kept.
|
||||
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
|
||||
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
|
||||
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
|
||||
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
|
||||
json!({
|
||||
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
|
||||
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
|
||||
})
|
||||
}
|
||||
|
||||
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
|
||||
for (id, value) in settings {
|
||||
let marker = format!(r#"<setting id="{id}" value=""#);
|
||||
@@ -84,6 +98,7 @@ pub fn configure_formatter(
|
||||
});
|
||||
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
|
||||
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
|
||||
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
|
||||
cfg.settings = Some(settings);
|
||||
let Some(style) = style else { return Ok(()) };
|
||||
let indent = indent_settings(style);
|
||||
@@ -300,6 +315,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let imports = |cfg: &LanguageServerConfig| {
|
||||
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
|
||||
};
|
||||
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle {
|
||||
class_count_to_use_import_with_star: Some(7),
|
||||
names_count_to_use_static_import_with_star: Some(4),
|
||||
..Default::default()
|
||||
};
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
|
||||
|
||||
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
|
||||
let mut cfg = config("jdtls");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
|
||||
|
||||
// A threshold set in the server configuration wins.
|
||||
let mut cfg = config("jdtls");
|
||||
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
|
||||
|
||||
let mut cfg = config("rust-analyzer");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -152,6 +152,8 @@ impl SshManager {
|
||||
let config = self.config(id)?;
|
||||
let secret = self.secret(&config);
|
||||
let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?);
|
||||
// The shared session carries the config's port forwards, restarted on every reconnect.
|
||||
session.start_forwards().await;
|
||||
self.sessions.lock().insert(id.to_owned(), session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
//! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a
|
||||
//! changed key is refused unless host key checking is off.
|
||||
|
||||
use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops};
|
||||
use crate::target::{
|
||||
ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops,
|
||||
};
|
||||
use ide_core::remote_settings::SshAuth;
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
@@ -113,6 +115,18 @@ pub struct Session {
|
||||
/// Sessions of the `ProxyJump` hosts, kept alive under `handle`.
|
||||
_jumps: Vec<Handle<Client>>,
|
||||
label: String,
|
||||
/// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`].
|
||||
forwards: Vec<PortForward>,
|
||||
/// `LocalForward` listeners, stopped with the session.
|
||||
listeners: Mutex<Vec<tokio::task::AbortHandle>>,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
for listener in self.listeners.lock().drain(..) {
|
||||
listener.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -158,8 +172,50 @@ impl Session {
|
||||
sessions.push(handle);
|
||||
}
|
||||
let handle = sessions.pop().expect("at least one hop");
|
||||
let label = hops.last().expect("at least one hop").label();
|
||||
Ok(Session { handle, _jumps: sessions, label })
|
||||
let last = hops.last().expect("at least one hop");
|
||||
Ok(Session {
|
||||
handle,
|
||||
_jumps: sessions,
|
||||
label: last.label(),
|
||||
forwards: last.forwards.clone(),
|
||||
listeners: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the
|
||||
/// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each
|
||||
/// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused
|
||||
/// by the server) is skipped with a warning, as `ssh` goes on without it.
|
||||
pub async fn start_forwards(self: &Arc<Self>) {
|
||||
for f in &self.forwards {
|
||||
let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port);
|
||||
match f.direction {
|
||||
ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await {
|
||||
Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label),
|
||||
Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label),
|
||||
},
|
||||
ForwardDirection::Local => {
|
||||
let bind = match f.bind.as_str() {
|
||||
"localhost" => "127.0.0.1",
|
||||
"" => "0.0.0.0",
|
||||
b => b,
|
||||
};
|
||||
match tokio::net::TcpListener::bind((bind, f.port)).await {
|
||||
Ok(listener) => {
|
||||
let task = tokio::spawn(local_forward(
|
||||
listener,
|
||||
Arc::downgrade(self),
|
||||
f.host.clone(),
|
||||
f.host_port,
|
||||
));
|
||||
self.listeners.lock().push(task.abort_handle());
|
||||
tracing::info!("{}: LocalForward {what}", self.label);
|
||||
}
|
||||
Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `user@host:port` of the target.
|
||||
@@ -404,6 +460,39 @@ fn io(message: impl Into<String>) -> IdeError {
|
||||
IdeError::new(ErrorKind::Io, message)
|
||||
}
|
||||
|
||||
/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to
|
||||
/// `host:port` from the SSH host, while the session lives.
|
||||
async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak<Session>, host: String, port: u16) {
|
||||
while let Ok((mut socket, _)) = listener.accept().await {
|
||||
let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return };
|
||||
let host = host.clone();
|
||||
tokio::spawn(async move {
|
||||
match session.direct_tcpip(&host, port).await {
|
||||
Ok(mut stream) => {
|
||||
drop(session);
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways.
|
||||
async fn remote_forward(channel: russh::Channel<Msg>, reply: client::ChannelOpenHandle, host: String, port: u16) {
|
||||
match tokio::net::TcpStream::connect((host.as_str(), port)).await {
|
||||
Ok(mut socket) => {
|
||||
reply.accept().await;
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}");
|
||||
reply.reject(russh::ChannelOpenFailure::ConnectFailed).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- connection ----------------------------------------------------------------
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -418,6 +507,8 @@ pub struct Client {
|
||||
known_hosts: PathBuf,
|
||||
host_key_policy: HostKeyPolicy,
|
||||
issue: Arc<Mutex<Option<HostKeyIssue>>>,
|
||||
/// The `RemoteForward`s whose connections this client accepts.
|
||||
remote_forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
impl client::Handler for Client {
|
||||
@@ -442,6 +533,26 @@ impl client::Handler for Client {
|
||||
*self.issue.lock() = Some(issue);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn server_channel_open_forwarded_tcpip(
|
||||
&mut self,
|
||||
channel: russh::Channel<Msg>,
|
||||
_connected_address: &str,
|
||||
connected_port: u32,
|
||||
_originator_address: &str,
|
||||
_originator_port: u32,
|
||||
reply: client::ChannelOpenHandle,
|
||||
_session: &mut client::Session,
|
||||
) -> Result<(), Self::Error> {
|
||||
// Only a port this client asked the server to forward is accepted.
|
||||
match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) {
|
||||
Some(f) => {
|
||||
tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port));
|
||||
}
|
||||
None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -600,6 +711,7 @@ where
|
||||
known_hosts: effective_known_hosts,
|
||||
host_key_policy: hop.host_key_policy,
|
||||
issue: issue.clone(),
|
||||
remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(),
|
||||
};
|
||||
let result = match stream {
|
||||
None => client::connect(config, (hop.host.as_str(), hop.port), handler).await,
|
||||
|
||||
@@ -54,6 +54,63 @@ pub(crate) struct Hop {
|
||||
pub host_key_policy: HostKeyPolicy,
|
||||
pub known_hosts: Option<PathBuf>,
|
||||
pub agent: Agent,
|
||||
/// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing).
|
||||
pub forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PortForward {
|
||||
pub direction: ForwardDirection,
|
||||
/// Address the listening side binds: empty for every address, `localhost` by default.
|
||||
pub bind: String,
|
||||
pub port: u16,
|
||||
/// Where each connection goes, as the other side sees it.
|
||||
pub host: String,
|
||||
pub host_port: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ForwardDirection {
|
||||
/// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host.
|
||||
Local,
|
||||
/// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine.
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6
|
||||
/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s
|
||||
/// dynamic (SOCKS) form.
|
||||
pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option<PortForward> {
|
||||
let spec = split_args(value).join(":");
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut bracket = false;
|
||||
for ch in spec.chars() {
|
||||
match ch {
|
||||
'[' if cur.is_empty() => bracket = true,
|
||||
']' if bracket => bracket = false,
|
||||
':' if !bracket => parts.push(std::mem::take(&mut cur)),
|
||||
'/' => return None,
|
||||
_ => cur.push(ch),
|
||||
}
|
||||
}
|
||||
parts.push(cur);
|
||||
let (bind, port, host, host_port) = match parts.as_slice() {
|
||||
[port, host, host_port] => (None, port, host, host_port),
|
||||
[bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port),
|
||||
_ => return None,
|
||||
};
|
||||
let bind = match bind {
|
||||
None => "localhost".to_owned(),
|
||||
Some("*") | Some("") => String::new(),
|
||||
Some(b) => b.to_owned(),
|
||||
};
|
||||
let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?);
|
||||
if host.is_empty() || host_port == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(PortForward { direction, bind, port, host: host.clone(), host_port })
|
||||
}
|
||||
|
||||
/// Where the SSH agent of a hop listens (`IdentityAgent`).
|
||||
@@ -158,6 +215,8 @@ struct RawConfig {
|
||||
host_key_policy: Option<HostKeyPolicy>,
|
||||
user_known_hosts_file: Option<String>,
|
||||
identity_agent: Option<String>,
|
||||
forwards: Vec<PortForward>,
|
||||
clear_forwardings: bool,
|
||||
}
|
||||
|
||||
fn strip_quotes(s: &str) -> &str {
|
||||
@@ -516,6 +575,23 @@ fn parse_config_file(
|
||||
out.user_known_hosts_file = Some(first);
|
||||
}
|
||||
}
|
||||
"localforward" | "remoteforward" => {
|
||||
let direction = if key.eq_ignore_ascii_case("localforward") {
|
||||
ForwardDirection::Local
|
||||
} else {
|
||||
ForwardDirection::Remote
|
||||
};
|
||||
match parse_forward(direction, value) {
|
||||
Some(f) if !out.forwards.contains(&f) => out.forwards.push(f),
|
||||
Some(_) => {}
|
||||
None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"),
|
||||
}
|
||||
}
|
||||
"clearallforwardings" => {
|
||||
if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") {
|
||||
out.clear_forwardings = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -559,7 +635,8 @@ fn config_hop(
|
||||
if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) };
|
||||
let agent =
|
||||
identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local)));
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent };
|
||||
let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards };
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards };
|
||||
(hop, proxy_jump)
|
||||
}
|
||||
|
||||
@@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop {
|
||||
_ => (rest, None),
|
||||
};
|
||||
let (hop, _) = config_hop(config, host, port, user);
|
||||
hop
|
||||
Hop { forwards: Vec::new(), ..hop }
|
||||
}
|
||||
|
||||
/// The SSH hosts to go through, the target last.
|
||||
@@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu
|
||||
host_key_policy: HostKeyPolicy::Ask,
|
||||
known_hosts: None,
|
||||
agent: Agent::Default,
|
||||
forwards: Vec::new(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_port_forwards_like_openssh() {
|
||||
let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port));
|
||||
let remote = ForwardDirection::Remote;
|
||||
assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222)));
|
||||
assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80)));
|
||||
assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432)));
|
||||
// Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards.
|
||||
assert_eq!(f(remote, "1080"), None);
|
||||
assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None);
|
||||
assert_eq!(f(remote, "8080 web:http"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = dir.path().join("config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
"Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\
|
||||
Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n",
|
||||
)
|
||||
.unwrap();
|
||||
let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() };
|
||||
let hops = resolve_hops(&target("box"), Some(&config)).unwrap();
|
||||
assert_eq!(hops.len(), 2);
|
||||
assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing");
|
||||
let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect();
|
||||
assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]);
|
||||
assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_aliases_and_proxy_jumps_from_ssh_config() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -98,6 +98,32 @@ impl server::Handler for Sshd {
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client.
|
||||
async fn tcpip_forward(
|
||||
&mut self,
|
||||
address: &str,
|
||||
port: &mut u32,
|
||||
session: &mut ServerSession,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) };
|
||||
let (handle, address, port) = (session.handle(), address.to_owned(), *port);
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut socket, peer)) = listener.accept().await {
|
||||
let Ok(channel) = handle
|
||||
.channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port()))
|
||||
.await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Echo server standing in for a remote service.
|
||||
@@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() {
|
||||
let msg = denied(env.connect(&target, None).await);
|
||||
assert!(msg.contains("has changed"), "{msg}");
|
||||
}
|
||||
|
||||
/// A free local port (bound and released).
|
||||
fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
async fn echoes(port: u16) {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens");
|
||||
s.write_all(b"ping").await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
s.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"ping");
|
||||
}
|
||||
|
||||
/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031).
|
||||
#[tokio::test]
|
||||
async fn config_port_forwards_follow_the_session() {
|
||||
let mut env = env().await;
|
||||
let (remote, local) = (free_port(), free_port());
|
||||
let config = env._tmp.path().join("ssh_config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
format!(
|
||||
"Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\
|
||||
\tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\
|
||||
\tRemoteForward /tmp/remote.sock /tmp/local.sock\n",
|
||||
echo = env.echo_port
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
env.files.config = Some(config);
|
||||
let target = SshTarget {
|
||||
host: "box".into(),
|
||||
port: Some(env.ssh_port),
|
||||
user: "coder".into(),
|
||||
auth: SshAuth::OpenSsh,
|
||||
..Default::default()
|
||||
};
|
||||
let session = Arc::new(env.connect(&target, None).await.expect("connects"));
|
||||
session.start_forwards().await;
|
||||
// The SSH host's port reaches the echo server here; the local port reaches it from the SSH host.
|
||||
echoes(remote).await;
|
||||
echoes(local).await;
|
||||
drop(session);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward");
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
//! without network.
|
||||
|
||||
use crate::platform::{Arch, Os, Platform};
|
||||
use crate::process::{Emit, Http};
|
||||
use crate::process::Emit;
|
||||
use crate::sources::Download;
|
||||
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -240,10 +240,6 @@ fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
fn http(&self) -> IdeResult<Http> {
|
||||
Http::new(&self.system_path)
|
||||
}
|
||||
|
||||
/// Java versions `vendor` publishes.
|
||||
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
|
||||
vendor_or_err(vendor)?;
|
||||
|
||||
@@ -557,6 +557,10 @@ impl Tools {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn http(&self) -> IdeResult<Http> {
|
||||
Ok(Http::new(&self.system_path)?.with_gh_from(&self.child_path))
|
||||
}
|
||||
|
||||
/// [`Tools::command`] in the project directory.
|
||||
fn command_in_project(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
|
||||
let mut cmd = self.command(program);
|
||||
@@ -902,7 +906,7 @@ impl Tools {
|
||||
_ => (ToolStatus::Missing, None, None),
|
||||
}
|
||||
}
|
||||
_ => match self.which(main) {
|
||||
_ => match self.which(main).or_else(|| self.found.get(main).cloned()) {
|
||||
Some(path) => {
|
||||
let version = self.query_version(spec, &path);
|
||||
(ToolStatus::OnPath, Some(path), version)
|
||||
@@ -1250,7 +1254,8 @@ impl Tools {
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
let pick = Http::new(&self.system_path)
|
||||
let pick = self
|
||||
.http()
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
match pick {
|
||||
Ok(dotnet::ToolPick::Latest) => Ok(None),
|
||||
@@ -1542,7 +1547,7 @@ impl Tools {
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let http = Http::new(&self.system_path)?;
|
||||
let http = self.http()?;
|
||||
let message = match source {
|
||||
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
|
||||
_ => "Resolving the latest release…".into(),
|
||||
@@ -1683,7 +1688,7 @@ impl Tools {
|
||||
fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult<Option<String>> {
|
||||
match method {
|
||||
Method::Release { source, assets, .. } => {
|
||||
let http = Http::new(&self.system_path)?;
|
||||
let http = self.http()?;
|
||||
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
|
||||
}
|
||||
Method::Npm { packages } => {
|
||||
|
||||
@@ -441,6 +441,17 @@ impl Http {
|
||||
self
|
||||
}
|
||||
|
||||
/// Looks up `gh` on `search_path` (e.g. a path that includes IDE-managed tools).
|
||||
pub(crate) fn with_gh_from(mut self, search_path: &std::ffi::OsStr) -> Self {
|
||||
self.gh = which::which_in("gh", Some(search_path), ".").ok();
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn gh_path(&self) -> Option<&Path> {
|
||||
self.gh.as_deref()
|
||||
}
|
||||
|
||||
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
|
||||
pub fn without_github_auth(mut self) -> Self {
|
||||
self.gh = None;
|
||||
|
||||
@@ -181,6 +181,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
needs: NODE,
|
||||
homepage: "https://github.com/devcontainers/cli",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "gh",
|
||||
display: "GitHub CLI",
|
||||
kind: Cli,
|
||||
commands: &["gh"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "cli/cli" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "gh_*_macOS_arm64.zip"),
|
||||
rule(Mac, X64, "gh_*_macOS_amd64.zip"),
|
||||
rule(Linux, Arm64, "gh_*_linux_arm64.tar.gz"),
|
||||
rule(Linux, X64, "gh_*_linux_amd64.tar.gz"),
|
||||
rule(Windows, Arm64, "gh_*_windows_arm64.zip"),
|
||||
rule(Windows, X64, "gh_*_windows_amd64.zip"),
|
||||
],
|
||||
locate: &["gh"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("gh"),
|
||||
needs: &[],
|
||||
homepage: "https://cli.github.com",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "oxfmt",
|
||||
display: "oxfmt",
|
||||
@@ -1483,4 +1505,56 @@ mod tests {
|
||||
let win_arm = Platform { os: Windows, arch: Arm64 };
|
||||
assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gh_release_picks_portable_archive_for_every_supported_platform() {
|
||||
use crate::platform::{Platform, select_asset};
|
||||
let names = [
|
||||
"gh_2.106.0_checksums.txt",
|
||||
"gh_2.106.0_linux_386.deb",
|
||||
"gh_2.106.0_linux_386.tar.gz",
|
||||
"gh_2.106.0_linux_amd64.deb",
|
||||
"gh_2.106.0_linux_amd64.rpm",
|
||||
"gh_2.106.0_linux_amd64.tar.gz",
|
||||
"gh_2.106.0_linux_arm64.deb",
|
||||
"gh_2.106.0_linux_arm64.tar.gz",
|
||||
"gh_2.106.0_linux_armv6.tar.gz",
|
||||
"gh_2.106.0_macOS_amd64.zip",
|
||||
"gh_2.106.0_macOS_arm64.zip",
|
||||
"gh_2.106.0_macOS_universal.pkg",
|
||||
"gh_2.106.0_windows_386.zip",
|
||||
"gh_2.106.0_windows_amd64.msi",
|
||||
"gh_2.106.0_windows_amd64.zip",
|
||||
"gh_2.106.0_windows_arm64.msi",
|
||||
"gh_2.106.0_windows_arm64.zip",
|
||||
];
|
||||
let spec = find("gh").unwrap();
|
||||
assert_eq!(spec.kind, Cli);
|
||||
let rules = spec.asset_rules();
|
||||
for (os, arch, expected) in [
|
||||
(Mac, Arm64, "gh_2.106.0_macOS_arm64.zip"),
|
||||
(Mac, X64, "gh_2.106.0_macOS_amd64.zip"),
|
||||
(Linux, Arm64, "gh_2.106.0_linux_arm64.tar.gz"),
|
||||
(Linux, X64, "gh_2.106.0_linux_amd64.tar.gz"),
|
||||
(Windows, Arm64, "gh_2.106.0_windows_arm64.zip"),
|
||||
(Windows, X64, "gh_2.106.0_windows_amd64.zip"),
|
||||
] {
|
||||
assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected));
|
||||
}
|
||||
|
||||
let Method::Release { locate, .. } = &spec.method else { unreachable!() };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let unix_bin = tmp.path().join("gh_2.106.0_macOS_arm64/bin/gh");
|
||||
std::fs::create_dir_all(unix_bin.parent().unwrap()).unwrap();
|
||||
std::fs::write(&unix_bin, "").unwrap();
|
||||
let unix_names: Vec<String> = locate.iter().map(|n| (*n).to_owned()).collect();
|
||||
assert_eq!(crate::archive::locate(tmp.path(), &unix_names), Some(unix_bin));
|
||||
|
||||
let win_dir = tempfile::tempdir().unwrap();
|
||||
let win_bin = win_dir.path().join("bin/gh.exe");
|
||||
std::fs::create_dir_all(win_bin.parent().unwrap()).unwrap();
|
||||
std::fs::write(&win_bin, "").unwrap();
|
||||
let win_names: Vec<String> = locate.iter().map(|n| format!("{n}.exe")).collect();
|
||||
assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin));
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,11 @@ fn pick_release(
|
||||
let checksum_url = assets
|
||||
.iter()
|
||||
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
|
||||
.or_else(|| {
|
||||
assets
|
||||
.iter()
|
||||
.find(|c| c.name.eq_ignore_ascii_case("checksums.txt") || c.name.ends_with("_checksums.txt"))
|
||||
})
|
||||
.map(|c| c.url.clone());
|
||||
return Ok(Download {
|
||||
version,
|
||||
@@ -622,6 +627,28 @@ mod tests {
|
||||
let sums = format!("{} other.zip\n{} *wanted.zip\n", "b".repeat(64), "C".repeat(64));
|
||||
assert_eq!(parse_checksum(&sums, "wanted.zip"), Some("c".repeat(64)));
|
||||
assert_eq!(parse_checksum(&sums, "missing.zip"), None);
|
||||
|
||||
let gh = serde_json::json!({
|
||||
"tag_name": "v2.106.0",
|
||||
"assets": [
|
||||
{
|
||||
"name": "gh_2.106.0_macOS_arm64.zip",
|
||||
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_macOS_arm64.zip"
|
||||
},
|
||||
{
|
||||
"name": "gh_2.106.0_checksums.txt",
|
||||
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt"
|
||||
}
|
||||
]
|
||||
})
|
||||
.to_string();
|
||||
let dl = github_pick(&gh, find("gh").unwrap().asset_rules(), MAC_ARM).unwrap();
|
||||
assert_eq!(dl.version, "2.106.0");
|
||||
assert_eq!(dl.name, "gh_2.106.0_macOS_arm64.zip");
|
||||
assert_eq!(
|
||||
dl.checksum_url.as_deref(),
|
||||
Some("https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1428,3 +1428,27 @@ fn a_mirror_never_installs_what_it_alone_vouches_for() {
|
||||
let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err();
|
||||
assert!(err.message.contains("checksum mismatch"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 0");
|
||||
let app_data = env.root.parent().unwrap();
|
||||
let gh_bin = env.root.join("gh/bin");
|
||||
assert!(tools_bin_dirs(app_data).contains(&gh_bin));
|
||||
|
||||
let missing = env.tools().info("gh", &[]).unwrap();
|
||||
assert_eq!(missing.kind, ToolKind::Cli);
|
||||
assert_eq!(missing.status, ToolStatus::Missing);
|
||||
assert!(missing.can_install);
|
||||
|
||||
env.script(&gh_bin, "gh", "echo 'gh version 2.106.0 (2026-11-20)'");
|
||||
let installed = env.tools().info("gh", &[]).unwrap();
|
||||
assert_eq!(installed.status, ToolStatus::Installed);
|
||||
assert_eq!(installed.version.as_deref(), Some("2.106.0"));
|
||||
assert!(installed.can_uninstall);
|
||||
|
||||
let http = env.tools().http().unwrap();
|
||||
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
|
||||
}
|
||||
@@ -174,6 +174,9 @@ struct DocState {
|
||||
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
|
||||
/// alone until the user saves explicitly or the buffer is reloaded.
|
||||
disk_conflict: bool,
|
||||
/// External changes seen while the buffer had unsaved changes (each `disk_conflict`), so an
|
||||
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
|
||||
external_writes: u64,
|
||||
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
|
||||
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
|
||||
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
|
||||
@@ -191,6 +194,35 @@ impl DocState {
|
||||
self.disk_conflict = false;
|
||||
self.clean_text = (!self.large).then(|| self.doc.clone());
|
||||
}
|
||||
|
||||
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
|
||||
fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> {
|
||||
let text = doc.text_for_save();
|
||||
Ok(if self.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &self.encoding, self.has_bom)?
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the file changed on disk since the buffer last matched it. A moved stamp with the
|
||||
/// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file
|
||||
/// only when the mtime moved but the length did not; without a clean text to compare (large
|
||||
/// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts.
|
||||
fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool {
|
||||
let mtime = ide_vfs::mtime_ms(meta);
|
||||
if mtime == self.disk_mtime && meta.len() == self.disk_len {
|
||||
return false;
|
||||
}
|
||||
let same_bytes = meta.len() == self.disk_len
|
||||
&& self.clean_text.as_ref().is_some_and(|clean| {
|
||||
self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes))
|
||||
});
|
||||
if same_bytes {
|
||||
self.disk_mtime = mtime;
|
||||
}
|
||||
!same_bytes
|
||||
}
|
||||
}
|
||||
|
||||
fn keys_for(path: &Path) -> Vec<PathBuf> {
|
||||
@@ -511,6 +543,7 @@ impl Documents {
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: None,
|
||||
@@ -587,6 +620,7 @@ impl Documents {
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(uri.to_owned()),
|
||||
@@ -647,6 +681,7 @@ impl Documents {
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(key.to_string_lossy().into_owned()),
|
||||
@@ -919,20 +954,7 @@ impl Documents {
|
||||
/// on disk after this buffer was edited, which only an explicit save may overwrite.
|
||||
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
// The watcher event for an external write may not have arrived yet: check the stamp now.
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
|
||||
{
|
||||
st.disk_mtime = ide_vfs::mtime_ms(&meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
self.check_disk_conflict(doc, st);
|
||||
if st.dirty && st.disk_conflict {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -940,6 +962,29 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// An unsaved buffer whose file another program wrote: the watcher event may not have arrived
|
||||
/// yet, so check the stamp now.
|
||||
fn check_disk_conflict(&self, doc: DocId, st: &mut DocState) {
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& st.changed_on_disk(&meta)
|
||||
{
|
||||
self.disk_conflict(doc, st, &meta);
|
||||
}
|
||||
}
|
||||
|
||||
fn disk_conflict(&self, doc: DocId, st: &mut DocState, meta: &std::fs::Metadata) {
|
||||
st.disk_mtime = ide_vfs::mtime_ms(meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
st.external_writes += 1;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
|
||||
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
|
||||
{
|
||||
if !st.dirty || st.uri.is_some() {
|
||||
@@ -1411,12 +1456,10 @@ impl Documents {
|
||||
return Ok(());
|
||||
}
|
||||
if st.dirty {
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
|
||||
if !st.changed_on_disk(&meta) {
|
||||
return Ok(());
|
||||
}
|
||||
self.disk_conflict(id, st, &meta);
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = if force_clean {
|
||||
|
||||
@@ -100,6 +100,8 @@ struct Record {
|
||||
paths: Vec<SavedPath>,
|
||||
documents: Vec<(DocId, DocState)>,
|
||||
after: Vec<WorkspaceEditPrecondition>,
|
||||
/// External writes seen by each open document as of `after` (see [`Documents::external_writes`]).
|
||||
writes: Vec<(DocId, u64)>,
|
||||
}
|
||||
|
||||
fn stale(path: &Path) -> IdeError {
|
||||
@@ -314,12 +316,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf,
|
||||
|
||||
/// The bytes saving `state` would write.
|
||||
fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> {
|
||||
let text = state.doc.text_for_save();
|
||||
Ok(if state.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &state.encoding, state.has_bom)?
|
||||
})
|
||||
state.bytes_for_save(&state.doc)
|
||||
}
|
||||
|
||||
/// A reverted edit may leave the dirty flag set even when all saved bytes match.
|
||||
@@ -374,6 +371,35 @@ impl Documents {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many external writes each open document under `roots` has seen, with its path. An
|
||||
/// unsaved buffer's file is checked first, for a write the watcher hasn't reported yet.
|
||||
fn external_writes(&self, roots: &[PathBuf]) -> IdeResult<Vec<(DocId, u64, PathBuf)>> {
|
||||
let mut writes = Vec::new();
|
||||
for id in self.open_documents() {
|
||||
self.with_doc(id, |state| {
|
||||
if roots.iter().any(|p| text_path(&state.path).is_ok_and(|file| file.starts_with(p))) {
|
||||
self.check_disk_conflict(id, state);
|
||||
writes.push((id, state.external_writes, state.path.clone()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(writes)
|
||||
}
|
||||
|
||||
/// Fingerprints see an unsaved buffer in place of its file, so another program writing that
|
||||
/// file since the record was made shows only as a disk conflict. The IDE's own saves don't count.
|
||||
fn validate_external_writes(&self, record: &Record, roots: &[PathBuf]) -> IdeResult<()> {
|
||||
for (id, writes, path) in self.external_writes(roots)? {
|
||||
// A document opened since then starts at zero.
|
||||
let before = record.writes.iter().find(|(doc, _)| *doc == id).map_or(0, |(_, writes)| *writes);
|
||||
if writes != before {
|
||||
return Err(stale(&path));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_preconditions(&self, expected: &[WorkspaceEditPrecondition]) -> IdeResult<()> {
|
||||
let current = self.fingerprints(&expected.iter().map(|p| p.path.to_path_buf()).collect::<Vec<_>>())?;
|
||||
for (before, after) in expected.iter().zip(current) {
|
||||
@@ -474,6 +500,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
record.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
if let Err(error) = fs::remove_file(record.directory.path().join("recovery")) {
|
||||
return Err(self.recover(record, error.into()));
|
||||
}
|
||||
@@ -573,6 +603,7 @@ impl Documents {
|
||||
paths,
|
||||
documents,
|
||||
after: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -874,8 +905,9 @@ impl Documents {
|
||||
if record.undone != redo {
|
||||
return Err(IdeError::invalid("the refactoring is already in the requested history state"));
|
||||
}
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let roots = record.paths.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
|
||||
self.validate_external_writes(record, &roots)?;
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let mut current = self.backup(&roots)?;
|
||||
fs::write(current.directory.path().join("recovery"), b"history restore in progress")?;
|
||||
let _active = ActiveEdit::new(&self.workspace_edit_active);
|
||||
@@ -886,6 +918,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.undone = !redo;
|
||||
current.created = record.created;
|
||||
if let Err(error) = fs::remove_file(current.directory.path().join("recovery")) {
|
||||
|
||||
@@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
|
||||
fn rewrite_later(path: &Path, bytes: &[u8]) {
|
||||
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
fs::write(path, bytes).unwrap();
|
||||
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_the_same_bytes_is_no_disk_conflict() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
}
|
||||
|
||||
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
|
||||
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
|
||||
let f = fixture();
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
|
||||
rewrite_later(&path, external);
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
|
||||
assert_eq!(fs::read(&path).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
|
||||
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
|
||||
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
|
||||
// Same length: only the byte comparison tells them apart.
|
||||
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() {
|
||||
let info = docs.open(&first).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
// An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer.
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
// An external write under the unsaved buffer, warned about before the refactoring.
|
||||
let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
std::fs::write(&first, "ext\n").unwrap();
|
||||
std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap();
|
||||
docs.on_disk_changed(std::slice::from_ref(&first));
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snap = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!(snap.text, "own\n");
|
||||
assert!(snap.dirty);
|
||||
assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -425,6 +426,80 @@ fn undo_refuses_later_changes_and_retains_the_record() {
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
/// An open file with unsaved typing, refactored: its buffer holds `new`, the disk still `old`.
|
||||
fn refactored_unsaved(path: &Path) -> (Documents, Arc<Mutex<Vec<IdeEvent>>>, ide_core::DocId) {
|
||||
std::fs::write(path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(path).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(path, "new")], ..Default::default() }).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
|
||||
(docs, events, info.id)
|
||||
}
|
||||
|
||||
fn type_text(docs: &Documents, id: ide_core::DocId, text: &str) {
|
||||
let snapshot = docs.snapshot(id).unwrap();
|
||||
let to = snapshot.text.encode_utf16().count() as u32;
|
||||
docs.edit(id, snapshot.version, ChangeSet { changes: vec![TextChange { from: 0, to, insert: text.into() }] })
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_an_external_write_under_an_unsaved_buffer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
// Not reported by a watcher: undo itself notices the write.
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(undo_id(&events)).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_after_saving_and_undoing_the_typing_is_allowed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
type_text(&docs, id, "typed later\n");
|
||||
docs.save(id).unwrap();
|
||||
// The typing undone: the buffer is back to the refactoring's text, the IDE's own save on disk.
|
||||
type_text(&docs, id, "new\n");
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_allows_a_disk_conflict_from_before_the_refactoring() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
type_text(&docs, info.id, "own\n");
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert!(!docs.autosave(info.id).unwrap(), "the external write is a disk conflict");
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redo_keeps_an_external_write_made_after_the_undo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
let undo = undo_id(&events);
|
||||
docs.undo_workspace_edit(undo).unwrap();
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.redo_workspace_edit(undo).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,7 +16,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
@@ -132,6 +132,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone.
|
||||
|
||||
For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). **New Tasks** model options are loaded for the authenticated account after sign-in or **Apply**.
|
||||
|
||||
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
@@ -114,6 +114,8 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
|
||||
|
||||
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
|
||||
|
||||
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
|
||||
|
||||
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
|
||||
|
||||
## Tabs
|
||||
@@ -145,17 +147,21 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
|
||||
## View options
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ---------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ------------------------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll Up and Move if Necessary** | — | — |
|
||||
| **Scroll Down and Move if Necessary** | — | — |
|
||||
| **Move Up and Scroll** | — | — |
|
||||
| **Move Down and Scroll** | — | — |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
|
||||
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
|
||||
@@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
|
||||
<Steps>
|
||||
<Step title="Install gh">
|
||||
Install the GitHub CLI. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`, then in
|
||||
`/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) or `C:\Program Files\GitHub CLI\gh.exe`
|
||||
(Windows).
|
||||
Install the GitHub CLI, either from OpenIDEA's **Install GitHub CLI** button (in the **Pull Requests** tool window,
|
||||
**Clone Repository › GitHub**, **Settings › Agents › GitHub Copilot**, or **Settings › Languages & Frameworks ›
|
||||
Language Servers › Other Tools**) or manually. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`
|
||||
(including IDE-managed tools), then in `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux)
|
||||
or `C:\Program Files\GitHub CLI\gh.exe` (Windows).
|
||||
</Step>
|
||||
<Step title="Sign in">
|
||||
Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not
|
||||
@@ -22,6 +24,14 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
The project needs a Git remote on `github.com`. With one GitHub remote, OpenIDEA connects to it automatically. With
|
||||
several, the tool window asks you to pick a **Repository**; the choice is remembered per project. To switch later,
|
||||
use **Change Repository or Account…** in the tool window's `⋮` menu.
|
||||
|
||||
When multiple `github.com` accounts are signed into `gh`, **Automatic** uses `gh`'s own active account without
|
||||
setting `GH_TOKEN`. In **Settings › Version Control › GitHub** and in the **Pull Requests** header, OpenIDEA can
|
||||
suggest a matching account for the repository (**Use `<login>` for this project**) or let you choose one
|
||||
explicitly (saved in `.openidea/settings.toml`). Choosing an account passes its `GH_TOKEN` to processes started in
|
||||
that project (terminals, agents, Git, Pull Requests, and run configurations) without changing your global
|
||||
`gh auth switch` selection.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ Scratch files are saved in a `scratches` folder in OpenIDEA's application data d
|
||||
| Windows | `%APPDATA%\ai.l0ng.openidea\scratches` |
|
||||
| Linux | `~/.local/share/ai.l0ng.openidea/scratches` |
|
||||
|
||||
They are listed under **Scratches** in the Project view, where you can open, rename and delete them like other files.
|
||||
They are listed under **Scratches** in the Project view, where you can open, rename and delete them like other files. To hide that node, turn off **Show Scratches and Consoles** in the Project view's **Options › Appearance** menu; the **Scratches and Consoles** view still lists them.
|
||||
|
||||
Because a scratch file is outside every project, some language servers give it only syntax checks; completion and navigation may be limited. A banner at the top of the editor says so when the server reports it.
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ A test run opens a tab in the **Run** tool window with the test tree next to the
|
||||
- Double-click, `Enter` or `F4` jumps to the test's source (**Jump to Source**).
|
||||
- **Show Passed** and **Show Ignored** filter the tree. Passed tests are hidden by default; the filters are remembered.
|
||||
- **⋯ › Test Runner Options › Select First Failed Test When Finished** selects the first failed test, with its output, when a run ends. It is off by default.
|
||||
- **⋯ › Test Runner Options › Track Running Test** selects each test, with its output, as it starts while the run is in progress. It is on by default.
|
||||
- Right-click a test or a selection for **Run '…'**, **Debug '…'** and **Jump to Source**.
|
||||
- For an assertion failure with expected and actual values, **Show Diff** opens them side by side.
|
||||
- For a Jest or Vitest snapshot mismatch, **Update Snapshot** (on the test or its file or suite, above the failure output, and in the gutter run menu) reruns just those tests with `-u`, so only their snapshots are rewritten.
|
||||
|
||||
@@ -90,7 +90,7 @@ Settings › Appearance & Behavior › System Settings, unless noted.
|
||||
| `dateFormat.overrideSystem` | `false` | **Override system date and time format** (Date Formats page). |
|
||||
| `dateFormat.pattern` | `"dd.MM.yyyy"` | Date pattern with `dd`, `MM`, `MMM`, `yy`, `yyyy`. |
|
||||
| `dateFormat.use24Hour` | `true` | 24-hour time. |
|
||||
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago". |
|
||||
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago" (in lists with time, in the annotate gutter as the day alone). |
|
||||
|
||||
### `[appearance]`
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
@@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
|
||||
|
||||
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。
|
||||
|
||||
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
@@ -145,17 +145,21 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
## 显示选项
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| -------------- | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| ------------------------------ | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **向上滚动并在必要时移动光标** | — | — |
|
||||
| **向下滚动并在必要时移动光标** | — | — |
|
||||
| **向上移动并滚动** | — | — |
|
||||
| **向下移动并滚动** | — | — |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
|
||||
@@ -9,9 +9,10 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
|
||||
|
||||
<Steps>
|
||||
<Step title="安装 gh">
|
||||
安装 GitHub CLI。OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`,以及
|
||||
`/opt/homebrew/bin`、`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub
|
||||
CLI\gh.exe`(Windows)中查找。
|
||||
安装 GitHub CLI:可以直接点击 OpenIDEA 里的 **安装 GitHub CLI** 按钮(位于 **拉取请求** 工具窗口、**克隆仓库 ›
|
||||
GitHub**、**设置 › 智能体 › GitHub Copilot** 或 **设置 › 语言与框架 › 语言服务器 › 其他工具**),也可以手动安装。
|
||||
OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`(包含 IDE 管理的工具目录),以及 `/opt/homebrew/bin`、
|
||||
`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub CLI\gh.exe`(Windows)中查找。
|
||||
</Step>
|
||||
<Step title="登录">
|
||||
在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login**
|
||||
@@ -20,6 +21,9 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
|
||||
<Step title="打开带 GitHub 远程的项目">
|
||||
项目需要有一个指向 `github.com` 的 Git 远程。只有一个 GitHub 远程时自动连接;有多个时,工具窗口会让你选择
|
||||
**仓库**,选择按项目记住。之后要切换,可在工具窗口的 `⋮` 菜单中选 **更改仓库或账户…**。
|
||||
|
||||
当 `gh` 中登录了多个 `github.com` 账户时,**自动**模式沿用 `gh` 当前的活动账户,不会在项目环境中设置 `GH_TOKEN`。在 **设置 › 版本控制 › GitHub** 和 **拉取请求** 标题栏中,OpenIDEA 会根据仓库远程提示匹配的账户(**对此项目使用 `<login>`**),也可以手动为项目指定账户(保存在 `.openidea/settings.toml`)。显式选择账户后,OpenIDEA 会将该账户的 `GH_TOKEN` 传递给此项目中启动的进程(终端、智能体、Git、拉取请求和运行配置),而不会改动全局的 `gh auth switch` 状态。
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ description: "在项目之外保留临时文件,并在 TODO 工具窗口中汇
|
||||
| Windows | `%APPDATA%\ai.l0ng.openidea\scratches` |
|
||||
| Linux | `~/.local/share/ai.l0ng.openidea/scratches` |
|
||||
|
||||
它们列在项目视图的 **临时文件** 节点下,可以像其他文件一样打开、重命名和删除。
|
||||
它们列在项目视图的 **临时文件** 节点下,可以像其他文件一样打开、重命名和删除。要隐藏这个节点,可在项目视图的 **选项 › 外观** 菜单中关闭 **显示临时文件和控制台**;**临时文件和控制台** 视图仍会列出它们。
|
||||
|
||||
临时文件不属于任何项目,所以部分语言服务器只对它做语法检查,补全和导航可能受限;服务器报告这种情况时,编辑器顶部会显示横幅说明。
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
|
||||
- 双击、按 `Enter` 或 `F4` 跳到测试源码(**跳转到源代码**)。
|
||||
- **显示已通过** 和 **显示已忽略** 用于筛选测试树。默认隐藏已通过的测试,筛选状态会被记住。
|
||||
- **⋯ › 测试运行器选项 › 完成后选中第一个失败的测试** 会在运行结束时选中第一个失败的测试并显示它的输出。默认关闭。
|
||||
- **⋯ › 测试运行器选项 › 跟踪正在运行的测试** 会在运行过程中,每个测试开始时选中它并显示它的输出。默认开启。
|
||||
- 右键单个测试或多选后,可以 **运行 '…'**、**调试 '…'** 或 **跳转到源代码**。
|
||||
- 对于带有期望值和实际值的断言失败,**显示差异** 会把两者并排对比。
|
||||
- 对于 Jest 或 Vitest 的快照不匹配,**更新快照**(在测试或其文件、套件上,失败输出上方,以及边栏运行菜单中)只用 `-u` 重新运行这些测试,只改写它们的快照。
|
||||
|
||||
@@ -90,7 +90,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
|
||||
| `dateFormat.overrideSystem` | `false` | **覆盖系统日期和时间格式**(日期格式页)。 |
|
||||
| `dateFormat.pattern` | `"dd.MM.yyyy"` | 日期格式,可用 `dd`、`MM`、`MMM`、`yy`、`yyyy`。 |
|
||||
| `dateFormat.use24Hour` | `true` | 使用 24 小时制。 |
|
||||
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间。 |
|
||||
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间(列表中带时间,注解装订区域仅显示日期)。 |
|
||||
|
||||
### `[appearance]`
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentConfigOption, AgentProvider, CopilotAuthStatus } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openAgents(page: Page) {
|
||||
const settings = "/src/features/settings/model/staging.ts";
|
||||
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings);
|
||||
return page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
}
|
||||
|
||||
test("unifies Copilot sign-in, gates per-account models on auth, and supports in-IDE account switching", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
let savedAccount = "";
|
||||
let cliAuthenticated = false;
|
||||
let ghAccounts: { login: string; active: boolean }[] = [{ login: "alice", active: true }];
|
||||
let loginChannel: unknown = null;
|
||||
|
||||
const personalModel: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "claude-sonnet-4.5",
|
||||
defaultValue: "claude-sonnet-4.5",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
const workModel: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "gemini-4-neon",
|
||||
defaultValue: "gemini-4-neon",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "gemini-4-neon", name: "Gemini 4 Neon", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
agent_registry_list: () => ({ agents: [], warning: null }),
|
||||
agent_providers: () => {
|
||||
const env: Record<string, string> = { COPILOT_TELEMETRY_OPTOUT: "1" };
|
||||
if (savedAccount) env.OPENIDEA_COPILOT_GITHUB_ACCOUNT = savedAccount;
|
||||
const provider: AgentProvider = {
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
program: "/tools/copilot",
|
||||
args: ["--headless", "--no-auto-update", "--stdio"],
|
||||
defaultProgram: "copilot",
|
||||
defaultArgs: ["--headless", "--no-auto-update", "--stdio"],
|
||||
loginHint: "Run `copilot login` in a terminal.",
|
||||
commandOverridden: false,
|
||||
commandEditable: false,
|
||||
commandReadOnlyReason: "registry",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
canCheckCliUpdate: false,
|
||||
env,
|
||||
config: [workModel],
|
||||
thoughtLevels: {},
|
||||
commands: [],
|
||||
source: { kind: "registry", version: "1.0.116", update: null },
|
||||
};
|
||||
return [provider];
|
||||
},
|
||||
agent_copilot_auth_status: (): CopilotAuthStatus => ({
|
||||
authenticated: cliAuthenticated,
|
||||
login: cliAuthenticated ? "alice" : null,
|
||||
authType: cliAuthenticated ? "oauth" : null,
|
||||
statusMessage: cliAuthenticated ? "alice" : null,
|
||||
ghInstalled: true,
|
||||
ghAccounts,
|
||||
}),
|
||||
agent_refresh_models: () => ({
|
||||
provider: "copilot",
|
||||
config: [savedAccount === "alice-work" ? workModel : personalModel],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
}),
|
||||
agent_set_env: ({ env }: { env: Record<string, string> }) => {
|
||||
savedAccount = env.OPENIDEA_COPILOT_GITHUB_ACCOUNT ?? "";
|
||||
return null;
|
||||
},
|
||||
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
loginChannel = onEvent;
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(loginChannel, { type: "output", data: "Opening GitHub in browser...\r\n" });
|
||||
cliAuthenticated = true;
|
||||
window.__ipc.send(loginChannel, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 1, pid: 1001, title: "copilot" };
|
||||
},
|
||||
agent_gh_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
loginChannel = onEvent;
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(loginChannel, { type: "output", data: "Logged in as alice-work\r\n" });
|
||||
ghAccounts = [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
];
|
||||
window.__ipc.send(loginChannel, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 2, pid: 1002, title: "gh" };
|
||||
},
|
||||
term_resize: () => null,
|
||||
term_write: () => null,
|
||||
term_kill: () => null,
|
||||
});
|
||||
});
|
||||
|
||||
const dialog = await openAgents(page);
|
||||
const signIn = dialog.getByRole("region", { name: "Sign In" });
|
||||
const newTasks = dialog.getByRole("region", { name: "New Tasks" });
|
||||
const launch = dialog.getByRole("region", { name: "Launch" });
|
||||
|
||||
// Unified Sign In section holds GitHub account; Launch has no duplicate account control.
|
||||
const accountSelect = signIn.getByRole("button", { name: "GitHub account" });
|
||||
await expect(accountSelect).toContainText("Copilot CLI default (not signed in)");
|
||||
await expect(launch.getByRole("button", { name: "GitHub account" })).toHaveCount(0);
|
||||
|
||||
// Unauthenticated state hides stale cached models.
|
||||
await expect(newTasks.getByText("Sign in above to view and choose models available for this account.")).toBeVisible();
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
|
||||
|
||||
// Sign In runs in-IDE PTY and unlocks personal account models.
|
||||
await signIn.getByRole("button", { name: "Sign In…" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Sign In to GitHub Copilot" })).toHaveCount(0);
|
||||
await expect(accountSelect).toContainText("Copilot CLI default (alice)");
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)");
|
||||
|
||||
// Add account runs gh auth login in-IDE, auto-selects alice-work, and gates models on Apply.
|
||||
await signIn.getByRole("button", { name: "Add account…" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Sign In to GitHub CLI" })).toHaveCount(0);
|
||||
await expect(accountSelect).toContainText("alice-work");
|
||||
await expect(newTasks.getByText("Click Apply to load the models available for the selected account.")).toBeVisible();
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
|
||||
|
||||
// Applying loads the new account's subscription models.
|
||||
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Gemini 4 Neon)");
|
||||
expect(await ipcCalls(page, "agent_set_env")).toEqual([
|
||||
{
|
||||
id: "copilot",
|
||||
env: {
|
||||
COPILOT_TELEMETRY_OPTOUT: "1",
|
||||
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "alice-work",
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -209,3 +209,48 @@ test("opens a folded process run with the keyboard and jumps back to the latest
|
||||
await expect(jump).toBeHidden();
|
||||
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(40);
|
||||
});
|
||||
|
||||
test("paints earlier turns past folded process runs longer than ENTRY_BATCH", async ({ page }) => {
|
||||
const longRun = (prefix: string, count: number): AgentEntry[] =>
|
||||
Array.from({ length: count }, (_, i): AgentEntry => ({
|
||||
type: "tool",
|
||||
id: `${prefix}-${i}`,
|
||||
kind: i % 3 === 0 ? "edit" : i % 2 === 0 ? "execute" : "read",
|
||||
title: `tool ${prefix}-${i}`,
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: null,
|
||||
diffs: [],
|
||||
}));
|
||||
const longProcessEntries: AgentEntry[] = [
|
||||
{ type: "user", text: "Earliest request before long runs", attachments: [], steered: false },
|
||||
{ type: "agent", text: "Initial reply" },
|
||||
{ type: "user", text: "Split PR into three focused PRs", attachments: [], steered: false },
|
||||
...longRun("batch-a", 75),
|
||||
{ type: "agent", text: "Interim status update" },
|
||||
...longRun("batch-b", 75),
|
||||
];
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task, entries }) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, { ...task, status: "running" }]]),
|
||||
entries: new Map([[task.id, entries]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries: longProcessEntries },
|
||||
);
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
await expect(stream.getByText("Earliest request before long runs")).toBeVisible();
|
||||
await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible();
|
||||
await expect(stream.getByText("Interim status update")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentConfigOption, AgentProvider } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openAgents(page: Page) {
|
||||
const settings = "/src/features/settings/model/staging.ts";
|
||||
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings);
|
||||
return page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
}
|
||||
|
||||
test("signs in to an agent in an IDE terminal dialog and refreshes its model catalog", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
const model: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "claude-sonnet-4.5",
|
||||
defaultValue: "claude-sonnet-4.5",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
let signedIn = false;
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
agent_registry_list: () => ({ agents: [], warning: null }),
|
||||
agent_providers: () => {
|
||||
const provider: AgentProvider = {
|
||||
id: "claude",
|
||||
name: "Claude Code",
|
||||
command: "claude",
|
||||
program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/claude/claude",
|
||||
args: [],
|
||||
defaultProgram: "claude",
|
||||
defaultArgs: [],
|
||||
loginHint:
|
||||
"Run `'/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/claude/claude'` in a terminal and sign in.",
|
||||
commandOverridden: false,
|
||||
commandEditable: false,
|
||||
commandReadOnlyReason: "registry",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
canCheckCliUpdate: false,
|
||||
env: {},
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
commands: [],
|
||||
source: { kind: "registry", version: "1.0.0", update: null },
|
||||
};
|
||||
return [provider];
|
||||
},
|
||||
agent_refresh_models: () => ({
|
||||
provider: "claude",
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: signedIn ? Date.now() : null,
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
}),
|
||||
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(onEvent, { type: "output", data: "Opening Claude in browser...\r\n" });
|
||||
signedIn = true;
|
||||
window.__ipc.send(onEvent, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 1, pid: 1001, title: "claude" };
|
||||
},
|
||||
term_resize: () => null,
|
||||
term_write: () => null,
|
||||
term_kill: () => null,
|
||||
});
|
||||
});
|
||||
|
||||
const dialog = await openAgents(page);
|
||||
const signIn = dialog.getByRole("region", { name: "Sign In" });
|
||||
const newTasks = dialog.getByRole("region", { name: "New Tasks" });
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
|
||||
|
||||
await signIn.getByRole("button", { name: "Sign In…" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Sign In to Claude Code" })).toHaveCount(0);
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)");
|
||||
expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["claude"]);
|
||||
});
|
||||
@@ -4,10 +4,11 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
await page.setViewportSize({ width: 1080, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/dev/acme-api/status.svg";
|
||||
const path = "/dev/acme-api/status.png";
|
||||
// A black 128 × 96 PNG.
|
||||
const image =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + image;
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
@@ -18,9 +19,8 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
|
||||
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
|
||||
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
|
||||
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
|
||||
const dimensions = toolbar.getByText(/128\s*×\s*96/);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
|
||||
await expect(dimensions).toBeVisible();
|
||||
const wideHeight = (await toolbar.boundingBox())!.height;
|
||||
|
||||
@@ -31,8 +31,7 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
|
||||
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
|
||||
await expect(dimensions).toHaveCSS("font-size", "13px");
|
||||
await expect(showText).toHaveCSS("white-space", "nowrap");
|
||||
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
|
||||
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
|
||||
await expect(item).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
|
||||
@@ -43,6 +42,33 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
|
||||
await chessboard.click();
|
||||
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
|
||||
await showText.click();
|
||||
});
|
||||
|
||||
test("an SVG file opens as its source with the image beside it", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 96, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
await editorService().openFile("/dev/acme-api/status.svg");
|
||||
});
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image viewer", exact: true });
|
||||
// Not an SVG yet: the preview says so, and draws the source once it is typed.
|
||||
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
|
||||
await page.locator(".cm-content").click();
|
||||
await page.keyboard.press("ControlOrMeta+A");
|
||||
await page.keyboard.insertText(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
|
||||
);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(toolbar.getByText(/128\s*×\s*96/)).toBeVisible();
|
||||
await expect(toolbar.getByRole("button", { name: "Open as Text", exact: true })).toHaveCount(0);
|
||||
|
||||
const layout = page.getByRole("toolbar", { name: "SVG editor layout", exact: true });
|
||||
await layout.getByRole("button", { name: "Preview Only", exact: true }).click();
|
||||
await expect(page.locator(".cm-content")).toBeHidden();
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await layout.getByRole("button", { name: "Editor Only", exact: true }).click();
|
||||
await expect(toolbar).toHaveCount(0);
|
||||
await expect(page.locator(".cm-content")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { GhProjectAccountStatus } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openGithubSettings(page: Page) {
|
||||
const settings = "/src/features/settings/model/staging.ts";
|
||||
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("vcs.github"), settings);
|
||||
return page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
}
|
||||
|
||||
test("suggests and configures a project-scoped GitHub account in Settings › Version Control › GitHub", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
let configuredAccount = "";
|
||||
const makeStatus = (): GhProjectAccountStatus => ({
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
configuredAccount,
|
||||
effectiveAccount: configuredAccount || "alice",
|
||||
suggestedAccount: configuredAccount ? null : "alice-work",
|
||||
});
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
gh_project_account_status: () => makeStatus(),
|
||||
gh_set_project_account: ({ account }: { account: string }) => {
|
||||
configuredAccount = account;
|
||||
return makeStatus();
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const dialog = await openGithubSettings(page);
|
||||
const select = dialog.getByRole("button", { name: "GitHub account" });
|
||||
await expect(select).toContainText("Automatic (alice)");
|
||||
await expect(
|
||||
dialog.getByText("Uses GitHub CLI's active account without setting GH_TOKEN in the project environment."),
|
||||
).toBeVisible();
|
||||
|
||||
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
|
||||
await expect(select).toContainText("alice-work");
|
||||
await expect(
|
||||
dialog.getByText(
|
||||
"Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).",
|
||||
),
|
||||
).toBeVisible();
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
@@ -78,9 +78,8 @@ block2 = "0.6"
|
||||
# Plugin secrets in the login keychain.
|
||||
security-framework = "3.7"
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTextCheckingClient", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSLocale", "NSNotification", "NSOperation", "NSString"] }
|
||||
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
|
||||
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
|
||||
@@ -2,7 +2,18 @@
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
|
||||
"windows": [
|
||||
"main",
|
||||
"project-*",
|
||||
"settings-*",
|
||||
"comparison-*",
|
||||
"diff-*",
|
||||
"editor-*",
|
||||
"deployment-*",
|
||||
"new-project-*",
|
||||
"clone-*",
|
||||
"connect-*"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-start-dragging",
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "e2e-bridge",
|
||||
"description": "Debug-only automation bridge",
|
||||
"windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
|
||||
"windows": [
|
||||
"main",
|
||||
"project-*",
|
||||
"settings-*",
|
||||
"comparison-*",
|
||||
"diff-*",
|
||||
"editor-*",
|
||||
"deployment-*",
|
||||
"new-project-*",
|
||||
"clone-*",
|
||||
"connect-*"
|
||||
],
|
||||
"permissions": ["mcp-bridge:default"]
|
||||
}
|
||||
@@ -52,8 +52,13 @@ pub async fn gh_availability(
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<GhAvailability> {
|
||||
let project = state.project(window.label())?;
|
||||
let root = root(&window, &state, repo)?;
|
||||
blocking(move || Ok(ide_github::availability(&root))).await
|
||||
blocking(move || {
|
||||
ide_host::github_auth::apply_to_project(&project);
|
||||
Ok(ide_github::availability(&root))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[desktop_command(trust = trusted)]
|
||||
|
||||
@@ -118,6 +118,9 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc<ide_host
|
||||
host.set_downloads(project_host.global_settings.effective().tool_downloads);
|
||||
#[cfg(target_os = "macos")]
|
||||
host.set_secret_store(Arc::new(KeychainSecrets));
|
||||
// Secret Service / Windows Credential Manager elsewhere, like saved SSH and agent values.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
host.use_credential_store();
|
||||
ide_host::plugins::set_editor_providers(Some(&host));
|
||||
let weak = Arc::downgrade(project_host);
|
||||
host.set_project_policy(Arc::new(move |root| {
|
||||
|
||||
@@ -152,6 +152,42 @@ pub async fn window_open_deployment(
|
||||
windows::open_deployment_window(&app, &window, server, paths, background)
|
||||
}
|
||||
|
||||
/// Opens this window's New Project window (or focuses it). `background` (`#rrggbb`) paints a new
|
||||
/// window until its page has loaded.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_new_project(
|
||||
app: AppHandle,
|
||||
window: WebviewWindow,
|
||||
background: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
windows::open_new_project_window(&app, &window, background)
|
||||
}
|
||||
|
||||
/// Opens this window's Get from VCS window (or focuses it), filling in `url` when given.
|
||||
/// `background` (`#rrggbb`) paints a new window until its page has loaded.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_clone(
|
||||
app: AppHandle,
|
||||
window: WebviewWindow,
|
||||
url: Option<String>,
|
||||
background: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
windows::open_clone_window(&app, &window, url, background)
|
||||
}
|
||||
|
||||
/// Opens this window's Remote Development window (or focuses it). `background` (`#rrggbb`)
|
||||
/// paints a new window until its page has loaded.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_connect(app: AppHandle, window: WebviewWindow, background: Option<String>) -> IdeResult<()> {
|
||||
windows::open_connect_window(&app, &window, background)
|
||||
}
|
||||
|
||||
/// Focuses the next / previous window (⌘` / ⇧⌘`).
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
@@ -437,7 +473,7 @@ pub fn menu_configure(
|
||||
|
||||
fn owns_menu_config(source: &str, target: &str) -> bool {
|
||||
let owner = match windows::auxiliary(target) {
|
||||
Some((windows::AuxKind::Settings, parent)) => parent,
|
||||
Some((kind, parent)) if kind.runs_menu_in_parent() => parent,
|
||||
_ => target,
|
||||
};
|
||||
source == owner
|
||||
@@ -1021,11 +1057,14 @@ ide_command::desktop_domain!(
|
||||
window_flash_taskbar,
|
||||
window_is_fullscreen,
|
||||
window_new,
|
||||
window_open_clone,
|
||||
window_open_comparison,
|
||||
window_open_connect,
|
||||
window_open_deployment,
|
||||
window_open_diff,
|
||||
window_open_editor,
|
||||
window_open_file_in_new_window,
|
||||
window_open_new_project,
|
||||
window_open_files,
|
||||
window_open_project,
|
||||
window_open_projects,
|
||||
|
||||
+273
-31
@@ -6,7 +6,7 @@
|
||||
//! (`window_take_launch`), and re-taken whenever [`LAUNCH_EVENT`] fires (a
|
||||
//! second app instance asking an already-loaded window to open a path).
|
||||
//!
|
||||
//! Auxiliary windows ([`AuxKind`]: Settings, Compare with Local, Diff, Sync with Deployed) belong to a project window and share its project (see
|
||||
//! Auxiliary windows ([`AuxKind`]: Settings, Compare with Local, Diff, Sync with Deployed, New Project, Get from VCS, Remote Development) belong to a project window and share its project (see
|
||||
//! [`AppState::project`]). Their labels name the kind and the parent
|
||||
//! (`settings-main`, `comparison-project-2-3`, `diff-main-0`); their [`Launch`] says what to show.
|
||||
|
||||
@@ -46,6 +46,12 @@ const EDITOR_SIZE: (f64, f64) = (1100.0, 720.0);
|
||||
const EDITOR_MIN_SIZE: (f64, f64) = (640.0, 360.0);
|
||||
const DEPLOYMENT_SIZE: (f64, f64) = (1400.0, 900.0);
|
||||
const DEPLOYMENT_MIN_SIZE: (f64, f64) = (800.0, 500.0);
|
||||
const NEW_PROJECT_SIZE: (f64, f64) = (860.0, 620.0);
|
||||
const NEW_PROJECT_MIN_SIZE: (f64, f64) = (720.0, 480.0);
|
||||
const CLONE_SIZE: (f64, f64) = (920.0, 620.0);
|
||||
const CLONE_MIN_SIZE: (f64, f64) = (640.0, 420.0);
|
||||
const CONNECT_SIZE: (f64, f64) = (600.0, 460.0);
|
||||
const CONNECT_MIN_SIZE: (f64, f64) = (520.0, 380.0);
|
||||
|
||||
/// What a freshly opened window should do once its frontend is up.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -83,6 +89,9 @@ pub struct Launch {
|
||||
/// Editor windows: the file to show (Open in New Window → lightweight aux editor).
|
||||
#[serde(default)]
|
||||
pub editor: Option<Box<EditorLaunch>>,
|
||||
/// Get from VCS windows: the repository URL to fill in.
|
||||
#[serde(default)]
|
||||
pub clone_url: Option<String>,
|
||||
}
|
||||
|
||||
/// What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
@@ -638,11 +647,22 @@ pub enum AuxKind {
|
||||
Diff,
|
||||
Editor,
|
||||
Deployment,
|
||||
NewProject,
|
||||
Clone,
|
||||
Connect,
|
||||
}
|
||||
|
||||
impl AuxKind {
|
||||
const ALL: [AuxKind; 5] =
|
||||
[AuxKind::Settings, AuxKind::Comparison, AuxKind::Diff, AuxKind::Editor, AuxKind::Deployment];
|
||||
const ALL: [AuxKind; 8] = [
|
||||
AuxKind::Settings,
|
||||
AuxKind::Comparison,
|
||||
AuxKind::Diff,
|
||||
AuxKind::Editor,
|
||||
AuxKind::Deployment,
|
||||
AuxKind::NewProject,
|
||||
AuxKind::Clone,
|
||||
AuxKind::Connect,
|
||||
];
|
||||
|
||||
/// Label prefix, and the key of the one remembered geometry shared by every window of the kind.
|
||||
pub fn name(self) -> &'static str {
|
||||
@@ -652,6 +672,9 @@ impl AuxKind {
|
||||
AuxKind::Diff => "diff",
|
||||
AuxKind::Editor => "editor",
|
||||
AuxKind::Deployment => "deployment",
|
||||
AuxKind::NewProject => "new-project",
|
||||
AuxKind::Clone => "clone",
|
||||
AuxKind::Connect => "connect",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -663,17 +686,23 @@ impl AuxKind {
|
||||
/// Shows the project's documents: gets its parent's events and edits made in sibling windows,
|
||||
/// and asks about its own unsaved changes before the parent closes it.
|
||||
pub fn shares_documents(self) -> bool {
|
||||
self != AuxKind::Settings
|
||||
!self.dialog()
|
||||
}
|
||||
|
||||
/// Has no actions of its own: menu items run in its project window.
|
||||
fn runs_menu_in_parent(self) -> bool {
|
||||
self == AuxKind::Settings
|
||||
/// Has no actions of its own: menu items run in its project window, which owns the menu.
|
||||
pub fn runs_menu_in_parent(self) -> bool {
|
||||
self.dialog()
|
||||
}
|
||||
|
||||
/// Needs its parent to have a project open.
|
||||
fn needs_project(self) -> bool {
|
||||
self != AuxKind::Settings
|
||||
!self.dialog()
|
||||
}
|
||||
|
||||
/// A dialog in its own window (Settings, New Project, Get from VCS, Remote Development):
|
||||
/// works without the parent's project or documents, and leaves the menu to the parent.
|
||||
fn dialog(self) -> bool {
|
||||
matches!(self, AuxKind::Settings | AuxKind::NewProject | AuxKind::Clone | AuxKind::Connect)
|
||||
}
|
||||
|
||||
pub fn min_size(self) -> (f64, f64) {
|
||||
@@ -683,6 +712,9 @@ impl AuxKind {
|
||||
AuxKind::Diff => DIFF_MIN_SIZE,
|
||||
AuxKind::Editor => EDITOR_MIN_SIZE,
|
||||
AuxKind::Deployment => DEPLOYMENT_MIN_SIZE,
|
||||
AuxKind::NewProject => NEW_PROJECT_MIN_SIZE,
|
||||
AuxKind::Clone => CLONE_MIN_SIZE,
|
||||
AuxKind::Connect => CONNECT_MIN_SIZE,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -693,6 +725,9 @@ impl AuxKind {
|
||||
AuxKind::Diff => DIFF_SIZE,
|
||||
AuxKind::Editor => EDITOR_SIZE,
|
||||
AuxKind::Deployment => DEPLOYMENT_SIZE,
|
||||
AuxKind::NewProject => NEW_PROJECT_SIZE,
|
||||
AuxKind::Clone => CLONE_SIZE,
|
||||
AuxKind::Connect => CONNECT_SIZE,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1069,7 +1104,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
(config.min_width, config.min_height) = (Some(min.0), Some(min.1));
|
||||
}
|
||||
let window = WebviewWindowBuilder::from_config(app, &config)
|
||||
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
|
||||
.and_then(|b| {
|
||||
macos_webview_configuration(app, webview_profile(app, b)).on_new_window(open_popup_in_browser).build()
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
|
||||
#[cfg(target_os = "linux")]
|
||||
decorate_csd(&window);
|
||||
@@ -1907,10 +1944,11 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
|
||||
// display's Space, so macOS keeps it too.
|
||||
#[cfg(target_os = "linux")]
|
||||
let builder = builder.and_then(|b| b.parent(&parent));
|
||||
let window = builder.and_then(|b| dev_font_preferences(webview_profile(app, b)).build()).map_err(|e| {
|
||||
windows.forget(&label);
|
||||
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
|
||||
})?;
|
||||
let window =
|
||||
builder.and_then(|b| macos_webview_configuration(app, webview_profile(app, b)).build()).map_err(|e| {
|
||||
windows.forget(&label);
|
||||
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
|
||||
})?;
|
||||
#[cfg(target_os = "linux")]
|
||||
decorate_csd(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -2126,6 +2164,60 @@ pub fn open_deployment_window(
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens (or focuses) the New Project window of `parent`'s project window: a separate window
|
||||
/// centred over it, so the wizard can be moved and sized on its own.
|
||||
pub fn open_new_project_window(app: &AppHandle, parent: &WebviewWindow, background: Option<String>) -> IdeResult<()> {
|
||||
open_auxiliary_window(
|
||||
app,
|
||||
parent,
|
||||
AuxWindow {
|
||||
kind: AuxKind::NewProject,
|
||||
title: "New Project",
|
||||
size: AuxKind::NewProject.default_size(),
|
||||
min_size: AuxKind::NewProject.min_size(),
|
||||
launch: Launch::default(),
|
||||
background,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens (or focuses, filling in `url`) the Get from VCS window of `parent`'s project window.
|
||||
pub fn open_clone_window(
|
||||
app: &AppHandle,
|
||||
parent: &WebviewWindow,
|
||||
url: Option<String>,
|
||||
background: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
open_auxiliary_window(
|
||||
app,
|
||||
parent,
|
||||
AuxWindow {
|
||||
kind: AuxKind::Clone,
|
||||
title: "Get from Version Control",
|
||||
size: AuxKind::Clone.default_size(),
|
||||
min_size: AuxKind::Clone.min_size(),
|
||||
launch: Launch { clone_url: url.filter(|u| !u.trim().is_empty()), ..Default::default() },
|
||||
background,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens (or focuses) the Remote Development window of `parent`'s project window.
|
||||
pub fn open_connect_window(app: &AppHandle, parent: &WebviewWindow, background: Option<String>) -> IdeResult<()> {
|
||||
open_auxiliary_window(
|
||||
app,
|
||||
parent,
|
||||
AuxWindow {
|
||||
kind: AuxKind::Connect,
|
||||
title: "Remote Development",
|
||||
size: AuxKind::Connect.default_size(),
|
||||
min_size: AuxKind::Connect.min_size(),
|
||||
launch: Launch::default(),
|
||||
background,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn resolve_aux_geometry(saved: Option<AuxGeometry>, default_size: (f64, f64), min_size: (f64, f64)) -> AuxGeometry {
|
||||
match saved.filter(|g| g.width.is_finite() && g.height.is_finite() && g.width > 0.0 && g.height > 0.0) {
|
||||
@@ -2443,18 +2535,86 @@ fn webview_profile<'a>(
|
||||
builder
|
||||
}
|
||||
|
||||
/// Reproduce WKWebView's user-font restriction before WKWebView creation. The
|
||||
/// private selector and environment override are absent from release builds.
|
||||
#[cfg(all(debug_assertions, target_os = "macos"))]
|
||||
fn dev_font_preferences(
|
||||
builder: WebviewWindowBuilder<'_, tauri::Wry, AppHandle>,
|
||||
) -> WebviewWindowBuilder<'_, tauri::Wry, AppHandle> {
|
||||
/// Configure macOS `WKWebViewConfiguration` before `WKWebView` creation:
|
||||
/// - Disable macOS 15+ Apple Intelligence Writing Tools so its floating selection
|
||||
/// affordance does not appear over Markdown previews, Quick Documentation, or editors.
|
||||
/// - In debug builds, optionally reproduce WKWebView's user-font restriction when
|
||||
/// `OPENIDEA_DEV_DISALLOW_USER_FONTS=1` is set (absent from release builds).
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_webview_configuration<'a>(
|
||||
app: &AppHandle,
|
||||
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
|
||||
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
|
||||
match build_macos_webview_configuration(app) {
|
||||
Some(config) => builder.with_webview_configuration(config),
|
||||
None => builder,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_macos_webview_configuration(
|
||||
app: &AppHandle,
|
||||
) -> Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>> {
|
||||
build_macos_webview_configuration_with(|f| app.run_on_main_thread(f))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_macos_webview_configuration_with(
|
||||
run_on_main_thread: impl FnOnce(Box<dyn FnOnce() + Send>) -> tauri::Result<()>,
|
||||
) -> Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>> {
|
||||
const ON_MAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
struct SendConfig(objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>);
|
||||
// SAFETY: Created and configured exclusively on the main thread, then moved untouched into
|
||||
// `WebviewWindowBuilder::with_webview_configuration`, which transfers it back to the main
|
||||
// thread when Wry constructs the WKWebView.
|
||||
unsafe impl Send for SendConfig {}
|
||||
|
||||
let make = |mtm: objc2::MainThreadMarker| {
|
||||
let config = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
|
||||
configure_macos_webview_configuration(&config).then_some(SendConfig(config))
|
||||
};
|
||||
|
||||
if let Some(mtm) = objc2::MainThreadMarker::new() {
|
||||
return make(mtm).map(|c| c.0);
|
||||
}
|
||||
|
||||
// Secondary project windows (`spawn_window`) and auxiliary windows (`open_auxiliary_window`)
|
||||
// build off the main thread; create the configuration on the AppKit main thread and fall back
|
||||
// to the default builder if the event loop cannot service it.
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
||||
if let Err(err) = run_on_main_thread(Box::new(move || {
|
||||
let result = objc2::MainThreadMarker::new().and_then(make);
|
||||
let _ = tx.send(result);
|
||||
})) {
|
||||
tracing::warn!("could not schedule macOS WKWebViewConfiguration on main thread: {err}");
|
||||
return None;
|
||||
}
|
||||
match rx.recv_timeout(ON_MAIN_TIMEOUT) {
|
||||
Ok(Some(config)) => Some(config.0),
|
||||
Ok(None) => None,
|
||||
Err(err) => {
|
||||
tracing::warn!("timed out waiting for macOS WKWebViewConfiguration on main thread: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn configure_macos_webview_configuration(config: &objc2_web_kit::WKWebViewConfiguration) -> bool {
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_app_kit::NSWritingToolsBehavior;
|
||||
use objc2_foundation::NSObjectProtocol;
|
||||
|
||||
let mut configured = false;
|
||||
if config.respondsToSelector(sel!(setWritingToolsBehavior:)) {
|
||||
unsafe {
|
||||
let _: () = msg_send![config, setWritingToolsBehavior: NSWritingToolsBehavior::None];
|
||||
}
|
||||
configured = true;
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
if std::env::var("OPENIDEA_DEV_DISALLOW_USER_FONTS").as_deref() == Ok("1") {
|
||||
use objc2::{MainThreadMarker, msg_send, sel};
|
||||
use objc2_foundation::NSObjectProtocol;
|
||||
let config = unsafe {
|
||||
objc2_web_kit::WKWebViewConfiguration::new(MainThreadMarker::new().expect("window creation on main thread"))
|
||||
};
|
||||
let preferences = unsafe { config.preferences() };
|
||||
if preferences.respondsToSelector(sel!(_setShouldAllowUserInstalledFonts:)) {
|
||||
unsafe {
|
||||
@@ -2462,17 +2622,19 @@ fn dev_font_preferences(
|
||||
}
|
||||
let allowed: bool = unsafe { msg_send![&preferences, _shouldAllowUserInstalledFonts] };
|
||||
tracing::info!(allowed, "Development user-installed fonts override");
|
||||
return builder.with_webview_configuration(config);
|
||||
configured = true;
|
||||
} else {
|
||||
tracing::warn!("WKPreferences user-font development selector unavailable");
|
||||
}
|
||||
tracing::warn!("WKPreferences user-font development selector unavailable");
|
||||
}
|
||||
builder
|
||||
configured
|
||||
}
|
||||
|
||||
#[cfg(not(all(debug_assertions, target_os = "macos")))]
|
||||
fn dev_font_preferences(
|
||||
builder: WebviewWindowBuilder<'_, tauri::Wry, AppHandle>,
|
||||
) -> WebviewWindowBuilder<'_, tauri::Wry, AppHandle> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn macos_webview_configuration<'a>(
|
||||
_app: &AppHandle,
|
||||
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
|
||||
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
|
||||
builder
|
||||
}
|
||||
|
||||
@@ -2561,6 +2723,76 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_webview_configuration_disables_writing_tools() {
|
||||
use objc2::{MainThreadMarker, msg_send, sel};
|
||||
use objc2_app_kit::NSWritingToolsBehavior;
|
||||
use objc2_foundation::NSObjectProtocol;
|
||||
|
||||
let Some(mtm) = MainThreadMarker::new() else {
|
||||
return;
|
||||
};
|
||||
let config = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
|
||||
let configured = configure_macos_webview_configuration(&config);
|
||||
if config.respondsToSelector(sel!(writingToolsBehavior)) {
|
||||
assert!(configured);
|
||||
let behavior: NSWritingToolsBehavior = unsafe { msg_send![&config, writingToolsBehavior] };
|
||||
assert_eq!(behavior, NSWritingToolsBehavior::None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_webview_configuration_handles_non_main_thread() {
|
||||
use objc2::{MainThreadMarker, sel};
|
||||
use objc2_foundation::NSObjectProtocol;
|
||||
|
||||
// Off-thread scheduling failure falls back to None instead of panicking.
|
||||
let result = std::thread::spawn(|| {
|
||||
assert!(MainThreadMarker::new().is_none());
|
||||
build_macos_webview_configuration_with(|_| Err(tauri::Error::FailedToReceiveMessage)).is_none()
|
||||
})
|
||||
.join()
|
||||
.expect("worker thread must not panic");
|
||||
assert!(result);
|
||||
|
||||
// Off-thread callback without a main-thread marker falls back to None instead of panicking.
|
||||
let result = std::thread::spawn(|| {
|
||||
assert!(MainThreadMarker::new().is_none());
|
||||
build_macos_webview_configuration_with(|f| {
|
||||
f();
|
||||
Ok(())
|
||||
})
|
||||
.is_none()
|
||||
})
|
||||
.join()
|
||||
.expect("worker thread must not panic");
|
||||
assert!(result);
|
||||
|
||||
// When a main thread is available (e.g. nextest or --test-threads=1), dispatching from a
|
||||
// worker thread constructs and configures WKWebViewConfiguration on the main thread.
|
||||
if let Some(mtm) = MainThreadMarker::new() {
|
||||
let probe = unsafe { objc2_web_kit::WKWebViewConfiguration::new(mtm) };
|
||||
let expects_config = probe.respondsToSelector(sel!(setWritingToolsBehavior:));
|
||||
|
||||
let (work_tx, work_rx) = std::sync::mpsc::sync_channel::<Box<dyn FnOnce() + Send>>(1);
|
||||
let worker = std::thread::spawn(move || {
|
||||
assert!(MainThreadMarker::new().is_none());
|
||||
build_macos_webview_configuration_with(move |f| {
|
||||
work_tx.send(f).map_err(|_| tauri::Error::FailedToReceiveMessage)
|
||||
})
|
||||
.is_some()
|
||||
});
|
||||
let work = work_rx.recv().expect("worker should schedule onto main thread");
|
||||
work();
|
||||
let got_config = worker.join().expect("worker thread must not panic");
|
||||
if expects_config {
|
||||
assert!(got_config);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_colours_from_the_ui_parse_as_hex() {
|
||||
for (hex, expected) in [
|
||||
@@ -3133,6 +3365,10 @@ mod tests {
|
||||
assert_eq!(auxiliary("diff-project-2-3"), Some((AuxKind::Diff, "project-2")));
|
||||
assert_eq!(auxiliary("editor-project-2-3"), Some((AuxKind::Editor, "project-2")));
|
||||
assert_eq!(auxiliary("deployment-project-2"), Some((AuxKind::Deployment, "project-2")));
|
||||
assert_eq!(auxiliary("new-project-project-2"), Some((AuxKind::NewProject, "project-2")));
|
||||
assert_eq!(auxiliary("new-project-main"), Some((AuxKind::NewProject, "main")));
|
||||
assert_eq!(auxiliary("clone-project-2"), Some((AuxKind::Clone, "project-2")));
|
||||
assert_eq!(auxiliary("connect-main"), Some((AuxKind::Connect, "main")));
|
||||
for label in ["main", "project-1", "comparison-main", "comparison-main-x", "settings-", "settingsmain"] {
|
||||
assert_eq!(auxiliary(label), None, "{label}");
|
||||
}
|
||||
@@ -3162,6 +3398,9 @@ mod tests {
|
||||
("settings-main", "app.checkForUpdates", Parent { label: "main", raise: true }),
|
||||
("settings-project-2", "file.newFile", Parent { label: "project-2", raise: true }),
|
||||
("settings-main", "editor.closeTab", Parent { label: "main", raise: true }),
|
||||
("new-project-main", "file.newFile", Parent { label: "main", raise: true }),
|
||||
("clone-main", "vcs.clone", Parent { label: "main", raise: true }),
|
||||
("new-project-project-2", "editor.closeTab", Parent { label: "project-2", raise: true }),
|
||||
("settings-main", "file.settings", Parent { label: "main", raise: false }),
|
||||
("settings-main", "app.quit", Parent { label: "main", raise: false }),
|
||||
("comparison-main-0", "app.quit", Parent { label: "main", raise: false }),
|
||||
@@ -3231,6 +3470,9 @@ mod tests {
|
||||
"comparison-project-2-0",
|
||||
"diff-main-9",
|
||||
"deployment-main",
|
||||
"new-project-main",
|
||||
"clone-main",
|
||||
"connect-main",
|
||||
] {
|
||||
assert!(!keeps_window_state(label), "{label} must not use physical window-state");
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ agent_cli_update trusted project_host bin
|
||||
agent_cli_update_check trusted project_host bindings async
|
||||
agent_commands always project_host bindings async
|
||||
agent_context_usage trusted project_host bindings async
|
||||
agent_copilot_auth_status outside_restricted project_host bindings async
|
||||
agent_create trusted project_host bindings async
|
||||
agent_custom_import trusted desktop bindings sync
|
||||
agent_custom_remove trusted desktop bindings sync
|
||||
@@ -19,9 +20,11 @@ agent_entries always project_host bin
|
||||
agent_external_sessions trusted project_host bindings async
|
||||
agent_fork trusted project_host bindings async
|
||||
agent_fork_session trusted project_host bindings async
|
||||
agent_gh_login_spawn outside_restricted project_host bindings async
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
agent_hermes_profiles trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_login_spawn outside_restricted project_host bindings async
|
||||
agent_mcp_discover_sources always project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
agent_mcp_import_selected always project_host bindings async
|
||||
@@ -315,6 +318,8 @@ gh_pr_prepare_diff trusted desktop bin
|
||||
gh_pr_review trusted desktop bindings async
|
||||
gh_pr_review_comments trusted desktop bindings async
|
||||
gh_pr_view trusted desktop bindings async
|
||||
gh_project_account_status outside_restricted project_host bindings async
|
||||
gh_set_project_account outside_restricted project_host bindings async
|
||||
git_credential_forget always desktop bindings sync
|
||||
git_credentials always desktop bindings sync
|
||||
gradle_dependencies trusted project_host bindings async
|
||||
@@ -862,12 +867,15 @@ window_group_restore always desktop bin
|
||||
window_group_select always desktop bindings async
|
||||
window_is_fullscreen always desktop bindings sync
|
||||
window_new always desktop bindings async
|
||||
window_open_clone always desktop bindings async
|
||||
window_open_comparison always desktop bindings async
|
||||
window_open_connect always desktop bindings async
|
||||
window_open_deployment always desktop bindings async
|
||||
window_open_diff always desktop bindings async
|
||||
window_open_editor always desktop bindings async
|
||||
window_open_file_in_new_window always desktop bindings async
|
||||
window_open_files always desktop bindings async
|
||||
window_open_new_project always desktop bindings async
|
||||
window_open_project always desktop bindings async
|
||||
window_open_projects always desktop bindings sync
|
||||
window_open_remote always desktop bindings async
|
||||
|
||||
@@ -30,5 +30,20 @@ export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }
|
||||
mountWindowRoot(bootDeploymentWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "new-project": {
|
||||
const { bootNewProjectWindow } = await import("./newProjectWindowBoot");
|
||||
mountWindowRoot(bootNewProjectWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "connect": {
|
||||
const { bootConnectWindow } = await import("./connectWindowBoot");
|
||||
mountWindowRoot(bootConnectWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "clone": {
|
||||
const { bootCloneWindow } = await import("./cloneWindowBoot");
|
||||
mountWindowRoot(bootCloneWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,8 @@ export const commands = {
|
||||
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
|
||||
/** Reads the running session's context categories without sending a prompt. */
|
||||
agentContextUsage: (task: string) => typedError<AgentContextUsage, IdeError>(__TAURI_INVOKE("agent_context_usage", { task })),
|
||||
/** Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`. */
|
||||
agentCopilotAuthStatus: () => typedError<CopilotAuthStatus, IdeError>(__TAURI_INVOKE("agent_copilot_auth_status")),
|
||||
agentCreate: (request: NewAgentTask) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create", { request })),
|
||||
/** Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents. */
|
||||
agentCustomImport: (text: string) => typedError<AcpImportOutcome[], IdeError>(__TAURI_INVOKE("agent_custom_import", { text })),
|
||||
@@ -69,12 +71,19 @@ export const commands = {
|
||||
* as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded.
|
||||
*/
|
||||
agentForkSession: (provider: string, sessionId: string, cwd: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork_session", { provider, sessionId, cwd })),
|
||||
/**
|
||||
* Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
|
||||
* variables cleared) and streams its output and exit code.
|
||||
*/
|
||||
agentGhLoginSpawn: (cols: number, rows: number, onEvent: Channel<AgentLoginEvent>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("agent_gh_login_spawn", { cols, rows, onEvent })),
|
||||
/** The task's uncommitted changes and the commits made since it started. */
|
||||
agentGroupedChanges: (task: string) => typedError<AgentChanges, IdeError>(__TAURI_INVOKE("agent_grouped_changes", { task })),
|
||||
/** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */
|
||||
agentHermesProfiles: () => typedError<HermesProfile[], IdeError>(__TAURI_INVOKE("agent_hermes_profiles")),
|
||||
/** Imports an external session as a task: its first turn loads and replays it. */
|
||||
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
|
||||
/** Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code. */
|
||||
agentLoginSpawn: (id: string, cols: number, rows: number, onEvent: Channel<AgentLoginEvent>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("agent_login_spawn", { id, cols, rows, onEvent })),
|
||||
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
|
||||
agentMcpDiscoverSources: () => typedError<McpExternalSource[], IdeError>(__TAURI_INVOKE("agent_mcp_discover_sources")),
|
||||
/** Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once. */
|
||||
@@ -786,6 +795,13 @@ export const commands = {
|
||||
ghPrReview: (repo: string | null, number: number, event: ReviewEvent, body: string) => typedError<null, IdeError>(__TAURI_INVOKE("gh_pr_review", { repo, number, event, body })),
|
||||
ghPrReviewComments: (repo: string | null, number: number) => typedError<PrReviewComment[], IdeError>(__TAURI_INVOKE("gh_pr_review_comments", { repo, number })),
|
||||
ghPrView: (repo: string | null, number: number) => typedError<PullRequestDetails, IdeError>(__TAURI_INVOKE("gh_pr_view", { repo, number })),
|
||||
/** Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project. */
|
||||
ghProjectAccountStatus: () => typedError<GhProjectAccountStatus, IdeError>(__TAURI_INVOKE("gh_project_account_status")),
|
||||
/**
|
||||
* Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
|
||||
* updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
|
||||
*/
|
||||
ghSetProjectAccount: (account: string) => typedError<GhProjectAccountStatus, IdeError>(__TAURI_INVOKE("gh_set_project_account", { account })),
|
||||
/** Forgets the credential of `key` (a `git_credentials` entry). */
|
||||
gitCredentialForget: (key: string) => __TAURI_INVOKE<void>("git_credential_forget", { key }),
|
||||
/** Settings › Git › Saved credentials: `scheme://host` of every saved entry. */
|
||||
@@ -2378,11 +2394,21 @@ export const commands = {
|
||||
windowIsFullscreen: () => __TAURI_INVOKE<boolean>("window_is_fullscreen"),
|
||||
/** Opens an empty (welcome) window; returns its label. */
|
||||
windowNew: () => typedError<string, IdeError>(__TAURI_INVOKE("window_new")),
|
||||
/**
|
||||
* Opens this window's Get from VCS window (or focuses it), filling in `url` when given.
|
||||
* `background` (`#rrggbb`) paints a new window until its page has loaded.
|
||||
*/
|
||||
windowOpenClone: (url: string | null, background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_clone", { url, background })),
|
||||
/**
|
||||
* Opens a window listing the files that differ between two revisions of this window's project.
|
||||
* `background` (`#rrggbb`) paints it until its page has loaded.
|
||||
*/
|
||||
windowOpenComparison: (comparison: ComparisonLaunch, background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_comparison", { comparison, background })),
|
||||
/**
|
||||
* Opens this window's Remote Development window (or focuses it). `background` (`#rrggbb`)
|
||||
* paints a new window until its page has loaded.
|
||||
*/
|
||||
windowOpenConnect: (background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_connect", { background })),
|
||||
/**
|
||||
* Opens this window's Sync with Deployed window comparing `paths` with `server` (or hands them
|
||||
* to the open one). `background` (`#rrggbb`) paints a new window until its page has loaded.
|
||||
@@ -2411,6 +2437,11 @@ export const commands = {
|
||||
* itself, in LightEdit.
|
||||
*/
|
||||
windowOpenFiles: (files: string[]) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("window_open_files", { files })),
|
||||
/**
|
||||
* Opens this window's New Project window (or focuses it). `background` (`#rrggbb`) paints a new
|
||||
* window until its page has loaded.
|
||||
*/
|
||||
windowOpenNewProject: (background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_new_project", { background })),
|
||||
/**
|
||||
* Opens `path` in a new window (`new_window`) or tells the caller to open it
|
||||
* itself (`current`). A project already open in some window is focused instead.
|
||||
@@ -2475,6 +2506,8 @@ export const commands = {
|
||||
deployment: DeploymentLaunch | null,
|
||||
/** Editor windows: the file to show (Open in New Window → lightweight aux editor). */
|
||||
editor: EditorLaunch_Serialize | null,
|
||||
/** Get from VCS windows: the repository URL to fill in. */
|
||||
cloneUrl: string | null,
|
||||
} | null>("window_take_launch"),
|
||||
/**
|
||||
* Local bootstrap snapshot for a `settings-<parent>` window, avoiding a sequential
|
||||
@@ -2899,6 +2932,9 @@ export type AgentLimit = {
|
||||
resetsMs: number | null,
|
||||
};
|
||||
|
||||
/** Output and completion of an interactive sign-in PTY started by the IDE. */
|
||||
export type AgentLoginEvent = { type: "output"; data: string } | { type: "exited"; code: number | null };
|
||||
|
||||
/** An MCP server passed to coding agents in `session/new`, `session/load` and `session/fork`. */
|
||||
export type AgentMcpServer = AgentMcpServer_Serialize | AgentMcpServer_Deserialize;
|
||||
|
||||
@@ -3013,6 +3049,8 @@ export type AgentProvider_Deserialize = {
|
||||
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
|
||||
/** Whether the command was found (on `PATH`). */
|
||||
installed: boolean,
|
||||
/** Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal. */
|
||||
canSignIn?: boolean,
|
||||
/** The built-in command can be owned by a global npm package. */
|
||||
canCheckCliUpdate?: boolean,
|
||||
/** Environment variables it starts with (from its agent file). */
|
||||
@@ -3044,6 +3082,8 @@ export type AgentProvider_Serialize = {
|
||||
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
|
||||
/** Whether the command was found (on `PATH`). */
|
||||
installed: boolean,
|
||||
/** Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal. */
|
||||
canSignIn: boolean,
|
||||
/** The built-in command can be owned by a global npm package. */
|
||||
canCheckCliUpdate: boolean,
|
||||
/** Environment variables it starts with (from its agent file). */
|
||||
@@ -4985,6 +5025,16 @@ export type ContributionInfo = {
|
||||
label: string,
|
||||
};
|
||||
|
||||
/** GitHub Copilot's default sign-in status alongside the accounts available through `gh`. */
|
||||
export type CopilotAuthStatus = {
|
||||
authenticated: boolean,
|
||||
login: string | null,
|
||||
authType: string | null,
|
||||
statusMessage: string | null,
|
||||
ghInstalled: boolean,
|
||||
ghAccounts: GhAuthAccount[],
|
||||
};
|
||||
|
||||
export type CoveragePrepared = CoveragePrepared_Serialize | CoveragePrepared_Deserialize;
|
||||
|
||||
export type CoveragePrepared_Deserialize = ({ status: "ready"; runner: string;
|
||||
@@ -5256,6 +5306,8 @@ export type DbColumnInfo = {
|
||||
nullable: boolean,
|
||||
default: string | null,
|
||||
primaryKey: boolean,
|
||||
/** `None` when it has none, or the engine keeps no comments. */
|
||||
comment?: string | null,
|
||||
};
|
||||
|
||||
/** The schema model SQL completion and resolution work from. */
|
||||
@@ -5678,6 +5730,8 @@ export type DbStatementOutcome = {
|
||||
};
|
||||
|
||||
export type DbTableDetails = {
|
||||
/** The table's comment; `None` when it has none, or the engine keeps no comments. */
|
||||
comment?: string | null,
|
||||
columns: DbColumnInfo[],
|
||||
indexes: DbIndexInfo[],
|
||||
foreignKeys: DbForeignKey[],
|
||||
@@ -7670,6 +7724,12 @@ export type GhApiRequest = {
|
||||
paginate: boolean,
|
||||
};
|
||||
|
||||
/** An authenticated `github.com` account stored in GitHub CLI (`gh`). */
|
||||
export type GhAuthAccount = {
|
||||
login: string,
|
||||
active: boolean,
|
||||
};
|
||||
|
||||
/** Whether pull requests can be shown for the project, and why not. */
|
||||
export type GhAvailability = { kind: "ready"; repo: GhRepo;
|
||||
/** The signed-in user. */
|
||||
@@ -7681,6 +7741,18 @@ login: string | null } |
|
||||
/** The project has no GitHub remote (or is not a git repository). */
|
||||
{ kind: "notGitHub"; message: string } | { kind: "error"; message: string };
|
||||
|
||||
/** GitHub CLI accounts available on this machine and which one applies to the project. */
|
||||
export type GhProjectAccountStatus = {
|
||||
ghInstalled: boolean,
|
||||
accounts: GhAuthAccount[],
|
||||
/** Value of `vcs.github.account` (`""` = Automatic). */
|
||||
configuredAccount: string,
|
||||
/** Account login currently used (`configured_account` if signed in, else `gh`'s active account). */
|
||||
effectiveAccount: string | null,
|
||||
/** Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty. */
|
||||
suggestedAccount: string | null,
|
||||
};
|
||||
|
||||
export type GhRepo = {
|
||||
/** `owner/name`. */
|
||||
nameWithOwner: string,
|
||||
@@ -7811,6 +7883,15 @@ export type GitSigningEdit = {
|
||||
key: string | null,
|
||||
};
|
||||
|
||||
/** Settings › Version Control › GitHub (`vcs.github`). */
|
||||
export type GithubSettings = {
|
||||
/**
|
||||
* GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
* Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
*/
|
||||
account?: string,
|
||||
};
|
||||
|
||||
export type GoBuildTags = {
|
||||
/** Empty values inherit the selected toolchain's defaults. */
|
||||
os?: string,
|
||||
@@ -9158,6 +9239,18 @@ export type LanguageCodeStyle_Deserialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard import once this many
|
||||
* classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
* 5; unset keeps the language server's default).
|
||||
*/
|
||||
classCountToUseImportWithStar?: number | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard static import once this
|
||||
* many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
* IDEA's default 3; unset keeps the language server's default).
|
||||
*/
|
||||
namesCountToUseStaticImportWithStar?: number | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
@@ -9188,6 +9281,18 @@ export type LanguageCodeStyle_Serialize = {
|
||||
keywordCase?: string | null,
|
||||
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
|
||||
identifierCase?: string | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard import once this many
|
||||
* classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
* 5; unset keeps the language server's default).
|
||||
*/
|
||||
classCountToUseImportWithStar?: number | null,
|
||||
/**
|
||||
* Java: organize imports switches to a wildcard static import once this
|
||||
* many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
* IDEA's default 3; unset keeps the language server's default).
|
||||
*/
|
||||
namesCountToUseStaticImportWithStar?: number | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
|
||||
semicolons?: string | null,
|
||||
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
|
||||
@@ -9408,6 +9513,8 @@ export type Launch_Deserialize = {
|
||||
deployment?: DeploymentLaunch | null,
|
||||
/** Editor windows: the file to show (Open in New Window → lightweight aux editor). */
|
||||
editor?: EditorLaunch_Deserialize | null,
|
||||
/** Get from VCS windows: the repository URL to fill in. */
|
||||
cloneUrl?: string | null,
|
||||
};
|
||||
|
||||
/** What a freshly opened window should do once its frontend is up. */
|
||||
@@ -9439,6 +9546,8 @@ export type Launch_Serialize = {
|
||||
deployment: DeploymentLaunch | null,
|
||||
/** Editor windows: the file to show (Open in New Window → lightweight aux editor). */
|
||||
editor: EditorLaunch_Serialize | null,
|
||||
/** Get from VCS windows: the repository URL to fill in. */
|
||||
cloneUrl: string | null,
|
||||
};
|
||||
|
||||
export type LegacyPasswordAction = "check" | "retry" | "removePlaintext";
|
||||
@@ -14526,6 +14635,8 @@ export type VcsSettings = {
|
||||
issueNavigation?: IssueLink[],
|
||||
/** Directory Mappings: repository roots added to or excluded from the detected ones. */
|
||||
mappings?: VcsMappings,
|
||||
/** Settings › Version Control › GitHub: per-project GitHub CLI account selection. */
|
||||
github?: GithubSettings,
|
||||
};
|
||||
|
||||
/** The tool that creates a new Python environment in "Add Python Interpreter". */
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { githubCloneSource } from "./features/github/clone/source";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activateCloneLaunches, CloneWindow } from "./features/vcs/cloneWindow";
|
||||
import { registerCloneSource } from "./workbench/contributions";
|
||||
import { activateDialogWindow } from "./workbench/dialogWindow";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/** Get from VCS window of project window `parent`: the clone dialog and its sources, no workbench. */
|
||||
export function bootCloneWindow(parent: string): ComponentType {
|
||||
activateList("clone window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["github", () => registerCloneSource(githubCloneSource)],
|
||||
["dialog", () => activateDialogWindow(parent)],
|
||||
["launch", activateCloneLaunches],
|
||||
]);
|
||||
return CloneWindow;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { ConnectWindow } from "./features/remote-dev/connectWindow";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activateDialogWindow } from "./workbench/dialogWindow";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/** Remote Development window of project window `parent`: the connect dialog only, no workbench. */
|
||||
export function bootConnectWindow(parent: string): ComponentType {
|
||||
activateList("remote development window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["dialog", () => activateDialogWindow(parent)],
|
||||
]);
|
||||
return ConnectWindow;
|
||||
}
|
||||
@@ -548,6 +548,29 @@ export function contributedAtAll<T>(state: EditorState, key: string, pos: number
|
||||
return state.languageDataAt<T>(key, pos);
|
||||
}
|
||||
|
||||
/**
|
||||
* A problem a feature marks on its own text (the database console's run errors
|
||||
* and unsafe-query warnings): the editor's hover shows it like a diagnostic.
|
||||
*
|
||||
* problemProviders.of((state) => state.field(myField).problems)
|
||||
*/
|
||||
export interface ContributedProblem {
|
||||
from: number;
|
||||
to: number;
|
||||
severity: "error" | "warning" | "info";
|
||||
message: string;
|
||||
}
|
||||
|
||||
export const problemProviders = Facet.define<(state: EditorState) => readonly ContributedProblem[]>();
|
||||
|
||||
/** The contributed problems whose range covers `pos`. */
|
||||
export function contributedProblemsAt(state: EditorState, pos: number): ContributedProblem[] {
|
||||
return state
|
||||
.facet(problemProviders)
|
||||
.flatMap((provider) => provider(state))
|
||||
.filter((p) => p.from <= pos && pos <= p.to);
|
||||
}
|
||||
|
||||
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */
|
||||
export interface ContributedIntention {
|
||||
id: string;
|
||||
|
||||
@@ -81,10 +81,12 @@ import {
|
||||
cursorParagraphBackward,
|
||||
cursorParagraphForward,
|
||||
scrollDown,
|
||||
scrollDownAndMove,
|
||||
scrollToBottom,
|
||||
scrollToCenter,
|
||||
scrollToTop,
|
||||
scrollUp,
|
||||
scrollUpAndMove,
|
||||
selectCodeBlockEnd,
|
||||
selectCodeBlockStart,
|
||||
selectPageBottom,
|
||||
@@ -95,7 +97,14 @@ import {
|
||||
} from "./cm/caretCommands";
|
||||
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
|
||||
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
|
||||
import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
|
||||
import {
|
||||
cloneCaretAbove,
|
||||
cloneCaretBelow,
|
||||
moveDownAndScroll,
|
||||
moveDownAndScrollWithSelection,
|
||||
moveUpAndScroll,
|
||||
moveUpAndScrollWithSelection,
|
||||
} from "./cm/verticalMotion";
|
||||
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
|
||||
import { cyclicExpandWord } from "./wordCompletion";
|
||||
import { copyReferenceToClipboard, declaredName, qualifiedReference, referenceOffset } from "./copyReference";
|
||||
@@ -1059,6 +1068,28 @@ export function registerEditorActions(): () => void {
|
||||
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollUpAndMove", "Scroll Up and Move if Necessary", (v) => scrollUpAndMove(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret("editor.scrollDownAndMove", "Scroll Down and Move if Necessary", (v) => scrollDownAndMove(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret("editor.moveUpAndScroll", "Move Up and Scroll", (v) => moveUpAndScroll(v), { category: "Editor Actions" }),
|
||||
caret("editor.moveDownAndScroll", "Move Down and Scroll", (v) => moveDownAndScroll(v), {
|
||||
category: "Editor Actions",
|
||||
}),
|
||||
caret(
|
||||
"editor.moveUpAndScrollWithSelection",
|
||||
"Move Up and Scroll with Selection",
|
||||
(v) => moveUpAndScrollWithSelection(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret(
|
||||
"editor.moveDownAndScrollWithSelection",
|
||||
"Move Down and Scroll with Selection",
|
||||
(v) => moveDownAndScrollWithSelection(v),
|
||||
{ category: "Editor Actions" },
|
||||
),
|
||||
caret("editor.scrollToTop", "Scroll to Top", (v) => scrollToTop(v), { category: "Editor Actions" }),
|
||||
caret("editor.scrollToBottom", "Scroll to Bottom", (v) => scrollToBottom(v), { category: "Editor Actions" }),
|
||||
caret("editor.moveToPageTop", "Move Caret to Page Top", (v) => cursorPageTop(v), { category: "Editor Actions" }),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { indentService, type LanguageSupport } from "@codemirror/language";
|
||||
import { codeFolding, foldEffect, indentService, type LanguageSupport } from "@codemirror/language";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands";
|
||||
import {
|
||||
@@ -14,9 +14,11 @@ import {
|
||||
nextParagraphBoundary,
|
||||
previousParagraphBoundary,
|
||||
scrollDown,
|
||||
scrollDownAndMove,
|
||||
scrollToBottom,
|
||||
scrollToTop,
|
||||
scrollUp,
|
||||
scrollUpAndMove,
|
||||
selectPageBottom,
|
||||
selectPageTop,
|
||||
selectParagraphForward,
|
||||
@@ -251,6 +253,104 @@ describe("Move Caret to Page Top / Bottom", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Scroll Up / Down and Move if Necessary", () => {
|
||||
/** jsdom has no layout: a scroller `height` line heights tall, scrolled to `top` line heights. */
|
||||
function scroller(view: EditorView, top: number, height: number) {
|
||||
const line = view.lineBlockAt(0).height;
|
||||
let px = top * line;
|
||||
Object.defineProperty(view.scrollDOM, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => px,
|
||||
set: (v: number) => (px = Math.max(0, v)),
|
||||
});
|
||||
Object.defineProperty(view, "documentTop", { configurable: true, get: () => -px });
|
||||
Object.defineProperty(view.scrollDOM, "clientHeight", { configurable: true, get: () => height * line });
|
||||
return () => px / line;
|
||||
}
|
||||
const lines = (marked: Record<number, string>) =>
|
||||
Array.from({ length: 10 }, (_, i) => marked[i] ?? `line ${i} text`).join("\n");
|
||||
const lineOf = (view: EditorView) => view.state.selection.ranges.map((r) => view.state.doc.lineAt(r.head).number - 1);
|
||||
const columnOf = (view: EditorView) =>
|
||||
view.state.selection.ranges.map((r) => r.head - view.state.doc.lineAt(r.head).from);
|
||||
|
||||
it("scrolls one line and keeps a caret that stays in view where it is", () => {
|
||||
const view = make(lines({ 4: "line 4 te|xt" }));
|
||||
const top = scroller(view, 2, 4);
|
||||
const before = view.state.selection;
|
||||
expect(scrollDownAndMove(view)).toBe(true);
|
||||
expect(top()).toBe(3);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
expect(scrollUpAndMove(view)).toBe(true);
|
||||
expect(top()).toBe(2);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
});
|
||||
|
||||
it("brings a caret that scrolls off the top down to the first line, keeping its column", () => {
|
||||
const view = make(lines({ 2: "line 2 te|xt" }));
|
||||
scroller(view, 2, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect([lineOf(view), columnOf(view)]).toEqual([[3], [9]]);
|
||||
});
|
||||
|
||||
it("brings a caret that scrolls off the bottom up to the last line, keeping its column", () => {
|
||||
const view = make(lines({ 5: "li|ne 5 text" }));
|
||||
scroller(view, 2, 4);
|
||||
scrollUpAndMove(view);
|
||||
expect([lineOf(view), columnOf(view)]).toEqual([[4], [2]]);
|
||||
});
|
||||
|
||||
it("moves a caret already out of view to the nearest edge", () => {
|
||||
const view = make(lines({ 9: "line 9 |text" }));
|
||||
scroller(view, 0, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect([lineOf(view), columnOf(view)]).toEqual([[4], [7]]);
|
||||
});
|
||||
|
||||
it("drops the selection of a caret it moves and keeps the others", () => {
|
||||
const view = make(lines({ 0: "|line 0 text" }));
|
||||
const at = (line: number, col: number) => view.state.doc.line(line + 1).from + col;
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
[EditorSelection.range(at(2, 0), at(2, 4)), EditorSelection.range(at(4, 0), at(4, 4))],
|
||||
1,
|
||||
),
|
||||
});
|
||||
scroller(view, 2, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect(view.state.selection.ranges.map((r) => [r.anchor, r.head])).toEqual([
|
||||
[at(3, 4), at(3, 4)],
|
||||
[at(4, 0), at(4, 4)],
|
||||
]);
|
||||
expect(view.state.selection.mainIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps a caret at the end of a folded block the view shows", () => {
|
||||
const view = make(lines({ 7: "line 7 text|" }));
|
||||
const { doc } = view.state;
|
||||
view.dispatch({
|
||||
effects: [
|
||||
StateEffect.appendConfig.of(codeFolding()),
|
||||
foldEffect.of({ from: doc.line(6).to, to: doc.line(8).to }),
|
||||
],
|
||||
});
|
||||
expect(view.lineBlockAt(doc.line(8).to).from).toBe(doc.line(6).from);
|
||||
const before = view.state.selection;
|
||||
scroller(view, 1, 4);
|
||||
scrollDownAndMove(view);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
});
|
||||
|
||||
it("only scrolls at the top of the file when the caret stays in view", () => {
|
||||
const view = make(lines({ 1: "|line 1 text" }));
|
||||
const top = scroller(view, 0, 4);
|
||||
const before = view.state.selection;
|
||||
scrollUpAndMove(view);
|
||||
expect(top()).toBe(0);
|
||||
expect(view.state.selection.eq(before)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe(lines({}));
|
||||
});
|
||||
});
|
||||
|
||||
describe("code block navigation", () => {
|
||||
let js: LanguageSupport;
|
||||
beforeAll(async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Page Top / Bottom, code block, brace and paragraph navigation. */
|
||||
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Scroll Up / Down and Move if Necessary, Page Top / Bottom, code block, brace and paragraph navigation. */
|
||||
import { countColumn, EditorSelection, findColumn, type EditorState, type Transaction } from "@codemirror/state";
|
||||
import { EditorView, type Command } from "@codemirror/view";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
@@ -66,15 +66,21 @@ function pageEdgeLine(view: EditorView, edge: "top" | "bottom"): number {
|
||||
return block.top >= bottom || (block.bottom > bottom && previous.top >= top) ? previous.from : block.from;
|
||||
}
|
||||
|
||||
/** `head` moved to the line starting at `lineStart`, keeping its visual column. */
|
||||
function sameColumnOn(state: EditorState, head: number, lineStart: number): number {
|
||||
const line = state.doc.lineAt(head);
|
||||
const target = state.doc.lineAt(lineStart);
|
||||
const column = countColumn(line.text, state.tabSize, head - line.from);
|
||||
return target.from + findColumn(target.text, column, state.tabSize);
|
||||
}
|
||||
|
||||
/** Move Caret to Page Top / Bottom (with Selection): every caret to that line, keeping its column. */
|
||||
function moveToPageEdge(edge: "top" | "bottom", extend = false): Command {
|
||||
return (view) => {
|
||||
const { state } = view;
|
||||
const target = state.doc.lineAt(pageEdgeLine(view, edge));
|
||||
const target = pageEdgeLine(view, edge);
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
const line = state.doc.lineAt(r.head);
|
||||
const column = countColumn(line.text, state.tabSize, r.head - line.from);
|
||||
const head = target.from + findColumn(target.text, column, state.tabSize);
|
||||
const head = sameColumnOn(state, r.head, target);
|
||||
return extend ? EditorSelection.range(r.anchor, head) : EditorSelection.cursor(head);
|
||||
});
|
||||
view.dispatch({
|
||||
@@ -90,6 +96,35 @@ export const cursorPageBottom = moveToPageEdge("bottom");
|
||||
export const selectPageTop = moveToPageEdge("top", true);
|
||||
export const selectPageBottom = moveToPageEdge("bottom", true);
|
||||
|
||||
/**
|
||||
* Scroll Up / Down and Move if Necessary: move the viewport by one line, then bring
|
||||
* a caret outside the lines the view shows whole to the first or last of them,
|
||||
* keeping its column. Carets in view keep their place and selection.
|
||||
*/
|
||||
const scrollByLineAndMove =
|
||||
(lines: number): Command =>
|
||||
(view) => {
|
||||
scrollByLine(lines)(view);
|
||||
const { state } = view;
|
||||
const first = pageEdgeLine(view, "top");
|
||||
const last = view.lineBlockAt(pageEdgeLine(view, "bottom"));
|
||||
let moved = false;
|
||||
const ranges = state.selection.ranges.map((r) => {
|
||||
if (r.head >= first && r.head <= last.to) return r;
|
||||
moved = true;
|
||||
return EditorSelection.cursor(sameColumnOn(state, r.head, r.head < first ? first : last.from));
|
||||
});
|
||||
if (moved) {
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(ranges, state.selection.mainIndex),
|
||||
userEvent: "select.navigate",
|
||||
});
|
||||
}
|
||||
return true;
|
||||
};
|
||||
export const scrollUpAndMove = scrollByLineAndMove(-1);
|
||||
export const scrollDownAndMove = scrollByLineAndMove(1);
|
||||
|
||||
const NOT_CODE = /String|Comment|Regexp|Char|Template/;
|
||||
|
||||
/** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
|
||||
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
|
||||
import {
|
||||
cloneCaretAbove,
|
||||
cloneCaretBelow,
|
||||
cursorLineDown,
|
||||
cursorLineUp,
|
||||
moveDownAndScroll,
|
||||
moveDownAndScrollWithSelection,
|
||||
moveUpAndScroll,
|
||||
moveUpAndScrollWithSelection,
|
||||
selectLineDown,
|
||||
visibleGoalColumns,
|
||||
} from "./verticalMotion";
|
||||
@@ -106,3 +110,122 @@ describe("Clone Caret Above / Below in visible columns", () => {
|
||||
expect(cloneCaretAbove(v)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Move Up / Down and Scroll", () => {
|
||||
/** jsdom has no layout: record what the command asks the scroller for, and whether it scrolled to the caret. */
|
||||
function track(v: EditorView, start: number) {
|
||||
let top = start;
|
||||
Object.defineProperty(v.scrollDOM, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => top,
|
||||
set: (x: number) => (top = x),
|
||||
});
|
||||
const scrolledToCaret: boolean[] = [];
|
||||
v.dispatch({
|
||||
effects: StateEffect.appendConfig.of(
|
||||
EditorView.updateListener.of((u) => u.transactions.forEach((tr) => scrolledToCaret.push(tr.scrollIntoView))),
|
||||
),
|
||||
});
|
||||
scrolledToCaret.length = 0;
|
||||
return { top: () => top, scrolledToCaret };
|
||||
}
|
||||
const rowGap = (v: EditorView, from: number, to: number) =>
|
||||
v.lineBlockAt(v.state.doc.line(to).from).top - v.lineBlockAt(v.state.doc.line(from).from).top;
|
||||
|
||||
it("moves the caret one line and scrolls the view by the same amount", () => {
|
||||
const v = make("abcdef\nabcdef\nabcdef\nabcdef", 7 + 3);
|
||||
const t = track(v, 100);
|
||||
const gap = rowGap(v, 2, 3);
|
||||
expect(gap).toBeGreaterThan(0);
|
||||
expect(moveDownAndScroll(v)).toBe(true);
|
||||
expect(heads(v)).toEqual([14 + 3]);
|
||||
expect(t.top()).toBe(100 + gap);
|
||||
expect(moveUpAndScroll(v)).toBe(true);
|
||||
expect(moveUpAndScroll(v)).toBe(true);
|
||||
expect(heads(v)).toEqual([3]);
|
||||
expect(t.top()).toBe(100 - rowGap(v, 1, 2));
|
||||
expect(v.state.selection.main.empty).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the goal column across a short line", () => {
|
||||
const v = make("abcdefgh\n张\nabcdefgh", 6);
|
||||
track(v, 0);
|
||||
moveDownAndScroll(v);
|
||||
moveDownAndScroll(v);
|
||||
expect(heads(v)).toEqual([11 + 6]);
|
||||
});
|
||||
|
||||
it("with Selection extends from the anchor", () => {
|
||||
const v = make("abcd\nabcd\nabcd", 5 + 2);
|
||||
const t = track(v, 40);
|
||||
moveDownAndScrollWithSelection(v);
|
||||
expect([v.state.selection.main.anchor, v.state.selection.main.head]).toEqual([7, 12]);
|
||||
moveUpAndScrollWithSelection(v);
|
||||
moveUpAndScrollWithSelection(v);
|
||||
expect([v.state.selection.main.anchor, v.state.selection.main.head]).toEqual([7, 2]);
|
||||
expect(t.top()).toBe(40 - rowGap(v, 1, 2));
|
||||
});
|
||||
|
||||
it("moves every caret and scrolls with the primary one", () => {
|
||||
const v = make("ab\nab\nab\nab", 0);
|
||||
v.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(1), EditorSelection.cursor(7)], 1) });
|
||||
const t = track(v, 0);
|
||||
moveDownAndScroll(v);
|
||||
expect(heads(v)).toEqual([4, 10]);
|
||||
expect(v.state.selection.mainIndex).toBe(1);
|
||||
expect(t.top()).toBe(rowGap(v, 3, 4));
|
||||
});
|
||||
|
||||
it("leaves scrolling to itself: never scrolls a caret out of view back into it", () => {
|
||||
const v = make("ab\nab\nab", 1);
|
||||
const t = track(v, 500);
|
||||
moveDownAndScroll(v);
|
||||
expect(t.scrolledToCaret).toEqual([false]);
|
||||
expect(t.top()).toBe(500 + rowGap(v, 1, 2));
|
||||
});
|
||||
|
||||
it("drops a selection and moves one line from its caret", () => {
|
||||
const v = make("abcd\nabcd\nabcd\nabcd", 0);
|
||||
v.dispatch({ selection: { anchor: 15 + 2, head: 2 } });
|
||||
const t = track(v, 0);
|
||||
moveDownAndScroll(v);
|
||||
expect(v.state.selection.main.empty).toBe(true);
|
||||
expect(heads(v)).toEqual([5 + 2]);
|
||||
expect(t.top()).toBe(rowGap(v, 1, 2));
|
||||
});
|
||||
|
||||
it("measures to the text of a line below a block widget (code lens)", () => {
|
||||
class Lens extends WidgetType {
|
||||
toDOM() {
|
||||
return document.createElement("div");
|
||||
}
|
||||
get estimatedHeight() {
|
||||
return 40;
|
||||
}
|
||||
}
|
||||
const v = make("ab\nab\nab", 1);
|
||||
const lens = Decoration.widget({ widget: new Lens(), block: true, side: -1 }).range(3);
|
||||
v.dispatch({ effects: StateEffect.appendConfig.of(EditorView.decorations.of(Decoration.set([lens]))) });
|
||||
const t = track(v, 0);
|
||||
const line = v.lineBlockAt(0).height;
|
||||
expect(v.lineBlockAt(3).height).toBeGreaterThan(line);
|
||||
moveDownAndScroll(v);
|
||||
expect(heads(v)).toEqual([4]);
|
||||
expect(t.top()).toBe(v.lineBlockAt(3).bottom - line);
|
||||
moveUpAndScroll(v);
|
||||
expect(t.top()).toBe(0);
|
||||
});
|
||||
|
||||
it("does not scroll at the document edge", () => {
|
||||
const v = make("ab\ncd", 1);
|
||||
const t = track(v, 0);
|
||||
expect(moveUpAndScroll(v)).toBe(true);
|
||||
expect(heads(v)).toEqual([0]);
|
||||
expect(moveUpAndScroll(v)).toBe(false);
|
||||
v.dispatch({ selection: { anchor: 4 } });
|
||||
expect(moveDownAndScroll(v)).toBe(true);
|
||||
expect(moveDownAndScroll(v)).toBe(false);
|
||||
expect(heads(v)).toEqual([5]);
|
||||
expect(t.top()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
* CodeMirror's pixel motion between their visual rows.
|
||||
*/
|
||||
import { EditorSelection, StateEffect, StateField, type EditorState, type SelectionRange } from "@codemirror/state";
|
||||
import type { Command, EditorView } from "@codemirror/view";
|
||||
import { BlockType, type BlockInfo, type Command, type EditorView } from "@codemirror/view";
|
||||
import { offsetAtVisibleColumn, visibleColumn } from "./visibleColumn";
|
||||
|
||||
/** Goal visible column per caret head, kept while only these commands move the carets. */
|
||||
@@ -52,11 +52,12 @@ export function verticalHead(view: EditorView, head: number, forward: boolean, g
|
||||
return moved === head ? null : moved;
|
||||
}
|
||||
|
||||
function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolean {
|
||||
/** `fromHead`: drop a selection and move its caret on from the head, as IDEA's caret-relative moves do. */
|
||||
function moveCarets(view: EditorView, forward: boolean, extend: boolean, fromHead = false): boolean {
|
||||
const { state } = view;
|
||||
const goals = new Map<number, number>();
|
||||
const ranges = state.selection.ranges.map((r): SelectionRange => {
|
||||
if (!extend && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
|
||||
if (!extend && !fromHead && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
|
||||
const goal = goalOf(state, r.head);
|
||||
let head = verticalHead(view, r.head, forward, goal);
|
||||
if (head === null) head = forward ? state.doc.lineAt(r.head).to : state.doc.lineAt(r.head).from;
|
||||
@@ -65,7 +66,8 @@ function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolea
|
||||
});
|
||||
const selection = EditorSelection.create(ranges, state.selection.mainIndex);
|
||||
if (selection.eq(state.selection)) return false;
|
||||
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: true, userEvent: "select" });
|
||||
// The caret-relative moves scroll the view themselves and may leave the caret out of view.
|
||||
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: !fromHead, userEvent: "select" });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -74,6 +76,41 @@ export const cursorLineDown: Command = (view) => moveCarets(view, true, false);
|
||||
export const selectLineUp: Command = (view) => moveCarets(view, false, true);
|
||||
export const selectLineDown: Command = (view) => moveCarets(view, true, true);
|
||||
|
||||
/** Top of the text of the line at `pos`, in document coordinates: below any block widgets (code lens, inline diff) joined to its line block. */
|
||||
function lineTextTop(view: EditorView, pos: number): number {
|
||||
const block = view.lineBlockAt(pos);
|
||||
if (!Array.isArray(block.type)) return block.top;
|
||||
const parts = block.type as readonly BlockInfo[];
|
||||
return (parts.find((b) => b.type === BlockType.Text && b.from <= pos && pos <= b.to) ?? block).top;
|
||||
}
|
||||
|
||||
/** Screen top of the caret's visual row when soft wrap splits lines into rows and the caret is drawn; otherwise null. */
|
||||
function caretRowTop(view: EditorView): number | null {
|
||||
if (!view.lineWrapping) return null;
|
||||
const { head, assoc } = view.state.selection.main;
|
||||
return view.coordsAtPos(head, assoc || 1)?.top ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move Up / Down and Scroll (with Selection), as IDEA: the carets move one line and
|
||||
* the view scrolls by as much, so the primary caret keeps its place on screen.
|
||||
*/
|
||||
function moveAndScroll(view: EditorView, forward: boolean, extend: boolean): boolean {
|
||||
const before = { row: caretRowTop(view), line: lineTextTop(view, view.state.selection.main.head) };
|
||||
if (!moveCarets(view, forward, extend, true)) return false;
|
||||
const row = before.row === null ? null : caretRowTop(view);
|
||||
view.scrollDOM.scrollTop +=
|
||||
row !== null && before.row !== null
|
||||
? row - before.row
|
||||
: lineTextTop(view, view.state.selection.main.head) - before.line;
|
||||
return true;
|
||||
}
|
||||
|
||||
export const moveUpAndScroll: Command = (view) => moveAndScroll(view, false, false);
|
||||
export const moveDownAndScroll: Command = (view) => moveAndScroll(view, true, false);
|
||||
export const moveUpAndScrollWithSelection: Command = (view) => moveAndScroll(view, false, true);
|
||||
export const moveDownAndScrollWithSelection: Command = (view) => moveAndScroll(view, true, true);
|
||||
|
||||
/** Clone Caret Above / Below: a caret on the next line at each caret's goal column. */
|
||||
function cloneCaret(view: EditorView, forward: boolean): boolean {
|
||||
const { state } = view;
|
||||
|
||||
@@ -24,6 +24,22 @@ import { installKeyboardDispatcher } from "@/platform/keymap";
|
||||
import { TEXT_WHEN } from "./actions";
|
||||
import { EDITOR_WHEN } from "@/editor/lsp/actions";
|
||||
import { setShownLine } from "@/editor/api";
|
||||
import { registerProjectActions } from "@/features/project-tree/actions";
|
||||
|
||||
/** `isTauri` is a spy (File Color writes need it true); the settings commands stand in for the backend. */
|
||||
const ipc = vi.hoisted(() => ({
|
||||
isTauri: vi.fn(() => false),
|
||||
settingsSet: vi.fn(async () => ({ status: "ok" as const, data: {} })),
|
||||
settingsGet: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: ipc.isTauri,
|
||||
commands: { ...real.commands, settingsSet: ipc.settingsSet, settingsGet: ipc.settingsGet },
|
||||
};
|
||||
});
|
||||
|
||||
let ctrl: EditorController | null = null;
|
||||
|
||||
@@ -422,6 +438,46 @@ describe("EditorController", () => {
|
||||
expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
|
||||
});
|
||||
|
||||
it("offers the project view's File Color submenu through actions", async () => {
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: false, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
ipc.isTauri.mockReturnValue(true);
|
||||
const disposeActions = registerProjectActions();
|
||||
try {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "", "/elsewhere/c.ts": "" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!;
|
||||
const raw = ctrl!.tabMenu(pane().id, pane().tabs[0]!);
|
||||
const entry = raw.find((i) => "label" in i && i.label === "File Color");
|
||||
expect(entry).toBeDefined();
|
||||
const items = resolveMenuItems((entry as { submenu: typeof raw }).submenu);
|
||||
expect(items.filter((i) => i.kind === "item").map((i) => i.label)).toEqual([
|
||||
"Blue",
|
||||
"Green",
|
||||
"Orange",
|
||||
"Rose",
|
||||
"Violet",
|
||||
"Yellow",
|
||||
"Gray",
|
||||
"Edit File Colors…",
|
||||
]);
|
||||
items.find((i) => i.label === "Blue")!.run!();
|
||||
await vi.waitFor(() => expect(ipc.settingsSet).toHaveBeenCalledTimes(2));
|
||||
expect(ipc.settingsSet).toHaveBeenNthCalledWith(1, "project", "scopes", expect.stringContaining('"file:a.ts"'));
|
||||
expect(ipc.settingsSet).toHaveBeenNthCalledWith(2, "project", "fileColors", expect.stringContaining("blue"));
|
||||
// A file outside the project has no File Color, as in the project view.
|
||||
await ctrl.openFile("/elsewhere/c.ts", { focus: false });
|
||||
const outside = pane().tabs.find((t) => t.input.path === "/elsewhere/c.ts")!;
|
||||
expect(ctrl.tabMenu(pane().id, outside).some((i) => "label" in i && i.label === "File Color")).toBe(false);
|
||||
ipc.isTauri.mockReturnValue(false);
|
||||
useProject.setState({ project: null, settings: null });
|
||||
} finally {
|
||||
disposeActions();
|
||||
}
|
||||
});
|
||||
it("keeps editor tabs and unsaved documents through attach and detach", async () => {
|
||||
const settings = {};
|
||||
useProject.setState({
|
||||
|
||||
@@ -12,7 +12,7 @@ import { create } from "zustand";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { basename, dirname, useProject } from "@/platform/project";
|
||||
import { basename, dirname, relativePath, useProject } from "@/platform/project";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import {
|
||||
_emitEditorEvent,
|
||||
@@ -60,6 +60,7 @@ import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
|
||||
import { isRemoteWindow, projectLocation } from "@/platform/remote";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { FILE_COLOR_NAMES, ownFileColor } from "@/platform/fileColors";
|
||||
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
|
||||
import {
|
||||
activateTab,
|
||||
@@ -2550,6 +2551,9 @@ export class EditorController implements SlotHost {
|
||||
{ kind: "separator" },
|
||||
...(path
|
||||
? ([
|
||||
...(inProject && path !== project!.root
|
||||
? ([{ label: "File Color", submenu: fileColorMenuItems(path) }, { kind: "separator" }] as MenuItem[])
|
||||
: []),
|
||||
{
|
||||
label: "Copy Path/Reference…",
|
||||
submenu: [
|
||||
@@ -2638,6 +2642,26 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* File Color submenu of a file tab: the project view's File Color rows as action items carrying
|
||||
* the path (features/project-tree owns the model and the titles), so both menus agree.
|
||||
*/
|
||||
function fileColorMenuItems(path: string): MenuItem[] {
|
||||
const { project, settings } = useProject.getState();
|
||||
const current = project ? ownFileColor(relativePath(project.root, path), false, settings)?.toLowerCase() : null;
|
||||
return [
|
||||
...FILE_COLOR_NAMES.map((name): MenuItem => ({
|
||||
kind: "action",
|
||||
action: `file.${name}`,
|
||||
arg: path,
|
||||
checked: current === name,
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
...(current ? [{ kind: "action" as const, action: "file.clearColor", arg: path }] : []),
|
||||
{ kind: "action", action: "file.editColors" },
|
||||
];
|
||||
}
|
||||
|
||||
/** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */
|
||||
function openInMenu(path: string, lines?: { line: number; endLine?: number }): MenuItem {
|
||||
return {
|
||||
|
||||
@@ -307,11 +307,13 @@ export function NavChildrenPopup({
|
||||
segment,
|
||||
anchor,
|
||||
openAbove = true,
|
||||
label,
|
||||
onClose,
|
||||
}: {
|
||||
segment: NavSegment;
|
||||
anchor: HTMLElement;
|
||||
openAbove?: boolean;
|
||||
label?: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [stack, setStack] = useState<NavSegment[]>([segment]);
|
||||
@@ -366,7 +368,7 @@ export function NavChildrenPopup({
|
||||
anchor={anchor}
|
||||
placement={openAbove ? "top-start" : "bottom-start"}
|
||||
onClose={onClose}
|
||||
aria-label={top.label}
|
||||
aria-label={label ?? top.label}
|
||||
className={styles.childPopup}
|
||||
>
|
||||
{stack.length > 1 && (
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
Menu,
|
||||
Popup,
|
||||
SelectListbox,
|
||||
showContextMenu,
|
||||
badgeKind,
|
||||
fileIconName,
|
||||
revealHorizontally,
|
||||
@@ -33,6 +34,7 @@ import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs }
|
||||
import { languageInfo } from "../cm/languages";
|
||||
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
import { siblingSegment } from "./navBar";
|
||||
import { NavChildrenPopup } from "./NavBarPopup";
|
||||
import type { NavSegment } from "./navBar";
|
||||
import styles from "./EditorArea.module.css";
|
||||
@@ -166,9 +168,15 @@ function updateBreadcrumbEdges(row: HTMLDivElement) {
|
||||
function BreadcrumbStrip({
|
||||
trail,
|
||||
activateOnDown = false,
|
||||
onActivateAltDown,
|
||||
children,
|
||||
...props
|
||||
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
|
||||
}: ComponentPropsWithoutRef<"nav"> & {
|
||||
trail: string;
|
||||
activateOnDown?: boolean;
|
||||
/** Alt+Down on a focused crumb opens its chooser (the crumb's element is passed). */
|
||||
onActivateAltDown?: (crumb: HTMLElement) => void;
|
||||
}) {
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const row = strip.current;
|
||||
@@ -189,10 +197,16 @@ function BreadcrumbStrip({
|
||||
<nav
|
||||
{...props}
|
||||
onKeyDown={(e) => {
|
||||
if (e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
const buttons = [...(strip.current?.querySelectorAll("button") ?? [])];
|
||||
const index = buttons.indexOf(e.target as HTMLButtonElement);
|
||||
if (index < 0) return;
|
||||
if (e.altKey && !e.ctrlKey && !e.metaKey && e.key === "ArrowDown" && onActivateAltDown) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onActivateAltDown?.(buttons[index]!);
|
||||
return;
|
||||
}
|
||||
if (e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
let next: number;
|
||||
if (e.key === "ArrowLeft") next = Math.max(0, index - 1);
|
||||
else if (e.key === "ArrowRight") next = Math.min(buttons.length - 1, index + 1);
|
||||
@@ -354,6 +368,7 @@ export function CodeBreadcrumbs({
|
||||
const editorSettings = useProject((s) => s.settings?.editor);
|
||||
const language = useDocMeta((s) => s[path]?.language);
|
||||
const outline = useOutline((s) => s[path]);
|
||||
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
|
||||
let chain = useCaretSymbols(path, outline);
|
||||
if (!chain) {
|
||||
// Not the active editor (another split): its own caret, as of this render.
|
||||
@@ -373,28 +388,56 @@ export function CodeBreadcrumbs({
|
||||
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
|
||||
: undefined;
|
||||
const fontSize = editorSettings?.fontSize ?? undefined;
|
||||
const navigate = (item: OutlineItem) =>
|
||||
void editorController().openFile(path, {
|
||||
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
|
||||
});
|
||||
// IDEA's breadcrumb chooser lives off the click: right-click or Alt+Down on a
|
||||
// crumb lists its siblings (Navigation Bar only).
|
||||
const chooseSiblings = (i: number, anchor: HTMLElement) => {
|
||||
if (!outline) return;
|
||||
setPopup({ nav: siblingSegment(path, chain, i), anchor });
|
||||
};
|
||||
const crumbMenu = (
|
||||
i: number,
|
||||
crumb: HTMLElement,
|
||||
e: { clientX: number; clientY: number; preventDefault: () => void },
|
||||
) => {
|
||||
e.preventDefault();
|
||||
if (outline)
|
||||
showContextMenu(e, [{ id: "chooseSymbol", label: "Choose Symbol…", run: () => chooseSiblings(i, crumb) }]);
|
||||
};
|
||||
return (
|
||||
<BreadcrumbStrip
|
||||
trail={JSON.stringify([path, fontFamily, fontSize, ...chain.map((item) => item.name)])}
|
||||
style={{ fontFamily, fontSize }}
|
||||
className={clsx(styles.codeCrumbs, position === "top" ? styles.codeCrumbsTop : styles.codeCrumbsBottom)}
|
||||
aria-label={tx("Code breadcrumbs")}
|
||||
onActivateAltDown={(crumb) => chooseSiblings(Number(crumb.dataset.crumbIndex), crumb)}
|
||||
>
|
||||
{chain.map((item, i) => (
|
||||
<BarButton
|
||||
key={`${item.name}:${item.detail ?? ""}:${item.selection_range.start.line}:${item.selection_range.start.col}`}
|
||||
data-crumb-index={i}
|
||||
className={styles.crumbButton}
|
||||
tooltip={item.detail ?? item.name}
|
||||
aria-current={i === chain.length - 1 ? "location" : undefined}
|
||||
onClick={() =>
|
||||
void editorController().openFile(path, {
|
||||
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
|
||||
})
|
||||
}
|
||||
onClick={() => navigate(item)}
|
||||
onContextMenu={(e) => crumbMenu(i, e.currentTarget, e)}
|
||||
>
|
||||
<span className={styles.crumbLabel}>{item.name}</span>
|
||||
</BarButton>
|
||||
))}
|
||||
{popup && (
|
||||
<NavChildrenPopup
|
||||
key={`${popup.nav.kind}:${popup.nav.path}:${popup.nav.label}`}
|
||||
segment={popup.nav}
|
||||
anchor={popup.anchor}
|
||||
openAbove={position === "bottom"}
|
||||
label={tx("Choose a symbol")}
|
||||
onClose={() => setPopup(null)}
|
||||
/>
|
||||
)}
|
||||
</BreadcrumbStrip>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -67,6 +67,17 @@ export function symbolChildren(path: string, items: readonly OutlineItem[]): Nav
|
||||
return items.map((item) => ({ kind: "symbol", path, label: item.name, item }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The segment whose children are the siblings of `chain[index]` (IDEA / PyCharm
|
||||
* breadcrumb chooser): the file for a top-level symbol, else its enclosing symbol.
|
||||
*/
|
||||
export function siblingSegment(path: string, chain: readonly OutlineItem[], index: number): NavSegment {
|
||||
const parent = index > 0 ? chain[index - 1]! : null;
|
||||
return parent
|
||||
? { kind: "symbol", path, label: parent.name, item: parent }
|
||||
: { kind: "file", path, label: nameOf(path) };
|
||||
}
|
||||
|
||||
export function iconOf(x: NavSegment | NavChild): string {
|
||||
if (x.kind === "dir") return "root" in x && x.root ? "module" : "folder";
|
||||
if (x.kind === "file") return fileIconName(x.label);
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Profiler } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { OutlineItem, Settings } from "@/platform/ipc";
|
||||
import type { EditorStatus } from "../controller";
|
||||
|
||||
const { openFile } = vi.hoisted(() => ({ openFile: vi.fn(async () => {}) }));
|
||||
|
||||
vi.mock("../controller", async () => {
|
||||
const { create } = await import("zustand");
|
||||
return {
|
||||
editorController: () => ({ openFile: vi.fn(), slots: new Map() }),
|
||||
editorController: () => ({ openFile, slots: new Map() }),
|
||||
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
|
||||
useGotoLine: create(() => ({ open: false })),
|
||||
useTabs: create(() => ({ panes: {}, activePane: "" })),
|
||||
@@ -21,6 +23,7 @@ const { useProject } = await import("@/platform/project");
|
||||
const { clearProjectViewLead, setProjectViewLead } = await import("@/workbench/contributions");
|
||||
const { Breadcrumbs, CodeBreadcrumbs } = await import("./StatusItems");
|
||||
const { NavBarPopup, openNavBarPopup, useNavBarPopup } = await import("./NavBarPopup");
|
||||
const { useContextMenuStore } = await import("@/ui");
|
||||
|
||||
const PATH = "/p/Orders.ts";
|
||||
const span = (from: number, to: number) => ({ start: { line: from, col: 0 }, end: { line: to, col: 0 } });
|
||||
@@ -307,3 +310,78 @@ it("elides the middle of a deep path without a duplicate React key", () => {
|
||||
view.unmount();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
});
|
||||
|
||||
describe("code breadcrumb symbol chooser", () => {
|
||||
beforeEach(() => {
|
||||
openFile.mockClear();
|
||||
useProject.setState({
|
||||
settings: {
|
||||
editor: { breadcrumbs: { show: true, placement: "bottom", disabledLanguages: [] } },
|
||||
} as unknown as Settings,
|
||||
});
|
||||
useEditorStatus.setState({ status: caret(3, 4) });
|
||||
});
|
||||
|
||||
it("navigates to the crumb's symbol on plain click, as the IDE does", async () => {
|
||||
// Orders class with place/cancel methods; caret sits inside `place`.
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
const crumbs = screen.getAllByRole("button");
|
||||
// The last crumb is the innermost symbol (place).
|
||||
const place = crumbs[crumbs.length - 1]!;
|
||||
expect(place.getAttribute("aria-haspopup")).toBeNull();
|
||||
fireEvent.click(place);
|
||||
await waitFor(() => expect(openFile).toHaveBeenCalledWith(PATH, { selection: { line: 2, col: 0 } }));
|
||||
// No chooser opened with the click: that belongs to the context menu / Alt+Down.
|
||||
expect(screen.queryByRole("listbox")).toBeNull();
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("opens the sibling chooser from the crumb's context menu", async () => {
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
const crumbs = screen.getAllByRole("button");
|
||||
fireEvent.contextMenu(crumbs[crumbs.length - 1]!);
|
||||
const menuItem = useContextMenuStore
|
||||
.getState()
|
||||
.menu?.items.find((i) => "label" in i && i.label === "Choose Symbol…") as { run?: () => void } | undefined;
|
||||
expect(menuItem?.run).toBeTruthy();
|
||||
act(() => menuItem!.run!());
|
||||
const list = await screen.findByRole("listbox", { name: "Orders" });
|
||||
expect(list.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);
|
||||
// Selecting a sibling navigates.
|
||||
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
|
||||
await waitFor(() =>
|
||||
expect(openFile).toHaveBeenCalledWith(PATH, {
|
||||
selection: { line: 12, col: 0 },
|
||||
focus: true,
|
||||
}),
|
||||
);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("opens the sibling chooser with Alt+Down while the strip has focus", async () => {
|
||||
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
const crumbs = screen.getAllByRole("button");
|
||||
const place = crumbs[crumbs.length - 1]!;
|
||||
place.focus();
|
||||
fireEvent.keyDown(place, { key: "ArrowDown", altKey: true });
|
||||
await screen.findByRole("listbox", { name: "Orders" });
|
||||
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
|
||||
await waitFor(() =>
|
||||
expect(openFile).toHaveBeenCalledWith(PATH, {
|
||||
selection: { line: 12, col: 0 },
|
||||
focus: true,
|
||||
}),
|
||||
);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("hides the bar when there is no outline chain", () => {
|
||||
useOutline.setState({ [PATH]: [] });
|
||||
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
|
||||
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
|
||||
view.unmount();
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,7 @@ import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { pathCompletionSource, pathContext, pathLike } from "./fileReferences";
|
||||
import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables";
|
||||
import { javaDeclarationAt, variableNameSource } from "./variableNames";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { showHint } from "./hint";
|
||||
@@ -930,6 +931,9 @@ function gated(source: CompletionSource): CompletionSource {
|
||||
if (ctx.state.field(smartLookup, false) && source !== claimingLspSource) return null;
|
||||
const only = exclusiveSource(ctx);
|
||||
if (only) return source === contributedSource ? only(ctx) : null;
|
||||
// At a Java declaration's name only names fit: IDEA lists no live templates there, and
|
||||
// jdtls' own name proposals repeat the type (`orderBookOrderBook`).
|
||||
if (source !== variableNameSource && javaDeclarationAt(ctx)) return null;
|
||||
if (!ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state))) return null;
|
||||
if (!editorPrefs().completion.sortAlphabetically) return source(ctx);
|
||||
return Promise.resolve(source(ctx)).then(
|
||||
@@ -1208,6 +1212,7 @@ export function completionExtension() {
|
||||
gated(contributedSource),
|
||||
gated(pathFallbackSource),
|
||||
gated(cssVariableSource),
|
||||
gated(variableNameSource),
|
||||
],
|
||||
icons: false,
|
||||
addToOptions: [
|
||||
|
||||
@@ -44,7 +44,7 @@ import { basename } from "@/platform/project";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { applyCodeAction, quickFixesAt } from "./intentions";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api";
|
||||
import { CONTRIBUTED_HOVER, contributedAtAll, contributedProblemsAt, type ContributedHover } from "@/editor/api";
|
||||
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
|
||||
import { languageSemantics } from "./semantic";
|
||||
import { cssVariableHover } from "./cssVariables";
|
||||
@@ -108,10 +108,14 @@ function diagnosticAction(label: string, shortcut: string | undefined, run: () =
|
||||
return button;
|
||||
}
|
||||
|
||||
function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLElement {
|
||||
interface HoverProblem extends PlacedDiagnostic {
|
||||
contributed: boolean;
|
||||
}
|
||||
|
||||
function renderDiagnostics(view: EditorView, diags: HoverProblem[]): HTMLElement {
|
||||
const box = document.createElement("div");
|
||||
box.className = "cm-lsp-hover-diagnostics";
|
||||
for (const { diagnostic: d, from, to } of diags) {
|
||||
for (const { diagnostic: d, from, to, contributed } of diags) {
|
||||
const row = document.createElement("div");
|
||||
row.className = `cm-lsp-diag cm-lsp-diag-${d.severity}`;
|
||||
row.appendChild(
|
||||
@@ -125,6 +129,10 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
|
||||
msg.className = "cm-lsp-diag-message";
|
||||
msg.textContent = d.message;
|
||||
row.appendChild(msg);
|
||||
if (contributed) {
|
||||
box.appendChild(row);
|
||||
continue;
|
||||
}
|
||||
if (d.source) {
|
||||
const src = document.createElement("span");
|
||||
src.className = "cm-lsp-diag-source";
|
||||
@@ -182,7 +190,15 @@ export function hoverCard(children: HTMLElement[]): HTMLElement {
|
||||
/** Problems always; quick documentation per Settings › Editor › Code Editing. */
|
||||
export async function hoverSource(view: EditorView, pos: number) {
|
||||
if (hoverYields()) return null;
|
||||
const diags = diagnosticsAt(view, pos);
|
||||
const diags: HoverProblem[] = [
|
||||
...contributedProblemsAt(view.state, pos).map(({ from, to, severity, message }) => ({
|
||||
from,
|
||||
to,
|
||||
diagnostic: { from, to, severity, message },
|
||||
contributed: true,
|
||||
})),
|
||||
...diagnosticsAt(view, pos).map((d) => ({ ...d, contributed: false })),
|
||||
];
|
||||
let hover: Hover | null = null;
|
||||
if (editorPrefs().codeEditing.quickDocOnHover)
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/** Problems a feature marks on its own text (database console) show in the editor hover like diagnostics. */
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { problemProviders } from "@/editor/api";
|
||||
import { hoverSource } from "./hover";
|
||||
|
||||
let view: EditorView | null = null;
|
||||
afterEach(() => {
|
||||
view?.destroy();
|
||||
view = null;
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
function editor() {
|
||||
const state = EditorState.create({
|
||||
doc: "DELETE FROM t WHERE 1=1",
|
||||
extensions: [problemProviders.of(() => [{ from: 20, to: 23, severity: "warning", message: "Unsafe query" }])],
|
||||
});
|
||||
return (view = new EditorView({ state, parent: document.body.appendChild(document.createElement("div")) }));
|
||||
}
|
||||
|
||||
describe("contributed problems in the hover", () => {
|
||||
it("shows the problem under the pointer with its severity icon and no quick-fix links", async () => {
|
||||
const tip = await hoverSource(editor(), 21);
|
||||
expect(tip).toMatchObject({ pos: 20, end: 23 });
|
||||
const { dom } = tip!.create();
|
||||
const row = dom.querySelector(".cm-lsp-diag-warning")!;
|
||||
expect(row.querySelector(".cm-lsp-diag-message")?.textContent).toBe("Unsafe query");
|
||||
expect(row.querySelector(".cm-lsp-diag-icon")).not.toBeNull();
|
||||
expect(dom.querySelector(".cm-lsp-link-button")).toBeNull();
|
||||
});
|
||||
|
||||
it("stays out away from the problem", async () => {
|
||||
expect(await hoverSource(editor(), 3)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { declarationAt, namesForType, pluralize } from "./variableNames";
|
||||
|
||||
const names = (before: string) => {
|
||||
const found = declarationAt(before);
|
||||
return found ? namesForType(found.type) : null;
|
||||
};
|
||||
|
||||
describe("variable names by type (IDEA)", () => {
|
||||
it("suggests the type's name and its shorter endings", () => {
|
||||
expect(names(" private IMesCheckStandardService c")).toEqual([
|
||||
"iMesCheckStandardService",
|
||||
"mesCheckStandardService",
|
||||
"checkStandardService",
|
||||
"standardService",
|
||||
"service",
|
||||
]);
|
||||
expect(names(" MesProductPlan p")).toEqual(["mesProductPlan", "productPlan", "plan"]);
|
||||
expect(names(" UserServiceImpl ")).toEqual(["userService", "service"]);
|
||||
expect(names(" HttpURLConnection c")).toEqual(["httpURLConnection", "urlConnection", "connection"]);
|
||||
});
|
||||
|
||||
it("names collections, arrays, optionals and generic types by their contents", () => {
|
||||
expect(names("List<MesProductCheck> l")).toEqual([
|
||||
"mesProductChecks",
|
||||
"productChecks",
|
||||
"checks",
|
||||
"mesProductCheckList",
|
||||
"productCheckList",
|
||||
"checkList",
|
||||
"list",
|
||||
]);
|
||||
expect(names("Order[] ")).toEqual(["orders"]);
|
||||
expect(names("Optional<User> ")).toEqual(["user", "optionalUser", "userOptional", "optional"]);
|
||||
expect(names("Map<String, Order> ")).toEqual(["stringOrderMap", "orderMap", "map"]);
|
||||
expect(pluralize("Category")).toBe("Categories");
|
||||
expect(pluralize("Box")).toBe("Boxes");
|
||||
});
|
||||
|
||||
it("gives locals and parameters IDEA's short names", () => {
|
||||
expect(names(" String ")).toEqual(["s", "string"]);
|
||||
expect(names(" private String ")).toEqual(["string"]);
|
||||
expect(names(" int ")).toEqual(["i"]);
|
||||
expect(names(" } catch (IOException ")).toEqual(["e", "ioException", "exception"]);
|
||||
expect(names("void run(Order o")).toEqual(["order"]);
|
||||
});
|
||||
|
||||
it("is quiet where no name is declared", () => {
|
||||
expect(declarationAt(" return Foo")).toBeNull();
|
||||
expect(declarationAt(" return value ")).toBeNull();
|
||||
expect(declarationAt("class Foo ")).toBeNull();
|
||||
expect(declarationAt(" throw new Error ")).toBeNull();
|
||||
expect(declarationAt("@Autowired ")).toBeNull();
|
||||
expect(declarationAt(" private c")).toBeNull();
|
||||
expect(declarationAt(" var x")).toBeNull();
|
||||
expect(declarationAt(" foo.bar")).toBeNull();
|
||||
expect(declarationAt(" Foo f")).toEqual({ type: expect.objectContaining({ name: "Foo" }), typed: "f" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Variable names by type, as IDEA's JavaCodeStyleManager suggests them: typing the name of a
|
||||
* Java declaration (`private IUserService |`, `List<Order> |`, `catch (IOException |`) lists
|
||||
* `userService`, `service`, `orders`, `e`… The language server offers nothing there.
|
||||
*/
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import { lspDoc } from "./lsp";
|
||||
|
||||
/** The declared type at a name being typed: `Map<String, Order>[]` → `Map`, `[String, Order]`, array. */
|
||||
export interface DeclaredType {
|
||||
name: string;
|
||||
args: string[];
|
||||
array: boolean;
|
||||
kind: "field" | "parameter" | "local";
|
||||
}
|
||||
|
||||
const PRIMITIVES = new Set(["int", "long", "short", "byte", "char", "boolean", "float", "double"]);
|
||||
|
||||
/** Words before a type that make what follows something other than a declaration's name. */
|
||||
const NOT_A_DECLARATION = new Set([
|
||||
"new",
|
||||
"class",
|
||||
"interface",
|
||||
"enum",
|
||||
"record",
|
||||
"extends",
|
||||
"implements",
|
||||
"permits",
|
||||
"throws",
|
||||
"import",
|
||||
"package",
|
||||
"return",
|
||||
"throw",
|
||||
"yield",
|
||||
"assert",
|
||||
"goto",
|
||||
"var",
|
||||
"this",
|
||||
"super",
|
||||
]);
|
||||
|
||||
const FIELD_MODIFIERS = /\b(?:private|protected|public|static|volatile|transient)\b/;
|
||||
|
||||
const DECLARATION =
|
||||
/(^|[\s(,;{}])((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*)\s*(<[^;(){}=]*>)?((?:\s*\[\s*\])*)\s+([A-Za-z_$][\w$]*)?$/;
|
||||
|
||||
/**
|
||||
* The type whose variable's name ends `before` (the line up to the caret), with the name typed so
|
||||
* far; null when the caret isn't at a declared name.
|
||||
*/
|
||||
export function declarationAt(before: string): { type: DeclaredType; typed: string } | null {
|
||||
const m = DECLARATION.exec(before);
|
||||
if (!m) return null;
|
||||
const qualified = m[2]!;
|
||||
const name = qualified.slice(qualified.lastIndexOf(".") + 1);
|
||||
if (!PRIMITIVES.has(name) && !/^[A-Z]/.test(name)) return null;
|
||||
const head = before.slice(0, m.index + m[1]!.length);
|
||||
const previous = /([A-Za-z_@][\w]*)\s*$/.exec(head)?.[1];
|
||||
if (previous && (NOT_A_DECLARATION.has(previous) || previous.startsWith("@"))) return null;
|
||||
if (/@\s*$/.test(head)) return null;
|
||||
const params = /[(,]\s*$/.test(head) || /\(\s*(?:final\s+)?$/.test(head) || /\bcatch\s*\(\s*$/.test(head);
|
||||
const kind = params ? "parameter" : FIELD_MODIFIERS.test(head) ? "field" : "local";
|
||||
return {
|
||||
type: { name, args: typeArguments(m[3] ?? ""), array: !!m[4]?.trim(), kind },
|
||||
typed: m[5] ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** The top-level type arguments' simple names (`<String, List<Order>>` → `String`, `List`); `?` and bounds skipped. */
|
||||
function typeArguments(generic: string): string[] {
|
||||
const inner = generic.slice(1, -1);
|
||||
const out: string[] = [];
|
||||
let depth = 0;
|
||||
let current = "";
|
||||
for (const ch of inner) {
|
||||
if (ch === "<") depth++;
|
||||
if (ch === ">") depth--;
|
||||
if (ch === "," && depth === 0) {
|
||||
out.push(current);
|
||||
current = "";
|
||||
} else if (depth === 0 && ch !== ">") current += ch;
|
||||
}
|
||||
out.push(current);
|
||||
return out
|
||||
.map((a) => a.trim())
|
||||
.filter((a) => /^[A-Za-z_$][\w$.]*$/.test(a))
|
||||
.map((a) => a.slice(a.lastIndexOf(".") + 1));
|
||||
}
|
||||
|
||||
/** IDEA's NameUtilCore.nameToWordList: `IUserURLService` → `I`, `User`, `URL`, `Service`. */
|
||||
function words(name: string): string[] {
|
||||
return name.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+|[A-Z]/g) ?? [];
|
||||
}
|
||||
|
||||
/** StringUtil.pluralize for the usual cases. */
|
||||
export function pluralize(word: string): string {
|
||||
if (/(?:s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
|
||||
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
|
||||
return `${word}s`;
|
||||
}
|
||||
|
||||
/** `UserService` → `userService`, `service` (longest first); an all-caps first word goes lower case. */
|
||||
function suffixNames(name: string): string[] {
|
||||
const ws = words(name);
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < ws.length; i++) {
|
||||
const first = ws[i]!;
|
||||
if (!/^[A-Za-z]/.test(first)) continue;
|
||||
const head = first === first.toUpperCase() ? first.toLowerCase() : first[0]!.toLowerCase() + first.slice(1);
|
||||
out.push(head + ws.slice(i + 1).join(""));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const SHORT_NAMES: Record<string, string> = {
|
||||
int: "i",
|
||||
boolean: "b",
|
||||
byte: "b",
|
||||
char: "c",
|
||||
long: "l",
|
||||
short: "i",
|
||||
double: "v",
|
||||
float: "v",
|
||||
Integer: "i",
|
||||
Short: "i",
|
||||
Long: "l",
|
||||
Boolean: "b",
|
||||
Byte: "b",
|
||||
Character: "c",
|
||||
Double: "v",
|
||||
Float: "v",
|
||||
Object: "o",
|
||||
String: "s",
|
||||
};
|
||||
|
||||
const ITERABLES = new Set([
|
||||
"Iterable",
|
||||
"Collection",
|
||||
"List",
|
||||
"ArrayList",
|
||||
"LinkedList",
|
||||
"Set",
|
||||
"HashSet",
|
||||
"LinkedHashSet",
|
||||
"TreeSet",
|
||||
"SortedSet",
|
||||
"NavigableSet",
|
||||
"Queue",
|
||||
"Deque",
|
||||
"ArrayDeque",
|
||||
"PriorityQueue",
|
||||
"Stack",
|
||||
"Vector",
|
||||
"CopyOnWriteArrayList",
|
||||
]);
|
||||
|
||||
/** `UserServiceImpl` names a `userService`, as in IDEA. */
|
||||
const normalize = (name: string) => (name.length > 4 && name.endsWith("Impl") ? name.slice(0, -4) : name);
|
||||
|
||||
const JAVA_KEYWORDS = new Set(
|
||||
(
|
||||
"abstract assert boolean break byte case catch char class const continue default do double else enum extends " +
|
||||
"final finally float for goto if implements import instanceof int interface long native new package private " +
|
||||
"protected public return short static strictfp super switch synchronized this throw throws transient try void " +
|
||||
"volatile while true false null var record yield"
|
||||
).split(" "),
|
||||
);
|
||||
|
||||
/** The names IDEA suggests for a variable of `type`, best first. */
|
||||
export function namesForType(type: DeclaredType): string[] {
|
||||
const base: string[] = [];
|
||||
const short = type.kind === "field" ? undefined : SHORT_NAMES[type.name];
|
||||
if (short) base.push(type.array ? pluralize(short) : short);
|
||||
const name = normalize(type.name);
|
||||
if (type.args.length === 1 && ITERABLES.has(type.name)) base.push(pluralize(normalize(type.args[0]!)));
|
||||
if (type.args.length === 1 && type.name === "Optional") {
|
||||
const content = normalize(type.args[0]!);
|
||||
base.push(content, `optional${content}`);
|
||||
}
|
||||
if (type.args.length) base.push(type.args.map(normalize).join("") + name);
|
||||
const own = type.array ? pluralize(name) : name;
|
||||
if (type.kind === "parameter" && type.name.endsWith("Exception")) base.push("e");
|
||||
base.push(own);
|
||||
if (own.length > "Entity".length && own.endsWith("Entity")) base.push(own.slice(0, -"Entity".length));
|
||||
const out: string[] = [];
|
||||
for (const b of base) {
|
||||
for (const n of PRIMITIVES.has(b) || b.length === 1 ? [b] : suffixNames(b)) {
|
||||
if (!out.includes(n) && !JAVA_KEYWORDS.has(n) && /^[A-Za-z_$][\w$]*$/.test(n)) out.push(n);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The declaration under the caret in a Java file (not in a comment or string), or null. */
|
||||
export function javaDeclarationAt(ctx: CompletionContext): { type: DeclaredType; typed: string } | null {
|
||||
if (ctx.state.facet(lspDoc)?.language !== "java") return null;
|
||||
const node = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
|
||||
if (/Comment|String|TextBlock/.test(node.name)) return null;
|
||||
const line = ctx.state.doc.lineAt(ctx.pos);
|
||||
return declarationAt(line.text.slice(0, ctx.pos - line.from));
|
||||
}
|
||||
|
||||
/** Completion source: the type's names at a Java declaration's name. */
|
||||
export function variableNameSource(ctx: CompletionContext): CompletionResult | null {
|
||||
const found = javaDeclarationAt(ctx);
|
||||
if (!found) return null;
|
||||
const names = namesForType(found.type);
|
||||
const options: Completion[] = names.map((label, i) => ({ label, type: "variable", boost: 50 - i }));
|
||||
return options.length ? { from: ctx.pos - found.typed.length, options, validFor: /^[\w$]*$/ } : null;
|
||||
}
|
||||
@@ -44,7 +44,7 @@
|
||||
|
||||
.table {
|
||||
flex: 1;
|
||||
min-height: calc(var(--h-list-row) * 3);
|
||||
min-height: calc(var(--h-list-row) * 2);
|
||||
overflow: auto;
|
||||
scrollbar-gutter: stable;
|
||||
scroll-padding-top: var(--h-list-row);
|
||||
|
||||
@@ -230,6 +230,14 @@
|
||||
color: var(--fg);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.statusNote {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
margin: 4px 0;
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.text code,
|
||||
.launch {
|
||||
font-family: var(--font-mono);
|
||||
@@ -237,6 +245,26 @@
|
||||
.text code {
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.signInRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin: 4px 0;
|
||||
}
|
||||
.signInHint {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
color: var(--fg);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.signInHint code {
|
||||
font-family: var(--font-mono);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
/* "Label: control" rows; a hint sits under its control. */
|
||||
.form {
|
||||
display: grid;
|
||||
@@ -286,6 +314,14 @@
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.accountField {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
.select {
|
||||
display: flex;
|
||||
width: 280px;
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
* start with, and how it is launched. Launch edits are staged until Apply; installs run in
|
||||
* the background and keep running after the page closes.
|
||||
*/
|
||||
import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from "react";
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import type {
|
||||
AgentConfigOption,
|
||||
AgentModelCatalog,
|
||||
AgentProvider,
|
||||
AgentRegistry,
|
||||
CopilotAuthStatus,
|
||||
CustomAgentInput,
|
||||
RegistryAgent,
|
||||
RequestId,
|
||||
@@ -19,9 +20,23 @@ import { isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { tx, useTxTemplate } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import clsx from "clsx";
|
||||
import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField, Select, Spinner, T } from "@/ui";
|
||||
import {
|
||||
Button,
|
||||
copyText,
|
||||
Dialog,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
List,
|
||||
ProgressBar,
|
||||
SearchField,
|
||||
Select,
|
||||
Spinner,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { AgentSignInDialog, type SignInTarget } from "./AgentSignInDialog";
|
||||
import { LocalCliUpdate } from "./LocalCliUpdate";
|
||||
import { approvalDefaults, cursorModelDefaults, isPerModelOption } from "./composerModel";
|
||||
import { providerIcon, slugifyId } from "./model";
|
||||
@@ -863,6 +878,42 @@ function ProviderSettings({
|
||||
return formatEnv(launchEnv(parsed));
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [signInTarget, setSignInTarget] = useState<SignInTarget | null>(null);
|
||||
const [copilotStatus, setCopilotStatus] = useState<CopilotAuthStatus | null>(null);
|
||||
const [copilotStatusLoaded, setCopilotStatusLoaded] = useState(false);
|
||||
const [authRevision, setAuthRevision] = useState(0);
|
||||
const pendingAddAccountPrevLogins = useRef<Set<string> | null>(null);
|
||||
const fetchCopilotStatus = backend.copilotAuthStatus;
|
||||
const reloadCopilotStatus = useCallback(async (): Promise<CopilotAuthStatus | null> => {
|
||||
if (agent.id !== "copilot" || !fetchCopilotStatus) return null;
|
||||
try {
|
||||
const next = await fetchCopilotStatus();
|
||||
setCopilotStatus(next);
|
||||
setCopilotStatusLoaded(true);
|
||||
return next;
|
||||
} catch {
|
||||
setCopilotStatusLoaded(true);
|
||||
return null;
|
||||
}
|
||||
}, [agent.id, fetchCopilotStatus]);
|
||||
useEffect(() => {
|
||||
if (agent.id !== "copilot" || !fetchCopilotStatus) return;
|
||||
let alive = true;
|
||||
void fetchCopilotStatus()
|
||||
.then((next) => {
|
||||
if (alive) {
|
||||
setCopilotStatus(next);
|
||||
setCopilotStatusLoaded(true);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setCopilotStatusLoaded(true);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [agent.id, fetchCopilotStatus]);
|
||||
const activeCopilotStatus = agent.id === "copilot" && fetchCopilotStatus ? copilotStatus : null;
|
||||
// An edit can have been staged by a previous page instance. Its Apply callback
|
||||
// refreshes that instance; the mounted one follows the newly applied value too.
|
||||
useEffect(() => {
|
||||
@@ -875,44 +926,157 @@ function ProviderSettings({
|
||||
? [agent.defaultProgram, ...agent.defaultArgs].join(" ")
|
||||
: formatArgs([agent.program, ...agent.args]);
|
||||
const envEditable = agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent";
|
||||
const canSignInInIde = agent.installed && (agent.canSignIn ?? false);
|
||||
const commandSpan = agent.loginHint ? (/`([^`]+)`/.exec(agent.loginHint)?.[1] ?? null) : null;
|
||||
const defaultAccountLabel =
|
||||
activeCopilotStatus?.authenticated && activeCopilotStatus.login
|
||||
? activeCopilotStatus.authType === "gh-cli"
|
||||
? tx`Copilot CLI default (${activeCopilotStatus.login} via GitHub CLI)`
|
||||
: tx`Copilot CLI default (${activeCopilotStatus.login})`
|
||||
: activeCopilotStatus && !activeCopilotStatus.authenticated
|
||||
? tx("Copilot CLI default (not signed in)")
|
||||
: tx("Copilot CLI default");
|
||||
const ghAccounts = activeCopilotStatus?.ghAccounts ?? [];
|
||||
const copilotAccountOptions = [
|
||||
{ value: "", label: defaultAccountLabel, verbatim: true },
|
||||
...ghAccounts.map((entry) => ({
|
||||
value: entry.login,
|
||||
label: entry.login,
|
||||
verbatim: true,
|
||||
})),
|
||||
...(account.value && !ghAccounts.some((entry) => entry.login === account.value)
|
||||
? [
|
||||
{
|
||||
value: account.value,
|
||||
label: activeCopilotStatus ? tx`${account.value} (not signed in)` : account.value,
|
||||
verbatim: true,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const copilotSelectedSignedIn =
|
||||
!activeCopilotStatus ||
|
||||
(account.value === ""
|
||||
? activeCopilotStatus.authenticated
|
||||
: activeCopilotStatus.ghInstalled && ghAccounts.some((entry) => entry.login === account.value));
|
||||
const authGate: DefaultsAuthGate =
|
||||
agent.id !== "copilot"
|
||||
? "ready"
|
||||
: fetchCopilotStatus && !activeCopilotStatus && !copilotStatusLoaded
|
||||
? "checking"
|
||||
: !copilotSelectedSignedIn
|
||||
? "unauthenticated"
|
||||
: account.value !== account.current
|
||||
? "pendingApply"
|
||||
: "ready";
|
||||
const accountScope =
|
||||
agent.id === "copilot"
|
||||
? `${account.current || `default:${activeCopilotStatus?.login ?? ""}`}:${authRevision}`
|
||||
: "default";
|
||||
return (
|
||||
<>
|
||||
{value.trim() === current && agent.installed && agent.canCheckCliUpdate && (
|
||||
<LocalCliUpdate key={agent.program} agent={agent} backend={backend} />
|
||||
)}
|
||||
{agent.loginHint && (
|
||||
{agent.id === "copilot" ? (
|
||||
<Section title="Sign In">
|
||||
<p className={styles.text}>
|
||||
<LoginHint text={agent.loginHint} />
|
||||
</p>
|
||||
</Section>
|
||||
)}
|
||||
<Section title="New Tasks">
|
||||
<AgentDefaults agent={agent} backend={backend} />
|
||||
</Section>
|
||||
<Section title="Launch">
|
||||
<div className={styles.form}>
|
||||
{agent.id === "copilot" && (
|
||||
<div className={styles.form}>
|
||||
<Row
|
||||
label={<T>GitHub account</T>}
|
||||
htmlFor={`agent-github-account-${agent.id}`}
|
||||
hint={
|
||||
<T>
|
||||
Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never
|
||||
stores it.
|
||||
GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch
|
||||
and never stored.
|
||||
</T>
|
||||
}
|
||||
>
|
||||
<Input
|
||||
id={`agent-github-account-${agent.id}`}
|
||||
mono
|
||||
value={account.value}
|
||||
disabled={account.saving}
|
||||
placeholder="github-username"
|
||||
onChange={(e) => account.set(e.target.value)}
|
||||
/>
|
||||
<div className={styles.accountField}>
|
||||
<div className={styles.select}>
|
||||
<Select
|
||||
id={`agent-github-account-${agent.id}`}
|
||||
value={account.value}
|
||||
disabled={account.saving}
|
||||
options={copilotAccountOptions}
|
||||
onChange={(nextValue) => account.set(nextValue)}
|
||||
/>
|
||||
</div>
|
||||
{account.value === "" && canSignInInIde && (
|
||||
<Button
|
||||
size="small"
|
||||
variant={activeCopilotStatus && !activeCopilotStatus.authenticated ? "primary" : "secondary"}
|
||||
onClick={() => {
|
||||
pendingAddAccountPrevLogins.current = null;
|
||||
setSignInTarget({ kind: "agent", id: agent.id, name: agent.name });
|
||||
}}
|
||||
>
|
||||
<T>Sign In…</T>
|
||||
</Button>
|
||||
)}
|
||||
{activeCopilotStatus?.ghInstalled && (
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => {
|
||||
pendingAddAccountPrevLogins.current = new Set(ghAccounts.map((entry) => entry.login));
|
||||
setSignInTarget({ kind: "gh" });
|
||||
}}
|
||||
>
|
||||
<T>Add account…</T>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Row>
|
||||
{activeCopilotStatus && !activeCopilotStatus.ghInstalled && (
|
||||
<p className={styles.rowHint}>
|
||||
<T>Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.</T>{" "}
|
||||
<ExternalLink url="https://cli.github.com/" label="Download GitHub CLI…" />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{!agent.installed && agent.loginHint && (
|
||||
<p className={styles.signInHint}>
|
||||
<LoginHint text={agent.loginHint} />
|
||||
</p>
|
||||
)}
|
||||
</Section>
|
||||
) : (
|
||||
(agent.loginHint || canSignInInIde) && (
|
||||
<Section title="Sign In">
|
||||
<div className={styles.signInRow}>
|
||||
{canSignInInIde && (
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
onClick={() => {
|
||||
pendingAddAccountPrevLogins.current = null;
|
||||
setSignInTarget({ kind: "agent", id: agent.id, name: agent.name });
|
||||
}}
|
||||
>
|
||||
<T>Sign In…</T>
|
||||
</Button>
|
||||
)}
|
||||
{agent.loginHint && (
|
||||
<p className={styles.signInHint}>
|
||||
<LoginHint text={agent.loginHint} />
|
||||
{commandSpan && (
|
||||
<IconButton
|
||||
size="small"
|
||||
icon="copy"
|
||||
title="Copy command"
|
||||
onClick={() => void copyText(commandSpan)}
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
)}
|
||||
<Section title="New Tasks">
|
||||
<AgentDefaults agent={agent} backend={backend} authGate={authGate} accountScope={accountScope} />
|
||||
</Section>
|
||||
<Section title="Launch">
|
||||
<div className={styles.form}>
|
||||
<Row label={<T>Command</T>}>
|
||||
<code className={styles.launch} title={launch}>
|
||||
{launch}
|
||||
@@ -1011,6 +1175,45 @@ function ProviderSettings({
|
||||
</p>
|
||||
)}
|
||||
</Section>
|
||||
{signInTarget && (
|
||||
<AgentSignInDialog
|
||||
target={signInTarget}
|
||||
spawner={backend}
|
||||
onClose={() => setSignInTarget(null)}
|
||||
onCompleted={() => {
|
||||
if (signInTarget.kind === "gh") {
|
||||
const prev = pendingAddAccountPrevLogins.current;
|
||||
pendingAddAccountPrevLogins.current = null;
|
||||
void reloadCopilotStatus().then((fresh) => {
|
||||
if (!prev || !fresh) return;
|
||||
const added = fresh.ghAccounts.find((entry) => !prev.has(entry.login));
|
||||
if (added) account.set(added.login);
|
||||
});
|
||||
return;
|
||||
}
|
||||
void refresh().catch((e: unknown) => setError(errorText(e)));
|
||||
onChanged?.();
|
||||
if (agent.id === "copilot") void reloadCopilotStatus();
|
||||
if (backend.refreshModels) {
|
||||
void backend
|
||||
.refreshModels(agent.id, null, true)
|
||||
.then((cat) => {
|
||||
useAgents.setState((s) => {
|
||||
const modelCatalogs = new Map(s.modelCatalogs);
|
||||
modelCatalogs.set(agent.id, cat);
|
||||
return { modelCatalogs };
|
||||
});
|
||||
setAuthRevision((n) => n + 1);
|
||||
})
|
||||
.catch(() => {
|
||||
setAuthRevision((n) => n + 1);
|
||||
});
|
||||
} else {
|
||||
setAuthRevision((n) => n + 1);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1093,23 +1296,90 @@ export function defaultOptions(
|
||||
}
|
||||
|
||||
const MODEL_SETTINGS_POLL_MS = 600;
|
||||
type DefaultsAuthGate = "checking" | "unauthenticated" | "pendingApply" | "ready";
|
||||
|
||||
function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: CommandsBackend }) {
|
||||
const isCatalogAuthError = (message: string | null | undefined): boolean =>
|
||||
!!message && /sign in required|authentication|not authenticated|unauthorized|not logged in/i.test(message);
|
||||
|
||||
function AgentDefaults({
|
||||
agent,
|
||||
backend,
|
||||
authGate,
|
||||
accountScope,
|
||||
}: {
|
||||
agent: AgentProvider;
|
||||
backend: CommandsBackend;
|
||||
authGate: DefaultsAuthGate;
|
||||
accountScope: string;
|
||||
}) {
|
||||
const form = useSettingsForm();
|
||||
const all = (form.useValue("agents.defaults") ?? {}) as Record<string, Record<string, string>>;
|
||||
const newTaskApprovals = (form.useValue("agents.newTaskApprovals") as "bypass" | "ask" | undefined) ?? "bypass";
|
||||
const chosen = all[agent.id] ?? {};
|
||||
const refreshModels = backend.refreshModels;
|
||||
const needsAccountCatalog = agent.id === "copilot" && agent.installed && !!refreshModels;
|
||||
const scopeKey = `${agent.id}:${accountScope}`;
|
||||
|
||||
const storeCatalog = useAgents((s) => s.modelCatalogs.get(agent.id));
|
||||
const [fetchedCatalog, setFetchedCatalog] = useState<AgentModelCatalog | null>(null);
|
||||
const catalog = fetchedCatalog?.provider === agent.id ? fetchedCatalog : storeCatalog;
|
||||
const [accountCatalog, setAccountCatalog] = useState<{ scopeKey: string; catalog: AgentModelCatalog } | null>(null);
|
||||
const [fetchedCatalog, setFetchedCatalog] = useState<{ scopeKey: string; catalog: AgentModelCatalog } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsAccountCatalog || authGate !== "ready" || !refreshModels) return;
|
||||
let live = true;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const next = await refreshModels(agent.id, null);
|
||||
if (!live) return;
|
||||
setAccountCatalog({ scopeKey, catalog: next });
|
||||
if (next.refreshing) {
|
||||
timer = setTimeout(() => void poll(), MODEL_SETTINGS_POLL_MS);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!live) return;
|
||||
setAccountCatalog({
|
||||
scopeKey,
|
||||
catalog: {
|
||||
provider: agent.id,
|
||||
config: [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: null,
|
||||
retryAtMs: null,
|
||||
error: errorText(e),
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
return () => {
|
||||
live = false;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [agent.id, authGate, needsAccountCatalog, refreshModels, scopeKey]);
|
||||
|
||||
const scopedAccountCatalog = accountCatalog?.scopeKey === scopeKey ? accountCatalog.catalog : null;
|
||||
const scopedFetchedCatalog = fetchedCatalog?.scopeKey === scopeKey ? fetchedCatalog.catalog : null;
|
||||
const catalog = scopedFetchedCatalog ?? scopedAccountCatalog ?? (needsAccountCatalog ? undefined : storeCatalog);
|
||||
const effectiveAgent = useMemo<AgentProvider>(() => {
|
||||
if (needsAccountCatalog) {
|
||||
if (!catalog || catalog.refreshedAtMs == null) {
|
||||
return { ...agent, config: [], thoughtLevels: {} };
|
||||
}
|
||||
return {
|
||||
...agent,
|
||||
config: catalog.config,
|
||||
thoughtLevels: catalog.thoughtLevels ?? {},
|
||||
};
|
||||
}
|
||||
if (!catalog) return agent;
|
||||
return {
|
||||
...agent,
|
||||
config: catalog.config.length ? catalog.config : agent.config,
|
||||
thoughtLevels: { ...agent.thoughtLevels, ...catalog.thoughtLevels },
|
||||
};
|
||||
}, [agent, catalog]);
|
||||
}, [agent, catalog, needsAccountCatalog]);
|
||||
const options = defaultOptions(effectiveAgent, chosen, newTaskApprovals);
|
||||
const modelOption = options.find((o) => o.category === "model");
|
||||
const selectedModel = (modelOption && chosen[modelOption.id]) || modelOption?.current || null;
|
||||
@@ -1117,9 +1387,10 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
|
||||
!!selectedModel &&
|
||||
!!modelOption?.values.some((v) => v.value === selectedModel) &&
|
||||
!Object.hasOwn(effectiveAgent.thoughtLevels ?? {}, selectedModel);
|
||||
const refreshModels = backend.refreshModels;
|
||||
const fetchKey =
|
||||
agent.installed && refreshModels && selectedModel && unknownModelSettings ? `${agent.id}:${selectedModel}` : null;
|
||||
authGate === "ready" && agent.installed && refreshModels && selectedModel && unknownModelSettings
|
||||
? `${scopeKey}:${selectedModel}`
|
||||
: null;
|
||||
const [settledKey, setSettledKey] = useState<string | null>(null);
|
||||
const loadingModel = fetchKey !== null && settledKey !== fetchKey;
|
||||
|
||||
@@ -1131,7 +1402,7 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
|
||||
try {
|
||||
const next = await refreshModels(agent.id, selectedModel);
|
||||
if (!live) return;
|
||||
setFetchedCatalog(next);
|
||||
setFetchedCatalog({ scopeKey, catalog: next });
|
||||
if (next.refreshing && !Object.hasOwn(next.thoughtLevels ?? {}, selectedModel)) {
|
||||
timer = setTimeout(() => void poll(), MODEL_SETTINGS_POLL_MS);
|
||||
} else {
|
||||
@@ -1146,8 +1417,42 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
|
||||
live = false;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [agent.id, fetchKey, refreshModels, selectedModel]);
|
||||
}, [agent.id, fetchKey, refreshModels, scopeKey, selectedModel]);
|
||||
|
||||
if (authGate === "checking") {
|
||||
return (
|
||||
<p className={styles.statusNote}>
|
||||
<Spinner size={12} /> <T>Checking sign-in status…</T>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (authGate === "unauthenticated" || isCatalogAuthError(catalog?.error)) {
|
||||
return (
|
||||
<p className={styles.text}>
|
||||
<T>Sign in above to view and choose models available for this account.</T>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (authGate === "pendingApply") {
|
||||
return (
|
||||
<p className={styles.text}>
|
||||
<T>Click Apply to load the models available for the selected account.</T>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (
|
||||
needsAccountCatalog &&
|
||||
(!scopedAccountCatalog || (scopedAccountCatalog.refreshing && scopedAccountCatalog.refreshedAtMs == null))
|
||||
) {
|
||||
return (
|
||||
<p className={styles.statusNote}>
|
||||
<Spinner size={12} /> <T>Loading models for this account…</T>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (needsAccountCatalog && scopedAccountCatalog?.refreshedAtMs == null && scopedAccountCatalog?.error) {
|
||||
return <p className={styles.error}>{scopedAccountCatalog.error}</p>;
|
||||
}
|
||||
if (!options.length)
|
||||
return (
|
||||
<p className={styles.text}>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding: 12px 16px 8px;
|
||||
}
|
||||
|
||||
.terminal {
|
||||
width: 100%;
|
||||
height: 300px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-editor, var(--bg));
|
||||
overflow: hidden;
|
||||
padding: 6px 8px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--fg-error, var(--danger, #d93025));
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Interactive sign-in dialog for coding agents (`copilot login`, `codex login`, `claude`, …)
|
||||
* and GitHub CLI (`gh auth login`), backed by an IDE-managed PTY (`agent_login_spawn` /
|
||||
* `agent_gh_login_spawn`) and a lazily loaded embedded terminal widget.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { AgentLoginEvent, TerminalId } from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { Dialog, Spinner, T } from "@/ui";
|
||||
import { embeddedTerminal, type EmbeddedTerminal } from "@/workbench/contributions";
|
||||
import styles from "./AgentSignInDialog.module.css";
|
||||
import { tauriCommands } from "./registry";
|
||||
|
||||
export type SignInTarget = { kind: "agent"; id: string; name: string } | { kind: "gh" };
|
||||
|
||||
export interface SignInSpawner {
|
||||
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
|
||||
ghLoginSpawn?(cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
|
||||
}
|
||||
|
||||
export function AgentSignInDialog({
|
||||
target,
|
||||
spawner,
|
||||
onClose,
|
||||
onCompleted,
|
||||
}: {
|
||||
target: SignInTarget;
|
||||
spawner?: SignInSpawner;
|
||||
onClose: () => void;
|
||||
onCompleted: () => void;
|
||||
}) {
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const ptyIdRef = useRef<TerminalId | null>(null);
|
||||
const completedRef = useRef(false);
|
||||
const callbacksRef = useRef({ onClose, onCompleted, spawner });
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { onClose, onCompleted, spawner };
|
||||
});
|
||||
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [exitCode, setExitCode] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const targetKind = target.kind;
|
||||
const agentId = target.kind === "agent" ? target.id : "";
|
||||
|
||||
useEffect(() => {
|
||||
const el = hostRef.current;
|
||||
if (!el) return;
|
||||
let disposed = false;
|
||||
let term: EmbeddedTerminal | null = null;
|
||||
const pendingOutput: string[] = [];
|
||||
let pendingSize: { cols: number; rows: number } = { cols: 80, rows: 18 };
|
||||
completedRef.current = false;
|
||||
setExitCode(null);
|
||||
setError(null);
|
||||
|
||||
const killPty = () => {
|
||||
const id = ptyIdRef.current;
|
||||
ptyIdRef.current = null;
|
||||
if (id !== null) void commands.termKill(id).catch(() => {});
|
||||
};
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
// Provided by the terminal feature (workbench windows) or the Settings window's boot.
|
||||
const factory = embeddedTerminal();
|
||||
if (!factory) throw new Error(tx("The terminal is not available in this window."));
|
||||
const instance = await factory(el, {
|
||||
onData: (data) => {
|
||||
const id = ptyIdRef.current;
|
||||
if (id !== null) void commands.termWrite(id, data).catch(() => {});
|
||||
},
|
||||
onResize: (cols, rows) => {
|
||||
pendingSize = { cols, rows };
|
||||
const id = ptyIdRef.current;
|
||||
if (id !== null) void commands.termResize(id, cols, rows).catch(() => {});
|
||||
},
|
||||
});
|
||||
if (disposed) {
|
||||
instance.dispose();
|
||||
return;
|
||||
}
|
||||
term = instance;
|
||||
for (const chunk of pendingOutput.splice(0)) {
|
||||
term.write(chunk);
|
||||
}
|
||||
term.focus();
|
||||
} catch (e) {
|
||||
if (!disposed) setError(e instanceof Error ? e.message : String(e));
|
||||
return;
|
||||
}
|
||||
|
||||
const onEvent = (event: AgentLoginEvent) => {
|
||||
if (disposed) return;
|
||||
if (event.type === "output") {
|
||||
if (term) term.write(event.data);
|
||||
else pendingOutput.push(event.data);
|
||||
} else {
|
||||
ptyIdRef.current = null;
|
||||
const code = event.code ?? -1;
|
||||
setExitCode(code);
|
||||
if (code === 0 && !completedRef.current) {
|
||||
completedRef.current = true;
|
||||
callbacksRef.current.onCompleted();
|
||||
callbacksRef.current.onClose();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const custom = callbacksRef.current.spawner;
|
||||
const ptyId =
|
||||
targetKind === "gh"
|
||||
? await (custom?.ghLoginSpawn ?? tauriCommands.ghLoginSpawn!)(pendingSize.cols, pendingSize.rows, onEvent)
|
||||
: await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)(
|
||||
agentId,
|
||||
pendingSize.cols,
|
||||
pendingSize.rows,
|
||||
onEvent,
|
||||
);
|
||||
if (disposed) {
|
||||
void commands.termKill(ptyId).catch(() => {});
|
||||
return;
|
||||
}
|
||||
ptyIdRef.current = ptyId;
|
||||
void commands.termResize(ptyId, pendingSize.cols, pendingSize.rows).catch(() => {});
|
||||
term?.focus();
|
||||
} catch (e) {
|
||||
if (!disposed) setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
killPty();
|
||||
term?.dispose();
|
||||
};
|
||||
}, [agentId, attempt, targetKind]);
|
||||
|
||||
const running = exitCode === null && !error;
|
||||
const title = target.kind === "gh" ? tx("Sign In to GitHub CLI") : tx`Sign In to ${target.name}`;
|
||||
|
||||
const finishAndClose = () => {
|
||||
const id = ptyIdRef.current;
|
||||
ptyIdRef.current = null;
|
||||
if (id !== null) void commands.termKill(id).catch(() => {});
|
||||
if (!completedRef.current) {
|
||||
completedRef.current = true;
|
||||
onCompleted();
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
const cancelAndClose = () => {
|
||||
const id = ptyIdRef.current;
|
||||
ptyIdRef.current = null;
|
||||
if (id !== null) void commands.termKill(id).catch(() => {});
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
blockWorkbenchShortcuts
|
||||
onClose={cancelAndClose}
|
||||
title={title}
|
||||
width={640}
|
||||
footerStart={
|
||||
running ? (
|
||||
<span className={styles.status}>
|
||||
<Spinner size={12} /> <T>Complete sign-in in your browser or the terminal above…</T>
|
||||
</span>
|
||||
) : exitCode !== null && exitCode !== 0 ? (
|
||||
<span className={styles.error}>{tx`Sign-in exited with code ${exitCode}.`}</span>
|
||||
) : undefined
|
||||
}
|
||||
buttons={
|
||||
running
|
||||
? [
|
||||
{ label: "Done", onClick: finishAndClose },
|
||||
{ label: "Cancel", role: "cancel", onClick: cancelAndClose },
|
||||
]
|
||||
: [
|
||||
{ label: "Retry", role: "default", onClick: () => setAttempt((n) => n + 1) },
|
||||
{ label: "Close", role: "cancel", onClick: cancelAndClose },
|
||||
]
|
||||
}
|
||||
>
|
||||
<div className={styles.body}>
|
||||
<div ref={hostRef} className={styles.terminal} data-autofocus />
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1071,6 +1071,12 @@
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.errorContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.working {
|
||||
display: flex;
|
||||
|
||||
@@ -2,8 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type {
|
||||
AcpImportOutcome,
|
||||
AgentLoginEvent,
|
||||
AgentProvider,
|
||||
AgentRegistry,
|
||||
CopilotAuthStatus,
|
||||
InstallEvent,
|
||||
RegistryAgent,
|
||||
RequestId,
|
||||
@@ -13,7 +15,7 @@ import { setLocale, tx } from "@/platform/i18n";
|
||||
import { iconMarkup } from "@/ui/icons";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import { AgentRegistryPage as RegistryPage } from "./AgentRegistryPage";
|
||||
import { SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
|
||||
import { provideEmbeddedTerminal, SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
|
||||
import { useSettingsFormFor } from "@/features/settings/components/context";
|
||||
import { closeSettings, openSettings, selectPage } from "@/features/settings/model/staging";
|
||||
import { SettingsDialog } from "@/features/settings/dialog/SettingsDialog";
|
||||
@@ -419,6 +421,10 @@ class FakeCommands implements CommandsBackend {
|
||||
list: AgentProvider[] = [];
|
||||
saved: [string, string | null][] = [];
|
||||
providers = vi.fn(async () => this.list);
|
||||
copilotAuthStatus?: () => Promise<CopilotAuthStatus>;
|
||||
loginSpawn?: CommandsBackend["loginSpawn"];
|
||||
ghLoginSpawn?: CommandsBackend["ghLoginSpawn"];
|
||||
refreshModels?: CommandsBackend["refreshModels"];
|
||||
chooseExecutable = vi.fn(async () => "/chosen/agent");
|
||||
saveCustom = vi.fn(async () => {});
|
||||
setAdditionalArgs = vi.fn<CommandsBackend["setAdditionalArgs"]>();
|
||||
@@ -608,8 +614,19 @@ describe("Built-in executable overrides", () => {
|
||||
expect(commands.savedEnv.at(-1)).toEqual(["claude", {}]);
|
||||
});
|
||||
|
||||
it("writes a Copilot GitHub account without storing a token or exposing the control variable", async () => {
|
||||
it("writes a Copilot GitHub account from the dropdown without storing a token or exposing the control variable", async () => {
|
||||
const commands = new FakeCommands();
|
||||
commands.copilotAuthStatus = vi.fn(async () => ({
|
||||
authenticated: true,
|
||||
login: "alice",
|
||||
authType: "gh-cli",
|
||||
statusMessage: "alice (via gh)",
|
||||
ghInstalled: true,
|
||||
ghAccounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
}));
|
||||
commands.list = [
|
||||
{
|
||||
...claudeProvider("copilot"),
|
||||
@@ -622,9 +639,16 @@ describe("Built-in executable overrides", () => {
|
||||
},
|
||||
];
|
||||
await openCommands(commands, vi.fn(), "GitHub Copilot");
|
||||
const account = screen.getByRole("textbox", { name: "GitHub account" });
|
||||
const signInSection = screen.getByRole("region", { name: "Sign In" });
|
||||
const launchSection = screen.getByRole("region", { name: "Launch" });
|
||||
const account = await within(signInSection).findByRole("button", { name: "GitHub account" });
|
||||
expect(within(launchSection).queryByRole("button", { name: "GitHub account" })).toBeNull();
|
||||
await waitFor(() => expect(account).toHaveTextContent("Copilot CLI default (alice via GitHub CLI)"));
|
||||
expect(screen.queryByRole("textbox", { name: "Environment variables" })).toBeNull();
|
||||
fireEvent.change(account, { target: { value: "dengliu_microsoft" } });
|
||||
fireEvent.click(account);
|
||||
fireEvent.click(await screen.findByRole("option", { name: "alice-work" }));
|
||||
expect(account).toHaveTextContent("alice-work");
|
||||
expect(screen.getByText("Click Apply to load the models available for the selected account.")).toBeInTheDocument();
|
||||
|
||||
await act(async () => fireEvent.click(apply()));
|
||||
|
||||
@@ -633,13 +657,210 @@ describe("Built-in executable overrides", () => {
|
||||
"copilot",
|
||||
{
|
||||
COPILOT_TELEMETRY_OPTOUT: "1",
|
||||
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "dengliu_microsoft",
|
||||
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "alice-work",
|
||||
},
|
||||
],
|
||||
]);
|
||||
expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i);
|
||||
});
|
||||
|
||||
it("hides stale Copilot models until authenticated and reloads per-account models after Apply", async () => {
|
||||
const staleModel: AgentProvider["config"][number] = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "gemini-4-neon",
|
||||
values: [
|
||||
{ value: "gemini-4-neon", name: "Gemini 4 Neon", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
via: "option",
|
||||
};
|
||||
const personalModel: AgentProvider["config"][number] = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "claude-sonnet-4.5",
|
||||
values: [
|
||||
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
via: "option",
|
||||
};
|
||||
const commands = new FakeCommands();
|
||||
commands.copilotAuthStatus = vi.fn(async () => ({
|
||||
authenticated: false,
|
||||
login: null,
|
||||
authType: null,
|
||||
statusMessage: null,
|
||||
ghInstalled: true,
|
||||
ghAccounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
}));
|
||||
commands.refreshModels = vi.fn(async () => {
|
||||
const currentAccount = commands.list[0]?.env.OPENIDEA_COPILOT_GITHUB_ACCOUNT ?? "";
|
||||
return {
|
||||
provider: "copilot",
|
||||
config: [currentAccount === "alice-work" ? staleModel : personalModel],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
};
|
||||
});
|
||||
commands.list = [
|
||||
{
|
||||
...claudeProvider("copilot"),
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
defaultProgram: "copilot",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
commandReadOnlyReason: "registry",
|
||||
config: [staleModel],
|
||||
},
|
||||
];
|
||||
await openCommands(commands, vi.fn(), "GitHub Copilot");
|
||||
|
||||
// Signed-out default account never leaks cached models from a previous session/account.
|
||||
await screen.findByText("Sign in above to view and choose models available for this account.");
|
||||
expect(screen.queryByRole("button", { name: "Model" })).toBeNull();
|
||||
|
||||
// Selecting `alice` stages the switch and asks for Apply before showing models.
|
||||
const account = screen.getByRole("button", { name: "GitHub account" });
|
||||
fireEvent.click(account);
|
||||
fireEvent.click(await screen.findByRole("option", { name: "alice" }));
|
||||
expect(screen.getByText("Click Apply to load the models available for the selected account.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Model" })).toBeNull();
|
||||
|
||||
// Applying loads `alice`'s subscription models.
|
||||
await act(async () => fireEvent.click(apply()));
|
||||
const modelButton = await screen.findByRole("button", { name: "Model" });
|
||||
expect(modelButton).toHaveTextContent("Agent's default (Claude Sonnet 4.5)");
|
||||
|
||||
// Switching to `alice-work` and applying loads its own subscription models.
|
||||
fireEvent.click(screen.getByRole("button", { name: "GitHub account" }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: "alice-work" }));
|
||||
expect(screen.queryByRole("button", { name: "Model" })).toBeNull();
|
||||
await act(async () => fireEvent.click(apply()));
|
||||
expect(await screen.findByRole("button", { name: "Model" })).toHaveTextContent("Agent's default (Gemini 4 Neon)");
|
||||
});
|
||||
|
||||
it("runs in-IDE Sign In and Add account PTY dialogs and selects the newly added gh account", async () => {
|
||||
const written: string[] = [];
|
||||
provideEmbeddedTerminal(async () => ({
|
||||
write: (d) => written.push(d),
|
||||
clear: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
fit: vi.fn(),
|
||||
dispose: vi.fn(),
|
||||
}));
|
||||
let onLoginEvent: ((e: AgentLoginEvent) => void) | null = null;
|
||||
try {
|
||||
const commands = new FakeCommands();
|
||||
commands.loginSpawn = vi.fn(async (_id, _cols, _rows, cb) => {
|
||||
onLoginEvent = cb;
|
||||
return 101;
|
||||
});
|
||||
commands.ghLoginSpawn = vi.fn(async (_cols, _rows, cb) => {
|
||||
onLoginEvent = cb;
|
||||
return 102;
|
||||
});
|
||||
const refreshModels = vi.fn().mockResolvedValue({
|
||||
provider: "copilot",
|
||||
config: [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
});
|
||||
commands.refreshModels = refreshModels;
|
||||
commands.copilotAuthStatus = vi
|
||||
.fn<() => Promise<CopilotAuthStatus>>()
|
||||
.mockResolvedValueOnce({
|
||||
authenticated: false,
|
||||
login: null,
|
||||
authType: null,
|
||||
statusMessage: null,
|
||||
ghInstalled: true,
|
||||
ghAccounts: [{ login: "alice", active: true }],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
authenticated: true,
|
||||
login: "alice",
|
||||
authType: "oauth",
|
||||
statusMessage: "alice",
|
||||
ghInstalled: true,
|
||||
ghAccounts: [{ login: "alice", active: true }],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
authenticated: true,
|
||||
login: "alice",
|
||||
authType: "oauth",
|
||||
statusMessage: "alice",
|
||||
ghInstalled: true,
|
||||
ghAccounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
});
|
||||
commands.list = [
|
||||
{
|
||||
...claudeProvider("copilot"),
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
defaultProgram: "copilot",
|
||||
loginHint: "Run `copilot login` in a terminal.",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
commandReadOnlyReason: "registry",
|
||||
},
|
||||
];
|
||||
await openCommands(commands, vi.fn(), "GitHub Copilot");
|
||||
|
||||
// 1) Agent Sign In dialog (`copilot login`)
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Sign In…" }));
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(commands.loginSpawn).toHaveBeenCalledWith(
|
||||
"copilot",
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
expect.any(Function),
|
||||
),
|
||||
);
|
||||
act(() => {
|
||||
onLoginEvent?.({ type: "output", data: "Opening browser…\r\n" });
|
||||
onLoginEvent?.({ type: "exited", code: 0 });
|
||||
});
|
||||
expect(written).toContain("Opening browser…\r\n");
|
||||
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeNull());
|
||||
expect(refreshModels).toHaveBeenCalledWith("copilot", null, true);
|
||||
|
||||
// 2) Add GitHub CLI account (`gh auth login`) auto-selects newly added account
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Add account…" }));
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(commands.ghLoginSpawn).toHaveBeenCalled());
|
||||
act(() => {
|
||||
onLoginEvent?.({ type: "exited", code: 0 });
|
||||
});
|
||||
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeNull());
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "GitHub account" })).toHaveTextContent("alice-work"),
|
||||
);
|
||||
} finally {
|
||||
provideEmbeddedTerminal(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("Cancel discards command edits without writing", async () => {
|
||||
const commands = new FakeCommands();
|
||||
commands.list = [
|
||||
|
||||
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача