Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 43163e3fd6 perf(agents): stop a running task's Changes tab from reloading every diff on each update
While a task runs, it is published again with every token count. The Changes tab rebuilt its
diff items from the whole task object, so each update re-read the base text of every changed
file over IPC, hashed all of them, and handed the view a new array that rendered every mounted
diff block and every row of the file tree again. The diffs now depend only on the task fields
they use (id, base, isolation, branch, cwd), an unchanged list keeps its array, and the file
tree is memoized. The all-in-one diff also works out each diff's key once per list instead of
hashing every file's text on every scroll frame (autosave off).
2026-11-27 09:49:24 +08:00
Nguyen Thinh 3240164840 feat(database): warn before running a statement that changes a whole table (#1496)
Before the SQL console runs a statement that changes or clears a whole table (a DELETE or UPDATE without WHERE, and similar cases), it shows a warning banner with Execute, Execute and Suppress (no more warnings in this console) and close; nothing runs until the user chooses. The statement also gets a squiggle, a gutter icon and a hover. The check runs on the text after parameter substitution, and works with the console's streaming execution.

Co-authored-by: kidp2h <[email protected]>
2026-11-27 09:39:21 +08:00
l0ng-ai f70f362a3d feat(ui): open New Project, Get from VCS and Remote Development in their own windows (#6208)
* feat(ui): open New Project, Get from VCS and Remote Development in their own windows

Each dialog gets a native window over its project window: a full-height
sidebar under the traffic lights, the title heading the content and the
buttons in its corner. The windows hand their result back to the project
window, which opens the created or cloned project or makes the remote
connection and reports its progress. Remote windows and the browser build
keep the dialogs in the page.

* feat(ui): show dialogs in the page as sheets without window buttons on macOS

The title heads the content instead of a title bar with drawn traffic
lights; Esc and Cancel close the dialog, and the title dims while the
window is inactive.

* fix(ui): give a macOS dialog without footer buttons a Close button

A sheet has no window buttons, so a dialog with neither buttons nor a
footer could only be closed with Esc. The Extract Interface members
table may shrink to two rows so the dialog still fits a short window
under the taller sheet title.
2026-11-27 08:59:33 +08:00
l0ng-ai 806bb4c78d ci(homebrew): push the cask to the tap with a deploy key (#6205) 2026-11-27 08:59:26 +08:00
Mansur Akhmadiтаmansur-akhmadi 57094bc285 feat(run): Track Running Test in Test Runner Options (#6285)
Test Runner Options gets Track Running Test (also in Find Action as run.toggleTrackRunningTest), remembered with the other test tree options and on by default. While a run is in progress, each test that starts is selected, its collapsed suites opened and its output shown; when several start together the last in tree order wins. A test finishing doesn't move the selection, so a test picked by hand stays selected until the next one starts, and focus doesn't move.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 08:18:37 +08:00
Deng Liuтаdengliu a5e0c41663 feat(github): add project-scoped GitHub CLI account selection (#6277)
A project can pin a GitHub CLI account in vcs.github.account (.openidea/settings.toml, a login, never a token), chosen in Settings > Version Control > GitHub or from the Pull Requests tool window header. With an account chosen, its token is resolved through gh and set as GH_TOKEN in the project environment for the project root and its agent worktrees; a .envrc GH_TOKEN still wins, and the token is cleared when the project closes or loses trust. Copilot keeps billing to its own account through COPILOT_GITHUB_TOKEN.

Automatic (the default) sets no GH_TOKEN and makes no GitHub calls on project open. When the settings page or the Pull Requests window asks for the status with several gh accounts signed in, the project's GitHub remote is probed to suggest a non-active account with access ("Use <login> for this project").

New commands: gh_project_account_status, gh_set_project_account. The gh account listing is shared with the Copilot account selector.

Co-authored-by: dengliu <[email protected]>
2026-11-27 08:16:10 +08:00
audichuang 77071238a0 fix(gradle): keep absolute owner for synced builds outside the project (#6260)
After a Gradle sync, an included build outside the project root (includeBuild('../svc')) was missing from Find in Files > Module: with_gradle_roots stamped plain Gradle as its owner, which the UI reads as the project root. Such builds now keep their absolute owner (<dir>/Gradle), which projectModules, the Module scope and changeModules already treat as an absolute module.

An ancestor of the opened folder (opening composite/app while Gradle reports composite) and a filesystem or drive root keep plain Gradle, so they can't claim every in-project file. Reported project dirs are canonicalized like the opened root, and moduleOf also recognises drive-letter module paths.

Co-authored-by: audichuang <[email protected]>
2026-11-27 07:56:28 +08:00
Deng Liuтаdengliu 64097d3c20 feat(agents): unify Copilot GitHub account selector and gate models on auth (#6269)
Copilot's Sign In notice and the free-text Launch > GitHub account field become one Sign In section: a GitHub account selector listing Copilot CLI's own default login (with its status from auth.getStatus) and the github.com accounts signed in to GitHub CLI (gh auth status, ignoring ambient token variables), plus Sign In... and an in-IDE Add account... that runs gh auth login in the sign-in dialog and selects the new account.

New Tasks model controls wait until the selected account is signed in and applied, and load that account's model catalog instead of showing a cached one from another account or subscription; changing the account evicts the idle Copilot catalog probe.

New commands: agent_copilot_auth_status, agent_gh_login_spawn.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:34:47 +08:00
Deng Liuтаdengliu cf0e57e5df fix(agents): advance history batching past long folded process runs (#6278)
A session's history paints from the end in batches of ENTRY_BATCH, and the first painted entry moves back over a leading run of tool calls so a folded process row is never split. Since all consecutive tool calls fold into one run, a run longer than a batch made the next batch end inside the same run, so start never moved: the background batches and loading earlier messages at the top both stalled, and earlier turns never appeared (also after a hidden tab trimmed its history).

The next batch now steps past what is actually painted. A conversation scrolled away from the end also keeps loading while its rows don't fill the viewport or it sits near the top.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:20:55 +08:00
l0ng-ai 703cf23296 fix(workspace): don't let refactoring undo overwrite an external write under an unsaved buffer (#6281)
Fingerprints hash an unsaved buffer in place of its file, so a file another
program wrote after a refactoring went unnoticed while its buffer had unsaved
changes, and undo (or redo) wrote the snapshot over it.

Each document now counts the disk conflicts it has seen (external writes while
the buffer had unsaved changes). The undo record keeps the counts as of the
refactoring; undo and redo first check unsaved buffers' files for a write the
watcher hasn't reported yet, then refuse when a count moved. The IDE's own
saves don't count, so saving and undoing typing before undoing the refactoring
still works, and a conflict from before the refactoring doesn't block it.

Fixes #6264
2026-11-27 07:16:02 +08:00
113 змінених файлів з 6093 додано та 804 видалено

No files matched your search

+7 -6
Переглянути файл
@@ -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'
+1 -1
Переглянути файл
@@ -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
+1 -1
Переглянути файл
@@ -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;
+51 -2
Переглянути файл
@@ -33,7 +33,7 @@ pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
pub use model::*;
pub use provider::LoginLaunch;
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
@@ -69,6 +69,34 @@ pub fn login_launch_without_project(
.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>;
@@ -804,6 +832,11 @@ 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());
@@ -853,6 +886,20 @@ impl AgentManager {
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<()> {
@@ -875,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.
+20
Переглянути файл
@@ -650,6 +650,26 @@ 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")]
+73 -1
Переглянути файл
@@ -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>,
+212 -21
Переглянути файл
@@ -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;
@@ -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);
@@ -268,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);
@@ -303,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)
}
@@ -311,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`:
@@ -333,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(
@@ -1251,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();
@@ -1265,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));
}
@@ -1550,6 +1700,47 @@ mod tests {
);
}
#[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();
+124 -11
Переглянути файл
@@ -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());
}
}
+12
Переглянути файл
@@ -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(),
}
}
}
+340
Переглянути файл
@@ -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);
}
}
+2
Переглянути файл
@@ -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 {
+39 -4
Переглянути файл
@@ -8,9 +8,9 @@ use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
RemoteSkillPreview, SkillsPolicy,
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,7 +108,21 @@ pub fn agent_set_env(
host.project(window)?.agents.set_builtin_env(&id, env)
}
pub(crate) fn spawn_login_pty(
/// 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,
@@ -175,6 +189,25 @@ pub async fn agent_login_spawn(
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)?;
@@ -1530,12 +1563,14 @@ 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,
+53
Переглянути файл
@@ -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,
+115 -6
Переглянути файл
@@ -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)]
+7
Переглянути файл
@@ -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();
+2
Переглянути файл
@@ -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
+8
Переглянути файл
@@ -24,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>
+1
Переглянути файл
@@ -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.
+2
Переглянути файл
@@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
+3
Переглянути файл
@@ -21,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>
+1
Переглянути файл
@@ -51,6 +51,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
- 双击、按 `Enter` 或 `F4` 跳到测试源码(**跳转到源代码**)。
- **显示已通过** 和 **显示已忽略** 用于筛选测试树。默认隐藏已通过的测试,筛选状态会被记住。
- **⋯ › 测试运行器选项 › 完成后选中第一个失败的测试** 会在运行结束时选中第一个失败的测试并显示它的输出。默认关闭。
- **⋯ › 测试运行器选项 › 跟踪正在运行的测试** 会在运行过程中,每个测试开始时选中它并显示它的输出。默认开启。
- 右键单个测试或多选后,可以 **运行 '…'**、**调试 '…'** 或 **跳转到源代码**。
- 对于带有期望值和实际值的断言失败,**显示差异** 会把两者并排对比。
- 对于 Jest 或 Vitest 的快照不匹配,**更新快照**(在测试或其文件、套件上,失败输出上方,以及边栏运行菜单中)只用 `-u` 重新运行这些测试,只改写它们的快照。
+164
Переглянути файл
@@ -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",
},
},
]);
});
+45
Переглянути файл
@@ -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();
});
+14 -14
Переглянути файл
@@ -30,15 +30,15 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
agent_registry_list: () => ({ agents: [], warning: null }),
agent_providers: () => {
const provider: AgentProvider = {
id: "copilot",
name: "GitHub Copilot",
command: "copilot --headless --no-auto-update --stdio",
program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot",
args: ["--headless", "--no-auto-update", "--stdio"],
defaultProgram: "copilot",
defaultArgs: ["--headless", "--no-auto-update", "--stdio"],
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/copilot/1.0.116/copilot' login` in a terminal.",
"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",
@@ -49,12 +49,12 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
config: signedIn ? [model] : [],
thoughtLevels: {},
commands: [],
source: { kind: "registry", version: "1.0.116", update: null },
source: { kind: "registry", version: "1.0.0", update: null },
};
return [provider];
},
agent_refresh_models: () => ({
provider: "copilot",
provider: "claude",
config: signedIn ? [model] : [],
thoughtLevels: {},
refreshing: false,
@@ -64,11 +64,11 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
}),
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
setTimeout(() => {
window.__ipc.send(onEvent, { type: "output", data: "Opening GitHub in browser...\r\n" });
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: "copilot" };
return { id: 1, pid: 1001, title: "claude" };
},
term_resize: () => null,
term_write: () => null,
@@ -82,7 +82,7 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
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 GitHub Copilot" })).toHaveCount(0);
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(["copilot"]);
expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["claude"]);
});
+52
Переглянути файл
@@ -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" }]);
});
+12 -1
Переглянути файл
@@ -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",
+12 -1
Переглянути файл
@@ -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"]
}
+6 -1
Переглянути файл
@@ -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)]
+40 -1
Переглянути файл
@@ -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,
+107 -8
Переглянути файл
@@ -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,
}
}
}
@@ -2129,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) {
@@ -3276,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}");
}
@@ -3305,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 }),
@@ -3374,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");
}
+7
Переглянути файл
@@ -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,6 +20,7 @@ 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
@@ -316,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
@@ -863,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
+15
Переглянути файл
@@ -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;
}
}
}
+74
Переглянути файл
@@ -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,6 +71,11 @@ 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. */
@@ -788,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. */
@@ -2380,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.
@@ -2413,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.
@@ -2477,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
@@ -4994,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;
@@ -7683,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. */
@@ -7694,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,
@@ -7824,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,
@@ -9445,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. */
@@ -9476,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";
@@ -14563,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". */
+20
Переглянути файл
@@ -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;
}
+16
Переглянути файл
@@ -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;
}
+23
Переглянути файл
@@ -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;
+20 -4
Переглянути файл
@@ -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 {
+37
Переглянути файл
@@ -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();
});
});
+1 -1
Переглянути файл
@@ -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);
+16
Переглянути файл
@@ -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);
@@ -306,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;
+300 -56
Переглянути файл
@@ -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,
@@ -878,6 +879,41 @@ function ProviderSettings({
});
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(() => {
@@ -892,65 +928,155 @@ function ProviderSettings({
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 || canSignInInIde) && (
{agent.id === "copilot" ? (
<Section title="Sign In">
<div className={styles.signInRow}>
{canSignInInIde && (
<Button
size="small"
variant="primary"
onClick={() => 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} />
</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}
@@ -1055,19 +1181,35 @@ function ProviderSettings({
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) =>
.then((cat) => {
useAgents.setState((s) => {
const modelCatalogs = new Map(s.modelCatalogs);
modelCatalogs.set(agent.id, cat);
return { modelCatalogs };
}),
)
.catch(() => {});
});
setAuthRevision((n) => n + 1);
})
.catch(() => {
setAuthRevision((n) => n + 1);
});
} else {
setAuthRevision((n) => n + 1);
}
}}
/>
@@ -1154,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;
@@ -1178,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;
@@ -1192,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 {
@@ -1207,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}>
+18 -12
Переглянути файл
@@ -1,6 +1,7 @@
/**
* Interactive sign-in dialog for coding agents (`copilot login`, `codex login`, `claude`, …),
* backed by an IDE-managed PTY (`agent_login_spawn`) and a lazily loaded embedded terminal widget.
* 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";
@@ -11,10 +12,11 @@ import { embeddedTerminal, type EmbeddedTerminal } from "@/workbench/contributio
import styles from "./AgentSignInDialog.module.css";
import { tauriCommands } from "./registry";
export type SignInTarget = { kind: "agent"; id: string; name: string };
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({
@@ -40,7 +42,8 @@ export function AgentSignInDialog({
const [exitCode, setExitCode] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const agentId = target.id;
const targetKind = target.kind;
const agentId = target.kind === "agent" ? target.id : "";
useEffect(() => {
const el = hostRef.current;
@@ -108,12 +111,15 @@ export function AgentSignInDialog({
try {
const custom = callbacksRef.current.spawner;
const ptyId = await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)(
agentId,
pendingSize.cols,
pendingSize.rows,
onEvent,
);
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;
@@ -131,10 +137,10 @@ export function AgentSignInDialog({
killPty();
term?.dispose();
};
}, [agentId, attempt]);
}, [agentId, attempt, targetKind]);
const running = exitCode === null && !error;
const title = tx`Sign In to ${target.name}`;
const title = target.kind === "gh" ? tx("Sign In to GitHub CLI") : tx`Sign In to ${target.name}`;
const finishAndClose = () => {
const id = ptyIdRef.current;
+161 -5
Переглянути файл
@@ -5,6 +5,7 @@ import type {
AgentLoginEvent,
AgentProvider,
AgentRegistry,
CopilotAuthStatus,
InstallEvent,
RegistryAgent,
RequestId,
@@ -420,7 +421,9 @@ 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 () => {});
@@ -611,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"),
@@ -625,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()));
@@ -636,14 +657,102 @@ 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("runs in-IDE Sign In PTY dialog and refreshes the agent's model catalog on exit", async () => {
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),
@@ -659,6 +768,10 @@ describe("Built-in executable overrides", () => {
onLoginEvent = cb;
return 101;
});
commands.ghLoginSpawn = vi.fn(async (_cols, _rows, cb) => {
onLoginEvent = cb;
return 102;
});
const refreshModels = vi.fn().mockResolvedValue({
provider: "copilot",
config: [],
@@ -669,6 +782,35 @@ describe("Built-in executable overrides", () => {
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"),
@@ -683,6 +825,8 @@ describe("Built-in executable overrides", () => {
},
];
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(() =>
@@ -700,6 +844,18 @@ describe("Built-in executable overrides", () => {
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);
}
+85
Переглянути файл
@@ -255,4 +255,89 @@ describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () =
// The one request in the trimmed part of the history is found.
expect(await screen.findByText("1/1", {}, { timeout: 10_000 })).toBeInTheDocument();
});
it("paints earlier messages past folded process runs longer than ENTRY_BATCH on open and after hiding", async () => {
const toolCalls = (prefix: string, count: number): AgentEntry[] =>
Array.from({ length: count }, (_, k): AgentEntry => ({
type: "tool",
id: `${prefix}-${k}`,
title: `Read src/file${k}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
}));
const longRuns: AgentEntry[] = [
...history(5),
{ type: "user", text: "Split the PR", attachments: [], sentMs: null },
...toolCalls("first-run", 75),
{ type: "agent", text: "Interim update" },
...toolCalls("second-run", 75),
];
useAgents.setState({
tasks: new Map([[task("A").id, { ...task("A"), status: "running" }]]),
entries: new Map([["A", longRuns]]),
});
const view = render(session(true));
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Split the PR")).toBeInTheDocument();
vi.useFakeTimers();
view.rerender(session(false));
await act(async () => {
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
expect(screen.queryByText("Request 0")).toBeNull();
vi.useRealTimers();
view.rerender(session(true));
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Split the PR")).toBeInTheDocument();
});
it("loads earlier messages past a long process run when scrolled to the top with stick disabled", async () => {
const longRun: AgentEntry[] = [
...history(3),
{ type: "user", text: "Prompt before long run", attachments: [], sentMs: null },
...Array.from({ length: 75 }, (_, k): AgentEntry => ({
type: "tool",
id: `top-run-${k}`,
title: `Read src/mod${k}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
})),
{ type: "agent", text: "Tail reply" },
];
useAgents.setState({ entries: new Map([["A", longRun]]) });
// Suppress background auto-follow after initial render by scrolling away before history finishes.
const view = render(session(true));
await settle("Tail reply");
vi.useFakeTimers();
view.rerender(session(false));
await act(async () => {
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
expect(screen.queryByText("Request 0")).toBeNull();
// User switches back while holding pointer down, then scrolls to the top (`stick: false`).
fireEvent.pointerDown(stream());
view.rerender(session(true));
const el = stream();
layOut(el);
fireEvent.wheel(el, { deltaY: -120 });
el.scrollTop = 0;
fireEvent.scroll(el);
fireEvent.pointerUp(window);
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000);
});
vi.useRealTimers();
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Prompt before long run")).toBeInTheDocument();
});
});
+10
Переглянути файл
@@ -11,6 +11,7 @@ import type {
AgentModelCatalog,
AgentProvider,
AgentRegistry,
CopilotAuthStatus,
CustomAgentInput,
InstallEvent,
RegistryAgent,
@@ -34,7 +35,9 @@ export interface CommandsBackend {
updateCli(id: string, offer: AgentCliOffer, request: RequestId): Promise<AgentCliUpdateResult>;
cancel(request: RequestId): void;
providers(): Promise<AgentProvider[]>;
copilotAuthStatus?(): Promise<CopilotAuthStatus>;
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
ghLoginSpawn?(cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
refreshModels?(id: string, model: string | null, force?: boolean): Promise<AgentModelCatalog>;
set(id: string, command: string | null): Promise<void>;
setAdditionalArgs(id: string, args: string[]): Promise<void>;
@@ -64,12 +67,19 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
copilotAuthStatus: () => call(commands.agentCopilotAuthStatus()),
loginSpawn: async (id, cols, rows, onEvent) => {
const channel = new Channel<AgentLoginEvent>();
channel.onmessage = onEvent;
const info = await call(commands.agentLoginSpawn(id, cols, rows, channel));
return info.id;
},
ghLoginSpawn: async (cols, rows, onEvent) => {
const channel = new Channel<AgentLoginEvent>();
channel.onmessage = onEvent;
const info = await call(commands.agentGhLoginSpawn(cols, rows, channel));
return info.id;
},
refreshModels: (id, model, force = false) => call(commands.agentRefreshModels(id, force, model)),
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
+119 -102
Переглянути файл
@@ -339,109 +339,120 @@ function TaskChanges({ task, tabKey }: { task: AgentTask; tabKey: string }) {
});
}
};
const items = useDiffItems(task, rows, grouped, scope);
// Running, the task is published again with every token count: its diffs only need these fields.
const { id: taskId, base, isolation, branch, cwd } = task;
const diffTask = useMemo(
() => ({ id: taskId, base, isolation, branch, cwd }),
[taskId, base, isolation, branch, cwd],
);
const items = useDiffItems(diffTask, rows, grouped, scope);
const diff = useRef<CombinedDiffHandle>(null);
const busy = task.status === "starting" || task.status === "running";
const fileTree =
changes === null ? (
<Spinner />
) : (
<Tree<ChangeRow>
key={view}
aria-label="Changed files"
roots={rows}
getKey={(n) => n.key}
getLabel={(n) =>
n.type === "file"
? basename(n.change.path)
: n.type === "commit"
? n.commit.summary
: n.type === "repo"
? basename(n.root)
: n.label
}
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
activateExpandable={(n) => n.type === "commit"}
selected={selected}
onSelectionChange={(sel, lead) => {
if (lead?.type === "file" && !lead.commit) setSelected(sel);
// The diff follows the tree: a row shows its first file.
const first = lead && firstFile(lead);
if (first) diff.current?.reveal(first);
}}
onActivate={(n) => {
const first = firstFile(n);
if (first) diff.current?.reveal(first);
}}
renderNode={(n) => {
if (n.type === "group") {
// Memoized like the diffs: a task update (every token count while it runs) mustn't render every row again.
const loading = changes === null;
const fileTree = useMemo(
() =>
loading ? (
<Spinner />
) : (
<Tree<ChangeRow>
key={view}
aria-label="Changed files"
roots={rows}
getKey={(n) => n.key}
getLabel={(n) =>
n.type === "file"
? basename(n.change.path)
: n.type === "commit"
? n.commit.summary
: n.type === "repo"
? basename(n.root)
: n.label
}
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
activateExpandable={(n) => n.type === "commit"}
selected={selected}
onSelectionChange={(sel, lead) => {
if (lead?.type === "file" && !lead.commit) setSelection({ view, keys: sel });
// The diff follows the tree: a row shows its first file.
const first = lead && firstFile(lead);
if (first) diff.current?.reveal(first);
}}
onActivate={(n) => {
const first = firstFile(n);
if (first) diff.current?.reveal(first);
}}
renderNode={(n) => {
if (n.type === "group") {
return (
<span className={styles.changeGroup}>
<span className={styles.changeGroupName}>
{n.label === "Uncommitted" ? <T>Uncommitted</T> : <T>Committed</T>}
</span>
<span className={styles.muted}>
{n.label === "Committed"
? tx(n.count === 1 ? "1 commit" : "{count} commits").replace("{count}", String(n.count))
: `${n.count} ${tx(n.count === 1 ? "file" : "files")}`}
</span>
<span className={styles.changeStat}>
{n.added > 0 && <span className={styles.added}>+{n.added}</span>}{" "}
{n.removed > 0 && <span className={styles.removed}>−{n.removed}</span>}
</span>
</span>
);
}
if (n.type === "repo") {
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
const stats = statsOf(files);
return (
<span className={styles.changeGroup} title={n.root}>
<Icon name="folder" size={14} />
<span className={styles.changeGroupName}>{basename(n.root)}</span>
<span className={styles.muted}>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
<span className={styles.changeStat}>
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
</span>
</span>
);
}
if (n.type === "commit") {
const stats = statsOf(n.commit.files);
return (
<span className={styles.changeCommit} title={n.commit.message}>
<Icon name="commit" size={14} />
<span className={styles.changeCommitHash}>{n.commit.shortId}</span>
<span className={styles.changeCommitSummary}>{n.commit.summary}</span>
{n.commit.timeMs != null && (
<span className={styles.changeCommitTime}>{formatSentAt(n.commit.timeMs)}</span>
)}
<span className={styles.changeStat}>
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
</span>
</span>
);
}
return (
<span className={styles.changeGroup}>
<span className={styles.changeGroupName}>
{n.label === "Uncommitted" ? <T>Uncommitted</T> : <T>Committed</T>}
</span>
<span className={styles.muted}>
{n.label === "Committed"
? tx(n.count === 1 ? "1 commit" : "{count} commits").replace("{count}", String(n.count))
: `${n.count} ${tx(n.count === 1 ? "file" : "files")}`}
<span className={styles.change} title={n.change.relPath}>
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} />
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
{basename(n.change.path)}
</span>
<span className={styles.changeDir}>{changeDir(diffTask, n.change)}</span>
<span className={styles.changeStat}>
{n.added > 0 && <span className={styles.added}>+{n.added}</span>}{" "}
{n.removed > 0 && <span className={styles.removed}>−{n.removed}</span>}
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
</span>
</span>
);
}
if (n.type === "repo") {
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
const stats = statsOf(files);
return (
<span className={styles.changeGroup} title={n.root}>
<Icon name="folder" size={14} />
<span className={styles.changeGroupName}>{basename(n.root)}</span>
<span className={styles.muted}>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
<span className={styles.changeStat}>
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
</span>
</span>
);
}
if (n.type === "commit") {
const stats = statsOf(n.commit.files);
return (
<span className={styles.changeCommit} title={n.commit.message}>
<Icon name="commit" size={14} />
<span className={styles.changeCommitHash}>{n.commit.shortId}</span>
<span className={styles.changeCommitSummary}>{n.commit.summary}</span>
{n.commit.timeMs != null && (
<span className={styles.changeCommitTime}>{formatSentAt(n.commit.timeMs)}</span>
)}
<span className={styles.changeStat}>
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
</span>
</span>
);
}
return (
<span className={styles.change} title={n.change.relPath}>
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} />
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
{basename(n.change.path)}
</span>
<span className={styles.changeDir}>{changeDir(task, n.change)}</span>
<span className={styles.changeStat}>
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
</span>
</span>
);
}}
/>
);
}}
/>
),
[loading, view, rows, grouped, selected, diffTask],
);
return (
<section className={styles.changes} aria-label={tx("Changes")}>
<CombinedDiffView
@@ -542,6 +553,9 @@ function TaskChanges({ task, tabKey }: { task: AgentTask; tabKey: string }) {
);
}
/** What a task's diffs are built from. */
type DiffTask = Pick<AgentTask, "id" | "base" | "isolation" | "branch" | "cwd">;
/** Key of the first file row at or under `row`: what the diff scrolls to for it. */
function firstFile(row: ChangeRow): string | null {
if (row.type === "file") return row.key;
@@ -563,7 +577,7 @@ function fileRows(rows: readonly ChangeRow[]): Extract<ChangeRow, { type: "file"
* whose diff is unchanged keeps its object, so its block doesn't load again as the task works.
*/
function useDiffItems(
task: AgentTask,
task: DiffTask,
rows: readonly ChangeRow[],
grouped: boolean,
scope: ChangesScope,
@@ -598,8 +612,11 @@ function useDiffItems(
? before
: item;
});
// Unchanged, the list keeps its array too: a new one renders every block again.
setItems((before) =>
before && before.length === kept.length && kept.every((item, i) => item === before[i]) ? before : kept,
);
previous.current = new Map(kept.map((item) => [item.key, item]));
setItems(kept);
});
return () => {
live = false;
@@ -609,14 +626,14 @@ function useDiffItems(
}
/** The folder of a changed file, as the tree names it. */
function changeDir(task: AgentTask, change: AgentChange): string {
function changeDir(task: Pick<AgentTask, "cwd">, change: AgentChange): string {
if (!change.repo) return relativeDir(task.cwd, change.path);
return change.relPath.includes("/") ? dirname(change.relPath) : "";
}
/** Diff of `path` between the task's start (or its last turn's) and now. */
async function changeDiffData(
task: AgentTask,
task: DiffTask,
path: string,
scope: ChangesScope,
kind?: AgentChange["kind"],
@@ -653,7 +670,7 @@ export async function openChangeDiff(task: AgentTask, path: string, scope: Chang
}
/** Diff of `path` in the grouped view: `HEAD` ↔ the working file. */
function uncommittedDiffData(task: AgentTask, change: AgentChange): DiffData {
function uncommittedDiffData(task: DiffTask, change: AgentChange): DiffData {
const left: DiffData["left"] =
change.kind === "added" || change.kind === "untracked"
? { type: "text", text: "", label: "(does not exist)", absent: true }
@@ -674,14 +691,14 @@ function uncommittedDiffData(task: AgentTask, change: AgentChange): DiffData {
}
/** Registration needed before a diff reads revisions inside the task's own worktree. */
async function ensureTaskRepo(task: AgentTask) {
async function ensureTaskRepo(task: DiffTask) {
// A worktree is its own repository, outside the project's: `vcs_file_at` reads it only once
// it is registered as an external log for this window.
if (task.isolation === "worktree") await call(commands.vcsOpenExternalLog(task.cwd)).catch(() => undefined);
}
/** Diff of a file of one of the task's commits: `parent ↔ commit`. */
function commitFileDiff(task: AgentTask, commit: AgentCommit, file: AgentChange): DiffData {
function commitFileDiff(task: DiffTask, commit: AgentCommit, file: AgentChange): DiffData {
return commitFileDiffData(
{
id: commit.id,
+52 -15
Переглянути файл
@@ -212,6 +212,24 @@ function clampMultiClick(target: EventTarget) {
if (row) clampSelectionToRow(document.getSelection(), row);
}
/** First entry index painted for a `shown` tail cap, keeping a leading process run intact. */
function historyStart(entries: readonly AgentEntry[], shown: number): number {
let start = Math.max(0, entries.length - shown);
// Keep a process run intact so prepending never replaces the anchored row.
while (start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
return start;
}
/**
* Next `shown` cap after one batch. Keeping a process run intact can already paint more than
* `shown` entries, so step past what is actually painted (`entries.length - start`) rather than
* `shown`; otherwise a process run longer than `ENTRY_BATCH` leaves `start` unchanged and stalls.
*/
function nextShownBatch(entries: readonly AgentEntry[] | null, shown: number): number {
if (!entries) return shown + ENTRY_BATCH;
return Math.max(shown, entries.length - historyStart(entries, shown)) + ENTRY_BATCH;
}
export function Stream({
loadError,
task,
@@ -239,9 +257,11 @@ export function Stream({
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
let start = finding || !entries ? 0 : Math.max(0, entries.length - shown);
// Keep a process run intact so prepending never replaces the anchored row.
while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
const start = finding || !entries ? 0 : historyStart(entries, shown);
const latest = useRef({ entries, start, visible });
useLayoutEffect(() => {
latest.current = { entries, start, visible };
});
const dragging = useRef(false);
// When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find):
// that leaves the end. WebKit also moves the offset back on its own while rows lay out,
@@ -280,11 +300,12 @@ export function Stream({
const anchor = useRef<{ el: Element; top: number } | null>(null);
const loadEarlier = useCallback(() => {
const el = ref.current;
if (!visible || !el || start <= 0 || dragging.current || anchor.current) return;
const { start: currentStart, visible: isVisible } = latest.current;
if (!isVisible || !el || currentStart <= 0 || dragging.current || anchor.current) return;
const first = el.firstElementChild;
if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top };
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n)));
}, []);
const loadTimer = useRef<number | null>(null);
/** Load the next batch once the user stops scrolling near the top. */
const loadWhenStill = useCallback(() => {
@@ -298,12 +319,19 @@ export function Stream({
const down = (event: PointerEvent) => {
if (!ref.current?.contains(event.target as Node)) return;
dragging.current = true;
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
loadTimer.current = null;
}
};
const up = () => {
if (!dragging.current) return;
dragging.current = false;
if (ref.current && (position.current.stick || ref.current.scrollTop < 120)) loadWhenStill();
if (
ref.current &&
(position.current.stick || ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)
)
loadWhenStill();
};
window.addEventListener("pointerdown", down, true);
window.addEventListener("pointerup", up, true);
@@ -314,16 +342,24 @@ export function Stream({
window.removeEventListener("pointerup", up, true);
window.removeEventListener("pointercancel", up, true);
window.removeEventListener("blur", up);
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
loadTimer.current = null;
}
};
}, [loadWhenStill]);
useEffect(() => {
// Following the end, paint the rest in the background. A user who scrolled away
// gets them only after stopping near the top (`loadWhenStill`), so the scrollbar
// is not resized mid-drag. A hidden tab paints nothing more.
if (visible && start > 0 && position.current.stick && !dragging.current)
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
// gets them only after stopping near the top (`loadWhenStill`), or when folded rows
// do not yet fill the viewport, so the scrollbar is not resized mid-drag. A hidden
// tab paints nothing more.
if (!visible || start <= 0 || dragging.current) return;
if (position.current.stick) {
startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n)));
} else if (ref.current && (ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)) {
loadWhenStill();
}
}, [loadWhenStill, start, visible]);
useEffect(() => {
// A conversation read to its end gives back the history painted above its recent entries
// once it stays behind other tabs: a few kept-alive tabs would otherwise hold every turn
@@ -418,6 +454,7 @@ export function Stream({
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill();
updateJumpVisibility(el);
});
observer.observe(el);
@@ -425,7 +462,7 @@ export function Stream({
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack, updateJumpVisibility]);
}, [key, loadWhenStill, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container
+277 -143
Переглянути файл
@@ -3,9 +3,14 @@
* left, the chosen one's form on the right, then a progress view while the backend
* creates the project. The new project opens in a new window (this one when it has
* no project).
*
* In the desktop app the wizard has its own native window (`new-project-<parent>`, see
* `newProjectWindow.tsx`), which hands the created folder back to its project window; remote
* windows and the browser build show it as a dialog in the page.
*/
import { Channel } from "@tauri-apps/api/core";
import { useEffect, useMemo, useRef, useState } from "react";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { create } from "zustand";
import {
call,
@@ -22,9 +27,14 @@ import {
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { logError } from "@/platform/errorLog";
import { isRemoteWindow } from "@/platform/remote";
import { windowBackgroundHex } from "@/workbench/theme";
import { WindowDialogFrame } from "@/workbench/WindowDialogFrame";
import {
Checkbox,
Dialog,
type DialogButton,
Icon,
IconButton,
Input,
@@ -48,10 +58,44 @@ import { defaultProjectDirectory, openProjectInWindow } from "./windows";
import styles from "./newProject.module.css";
const useNewProject = create<{ open: boolean }>(() => ({ open: false }));
export const showNewProject = () => useNewProject.setState({ open: true });
const showInPage = () => useNewProject.setState({ open: true });
/** Sent by the New Project window to its project window with the created folder. */
export const NEW_PROJECT_CREATED = "openidea://new-project/created";
/** File › New Project…: its own window in the desktop app, else a dialog in this page. */
export function showNewProject() {
if (!isTauri() || isRemoteWindow()) return showInPage();
void call(commands.windowOpenNewProject(windowBackgroundHex())).catch((e: unknown) => {
logError("cannot open the New Project window", e);
showInPage();
});
}
/** Opens a project the New Project window created, like the in-page dialog does. */
export function openCreatedProject(dir: string) {
void getCurrentWebviewWindow()
.setFocus()
.catch(() => {});
return openProjectInWindow(dir, useProject.getState().project !== null);
}
export function NewProjectOverlay() {
const open = useNewProject((s) => s.open);
useEffect(() => {
if (!isTauri()) return;
let disposed = false;
let off: (() => void) | undefined;
void getCurrentWebviewWindow()
.listen<{ dir: string }>(NEW_PROJECT_CREATED, ({ payload }) => {
void openCreatedProject(payload.dir).catch((e: unknown) => logError("cannot open the new project", e));
})
.then((u) => (disposed ? u() : (off = u)));
return () => {
disposed = true;
off?.();
};
}, []);
return open ? <NewProjectDialog onClose={() => useNewProject.setState({ open: false })} /> : null;
}
@@ -139,7 +183,68 @@ function saveDialogSize(size: { w: number; h: number }) {
}
}
function NewProjectDialog({ onClose }: { onClose: () => void }) {
interface FrameProps {
standalone: boolean;
onClose: () => void;
buttons: readonly DialogButton[];
children: ReactNode;
/** The wizard form: resizable, its size remembered. */
form?: boolean;
/** In the window: the generator list, beside the content. */
sidebar?: ReactNode;
}
/** The wizard's own window, or a dialog in the page. */
function Frame({ standalone, onClose, buttons, children, form = false, sidebar }: FrameProps) {
if (standalone)
return (
<WindowDialogFrame
title="New Project"
buttons={buttons}
onCancel={onClose}
sidebar={sidebar}
bodyClassName={styles.windowBody}
>
{children}
</WindowDialogFrame>
);
return form ? (
<Dialog
open
title="New Project"
onClose={onClose}
width={860}
resizable="both"
minWidth={720}
minHeight={480}
initialSize={loadDialogSize()}
onResized={saveDialogSize}
className={styles.dialog}
buttons={buttons}
>
{children}
</Dialog>
) : (
<Dialog open title="New Project" onClose={onClose} width={860} buttons={buttons}>
{children}
</Dialog>
);
}
/**
* The wizard. `standalone`: it fills the New Project window, and the created project opens in
* `parent` (the window's project window) instead of here.
*/
export function NewProjectDialog({
onClose,
standalone = false,
onCreated,
}: {
onClose: () => void;
standalone?: boolean;
/** Opens the created project; defaults to opening it from this window. */
onCreated?: (dir: string) => Promise<void>;
}) {
const tx = useTx();
const txTemplate = useTxTemplate();
const [catalog, setCatalog] = useState<GeneratorInfo[] | null>(null);
@@ -338,6 +443,10 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
),
);
saveLocation(location.trim());
if (onCreated) {
await onCreated(dir);
return;
}
onClose();
await openProjectInWindow(dir, useProject.getState().project !== null);
} catch (e) {
@@ -346,25 +455,143 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
}
};
if (job) return <ProgressView job={job} onBack={() => setJob(null)} onClose={onClose} />;
if (job) return <ProgressView job={job} standalone={standalone} onBack={() => setJob(null)} onClose={onClose} />;
return (
<Dialog
open
title="New Project"
onClose={onClose}
width={860}
resizable="both"
minWidth={720}
minHeight={480}
initialSize={loadDialogSize()}
onResized={saveDialogSize}
className={styles.dialog}
buttons={[
{ label: "Create", role: "default", disabled: invalid, onClick: () => void createProject() },
{ label: "Cancel", role: "cancel" },
]}
const buttons: DialogButton[] = [
{ label: "Create", role: "default", disabled: invalid, onClick: () => void createProject() },
{ label: "Cancel", role: "cancel" },
];
const generators = (
<>
<Input
className={styles.search}
value={query}
placeholder="Search"
onChange={(e) => setQuery(e.target.value)}
aria-label="Search generators"
/>
<div className={styles.list} role="listbox" aria-label={tx("Generators")}>
{catalogError && <div className={styles.error}>{txTemplate(catalogError)}</div>}
{groupedEntries(catalog ?? [], query).map(([group, entries]) => (
<div key={group} role="group" aria-label={tx(group)}>
<div className={styles.groupLabel}>{tx(group)}</div>
{entries.map((g) => (
<button
key={g.id}
type="button"
role="option"
aria-selected={g.id === selected}
className={styles.entry}
title={tx(g.name)}
onClick={() => setSelected(g.id)}
>
<Icon name={hasIcon(g.icon) ? g.icon : "folder"} />
<span>{tx(g.name)}</span>
</button>
))}
</div>
))}
</div>
</>
);
const formView = (
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void createProject();
}}
>
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
<div className={styles.grid}>
<label className={styles.label} htmlFor="np-name">
<T>Name:</T>
</label>
<Input
id="np-name"
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => {
setNameEdited(true);
setName(e.target.value);
}}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
</label>
<div className={styles.location}>
<Input
id="np-location"
variant="bare"
className={styles.locationInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton
icon="folder-open"
title="Browse…"
size="small"
onClick={() => void browse()}
disabled={!isTauri()}
/>
</div>
<span />
<div className={nameError ? `${styles.hint} ${styles.hintError}` : styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
<>
<span />
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
</>
)}
{visibleFields.map((f) => (
<FieldRow
key={f.id}
field={f}
value={values[f.id] ?? ""}
onChange={(v) => setValue(f.id, v)}
sdks={f.kind.type === "sdk" ? (sdks[f.kind.sdk] ?? null) : null}
/>
))}
{loadingDynamic && (
<>
<span />
<div className={styles.hint}>
<T>Loading options…</T>
</div>
</>
)}
{dynamicError && (
<>
<span />
<div className={styles.error}>{txTemplate(dynamicError)}</div>
</>
)}
</div>
{missing.map((r) => (
<div key={r.program} className={styles.missing}>
<Icon name="warning" />
<span>
{r.found
? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.`
: tx`${r.program} is not installed.`}{" "}
{r.hint && tx(r.hint)}
</span>
</div>
))}
</form>
);
if (standalone)
return (
<Frame standalone onClose={onClose} buttons={buttons} sidebar={generators}>
{formView}
</Frame>
);
return (
<Frame standalone={false} form onClose={onClose} buttons={buttons}>
<SplitGroup
className={styles.layout}
elementRef={layout}
@@ -378,128 +605,14 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
maxSize="45%"
className={styles.sidebar}
>
<Input
className={styles.search}
value={query}
placeholder="Search"
onChange={(e) => setQuery(e.target.value)}
aria-label="Search generators"
/>
<div className={styles.list} role="listbox" aria-label={tx("Generators")}>
{catalogError && <div className={styles.error}>{txTemplate(catalogError)}</div>}
{groupedEntries(catalog ?? [], query).map(([group, entries]) => (
<div key={group} role="group" aria-label={tx(group)}>
<div className={styles.groupLabel}>{tx(group)}</div>
{entries.map((g) => (
<button
key={g.id}
type="button"
role="option"
aria-selected={g.id === selected}
className={styles.entry}
title={tx(g.name)}
onClick={() => setSelected(g.id)}
>
<Icon name={hasIcon(g.icon) ? g.icon : "folder"} />
<span>{tx(g.name)}</span>
</button>
))}
</div>
))}
</div>
{generators}
</SplitPanel>
<SplitHandle aria-label={tx("Generators")} />
<SplitPanel id="new-project-form" defaultSize="75%">
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void createProject();
}}
>
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
<div className={styles.grid}>
<label className={styles.label} htmlFor="np-name">
<T>Name:</T>
</label>
<Input
id="np-name"
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => {
setNameEdited(true);
setName(e.target.value);
}}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
</label>
<div className={styles.location}>
<Input
id="np-location"
variant="bare"
className={styles.locationInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton
icon="folder-open"
title="Browse…"
size="small"
onClick={() => void browse()}
disabled={!isTauri()}
/>
</div>
<span />
<div className={nameError ? `${styles.hint} ${styles.hintError}` : styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
<>
<span />
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
</>
)}
{visibleFields.map((f) => (
<FieldRow
key={f.id}
field={f}
value={values[f.id] ?? ""}
onChange={(v) => setValue(f.id, v)}
sdks={f.kind.type === "sdk" ? (sdks[f.kind.sdk] ?? null) : null}
/>
))}
{loadingDynamic && (
<>
<span />
<div className={styles.hint}>
<T>Loading options…</T>
</div>
</>
)}
{dynamicError && (
<>
<span />
<div className={styles.error}>{txTemplate(dynamicError)}</div>
</>
)}
</div>
{missing.map((r) => (
<div key={r.program} className={styles.missing}>
<Icon name="warning" />
<span>
{r.found
? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.`
: tx`${r.program} is not installed.`}{" "}
{r.hint && tx(r.hint)}
</span>
</div>
))}
</form>
{formView}
</SplitPanel>
</SplitGroup>
</Dialog>
</Frame>
);
}
@@ -662,7 +775,17 @@ function DependencyPicker({
);
}
function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void; onClose: () => void }) {
function ProgressView({
job,
standalone,
onBack,
onClose,
}: {
job: Job;
standalone: boolean;
onBack: () => void;
onClose: () => void;
}) {
const txTemplate = useTxTemplate();
const tx = useTx();
const log = useRef<HTMLPreElement>(null);
@@ -671,12 +794,23 @@ function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void;
if (el) el.scrollTop = el.scrollHeight;
}, [job.lines.length]);
const failed = job.error !== null;
useEffect(() => {
if (!standalone || failed || !isTauri()) return;
// Closing the window stops the generator instead of leaving it running unseen.
let disposed = false;
let off: (() => void) | undefined;
void getCurrentWebviewWindow()
.onCloseRequested(() => job.cancel())
.then((u) => (disposed ? u() : (off = u)));
return () => {
disposed = true;
off?.();
};
}, [standalone, failed, job]);
return (
<Dialog
open
title="New Project"
<Frame
standalone={standalone}
onClose={() => (failed ? onClose() : job.cancel())}
width={860}
buttons={
failed
? [
@@ -700,6 +834,6 @@ function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void;
</pre>
{failed && <div className={styles.error}>{txTemplate(job.error ?? "")}</div>}
</div>
</Dialog>
</Frame>
);
}
+13 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { GeneratorInfo } from "@/bindings";
import { NewProjectOverlay, showNewProject } from "../NewProject";
import { NewProjectDialog, NewProjectOverlay, showNewProject } from "../NewProject";
const mocks = vi.hoisted(() => ({
freeName: vi.fn(),
@@ -114,6 +114,18 @@ describe("File › New Project… name and location", () => {
await waitFor(() => expect(mocks.open).toHaveBeenCalled());
expect(localStorage.getItem("openidea.newProject.location")).toBe("/elsewhere");
});
it("in its own window, hands the created project to its project window instead of opening it", async () => {
const created = vi.fn(() => Promise.resolve());
render(<NewProjectDialog standalone onClose={() => {}} onCreated={created} />);
expect(screen.queryByRole("dialog")).toBeNull();
await waitFor(() => expect(nameInput()).toHaveValue("untitled2"));
await waitFor(() => expect(createButton()).toBeEnabled());
fireEvent.click(createButton());
await waitFor(() => expect(created).toHaveBeenCalledWith("/work/projects/untitled2"));
expect(mocks.open).not.toHaveBeenCalled();
expect(localStorage.getItem("openidea.newProject.location")).toBe("/work/projects");
});
});
describe("File › New Project… SDK fields", () => {
+14
Переглянути файл
@@ -237,3 +237,17 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* The New Project window */
.windowBody {
display: flex;
flex-direction: column;
overflow: hidden;
}
.windowBody .form {
padding-top: 0;
}
.windowBody .progress {
height: 100%;
padding-top: 0;
}
+27
Переглянути файл
@@ -0,0 +1,27 @@
/**
* The New Project window (`new-project-<parent>`): the wizard in its own native window. The
* created project opens from the parent project window, which then has it (or a new window).
*/
import { emitTo } from "@tauri-apps/api/event";
import { closeDialogWindow, useDialogWindow } from "@/workbench/dialogWindow";
import { OverlayHost } from "@/workbench/OverlayHost";
import { useApplyTheme } from "@/workbench/theme";
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
import { NEW_PROJECT_CREATED, NewProjectDialog } from "./NewProject";
export function NewProjectWindow() {
useApplyTheme();
const parent = useDialogWindow((s) => s.parent);
const created = async (dir: string) => {
if (!parent) return;
await emitTo(parent, NEW_PROJECT_CREATED, { dir });
closeDialogWindow();
};
return (
<>
{parent && <NewProjectDialog standalone onClose={closeDialogWindow} onCreated={created} />}
<OverlayHost />
<WindowResizeHandles />
</>
);
}
+27
Переглянути файл
@@ -396,6 +396,17 @@
padding-inline: var(--space-2);
}
/* An unsafe statement waiting for confirmation. */
:global(.cm-openidea-db-warning) {
text-decoration-line: underline;
text-decoration-style: wavy;
text-decoration-color: var(--wave-warning);
text-underline-offset: 3px;
}
:global(.cm-openidea-db-run-warning svg) {
color: var(--warning);
}
/* Inline statement errors in consoles. */
:global(.cm-openidea-db-error) {
text-decoration-line: underline;
@@ -835,6 +846,22 @@
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
:global(.cm-openidea-db-banner-warning) {
background: color-mix(in srgb, var(--warning) 12%, var(--bg-editor));
}
:global(.cm-openidea-db-banner-action) {
height: 22px;
padding: 0 6px;
border: none;
border-radius: var(--radius-small);
background: transparent;
color: var(--link);
font: inherit;
cursor: pointer;
}
:global(.cm-openidea-db-banner-action:hover) {
background: var(--bg-hover);
}
:global(.cm-openidea-db-banner-text) {
flex: 1;
min-width: 0;
+139
Переглянути файл
@@ -0,0 +1,139 @@
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { act } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { EditorDocContext } from "@/editor/api";
import { consoleExtension, executeInView } from "./console";
import { unsafeStatement } from "./sql/unsafe";
import { executeConsole, type ConfirmUnsafe } from "./store";
// No backend here: the console bar's data source read would fail and log an error.
vi.mock("./store", async (original) => ({
...(await original<typeof import("./store")>()),
executeConsole: vi.fn(),
loadSources: vi.fn(async () => {}),
}));
const DOC = "select 1;\nDELETE FROM t_digital_tachometer_file WHERE 1=1;";
const FROM = DOC.indexOf("DELETE");
const TO = DOC.length - 1;
/** Runs the console's statement through `executeInView`, recording the unsafe-query answer. */
function run(view: EditorView, path: string, ready?: Promise<void>) {
let answer: boolean | undefined;
vi.mocked(executeConsole).mockImplementationOnce(
async (_p, _t, _f, _to, _start, _progress, confirm?: ConfirmUnsafe) => {
await ready;
const text = DOC.slice(FROM, TO);
answer = await confirm!({ from: FROM, to: TO, text }, unsafeStatement(text, "postgres")!);
return [];
},
);
const done = executeInView(view, path);
return { done, answer: () => answer };
}
const flush = () => act(async () => {});
const banner = (view: EditorView) => view.dom.querySelector(".cm-openidea-db-banner-warning");
const button = (view: EditorView, label: string) =>
[...view.dom.querySelectorAll<HTMLButtonElement>(".cm-openidea-db-banner button")].find(
(b) => b.textContent === label || b.getAttribute("aria-label") === label,
)!;
describe("unsafe query warning", () => {
const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
function open(path: string) {
const ctx = { language: "sql", path, virtual: false, readOnly: false } as unknown as EditorDocContext;
const view = new EditorView({
state: EditorState.create({ doc: DOC, extensions: consoleExtension(ctx) }),
parent: document.body,
});
views.push(view);
return view;
}
it("asks before running and marks the always-true condition", async () => {
const view = open("/p/console.sql");
const first = run(view, "/p/console.sql");
await flush();
expect(banner(view)?.textContent).toContain(
"Unsafe query: 'Delete' statement clears all data in the table because 'where' condition is always true",
);
expect(view.dom.querySelector(".cm-openidea-db-warning")?.textContent).toBe("1=1");
expect(view.dom.querySelector(".cm-openidea-db-run-warning")).not.toBeNull();
expect(first.answer()).toBeUndefined();
button(view, "Close").click();
await first.done;
expect(first.answer()).toBe(false);
expect(banner(view)).toBeNull();
expect(view.dom.querySelector(".cm-openidea-db-warning")).toBeNull();
const second = run(view, "/p/console.sql");
await flush();
button(view, "Execute").click();
await second.done;
expect(second.answer()).toBe(true);
expect(banner(view)).toBeNull();
});
it("cancels the run when the console is edited while it asks", async () => {
const view = open("/p/edited.sql");
const pending = run(view, "/p/edited.sql");
await flush();
expect(banner(view)).not.toBeNull();
// Narrowing the condition must not run the statement read before the edit.
view.dispatch({ changes: { from: TO, insert: " AND id = 5" } });
await pending.done;
expect(pending.answer()).toBe(false);
expect(banner(view)).toBeNull();
expect(view.dom.querySelector(".cm-openidea-db-warning")).toBeNull();
});
it.each(["before", "during"])("keeps confirmation when save adds a final newline %s the warning", async (when) => {
const path = `/p/save-${when}.sql`;
const view = open(path);
let proceed!: () => void;
const gate = new Promise<void>((resolve) => (proceed = resolve));
const pending = run(view, path, gate);
if (when === "during") {
proceed();
await flush();
expect(banner(view)).not.toBeNull();
}
view.dispatch({ changes: { from: DOC.length, insert: "\n" }, userEvent: "input.save" });
proceed();
await flush();
expect(banner(view)).not.toBeNull();
button(view, "Execute").click();
await pending.done;
expect(pending.answer()).toBe(true);
});
it("cancels the run when the console closes while it asks", async () => {
const view = open("/p/closed.sql");
const pending = run(view, "/p/closed.sql");
await flush();
expect(banner(view)).not.toBeNull();
views.splice(views.indexOf(view), 1);
view.destroy();
await pending.done;
expect(pending.answer()).toBe(false);
});
it("stops asking in that console after Execute and Suppress", async () => {
const view = open("/p/other.sql");
const first = run(view, "/p/other.sql");
await flush();
button(view, "Execute and Suppress").click();
await first.done;
expect(first.answer()).toBe(true);
const second = run(view, "/p/other.sql");
await second.done;
expect(second.answer()).toBe(true);
expect(banner(view)).toBeNull();
});
});
+192 -43
Переглянути файл
@@ -28,6 +28,8 @@ import {
StateEffect,
StateField,
type Extension,
type Text,
type Transaction,
} from "@codemirror/state";
import {
Decoration,
@@ -45,7 +47,7 @@ import {
} from "@codemirror/view";
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import type { EditorDocContext } from "@/editor/api";
import { problemProviders, type ContributedProblem, type EditorDocContext } from "@/editor/api";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import {
call,
@@ -78,6 +80,7 @@ import {
type SqlCandidate,
type SqlCatalog,
} from "./sql/complete";
import { unsafeMessage } from "./sql/unsafe";
import { WHOLE_FILE, sqlSupport, type SqlText } from "./sqlSupport";
import { snowflakeLanguage } from "./sql/snowflakeHighlight";
import {
@@ -105,6 +108,7 @@ import {
setManualCommit,
sourceById,
useDatabase,
type ConfirmUnsafe,
} from "./store";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
@@ -142,7 +146,14 @@ function activeSpan(ex: Executing | null) {
return span && span.from < span.to ? span : undefined;
}
interface AskMark {
from: number;
to: number;
message: string;
}
interface RunState {
ask?: AskMark | null;
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
@@ -150,12 +161,25 @@ interface RunState {
}
const setRun = StateEffect.define<RunState>();
const setAsk = StateEffect.define<AskMark | null>();
/** Saving can append the final newline without changing any submitted SQL or statement offsets. */
function savedFinalNewline(tr: Transaction): boolean {
if (!tr.docChanged || !tr.isUserEvent("input.save")) return false;
const end = tr.startState.doc.length;
let only = true;
tr.changes.iterChanges((from, to, _f, _t, insert) => {
only &&= from === end && to === end && insert.toString() === "\n";
});
return only;
}
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) return e.value;
if (!tr.docChanged) return value;
for (const e of tr.effects) if (e.is(setRun)) value = { ...e.value, ask: value.ask };
for (const e of tr.effects) if (e.is(setAsk)) value = { ...value, ask: e.value };
if (!tr.docChanged || savedFinalNewline(tr)) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
@@ -177,7 +201,7 @@ const runField = StateField.define<RunState>({
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing };
return { ...value, marks, executing, ask: null };
},
provide: (f) => [
EditorView.decorations.compute([f], (state) => {
@@ -192,16 +216,25 @@ const runField = StateField.define<RunState>({
ranges.push(Decoration.widget({ widget: new ElapsedWidget(active.startedAt), side: 1 }).range(at));
}
for (const m of st.marks) {
if (m.error)
ranges.push(
Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to),
);
if (m.error) ranges.push(Decoration.mark({ class: "cm-openidea-db-error" }).range(m.from, m.to));
if (m.ms !== null)
ranges.push(Decoration.widget({ widget: new TimingWidget(m.ms), side: 1 }).range(m.timingAt));
}
const u = st.ask;
if (u && u.from < u.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-warning" }).range(u.from, u.to));
return Decoration.set(ranges, true);
}),
showPanel.from(f, (st) => (st.banner ? errorBanner(st.banner) : null)),
showPanel.from(f, (st) => (st.ask ? askBanner(st.ask) : st.banner ? errorBanner(st.banner) : null)),
// The editor's hover shows the run errors and the unsafe-query warning like other problems.
problemProviders.compute([f], (state) => {
const st = state.field(f);
const problems: ContributedProblem[] = [];
for (const m of st.marks)
if (m.error && m.from < m.to) problems.push({ from: m.from, to: m.to, severity: "error", message: m.error });
const u = st.ask;
if (u && u.from < u.to) problems.push({ from: u.from, to: u.to, severity: "warning", message: u.message });
return () => problems;
}),
],
});
@@ -257,19 +290,27 @@ class ExecutingMarker extends GutterMarker {
}
class RunMarker extends GutterMarker {
constructor(readonly error: string | null) {
constructor(
readonly error: string | null,
readonly warning: string | null = null,
) {
super();
}
eq(other: RunMarker) {
return other.error === this.error;
return other.error === this.error && other.warning === this.warning;
}
toDOM() {
if (this.warning) {
const el = iconNode("warning", 14, "cm-openidea-db-run-warning");
el.dataset.tooltip = this.warning;
return el;
}
const el = iconNode(
this.error ? "error" : "check",
14,
this.error ? "cm-openidea-db-run-error" : "cm-openidea-db-run-ok",
);
el.title = this.error ?? "Executed";
el.dataset.tooltip = this.error ?? tx("Executed");
return el;
}
}
@@ -281,10 +322,13 @@ const runGutter = gutter({
const doc = view.state.doc;
const active = activeSpan(st.executing);
const line = active ? doc.lineAt(active.from).from : undefined;
const unsafe = st.ask;
const unsafeLine = unsafe && unsafe.from <= doc.length ? doc.lineAt(unsafe.from).from : -1;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length)
.filter((m) => m.from <= doc.length && doc.lineAt(m.from).from !== unsafeLine)
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
if (line !== undefined) ranges.push(new ExecutingMarker().range(line));
if (line !== undefined && line !== unsafeLine) ranges.push(new ExecutingMarker().range(line));
if (unsafe && unsafeLine >= 0) ranges.push(new RunMarker(null, unsafe.message).range(unsafeLine));
return RangeSet.of(ranges, true);
},
});
@@ -309,16 +353,111 @@ function errorBanner(message: string) {
};
}
type AskChoice = "execute" | "suppress" | "cancel";
/** The answer to the banner a view asks with. */
const askAnswers = new WeakMap<EditorView, (choice: AskChoice) => void>();
/** Consoles whose unsafe queries run without asking (Execute and Suppress), until the app restarts. */
const unsafeSuppressed = new Set<string>();
function askBanner(mark: AskMark) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner cm-openidea-db-banner-warning";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = mark.message;
text.dataset.tooltip = mark.message;
const answer = (choice: AskChoice) => askAnswers.get(view)?.(choice);
const action = (label: string, choice: AskChoice) => {
const b = document.createElement("button");
b.type = "button";
b.className = "cm-openidea-db-banner-action";
b.textContent = label;
b.onclick = () => answer(choice);
return b;
};
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", tx("Close"));
close.appendChild(iconNode("close", 14));
close.onclick = () => answer("cancel");
const actions = [action(tx("Execute"), "execute"), action(tx("Execute and Suppress"), "suppress")];
dom.append(text, ...actions, close);
return { dom, top: false };
};
}
/**
* Editing or closing the console while the unsafe-query banner waits cancels the run.
*/
const cancelAskOnEdit = [
EditorView.updateListener.of((u) => {
if (!u.docChanged) return;
if (u.transactions.every((tr) => !tr.docChanged || savedFinalNewline(tr))) {
const preparing = preparingViews.get(u.view);
if (preparing?.doc === u.startState.doc) preparing.doc = u.state.doc;
return;
}
if (u.startState.field(runField).ask) askAnswers.get(u.view)?.("cancel");
}),
ViewPlugin.define((view) => ({
destroy: () => {
closedViews.add(view);
askAnswers.get(view)?.("cancel");
},
})),
];
/** Views destroyed with a question open: nothing more to dispatch to them. */
const closedViews = new WeakSet<EditorView>();
/** Shows `mark` in the banner and waits for the answer. */
function ask(view: EditorView, mark: AskMark): Promise<AskChoice> {
askAnswers.get(view)?.("cancel");
return new Promise<AskChoice>((resolve) => {
askAnswers.set(view, (choice) => {
askAnswers.delete(view);
if (!closedViews.has(view) && view.state.field(runField, false)?.ask) view.dispatch({ effects: setAsk.of(null) });
resolve(choice);
});
view.dispatch({ effects: setAsk.of(mark) });
});
}
/** Shows the unsafe-query banner for `statement` and waits for the answer (true: run it). */
function confirmUnsafe(view: EditorView, path: string, current: () => boolean): ConfirmUnsafe {
return async (statement, unsafe) => {
if (!current()) return false;
if (unsafeSuppressed.has(path)) return true;
const len = view.state.doc.length;
const choice = await ask(view, {
from: Math.min(len, statement.from + unsafe.from),
to: Math.min(len, statement.from + unsafe.to),
message: unsafeMessage(unsafe),
});
if (choice === "suppress") unsafeSuppressed.add(path);
return choice !== "cancel";
};
}
let nextExecution = 0;
const preparingViews = new WeakMap<EditorView, { doc: Text }>();
/** Runs `from`–`to` of `view`, following each statement as it executes. */
async function executeRange(view: EditorView, path: string, from: number, to: number) {
const token = ++nextExecution;
const sent = view.state.doc;
askAnswers.get(view)?.("cancel");
const preparing = { doc: sent };
preparingViews.set(view, preparing);
const current = () =>
!closedViews.has(view) && view.state.doc === preparing.doc && preparingViews.get(view) === preparing;
const start = (statements: readonly SqlStatement[]) => {
const st = view.state.field(runField, false);
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (!st || view.state.doc !== sent) return;
if (!st || !current()) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const first = spans[0]!;
const last = spans[spans.length - 1]!;
@@ -326,35 +465,44 @@ async function executeRange(view: EditorView, path: string, from: number, to: nu
view.dispatch({ effects: setRun.of({ marks, banner: null, executing: { token, spans, active: null } }) });
};
try {
await executeConsole(path, sent.toString(), from, to, start, (events) => {
const st = view.state.field(runField, false);
const ex = st?.executing;
if (!st || ex?.token !== token) return;
const last = events[events.length - 1]!;
const active = last.type === "started" ? { index: last.index, startedAt: Date.now() } : null;
const marks = [...st.marks];
let banner = st.banner;
const placed = new Map<number, DbStatementOutcome>();
for (const event of events) {
if (event.type === "started") continue;
const span = ex.spans[event.index];
if (!span || span.from >= span.to) continue;
const { from, to } = span;
const { error, result } = event.outcome;
marks.push({
from,
to,
timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to,
error,
ms: result?.elapsedMs ?? null,
});
if (error) banner = `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`;
placed.set(event.index, { ...event.outcome, statement: { ...event.outcome.statement, ...span } });
}
view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) });
return placed;
});
await executeConsole(
path,
sent.toString(),
from,
to,
start,
(events) => {
const st = view.state.field(runField, false);
const ex = st?.executing;
if (!st || ex?.token !== token) return;
const last = events[events.length - 1]!;
const active = last.type === "started" ? { index: last.index, startedAt: Date.now() } : null;
const marks = [...st.marks];
let banner = st.banner;
const placed = new Map<number, DbStatementOutcome>();
for (const event of events) {
if (event.type === "started") continue;
const span = ex.spans[event.index];
if (!span || span.from >= span.to) continue;
const { from, to } = span;
const { error, result } = event.outcome;
marks.push({
from,
to,
timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to,
error,
ms: result?.elapsedMs ?? null,
});
if (error) banner = `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`;
placed.set(event.index, { ...event.outcome, statement: { ...event.outcome.statement, ...span } });
}
view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) });
return placed;
},
confirmUnsafe(view, path, current),
);
} finally {
if (preparingViews.get(view) === preparing) preparingViews.delete(view);
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
}
@@ -1366,6 +1514,7 @@ export function consoleExtension(ctx: EditorDocContext): Extension {
consolePath.of(ctx.path),
runField,
runGutter,
cancelAskOnEdit,
previewField,
previewLayer,
previewSync,
+7
Переглянути файл
@@ -201,6 +201,12 @@ describe("statements in flight", () => {
try {
await act(async () => {
pending = mode === "selection" ? executeInView(view, PATH) : executeScriptInView(view, PATH);
await vi.waitFor(() => expect(view.dom.querySelector(".cm-openidea-db-banner-warning")).not.toBeNull());
expect(backend.stream).not.toHaveBeenCalled();
const execute = [...view.dom.querySelectorAll<HTMLButtonElement>(".cm-openidea-db-banner-action")].find(
(button) => button.textContent === "Execute",
);
execute!.click();
await vi.waitFor(() => expect(cells()).toEqual(["first"]));
});
expect(highlighted()).toEqual(["UPDATE t SET n = 2"]);
@@ -217,6 +223,7 @@ describe("statements in flight", () => {
expect(view.dom.querySelectorAll(".cm-openidea-db-run-ok")).toHaveLength(3);
expect(view.state.selection.main.head).toBe(mode === "selection" ? doc.length : 0);
} finally {
view.dom.querySelector<HTMLButtonElement>(".cm-openidea-db-banner-warning .cm-openidea-db-banner-close")?.click();
finish();
if (pending)
await act(async () => {
+21
Переглянути файл
@@ -744,6 +744,27 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
);
});
it("checks the SQL after binding parameters and submits only the confirmed text", async () => {
const text = "DELETE FROM t WHERE :condition";
let accept!: (value: boolean) => void;
const answer = vi.fn(() => new Promise<boolean>((resolve) => (accept = resolve)));
const pending = executeConsole("a.sql", text, 0, text.length, undefined, undefined, answer);
await vi.waitFor(() => expect(useDatabase.getState().dialog?.kind).toBe("params"));
const dialog = useDatabase.getState().dialog;
if (dialog?.kind !== "params") throw new Error("Expected parameter dialog");
useDatabase.setState({ dialog: null });
dialog.resolve({ ":condition": "1=1" });
await vi.waitFor(() => expect(answer).toHaveBeenCalledOnce());
expect(backend.execute).not.toHaveBeenCalled();
expect(answer).toHaveBeenCalledWith(
{ text, from: 0, to: text.length },
expect.objectContaining({ kind: "delete", reason: "always-true", from: 0, to: text.length }),
);
accept(true);
await pending;
expect(backend.execute.mock.calls[0]?.[2]).toEqual([{ text: "DELETE FROM t WHERE 1=1", from: 0, to: text.length }]);
});
it("replaces the console's result in place with a fresh tab, leaving other consoles' results", async () => {
await runIn("a.sql", "SELECT 1");
await runIn("b.sql", "SELECT b");
+27 -1
Переглянути файл
@@ -59,8 +59,34 @@ export function bindParams(
let out = "";
let at = 0;
for (const p of params) {
out += text.slice(at, p.from) + (values[p.name]?.trim() || "NULL");
out += text.slice(at, p.from) + boundValue(p, values);
at = p.to;
}
return out + text.slice(at);
}
const boundValue = (p: SqlParam, values: Readonly<Record<string, string>>) => values[p.name]?.trim() || "NULL";
/**
* The range `from..to` of `bindParams`' output in the text it bound, for
* marking it in the editor; `null` when it overlaps a bound value.
*/
export function unbindRange(
params: readonly SqlParam[],
values: Readonly<Record<string, string>>,
from: number,
to: number,
): { from: number; to: number } | null {
/** Bound offset minus unbound offset, past the parameters seen so far. */
let shift = 0;
let start: number | undefined;
for (const p of params) {
const boundFrom = p.from + shift;
const boundTo = boundFrom + boundValue(p, values).length;
if (from < boundTo && to > boundFrom) return null;
if (start === undefined && from <= boundFrom) start = from - shift;
if (to <= boundFrom) return { from: start!, to: to - shift };
shift = boundTo - p.to;
}
return { from: start ?? from - shift, to: to - shift };
}
+20 -1
Переглянути файл
@@ -6,7 +6,7 @@ import { analyze, templateContexts, valuesSlot } from "./analyze";
import { aliasFor, quoteIdent, sqlCandidates, type SqlCandidate } from "./complete";
import { identName, inLiteral, lex } from "./lexer";
import { DATA_TYPES, statementStarters } from "./dialect";
import { bindParams, findParams } from "./params";
import { bindParams, findParams, unbindRange } from "./params";
import { SqlResolver } from "./resolve";
import { jdbcDialect } from "../vendors";
@@ -789,6 +789,25 @@ describe("params", () => {
expect(bindParams("select ?", findParams("select ?", "sqlite"), {})).toBe("select NULL");
});
it("maps a range of the bound text back to the text it bound", () => {
const sql = "delete from t where :a = :bb and 1 = 1";
const params = findParams(sql, "sqlite");
const values = { ":a": "'xyz'", ":bb": "2" };
const bound = bindParams(sql, params, values);
const back = (part: string) => {
const from = bound.indexOf(part);
const r = unbindRange(params, values, from, from + part.length);
return r && sql.slice(r.from, r.to);
};
expect(back("delete from t")).toBe("delete from t");
expect(back("1 = 1")).toBe("1 = 1");
expect(back(" = ")).toBe(" = ");
expect(back("'xyz' = 2")).toBeNull();
expect(back("2 and 1")).toBeNull();
expect(back(bound)).toBeNull();
expect(unbindRange([], {}, 3, 5)).toEqual({ from: 3, to: 5 });
});
it("leaves Snowflake variant paths, casts, stages and session variables alone", () => {
const names = (sql: string) => findParams(sql, "snowflake").map((p) => p.name);
const sql = "SELECT src:customer.name::string, $1 FROM @my_stage/path (FILE_FORMAT => 'ff') t WHERE x = :id";
+307
Переглянути файл
@@ -0,0 +1,307 @@
import { describe, expect, it } from "vitest";
import { unsafeMessage, unsafeStatement } from "./unsafe";
const check = (text: string) => unsafeStatement(text, "postgres");
describe("unsafeStatement", () => {
it("flags DELETE and UPDATE without WHERE", () => {
expect(check("DELETE FROM t")).toMatchObject({ kind: "delete", reason: "no-where" });
expect(check("delete from t returning *")).toMatchObject({ kind: "delete", reason: "no-where" });
expect(check("UPDATE t SET a = 1")).toMatchObject({ kind: "update", reason: "no-where" });
expect(check("update t set a = (select max(b) from u where u.id = 3)")).toMatchObject({
kind: "update",
reason: "no-where",
});
});
it("flags a WHERE that is always true", () => {
expect(check("DELETE FROM t_digital_tachometer_file WHERE 1=1")).toMatchObject({
kind: "delete",
reason: "always-true",
});
for (const where of [
"TRUE",
"1",
"(1 = 1)",
"'a' = 'a'",
"1 <> 2",
"2 > 1",
"NOT FALSE",
"NOT (1 = 0)",
"id = 5 OR 1 = 1",
"1 = 1 AND true",
"1 IS NOT NULL",
"-1 = -1",
])
expect(check(`delete from t where ${where}`), where).toMatchObject({ reason: "always-true" });
expect(check("update t set a = 1 where 1=1 returning a")).toMatchObject({ kind: "update", reason: "always-true" });
});
it("marks the condition of an always-true WHERE, the whole statement otherwise", () => {
const text = "DELETE FROM t WHERE 1=1";
const u = check(text)!;
expect(text.slice(u.from, u.to)).toBe("1=1");
const all = check("DELETE FROM t")!;
expect([all.from, all.to]).toEqual([0, "DELETE FROM t".length]);
});
it("leaves statements with a real condition alone", () => {
for (const text of [
"DELETE FROM t WHERE id = 1",
"DELETE FROM t WHERE 1 = 1 AND id = 3",
"delete from t where 1 = 0 or id = 2",
"delete from t where x between 1 and 2",
"delete from t where 1 = 2",
"update t set a = 1 where current of c",
"DELETE FROM t USING u WHERE t.id = u.id",
"SELECT * FROM t",
"INSERT INTO t VALUES (1)",
"CREATE RULE r AS ON DELETE TO t DO INSTEAD NOTHING",
"-- DELETE FROM t\nSELECT 1",
"SELECT 'DELETE FROM t'",
])
expect(check(text), text).toBeNull();
});
it("flags more constant conditions", () => {
for (const where of [
"NULL IS NULL",
"1 + 1 = 2",
"2 * 3 > 5",
"(1 + 2) * 2 = 6",
"10 / 2 = 5",
"1 IN (1, 2)",
"3 NOT IN (1, 2)",
"'a' IN ('a', 'b')",
"2 BETWEEN 1 AND 3",
"5 NOT BETWEEN 1 AND 3",
"'abc' LIKE 'a%'",
"'abc' LIKE '_b_'",
"'x' NOT LIKE 'y%'",
"'ABC' ILIKE 'abc'",
"EXISTS (SELECT 1)",
"TRUE = TRUE",
"id IS NULL OR id IS NOT NULL",
"status = 1 OR t.x IS NOT NULL OR t.x IS NULL",
"NOT NOT TRUE",
"1 = 1 AND 2 BETWEEN 1 AND 3",
])
expect(check(`delete from t where ${where}`), where).toMatchObject({ reason: "always-true" });
});
it("leaves conditions that are not certainly true alone", () => {
for (const where of [
"NULL = NULL",
"NULL IS NOT NULL",
"1 IN (2, NULL)",
"1 NOT IN (2, NULL)",
"id IN (1, 2)",
"1 IN (SELECT id FROM u)",
"'a' = 'A'",
"'a' < 'b'",
"'1' = 1",
"5 / 2 = 2",
"1 / 0 = 1",
"'ABC' LIKE 'abc'",
"'a_c' LIKE 'a!_c' ESCAPE '!'",
"EXISTS (SELECT 1 FROM u)",
"EXISTS (SELECT 1 WHERE false)",
"id IS NULL OR name IS NOT NULL",
"NULL",
"0",
"x BETWEEN 1 AND 3",
])
expect(check(`delete from t where ${where}`), where).toBeNull();
});
it("flags statements that drop or clear tables", () => {
expect(check("TRUNCATE TABLE t")).toMatchObject({ kind: "truncate", reason: "clears-table" });
expect(check("truncate t, u cascade")).toMatchObject({ kind: "truncate" });
expect(check("DROP TABLE t")).toMatchObject({ kind: "drop", reason: "drops-table" });
expect(check("drop table if exists t")).toMatchObject({ reason: "drops-table" });
expect(check("DROP TEMPORARY TABLE t")).toMatchObject({ reason: "drops-table" });
expect(check("DROP DATABASE app")).toMatchObject({ reason: "drops-database" });
expect(check("DROP SCHEMA s CASCADE")).toMatchObject({ reason: "drops-schema" });
expect(check("ALTER TABLE t DROP COLUMN c")).toMatchObject({ kind: "alter", reason: "drops-column" });
expect(check("alter table t drop c")).toMatchObject({ reason: "drops-column" });
expect(check("ALTER TABLE t ADD x int, DROP COLUMN IF EXISTS c")).toMatchObject({ reason: "drops-column" });
const all = check("DROP TABLE t")!;
expect([all.from, all.to]).toEqual([0, "DROP TABLE t".length]);
});
it("leaves drops that keep the data alone", () => {
for (const text of [
"DROP VIEW v",
"DROP INDEX i",
"DROP FUNCTION f()",
"ALTER TABLE t DROP CONSTRAINT c",
"ALTER TABLE t ALTER COLUMN c DROP DEFAULT",
"ALTER TABLE t ALTER COLUMN c DROP NOT NULL",
"ALTER TABLE t DROP PRIMARY KEY",
"ALTER TABLE t DROP FOREIGN KEY fk",
"ALTER TABLE t ADD COLUMN c int",
"ALTER INDEX i RENAME TO j",
])
expect(check(text), text).toBeNull();
});
it("evaluates IS TRUE / DISTINCT FROM, <=>, N'…' and casts that keep the value", () => {
for (const where of [
"TRUE IS TRUE",
"1 = 1 IS NOT FALSE",
"FALSE IS NOT TRUE",
"1 <=> 1",
"NULL <=> NULL",
"NULL IS NOT DISTINCT FROM NULL",
"1 IS DISTINCT FROM 2",
"N'a' = N'a'",
"1::int = 1",
"-1::int = -1",
"'a'::text = 'a'",
"CAST(1 AS bigint) = 1",
"1.5 = 1.5",
"1 = 1.0",
])
expect(check(`delete from t where ${where}`), where).toMatchObject({ reason: "always-true" });
});
it("leaves NULL, lossy casts and inexact numbers alone", () => {
for (const where of [
"NOT NULL",
"NOT (NULL)",
"NULL IS UNKNOWN",
"1 <=> NULL",
"1 IS DISTINCT FROM 1",
"1.5::int = 2",
"'1'::int = 1",
"'ab'::varchar(1) = 'a'",
"CAST('1' AS int) = 1",
"E'a\\nb' = 'a'",
"9007199254740993 = 9007199254740992",
"0.1 + 0.2 <> 0.3",
"0x1 = 1",
])
expect(check(`delete from t where ${where}`), where).toBeNull();
});
it("flags a column compared with itself", () => {
const text = "DELETE FROM t_arrangement_request WHERE arrangement_request_id = arrangement_request_id";
const u = check(text)!;
expect(u).toMatchObject({ kind: "delete", reason: "always-true" });
expect(text.slice(u.from, u.to)).toBe("arrangement_request_id = arrangement_request_id");
for (const where of [
"t.a >= t.a",
'a."Id" <= a."Id"',
"id = id AND 1 = 1",
"NOT (id <> id)",
"x BETWEEN x AND x",
"a IS NOT DISTINCT FROM a",
"a <=> a",
"status = 2 OR id = id",
])
expect(check(`delete from t where ${where}`), where).toMatchObject({ reason: "always-true" });
for (const where of [
"t.id = id",
"id = id + 0",
"id <> id",
"a IS DISTINCT FROM a",
"random() = random()",
"now() = now()",
"(select max(id) from u) = (select max(id) from u)",
"x BETWEEN x AND 10",
"status = 2 AND id = id",
])
expect(check(`delete from t where ${where}`), where).toBeNull();
});
it("finds a statement inside parentheses, EXPLAIN ANALYZE and a WITH clause's queries", () => {
expect(check("(DELETE FROM t)")).toMatchObject({ kind: "delete", reason: "no-where" });
expect(check("EXPLAIN ANALYZE DELETE FROM t")).toMatchObject({ kind: "delete", reason: "no-where" });
expect(check("explain analyze verbose update t set a = 1 where 1 = 1")).toMatchObject({ reason: "always-true" });
expect(check("EXPLAIN (ANALYZE, BUFFERS) UPDATE t SET a = 1")).toMatchObject({ kind: "update" });
const cte = "WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d";
const u = check(cte)!;
expect(u).toMatchObject({ kind: "delete", reason: "no-where" });
expect(cte.slice(u.from, u.to)).toBe("DELETE FROM t RETURNING *");
expect(check("with x as (select 1), d as materialized (update t set a = 1) select 1")).toMatchObject({
kind: "update",
});
for (const text of [
"EXPLAIN DELETE FROM t",
"EXPLAIN (ANALYZE false) DELETE FROM t",
"EXPLAIN (FORMAT JSON) DELETE FROM t",
"WITH d AS (DELETE FROM t WHERE id = 1 RETURNING *) SELECT * FROM d",
"WITH x(a) AS (SELECT 1) SELECT * FROM x",
"(SELECT 1)",
])
expect(check(text), text).toBeNull();
});
it("flags a MERGE whose ON is always true", () => {
const merge = "MERGE INTO t USING u ON 1=1 WHEN MATCHED THEN DELETE";
const u = check(merge)!;
expect(u).toMatchObject({ kind: "merge-delete", reason: "always-true" });
expect(merge.slice(u.from, u.to)).toBe("1=1");
expect(
check(
"merge into t using u on (1 = 1) when matched then update set a = u.a when not matched then insert values (1)",
),
).toMatchObject({ kind: "merge-update" });
expect(check("MERGE t USING u ON TRUE WHEN MATCHED AND 1 = 1 THEN DELETE")).toMatchObject({ kind: "merge-delete" });
for (const text of [
"MERGE INTO t USING u ON t.id = u.id WHEN MATCHED THEN DELETE",
"MERGE INTO t USING u ON 1=1 WHEN MATCHED AND t.x = 1 THEN DELETE",
"MERGE INTO t USING u ON 1=1 WHEN NOT MATCHED THEN INSERT VALUES (1)",
"MERGE INTO t USING u ON 1=1 WHEN MATCHED THEN DO NOTHING",
])
expect(check(text), text).toBeNull();
});
it("flags ALTER TABLE forms that drop partitions or history", () => {
expect(check("ALTER TABLE t DROP PARTITION p0, p1")).toMatchObject({ kind: "alter", reason: "drops-partition" });
expect(check("alter table t truncate partition p0")).toMatchObject({ reason: "clears-partition" });
expect(check("ALTER TABLE t DROP SYSTEM VERSIONING")).toMatchObject({ reason: "drops-history" });
for (const text of [
"ALTER TABLE t ALTER COLUMN c DROP STORED",
"ALTER TABLE t DROP PERIOD FOR p",
"ALTER TABLE t DROP UNIQUE (c)",
"ALTER TABLE t ALTER COLUMN c DROP IDENTITY IF EXISTS",
])
expect(check(text), text).toBeNull();
});
it("reads past a WITH clause and comments", () => {
expect(check("WITH x AS (SELECT 1) DELETE FROM t")).toMatchObject({ kind: "delete", reason: "no-where" });
expect(check("with x as (select id from u where true) delete from t where id in (select id from x)")).toBeNull();
expect(check("/* cleanup */ DELETE FROM t -- all of it")).toMatchObject({ reason: "no-where" });
});
});
describe("unsafeMessage", () => {
it("says what the statement does, like IDEA", () => {
expect(unsafeMessage({ kind: "delete", reason: "always-true", from: 0, to: 0 })).toBe(
"Unsafe query: 'Delete' statement clears all data in the table because 'where' condition is always true",
);
expect(unsafeMessage({ kind: "delete", reason: "no-where", from: 0, to: 0 })).toBe(
"Unsafe query: 'Delete' statement without 'where' clears all data in the table",
);
expect(unsafeMessage({ kind: "update", reason: "always-true", from: 0, to: 0 })).toBe(
"Unsafe query: 'Update' statement updates all rows in the table because 'where' condition is always true",
);
expect(unsafeMessage({ kind: "update", reason: "no-where", from: 0, to: 0 })).toBe(
"Unsafe query: 'Update' statement without 'where' updates all rows in the table",
);
expect(unsafeMessage({ kind: "truncate", reason: "clears-table", from: 0, to: 0 })).toBe(
"Unsafe query: 'Truncate' statement clears all data in the table",
);
expect(unsafeMessage({ kind: "drop", reason: "drops-database", from: 0, to: 0 })).toBe(
"Unsafe query: 'Drop' statement deletes the database with all its data",
);
expect(unsafeMessage({ kind: "merge-delete", reason: "always-true", from: 0, to: 0 })).toBe(
"Unsafe query: 'Merge' statement deletes all rows in the table because 'on' condition is always true",
);
expect(unsafeMessage({ kind: "alter", reason: "drops-partition", from: 0, to: 0 })).toBe(
"Unsafe query: 'Alter' statement drops a partition with all its data",
);
});
});
+690
Переглянути файл
@@ -0,0 +1,690 @@
/**
* IDEA's unsafe-query check: statements that wipe a whole table or more. A
* DELETE or UPDATE without WHERE, or whose WHERE is always true (`WHERE 1=1`),
* touches every row of its table, as does a MERGE whose ON is always true;
* TRUNCATE, DROP TABLE / DATABASE / SCHEMA and ALTER TABLE … DROP COLUMN /
* PARTITION lose data outright. Such a statement is found inside parentheses,
* a WITH clause's queries and EXPLAIN ANALYZE (which runs it) too. The console
* asks before running one.
*
* Conditions are evaluated compositionally (`evaluate` → `term` → `value`):
* each operator is supported once and combines with the others. Anything
* uncertain (data, functions, collations, dialect differences) counts as not
* constant, so the check never warns about a statement it cannot prove unsafe.
* The one exception is a column compared with itself (`id = id`): true on
* every row but those where it is NULL, which a key never is.
*/
import type { DbDriver } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { lex, type Token } from "./lexer";
export interface UnsafeStatement {
kind: "delete" | "update" | "merge-delete" | "merge-update" | "truncate" | "drop" | "alter";
reason:
| "no-where"
| "always-true"
| "clears-table"
| "drops-table"
| "drops-database"
| "drops-schema"
| "drops-column"
| "drops-partition"
| "clears-partition"
| "drops-history";
/** What to mark, offsets into the statement text: the condition, else the whole statement. */
from: number;
to: number;
}
/** Words ending a DELETE / UPDATE condition. */
const AFTER_WHERE = new Set(["RETURNING", "ORDER", "LIMIT", "OFFSET", "OPTION", "SETTINGS"]);
const STATEMENT = new Set(["DELETE", "UPDATE", "SELECT", "INSERT", "MERGE", "VALUES", "TABLE"]);
/** What `DROP <word>` removes, by the object word (after TEMPORARY / TEMP). */
const DROPPED: Record<string, UnsafeStatement["reason"]> = {
TABLE: "drops-table",
DATABASE: "drops-database",
SCHEMA: "drops-schema",
};
/** `ALTER TABLE … DROP <word>` forms that remove no data. */
const DROP_NOT_COLUMN = new Set([
"CONSTRAINT",
"INDEX",
"KEY",
"PRIMARY",
"FOREIGN",
"UNIQUE",
"CHECK",
"DEFAULT",
"NOT",
"IDENTITY",
"EXPRESSION",
"STORED",
"PERIOD",
"TRIGGER",
"RULE",
"PROJECTION",
"STATISTICS",
]);
/** `ALTER TABLE … DROP <word>` forms that remove data other than a column. */
const DROP_DATA: Record<string, UnsafeStatement["reason"]> = {
PARTITION: "drops-partition",
SUBPARTITION: "drops-partition",
// MariaDB's `DROP SYSTEM VERSIONING` deletes the row history.
SYSTEM: "drops-history",
};
/** `EXPLAIN` options before the statement; ANALYZE runs it. */
const EXPLAIN_OPTIONS = new Set(["ANALYZE", "ANALYSE", "VERBOSE"]);
/** Depth of each token in parentheses (a token's own `(` / `)` counts outside). */
function depths(tokens: readonly Token[]): number[] {
let depth = 0;
return tokens.map((t) => {
if (t.text === ")") depth = Math.max(0, depth - 1);
const d = depth;
if (t.text === "(") depth++;
return d;
});
}
const isWord = (t: Token | undefined, word: string) => t?.kind === "word" && t.upper === word;
export function unsafeStatement(text: string, driver: DbDriver): UnsafeStatement | null {
return check(lex(text, driver).tokens.filter((t) => t.text !== ";"));
}
/** Index of the `)` closing the `(` at `open`, or -1. */
function closing(tokens: readonly Token[], open: number): number {
let depth = 0;
for (let i = open; i < tokens.length; i++) {
if (tokens[i]!.text === "(") depth++;
else if (tokens[i]!.text === ")" && --depth === 0) return i;
}
return -1;
}
/** A statement as it runs: its tokens, their depths, its verb's index and its WITH clause's queries. */
interface Parts {
tokens: readonly Token[];
depth: number[];
/** -1 when there is none (a WITH clause alone). */
verb: number;
queries: Token[][];
}
/**
* The statement `tokens` runs, read past parentheses (`(DELETE FROM t)`) and
* `EXPLAIN ANALYZE` (which runs it); `null` for a plain EXPLAIN, which does not.
*/
function parts(tokens: readonly Token[]): Parts | null {
if (!tokens.length) return null;
if (wrapped(tokens)) return parts(tokens.slice(1, -1));
if (isWord(tokens[0], "EXPLAIN")) {
const target = explained(tokens);
return target && parts(target);
}
const depth = depths(tokens);
if (!isWord(tokens[0], "WITH")) return { tokens, depth, verb: 0, queries: [] };
// The statement's own verb: the first word at depth 0 after the WITH clause's queries.
const verb = tokens.findIndex((t, i) => i > 0 && depth[i] === 0 && t.kind === "word" && STATEMENT.has(t.upper));
// A query of the WITH clause can modify data itself: `WITH d AS (DELETE FROM t RETURNING *) SELECT …`.
const queries: Token[][] = [];
for (let i = 1; i < (verb < 0 ? tokens.length : verb); i++) {
if (tokens[i]!.text !== "(" || depth[i] !== 0) continue;
const close = closing(tokens, i);
if (close < 0) break;
// A query follows AS [[NOT] MATERIALIZED]; other parentheses list the columns.
if (isWord(tokens[i - 1], "AS") || isWord(tokens[i - 1], "MATERIALIZED")) queries.push(tokens.slice(i + 1, close));
i = close;
}
return { tokens, depth, verb, queries };
}
function check(all: readonly Token[]): UnsafeStatement | null {
const p = parts(all);
if (!p) return null;
for (const q of p.queries) {
const found = check(q);
if (found) return found;
}
const { tokens, depth, verb } = p;
if (verb < 0) return null;
const last = tokens.at(-1)!;
const whole = (kind: UnsafeStatement["kind"], reason: UnsafeStatement["reason"]): UnsafeStatement => ({
kind,
reason,
from: tokens[0]!.from,
to: last.to,
});
const v = tokens[verb]!.kind === "word" ? tokens[verb]!.upper : "";
if (v === "TRUNCATE") return whole("truncate", "clears-table");
if (v === "DROP") {
let i = verb + 1;
if (isWord(tokens[i], "TEMPORARY") || isWord(tokens[i], "TEMP")) i++;
const reason = tokens[i]?.kind === "word" ? DROPPED[tokens[i]!.upper] : undefined;
return reason ? whole("drop", reason) : null;
}
if (v === "ALTER") {
const reason = isWord(tokens[verb + 1], "TABLE") ? alterLoses(tokens, depth) : null;
return reason ? whole("alter", reason) : null;
}
if (v === "MERGE") return merged(tokens, depth);
if (v !== "DELETE" && v !== "UPDATE") return null;
const kind = v === "DELETE" ? "delete" : "update";
const where = tokens.findIndex((t, i) => i > verb && depth[i] === 0 && t.kind === "word" && t.upper === "WHERE");
if (where < 0) return whole(kind, "no-where");
let end = tokens.findIndex((t, i) => i > where && depth[i] === 0 && t.kind === "word" && AFTER_WHERE.has(t.upper));
if (end < 0) end = tokens.length;
if (end === where + 1) return null;
const condition = tokens.slice(where + 1, end);
if (evaluate(condition) !== true) return null;
return { kind, reason: "always-true", from: condition[0]!.from, to: condition.at(-1)!.to };
}
/**
* The statement an EXPLAIN runs: `EXPLAIN ANALYZE …` / `EXPLAIN (ANALYZE, …) …`
* execute it; a plain EXPLAIN (or `EXPLAIN (ANALYZE false)`) only plans it.
*/
function explained(tokens: readonly Token[]): readonly Token[] | null {
let i = 1;
let analyze = false;
if (tokens[1]?.text === "(") {
const close = closing(tokens, 1);
if (close < 0) return null;
for (const option of commaList(tokens.slice(2, close))) {
const [name, setting] = option;
if (!isWord(name, "ANALYZE") && !isWord(name, "ANALYSE")) continue;
analyze = !setting || !["FALSE", "OFF", "0"].includes(setting.upper);
}
i = close + 1;
}
while (tokens[i]?.kind === "word" && EXPLAIN_OPTIONS.has(tokens[i]!.upper)) {
if (tokens[i]!.upper !== "VERBOSE") analyze = true;
i++;
}
return analyze ? tokens.slice(i) : null;
}
/**
* A MERGE that deletes or updates every row of its target: its ON is always
* true and a `WHEN MATCHED [AND <always true>] THEN DELETE / UPDATE` applies.
*/
function merged(tokens: readonly Token[], depth: readonly number[]): UnsafeStatement | null {
const on = tokens.findIndex((t, i) => depth[i] === 0 && isWord(t, "ON"));
const whens = tokens.flatMap((t, i) => (depth[i] === 0 && isWord(t, "WHEN") ? [i] : []));
if (on < 0 || !whens.length || whens[0]! <= on + 1) return null;
const condition = tokens.slice(on + 1, whens[0]);
if (evaluate(condition) !== true) return null;
let kind: "merge-delete" | "merge-update" | null = null;
for (const [n, w] of whens.entries()) {
const clause = tokens.slice(w + 1, whens[n + 1] ?? tokens.length);
if (!isWord(clause[0], "MATCHED")) continue;
const then = clause.findIndex((t) => isWord(t, "THEN"));
if (then < 0) continue;
// `WHEN MATCHED AND <cond>` narrows the rows unless <cond> is always true too.
if (then > 1 && !(isWord(clause[1], "AND") && evaluate(clause.slice(2, then)) === true)) continue;
const verb = clause[then + 1]?.upper;
if (verb === "DELETE") kind = "merge-delete";
else if (verb === "UPDATE") kind ??= "merge-update";
}
if (!kind) return null;
return {
kind,
reason: "always-true",
from: condition[0]!.from,
to: condition.at(-1)!.to,
};
}
/**
* What an ALTER TABLE loses: a column (`DROP [COLUMN] [IF EXISTS] c`), a
* partition (`DROP / TRUNCATE PARTITION`) or the row history (`DROP SYSTEM
* VERSIONING`); `null` for drops of constraints, defaults, indexes, ….
*/
function alterLoses(tokens: readonly Token[], depth: readonly number[]): UnsafeStatement["reason"] | null {
for (let i = 0; i < tokens.length - 1; i++) {
if (depth[i] !== 0) continue;
const next = tokens[i + 1]!;
const word = next.kind === "word" ? next.upper : "";
if (isWord(tokens[i], "TRUNCATE") && (word === "PARTITION" || word === "SUBPARTITION")) return "clears-partition";
if (!isWord(tokens[i], "DROP")) continue;
if (word === "COLUMN") return "drops-column";
if (DROP_DATA[word]) return DROP_DATA[word];
if (!DROP_NOT_COLUMN.has(word)) return "drops-column";
}
return null;
}
/** The banner's text for `u`. */
export function unsafeMessage(u: UnsafeStatement): string {
switch (u.reason) {
case "clears-table":
return tx("Unsafe query: 'Truncate' statement clears all data in the table");
case "drops-table":
return tx("Unsafe query: 'Drop' statement deletes the table with all its data");
case "drops-database":
return tx("Unsafe query: 'Drop' statement deletes the database with all its data");
case "drops-schema":
return tx("Unsafe query: 'Drop' statement deletes the schema with all its objects");
case "drops-column":
return tx("Unsafe query: 'Alter' statement drops a column with all its data");
case "drops-partition":
return tx("Unsafe query: 'Alter' statement drops a partition with all its data");
case "clears-partition":
return tx("Unsafe query: 'Alter' statement clears all data in a partition");
case "drops-history":
return tx("Unsafe query: 'Alter' statement deletes the history of all rows");
}
if (u.kind === "merge-delete")
return tx("Unsafe query: 'Merge' statement deletes all rows in the table because 'on' condition is always true");
if (u.kind === "merge-update")
return tx("Unsafe query: 'Merge' statement updates all rows in the table because 'on' condition is always true");
if (u.kind === "delete")
return u.reason === "no-where"
? tx("Unsafe query: 'Delete' statement without 'where' clears all data in the table")
: tx("Unsafe query: 'Delete' statement clears all data in the table because 'where' condition is always true");
return u.reason === "no-where"
? tx("Unsafe query: 'Update' statement without 'where' updates all rows in the table")
: tx("Unsafe query: 'Update' statement updates all rows in the table because 'where' condition is always true");
}
/** A condition's constant truth; `null` when it depends on the rows (or is SQL's unknown). */
type Truth = boolean | null;
/** A constant expression's value: SQL NULL as `null`, `undefined` when it is not a constant. */
type Value = number | string | boolean | null | undefined;
/** Splits `tokens` at depth-0 words `word` (an AND closing a BETWEEN stays inside its term). */
function split(tokens: readonly Token[], word: "OR" | "AND"): Token[][] {
const depth = depths(tokens);
const parts: Token[][] = [[]];
let between = false;
tokens.forEach((t, i) => {
if (depth[i] === 0 && t.kind === "word") {
if (t.upper === "BETWEEN") between = true;
else if (t.upper === word) {
if (word === "AND" && between) between = false;
else {
parts.push([]);
return;
}
}
}
parts.at(-1)!.push(t);
});
return parts;
}
/** Splits `tokens` at depth-0 commas. */
function commaList(tokens: readonly Token[]): Token[][] {
const depth = depths(tokens);
const parts: Token[][] = [[]];
tokens.forEach((t, i) => {
if (depth[i] === 0 && t.text === ",") parts.push([]);
else parts.at(-1)!.push(t);
});
return parts;
}
/** Whether one pair of parentheses encloses all of `tokens`. */
function wrapped(tokens: readonly Token[]): boolean {
if (tokens.length < 2 || tokens[0]!.text !== "(" || tokens.at(-1)!.text !== ")") return false;
return depths(tokens)
.slice(1, -1)
.every((d) => d > 0);
}
/** The constant truth value of a condition; `null` when it depends on the rows. */
function evaluate(tokens: readonly Token[]): Truth {
const branches = split(tokens, "OR");
if (coversNull(branches)) return true;
const ors = branches.map((branch) => {
const ands = split(branch, "AND").map(term);
if (ands.some((a) => a === false)) return false;
return ands.every((a) => a === true) ? true : null;
});
if (ors.some((o) => o === true)) return true;
return ors.every((o) => o === false) ? false : null;
}
const key = (tokens: readonly Token[]) => tokens.map((t) => t.upper).join(" ");
/**
* Whether two operands are the same column expression, so `a = b` holds on
* every row where it is not NULL (a primary key never is): `id = id`,
* `t."Id" >= t."Id"`. Function calls and subqueries may differ between
* copies (`random() = random()`), so they never count.
*/
function sameOperand(a: readonly Token[], b: readonly Token[]): boolean {
if (!a.length || a.length !== b.length || key(a) !== key(b)) return false;
// Constants compare by value (`NULL = NULL` is unknown).
if (value(a) !== undefined) return false;
return !a.some((t, i) => (t.text === "(" && a[i - 1]?.kind === "word") || isWord(t, "SELECT"));
}
/** `e IS NULL OR e IS NOT NULL` (any order, among other branches): true for every row. */
function coversNull(branches: readonly Token[][]): boolean {
const isNull = new Set<string>();
const notNull = new Set<string>();
for (const b of branches) {
const n = b.length;
if (n < 3 || !isWord(b[n - 1], "NULL")) continue;
if (isWord(b[n - 2], "NOT") && isWord(b[n - 3], "IS") && n > 3) notNull.add(key(b.slice(0, n - 3)));
else if (isWord(b[n - 2], "IS")) isNull.add(key(b.slice(0, n - 2)));
}
return [...isNull].some((k) => notNull.has(k));
}
/** Whether `tokens[i]` ends an operand (so a following `-` / `+` is binary). */
function endsOperand(t: Token | undefined): boolean {
return (
!!t && (t.text === ")" || t.kind === "number" || t.kind === "string" || t.kind === "quoted" || t.kind === "word")
);
}
/** A number literal SQL and JavaScript read alike: no hex (a MySQL string), no integer past 2^53. */
function numberLiteral(text: string): number | undefined {
if (!/^(\d+(\.\d*)?|\.\d+)([eE]\d+)?$/.test(text)) return undefined;
const n = Number(text);
if (!Number.isFinite(n) || (Number.isInteger(n) && !Number.isSafeInteger(n))) return undefined;
// `0.1000000000000000001` would round to `0.1`.
return text.replace(/^[0.]+|\.|[eE].*$/g, "").length <= 15 ? n : undefined;
}
/**
* Integer arithmetic only: SQL's exact decimals (`0.1 + 0.2 = 0.3`) differ
* from JavaScript's floating point.
*/
function arithmetic(op: string, a: number, b: number): number | undefined {
if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b)) return undefined;
const r = integerArithmetic(op, a, b);
return r === undefined || Number.isSafeInteger(r) ? r : undefined;
}
function integerArithmetic(op: string, a: number, b: number): number | undefined {
switch (op) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
// Integer division truncates in some dialects: only exact quotients are certain.
case "/":
return b !== 0 && a % b === 0 ? a / b : undefined;
case "%":
return b !== 0 ? a % b : undefined;
}
return undefined;
}
const INTEGER_TYPES = new Set([
"INT",
"INTEGER",
"INT2",
"INT4",
"INT8",
"SMALLINT",
"BIGINT",
"TINYINT",
"MEDIUMINT",
"SIGNED",
"NUMERIC",
"DECIMAL",
"DEC",
]);
const TEXT_TYPES = new Set(["TEXT", "VARCHAR", "NVARCHAR", "STRING"]);
const BOOLEAN_TYPES = new Set(["BOOLEAN", "BOOL"]);
/**
* `v` cast to the type `type` names, when the cast keeps it as it is: an
* integer to a number type, a string to an unsized text type, a boolean to
* boolean. Others (`1.5::int` rounds, `'ab'::varchar(1)` truncates, `'1'::int`
* parses) are not certain.
*/
function cast(v: Value, type: readonly Token[]): Value {
if (v === undefined || v === null) return v;
if (type.length !== 1 || type[0]!.kind !== "word") return undefined;
const name = type[0]!.upper;
if (typeof v === "number") return Number.isInteger(v) && INTEGER_TYPES.has(name) ? v : undefined;
if (typeof v === "string") return TEXT_TYPES.has(name) ? v : undefined;
return BOOLEAN_TYPES.has(name) ? v : undefined;
}
/** `a IS NOT DISTINCT FROM b` / MySQL's `a <=> b`: equality where NULL equals NULL. */
function nullSafeEqual(a: Value, b: Value): Truth {
if (a === undefined || b === undefined) return null;
if (a === null || b === null) return a === b;
const c = compare(a, b, true);
return c === undefined ? null : c === 0;
}
/**
* The value of a constant expression: literals (`N'…'` too), NULL, TRUE /
* FALSE, parentheses, `+ - * / %` and casts that keep the value.
*/
function value(tokens: readonly Token[]): Value {
if (!tokens.length) return undefined;
if (wrapped(tokens)) return value(tokens.slice(1, -1));
// `N'a'` (national), `E'a'` (escapes: only without any).
const [prefix, literal] = tokens;
if (tokens.length === 2 && prefix!.kind === "word" && literal!.kind === "string" && prefix!.to === literal!.from) {
const plain = prefix!.upper === "N" || (prefix!.upper === "E" && !literal!.text.includes("\\"));
return plain ? value([literal!]) : undefined;
}
if (tokens.length === 1) {
const t = tokens[0]!;
if (t.kind === "number") return numberLiteral(t.text);
if (t.kind === "string" && t.text.startsWith("'") && t.text.endsWith("'") && t.text.length > 1)
return t.text.slice(1, -1).replaceAll("''", "'");
if (t.kind === "word") {
if (t.upper === "NULL") return null;
if (t.upper === "TRUE") return true;
if (t.upper === "FALSE") return false;
}
return undefined;
}
const depth = depths(tokens);
for (const ops of [
["+", "-"],
["*", "/", "%"],
]) {
// The rightmost operator splits first: left-associative.
for (let i = tokens.length - 1; i > 0; i--) {
const t = tokens[i]!;
if (depth[i] !== 0 || t.kind !== "punct" || !ops.includes(t.text) || !endsOperand(tokens[i - 1])) continue;
const a = value(tokens.slice(0, i));
const b = value(tokens.slice(i + 1));
if (a === undefined || b === undefined) return undefined;
if (a === null || b === null) return null;
return typeof a === "number" && typeof b === "number" ? arithmetic(t.text, a, b) : undefined;
}
}
// `CAST(<expr> AS <type>)`
if (isWord(tokens[0], "CAST") && wrapped(tokens.slice(1))) {
const inner = tokens.slice(2, -1);
const d = depths(inner);
const as = inner.findIndex((t, i) => d[i] === 0 && isWord(t, "AS"));
return as > 0 ? cast(value(inner.slice(0, as)), inner.slice(as + 1)) : undefined;
}
// `<expr>::<type>`, binding tighter than a sign (`-1::int`).
for (let i = tokens.length - 1; i > 0; i--)
if (depth[i] === 0 && tokens[i]!.text === "::") return cast(value(tokens.slice(0, i)), tokens.slice(i + 1));
const sign = tokens[0]!.text;
if (sign === "-" || sign === "+") {
const v = value(tokens.slice(1));
if (v === null) return null;
return typeof v === "number" ? (sign === "-" ? -v : v) : undefined;
}
return undefined;
}
/**
* Order of two constants (negative, 0, positive); `undefined` when they are
* not comparable for certain (different types, or strings a collation may
* order or equate differently).
*/
function compare(a: Value, b: Value, equalityOnly: boolean): number | undefined {
if (a === undefined || b === undefined || a === null || b === null || typeof a !== typeof b) return undefined;
if (typeof a === "string" && typeof b === "string") {
if (a === b) return 0;
// Case-insensitive collations (MySQL's default) equate these.
if (a.toLowerCase() === b.toLowerCase() || !equalityOnly) return undefined;
return 1;
}
return a === b ? 0 : a < b ? -1 : 1;
}
const COMPARE: Record<string, (c: number) => boolean> = {
"=": (c) => c === 0,
"<>": (c) => c !== 0,
"!=": (c) => c !== 0,
"<": (c) => c < 0,
">": (c) => c > 0,
"<=": (c) => c <= 0,
">=": (c) => c >= 0,
};
/** A LIKE pattern as a regular expression (`%` any run, `_` one character). */
function likePattern(pattern: string, flags: string): RegExp {
const body = [...pattern]
.map((c) => (c === "%" ? "[\\s\\S]*" : c === "_" ? "[\\s\\S]" : c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))
.join("");
return new RegExp(`^${body}$`, flags);
}
/** Words of a sub-SELECT that make its result depend on data. */
const SELECT_SOURCES = new Set([
"FROM",
"WHERE",
"HAVING",
"LIMIT",
"OFFSET",
"FETCH",
"GROUP",
"UNION",
"INTERSECT",
"EXCEPT",
]);
function term(tokens: readonly Token[]): Truth {
if (!tokens.length) return null;
const first = tokens[0]!;
if (isWord(first, "NOT")) {
const inner = term(tokens.slice(1));
return inner === null ? null : !inner;
}
if (wrapped(tokens)) return evaluate(tokens.slice(1, -1));
// `EXISTS (SELECT 1)`: a SELECT without a source always has a row.
if (isWord(first, "EXISTS") && wrapped(tokens.slice(1))) {
const inner = tokens.slice(2, -1);
const d = depths(inner);
const constant =
isWord(inner[0], "SELECT") &&
!inner.some((t, i) => d[i] === 0 && t.kind === "word" && SELECT_SOURCES.has(t.upper));
return constant ? true : null;
}
const depth = depths(tokens);
const at = (word: string) => tokens.findIndex((t, i) => i > 0 && depth[i] === 0 && isWord(t, word));
/** Whether NOT precedes the operator word at `i` (`NOT IN`, `NOT LIKE`, …). */
const negated = (i: number) => isWord(tokens[i - 1], "NOT");
// `<expr> IS [NOT] NULL / TRUE / FALSE / UNKNOWN / DISTINCT FROM <expr>`
const is = at("IS");
if (is > 0) {
const not = isWord(tokens[is + 1], "NOT");
const rest = tokens.slice(is + (not ? 2 : 1));
const left = tokens.slice(0, is);
if (isWord(rest[0], "DISTINCT") && isWord(rest[1], "FROM")) {
const right = rest.slice(2);
// NULL is not distinct from NULL: `x IS NOT DISTINCT FROM x` holds on every row.
const same = sameOperand(left, right) || nullSafeEqual(value(left), value(right));
return same === null ? null : same === not;
}
if (rest.length !== 1 || rest[0]!.kind !== "word") return null;
const what = rest[0]!.upper;
if (what === "NULL") {
const v = value(left);
return v === undefined ? null : (v === null) !== not;
}
if (what !== "TRUE" && what !== "FALSE" && what !== "UNKNOWN") return null;
// An unknown left side (`NULL IS UNKNOWN`) counts as not constant: `term` does not tell it from data.
const truth = term(left);
if (truth === null) return null;
return (what !== "UNKNOWN" && truth === (what === "TRUE")) !== not;
}
// `<expr> [NOT] BETWEEN <expr> AND <expr>`
const between = at("BETWEEN");
if (between > 0) {
const not = negated(between);
const and = tokens.findIndex((t, i) => i > between && depth[i] === 0 && isWord(t, "AND"));
if (and < 0) return null;
const operand = tokens.slice(0, not ? between - 1 : between);
const low = tokens.slice(between + 1, and);
const high = tokens.slice(and + 1);
// `x BETWEEN x AND x`, like `x = x`.
if (sameOperand(operand, low) && sameOperand(operand, high)) return !not;
const v = value(operand);
const lo = compare(v, value(low), false);
const hi = compare(v, value(high), false);
if (lo === undefined || hi === undefined) return null;
return lo >= 0 && hi <= 0 ? !not : not;
}
// `<expr> [NOT] IN (<expr>, …)`
const inAt = at("IN");
if (inAt > 0) {
const not = negated(inAt);
const list = tokens.slice(inAt + 1);
if (!wrapped(list) || isWord(list[1], "SELECT")) return null;
const v = value(tokens.slice(0, not ? inAt - 1 : inAt));
if (v === undefined || v === null) return null;
const items = commaList(list.slice(1, -1)).map(value);
if (items.some((i) => i === undefined)) return null;
const order = items.map((i) => compare(v, i, true));
if (order.some((o) => o === 0)) return !not;
// A NULL item (or an uncertain comparison) leaves a miss unknown.
if (items.some((i) => i === null) || order.some((o) => o === undefined)) return null;
return not;
}
// `<expr> [NOT] LIKE / ILIKE <pattern>`
const like = Math.max(at("LIKE"), at("ILIKE"));
if (like > 0) {
if (at("ESCAPE") > 0) return null;
const not = negated(like);
const v = value(tokens.slice(0, not ? like - 1 : like));
const p = value(tokens.slice(like + 1));
if (typeof v !== "string" || typeof p !== "string") return null;
const insensitive = likePattern(p, "i").test(v);
// LIKE's case sensitivity is the collation's: only agreeing answers are certain.
const matches = isWord(tokens[like], "ILIKE") ? insensitive : likePattern(p, "").test(v);
if (matches !== insensitive) return null;
return matches !== not;
}
// `<expr> <op> <expr>`
const op = tokens.findIndex((t, i) => i > 0 && depth[i] === 0 && t.kind === "punct" && t.text in COMPARE);
if (op > 0) {
// MySQL's null-safe `<=>` lexes as `<=` `>`.
const next = tokens[op + 1];
if (tokens[op]!.text === "<=" && next?.text === ">" && next.from === tokens[op]!.to)
return (
sameOperand(tokens.slice(0, op), tokens.slice(op + 2)) ||
nullSafeEqual(value(tokens.slice(0, op)), value(tokens.slice(op + 2)))
);
const left = tokens.slice(0, op);
const right = tokens.slice(op + 1);
const symbol = tokens[op]!.text;
const c = compare(value(left), value(right), ["=", "<>", "!="].includes(symbol));
if (c !== undefined) return COMPARE[symbol]!(c);
// `id = id` is true (`id <> id` false) on every row where id is not NULL.
return sameOperand(left, right) ? COMPARE[symbol]!(0) : null;
}
// A bare constant: numbers are true unless 0 (MySQL, SQLite). NULL is unknown, not false:
// `NOT NULL` matches nothing either.
const v = value(tokens);
if (typeof v === "number") return v !== 0;
if (typeof v === "boolean") return v;
return null;
}
+51 -16
Переглянути файл
@@ -63,7 +63,8 @@ import type { DiagramData } from "./erDiagram";
import type { ExportData, ExportFormat } from "./export";
import type { DbObjectRef } from "./objects";
import { formatted } from "./sql/format";
import { bindParams, findParams } from "./sql/params";
import { unsafeStatement, type UnsafeStatement } from "./sql/unsafe";
import { bindParams, findParams, unbindRange } from "./sql/params";
import { isReadOnlyQuery } from "./sql/readOnly";
import { pageFetch } from "./resultView";
import type { TableSnapshot } from "./schemaCompare";
@@ -1492,15 +1493,15 @@ export async function openDdl(id: string, schema: string, name: string): Promise
}
}
/**
* Runs the statement at `from` (or the selection `from..to`, UTF-16 offsets)
* of console `path` on its data source. Result sets open as `Result N` tabs
* of the Services view, replacing the console's unpinned ones; everything is
* logged to its Output tab; returns the outcomes (errors included) for the
* editor's marks.
*/
/** Asks for the values of the statements' query parameters and binds them; `[]` when cancelled. */
async function withParams(statements: SqlStatement[], driver: DbDriver): Promise<SqlStatement[]> {
interface BoundStatements {
/** The statements with their parameters' values in their text; `[]` when cancelled. */
statements: SqlStatement[];
/** A range of statement `i`'s bound text in its unbound text; `null` when it overlaps a value. */
unbind: (i: number, from: number, to: number) => { from: number; to: number } | null;
}
/** Asks for the values of the statements' query parameters and binds them. */
async function withParams(statements: SqlStatement[], driver: DbDriver): Promise<BoundStatements> {
let numbered = 0;
const found = statements.map((st) => {
const params = findParams(st.text, driver, numbered);
@@ -1508,15 +1509,29 @@ async function withParams(statements: SqlStatement[], driver: DbDriver): Promise
return params;
});
const names = [...new Set(found.flat().map((p) => p.name))];
if (!names.length) return statements;
const same: BoundStatements["unbind"] = (_i, from, to) => ({ from, to });
if (!names.length) return { statements, unbind: same };
const values = await new Promise<Record<string, string> | null>((resolve) =>
useDatabase.setState({ dialog: { kind: "params", names, resolve } }),
);
if (!values) return [];
if (!values) return { statements: [], unbind: same };
useDatabase.setState((s) => ({ paramValues: { ...s.paramValues, ...values } }));
return statements.map((st, i) => ({ ...st, text: bindParams(st.text, found[i]!, values) }));
return {
statements: statements.map((st, i) => ({ ...st, text: bindParams(st.text, found[i]!, values) })),
unbind: (i, from, to) => unbindRange(found[i]!, values, from, to),
};
}
/** Asks whether to run an unsafe statement (see `sql/unsafe`); false cancels the run. */
export type ConfirmUnsafe = (statement: SqlStatement, unsafe: UnsafeStatement) => Promise<boolean>;
/**
* Runs the statement at `from` (or the selection `from..to`, UTF-16 offsets)
* of console `path` on its data source. Result sets open as `Result N` tabs
* of the Services view, replacing the console's unpinned ones; everything is
* logged to its Output tab; returns the outcomes (errors included) for the
* editor's marks.
*/
export async function executeConsole(
path: string,
text: string,
@@ -1525,6 +1540,7 @@ export async function executeConsole(
/** Called once the statements are submitted, with what was submitted. */
onStart?: (statements: readonly SqlStatement[]) => void,
onProgress?: (events: readonly StatementProgress[]) => ReadonlyMap<number, DbStatementOutcome> | void,
confirmUnsafe?: ConfirmUnsafe,
): Promise<DbStatementOutcome[]> {
const id = consoleSource(path);
if (!id) {
@@ -1549,7 +1565,7 @@ export async function executeConsole(
let statementCancelled = false;
let deliveryIncomplete = false;
try {
const statements = await consoleStatements(id, text, from, to);
const statements = await consoleStatements(id, text, from, to, confirmUnsafe);
if (!current() || preparingConsoles.get(path) !== request || !statements.length) return [];
preparingConsoles.delete(path);
const prev = useDatabase.getState().running[path];
@@ -1706,10 +1722,29 @@ function capResults(results: ResultTab[], fresh: ReadonlySet<number>): ResultTab
}
/** The statements of console `path` to run or explain: the selection's, else the one at `from`, parameters bound. */
async function consoleStatements(id: string, text: string, from: number, to: number): Promise<SqlStatement[]> {
async function consoleStatements(
id: string,
text: string,
from: number,
to: number,
confirmUnsafe?: ConfirmUnsafe,
): Promise<SqlStatement[]> {
const statements: SqlStatement[] = await call(commands.dbStatements(id, text, from, to));
if (!statements.length) return [];
return withParams(statements, sourceById(id)?.driver ?? "sqlite");
const driver = sourceById(id)?.driver ?? "sqlite";
const bound = await withParams(statements, driver);
// The bound text is what runs: a parameter's value can make it unsafe (`where :cond`, `1=1`).
if (confirmUnsafe)
for (const [i, st] of bound.statements.entries()) {
const unsafe = unsafeStatement(st.text, driver);
if (!unsafe) continue;
const original = statements[i]!;
// A mark inside a parameter's value marks the whole statement.
const at = bound.unbind(i, unsafe.from, unsafe.to) ?? { from: 0, to: original.text.length };
// oxlint-disable-next-line no-await-in-loop -- each warning must be answered before asking the next
if (!(await confirmUnsafe(original, { ...unsafe, ...at }))) return [];
}
return bound.statements;
}
const PLAN_TITLE = "Query Plan";
+11
Переглянути файл
@@ -0,0 +1,11 @@
import { lazyComponent } from "@/ui";
import type { CloneSourceContribution } from "@/workbench/contributions";
/** Get from VCS › GitHub: the signed-in accounts' repositories. */
export const githubCloneSource: CloneSourceContribution = {
id: "github",
label: "GitHub",
icon: "github",
order: 10,
component: lazyComponent(() => import("./GitHubCloneSource").then((m) => m.GitHubCloneSource)),
};
+79
Переглянути файл
@@ -0,0 +1,79 @@
/**
* Per-project GitHub CLI (`gh`) account selection (`vcs.github.account` in `.openidea/settings.toml`).
* Kept free of editor/markdown imports so `GithubSettingsPage` stays within `settingsWindowBoot`.
*/
import { create } from "zustand";
import type { GhProjectAccountStatus } from "@/bindings";
import { tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import type { SelectOption } from "@/ui";
interface GhProjectAccountState {
status: GhProjectAccountStatus | null;
loading: boolean;
saving: boolean;
/** Incremented whenever the user changes the project GitHub account so open views reconnect. */
revision: number;
}
export const useGhProjectAccount = create<GhProjectAccountState>(() => ({
status: null,
loading: false,
saving: false,
revision: 0,
}));
export async function loadProjectGithubAccount(): Promise<GhProjectAccountStatus | null> {
if (!isTauri()) return useGhProjectAccount.getState().status;
useGhProjectAccount.setState({ loading: true });
try {
const status = await call(commands.ghProjectAccountStatus());
useGhProjectAccount.setState({ status, loading: false });
return status;
} catch {
useGhProjectAccount.setState({ loading: false });
return null;
}
}
export async function setProjectGithubAccount(account: string): Promise<GhProjectAccountStatus | null> {
if (!isTauri()) {
useGhProjectAccount.setState((s) => ({
status: s.status
? {
...s.status,
configuredAccount: account,
effectiveAccount: account || s.status.accounts.find((a) => a.active)?.login || null,
suggestedAccount: account ? null : s.status.suggestedAccount,
}
: null,
revision: s.revision + 1,
}));
return useGhProjectAccount.getState().status;
}
useGhProjectAccount.setState({ saving: true });
try {
const status = await call(commands.ghSetProjectAccount(account));
useGhProjectAccount.setState((s) => ({ status, saving: false, revision: s.revision + 1 }));
return status;
} catch {
useGhProjectAccount.setState({ saving: false });
return null;
}
}
export function projectAccountOptions(status: GhProjectAccountStatus | null): SelectOption[] {
const accounts = status?.accounts ?? [];
const configured = status?.configuredAccount ?? "";
const activeLogin =
accounts.find((a) => a.active)?.login ?? (!configured ? (status?.effectiveAccount ?? null) : null);
const automaticLabel = activeLogin ? tx`Automatic (${activeLogin})` : tx("Automatic");
return [
{ value: "", label: automaticLabel, verbatim: true },
...accounts.map((a) => ({ value: a.login, label: a.login, verbatim: true })),
...(configured && !accounts.some((a) => a.login === configured)
? [{ value: configured, label: tx`${configured} (not signed in)`, verbatim: true }]
: []),
];
}
+6 -1
Переглянути файл
@@ -224,7 +224,12 @@ export async function connect(
if (seq !== connectSeq) return false;
if (!repository) throw new Error(`Repository ${nameWithOwner(coordinates)} not found`);
const previous = useGhRepository.getState().connection;
if (!sameRepository(previous?.coordinates, coordinates) || previous?.root !== root) resetRepositoryData();
if (
!sameRepository(previous?.coordinates, coordinates) ||
previous?.root !== root ||
previous?.currentUser.login !== currentUser.login
)
resetRepositoryData();
setCurrentRepository({ ...coordinates, id: repository.id, root });
useGhRepository.setState((s) => ({
connection: { coordinates, repository, currentUser, root, remotes },
+75 -8
Переглянути файл
@@ -1,20 +1,87 @@
/**
* Settings › Version Control › GitHub (`GithubSettingsConfigurable`); accounts are gh's, so
* only the pull request option is here. Applies at once, like the Log page.
* Settings › Version Control › GitHub (`GithubSettingsConfigurable`): per-project GitHub CLI
* account selection (`vcs.github.account`) and pull request review options. Applies at once,
* like the Log page.
*/
import { Checkbox } from "@/ui";
import { useEffect, useId } from "react";
import { tx } from "@/platform/i18n";
import { Button, Checkbox, Select, T } from "@/ui";
import {
loadProjectGithubAccount,
projectAccountOptions,
setProjectGithubAccount,
useGhProjectAccount,
} from "../data/account";
import { setReviewDiffSettings, useReviewDiffSettings } from "./settings";
import styles from "./ReviewDiff.module.css";
export function GithubSettingsPage() {
const autoMarkViewed = useReviewDiffSettings((s) => s.autoMarkViewed);
const status = useGhProjectAccount((s) => s.status);
const saving = useGhProjectAccount((s) => s.saving);
const accountHeading = useId();
const prHeading = useId();
const selectId = useId();
useEffect(() => {
void loadProjectGithubAccount();
}, []);
const options = projectAccountOptions(status);
const value = status?.configuredAccount ?? "";
const suggested = !value ? (status?.suggestedAccount ?? null) : null;
return (
<div className={styles.page}>
<Checkbox
checked={autoMarkViewed}
onChange={(v) => setReviewDiffSettings({ autoMarkViewed: v })}
label="Automatically mark opened files as viewed"
/>
<section className={styles.section} aria-labelledby={accountHeading}>
<h2 id={accountHeading} className={styles.heading}>
<T>Account</T>
</h2>
<div className={styles.accountRow}>
<label htmlFor={selectId} className={styles.accountLabel}>
<T>GitHub account</T>:
</label>
<div className={styles.accountControl}>
<div className={styles.accountField}>
<div className={styles.accountSelect}>
<Select
id={selectId}
aria-label="GitHub account"
value={value}
disabled={saving}
options={options}
onChange={(next) => void setProjectGithubAccount(next)}
/>
</div>
{suggested && (
<Button size="small" disabled={saving} onClick={() => void setProjectGithubAccount(suggested)}>
{tx`Use ${suggested} for this project`}
</Button>
)}
</div>
<p className={styles.accountHint}>
{value ? (
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and
run configurations).
</T>
) : (
<T>Uses GitHub CLI&apos;s active account without setting GH_TOKEN in the project environment.</T>
)}
</p>
</div>
</div>
</section>
<section className={styles.section} aria-labelledby={prHeading}>
<h2 id={prHeading} className={styles.heading}>
<T>Pull Requests</T>
</h2>
<Checkbox
checked={autoMarkViewed}
onChange={(v) => setReviewDiffSettings({ autoMarkViewed: v })}
label="Automatically mark opened files as viewed"
/>
</section>
</div>
);
}
+64 -1
Переглянути файл
@@ -29,6 +29,69 @@
.page {
display: flex;
flex-direction: column;
gap: var(--space-2);
gap: var(--space-4);
padding: 4px 0;
}
.section {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.heading {
margin: 0;
padding-bottom: 4px;
border-bottom: 1px solid var(--border);
color: var(--fg-strong);
font-size: var(--fs-ui);
font-weight: 600;
}
.accountRow {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
align-items: start;
column-gap: var(--space-3);
row-gap: var(--space-1);
}
.accountLabel {
line-height: var(--h-field);
color: var(--fg);
white-space: nowrap;
}
.accountControl {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-width: 0;
}
.accountField {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
min-width: 0;
}
.accountSelect {
display: flex;
width: 280px;
max-width: 100%;
min-width: 0;
}
.accountSelect > button {
flex: 1;
min-width: 0;
}
.accountHint {
margin: 0;
max-width: 480px;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
+2 -7
Переглянути файл
@@ -12,6 +12,7 @@ import "./ui/palette.css";
import { registerActions, type Action } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { lazyComponent } from "@/ui";
import { githubCloneSource } from "./clone/source";
import {
registerCloneSource,
registerEditorKind,
@@ -257,13 +258,7 @@ export function activate(): () => void {
setContext("githubPrTab", "list");
const disposers = [
activateSettingsPages(),
registerCloneSource({
id: "github",
label: "GitHub",
icon: "github",
order: 10,
component: lazyComponent(() => import("./clone/GitHubCloneSource").then((m) => m.GitHubCloneSource)),
}),
registerCloneSource(githubCloneSource),
registerGitLogChecks(lazyComponent(() => import("./LogCommitChecks").then((m) => m.LogCommitChecks))),
registerToolWindow({
id: WINDOW,
+22 -3
Переглянути файл
@@ -8,7 +8,8 @@ import { getContext, setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { activateReviewDiff, toggleReviewDiffViewed } from "./diff";
import { reloadList } from "./data/list";
import { loadProjectGithubAccount, useGhProjectAccount } from "./data/account";
import { reloadList, useGhPrList } from "./data/list";
import { checkoutPullRequest, clearDiffCache, copyUrl, openInBrowser, openInWorktree } from "./data/local";
import { deleteMergedBranch } from "./data/operations";
import { cachedDetails, loadPullRequestData, reloadPullRequest } from "./data/pullRequest";
@@ -99,9 +100,10 @@ export const timeline = {
export function activate(): () => void {
const sync = () => {
const s = useGhRepository.getState();
const acct = useGhProjectAccount.getState().status;
setContext("githubConnected", !!s.connection);
setContext("githubTimelineActive", activeTimelinePullRequest() !== null);
useGithubShell.setState({ headerMenu: headerMenu(s) });
useGithubShell.setState({ headerMenu: headerMenu(s, acct) });
};
sync();
const disposers = [
@@ -112,10 +114,27 @@ export function activate(): () => void {
if (a?.owner !== b?.owner || a?.name !== b?.name) {
resetTabs();
clearDiffCache();
} else if (
s.connection &&
prev.connection &&
s.connection.currentUser.login !== prev.connection.currentUser.login &&
useGhPrList.getState().loaded
) {
void reloadList();
}
}),
useGhProjectAccount.subscribe((s, prev) => {
sync();
if (s.revision !== prev.revision) {
void refreshConnection();
}
}),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) resetConnection();
if (s.project?.root !== prev.project?.root) {
useGhProjectAccount.setState({ status: null, loading: false, saving: false });
resetConnection();
if (s.project) void loadProjectGithubAccount();
}
}),
activateReviewDiff(),
activateReviewMode(),
+37 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { useSettingsPages } from "@/workbench/contributions";
import { useGhProjectAccount } from "./data/account";
import { activateSettingsPages } from "./settingsPages";
import { GithubSettingsPage } from "./diff/GithubSettingsPage";
import { setReviewDiffSettings, useReviewDiffSettings } from "./diff/settings";
@@ -10,6 +11,11 @@ const KEY = "openidea.github.reviewDiff.v1";
beforeEach(() => {
localStorage.removeItem(KEY);
window.dispatchEvent(new StorageEvent("storage", { key: KEY }));
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
});
afterEach(() => {
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
});
describe("GitHub settings pages", () => {
@@ -49,4 +55,34 @@ describe("GitHub settings pages", () => {
window.dispatchEvent(new StorageEvent("storage", { key: KEY }));
expect(useReviewDiffSettings.getState().autoMarkViewed).toBe(false);
});
it("suggests a matching non-active GitHub account and shows the GH_TOKEN scope note once chosen", () => {
useGhProjectAccount.setState({
status: {
ghInstalled: true,
accounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
configuredAccount: "",
effectiveAccount: "alice",
suggestedAccount: "alice-work",
},
});
render(<GithubSettingsPage />);
const select = screen.getByRole("button", { name: "GitHub account" });
expect(select).toHaveTextContent("Automatic (alice)");
expect(
screen.getByText("Uses GitHub CLI's active account without setting GH_TOKEN in the project environment."),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Use alice-work for this project" }));
expect(screen.getByRole("button", { name: "GitHub account" })).toHaveTextContent("alice-work");
expect(useGhProjectAccount.getState().status?.configuredAccount).toBe("alice-work");
expect(
screen.getByText(
"Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).",
),
).toBeInTheDocument();
});
});
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ export function activateSettingsPages(): () => void {
id: "vcs.github",
title: "GitHub",
order: 9,
keywords: ["pull request", "viewed", "review"],
keywords: ["pull request", "viewed", "review", "account", "gh", "token"],
component: lazyComponent(() => import("./diff/GithubSettingsPage").then((m) => m.GithubSettingsPage)),
});
}
+147 -8
Переглянути файл
@@ -5,6 +5,7 @@
* the repository, `#N` tabs and "New Pull Request at {repo}" — in the header.
*/
import { useEffect, useRef, useState, type RefObject } from "react";
import type { GhProjectAccountStatus } from "@/bindings";
import type { GhAvailability } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
@@ -14,6 +15,12 @@ import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMe
import { CreatePanel } from "../create/CreatePanel";
import { DetailsPanel } from "../details/DetailsPanel";
import { ListPanel } from "../list/ListPanel";
import {
loadProjectGithubAccount,
projectAccountOptions,
setProjectGithubAccount,
useGhProjectAccount,
} from "../data/account";
import { reloadList, useGhPrList } from "../data/list";
import { cancelBusy, openInBrowser, useGhBusy } from "../data/local";
import { repositoryDisplayName } from "../data/model";
@@ -29,6 +36,42 @@ import {
import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store";
import styles from "./ToolWindow.module.css";
function ProjectAccountInline() {
const status = useGhProjectAccount((s) => s.status);
const saving = useGhProjectAccount((s) => s.saving);
if (!status || status.accounts.length === 0) return null;
const suggested = !status.configuredAccount ? status.suggestedAccount : null;
return (
<div className={styles.accountInline}>
{suggested && (
<Button
size="small"
variant="primary"
disabled={saving}
onClick={() => void setProjectGithubAccount(suggested)}
>
{tx`Use ${suggested} for this project`}
</Button>
)}
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={saving}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and run
configurations).
</T>
</div>
)}
</div>
);
}
function Unavailable({ availability }: { availability: GhAvailability }) {
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
@@ -101,6 +144,7 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
}
>
<T>Run</T> <code>gh auth login</code> <T>in a terminal, then retry.</T>
<ProjectAccountInline />
</EmptyState>
);
case "notGitHub":
@@ -115,7 +159,8 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
case "error":
return (
<EmptyState title="Could not reach GitHub" actions={retry}>
{availability.message}
<div>{availability.message}</div>
<ProjectAccountInline />
</EmptyState>
);
default:
@@ -123,12 +168,14 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
}
}
/** IntelliJ's repository selector: the repositories (owner always shown) and "View Pull Requests". */
/** IntelliJ's repository selector: the repositories (owner always shown), project account, and "View Pull Requests". */
function RepositorySelector() {
const remotes = useGhRepository((s) => s.remotes);
const defaultRemote = useGhRepository((s) => s.defaultRemote);
const connecting = useGhRepository((s) => s.connecting);
const error = useGhRepository((s) => s.connectionError);
const status = useGhProjectAccount((s) => s.status);
const savingAccount = useGhProjectAccount((s) => s.saving);
const [chosen, setChosen] = useState<string | null>(null);
const value =
chosen ??
@@ -136,6 +183,36 @@ function RepositorySelector() {
const target = remotes.find((r) => nameWithOwner(r) === value);
return (
<div className={styles.selector}>
{status && status.accounts.length > 0 && (
<>
<div className={styles.selectorRow}>
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={savingAccount}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
{!status.configuredAccount && status.suggestedAccount && (
<Button
size="small"
disabled={savingAccount}
onClick={() => void setProjectGithubAccount(status.suggestedAccount!)}
>
{tx`Use ${status.suggestedAccount} for this project`}
</Button>
)}
</div>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and
run configurations).
</T>
</div>
)}
</>
)}
<div className={styles.selectorRow}>
<Select
value={value}
@@ -231,6 +308,7 @@ export function PullRequestsToolWindow() {
const connected = useGhRepository((s) => !!s.connection);
const connecting = useGhRepository((s) => s.connecting);
useEffect(() => {
if (!useGhProjectAccount.getState().status) void loadProjectGithubAccount();
if (!useGhRepository.getState().availability) void refreshConnection();
}, []);
if (!availability)
@@ -297,21 +375,82 @@ export function PullRequestsTabs() {
);
}
/** Title actions: Create Pull Request… (+) and Select Opened Pull Request, while connected. */
/** Title actions: account switcher (when multi-account), Create Pull Request… (+) and Select Opened Pull Request. */
export function PullRequestsHeaderActions() {
const connected = useGhRepository((s) => !!s.connection);
if (!connected) return null;
const connection = useGhRepository((s) => s.connection);
const status = useGhProjectAccount((s) => s.status);
if (!connection) return null;
const showAccount = (status?.accounts.length ?? 0) > 1 || !!status?.configuredAccount;
const activeLogin = connection.currentUser.login || status?.effectiveAccount || "";
const suggested = !status?.configuredAccount ? (status?.suggestedAccount ?? null) : null;
return (
<>
{showAccount && status && activeLogin && (
<button
type="button"
className={styles.accountBadge}
title={suggested ? tx`Use ${suggested} for this project` : tx`GitHub account: @${activeLogin}`}
onClick={(e) => {
const configured = status.configuredAccount;
const defaultLogin = status.accounts.find((a) => a.active)?.login ?? null;
const autoLabel = defaultLogin ? tx`Automatic (${defaultLogin})` : tx("Automatic");
const items: MenuItem[] = [
...(suggested
? [
{
label: tx`Use ${suggested} for this project`,
verbatim: true,
run: () => void setProjectGithubAccount(suggested),
},
{ kind: "separator" as const },
]
: []),
{
label: autoLabel,
verbatim: true,
checked: configured === "",
run: () => void setProjectGithubAccount(""),
},
...status.accounts.map((a) => ({
label: `@${a.login}`,
verbatim: true,
checked: configured === a.login,
run: () => void setProjectGithubAccount(a.login),
})),
];
showContextMenu(e, items);
}}
>
@{activeLogin}
</button>
)}
<IconButton icon="plus" size="small" iconSize={16} action="github.createPullRequest" />
<IconButton icon="locate" size="small" iconSize={16} action="github.selectOpenedPullRequest" />
</>
);
}
/** The "⋮" menu's own items: Change Repository or Account… (connected, several GitHub remotes). */
export function headerMenu(s: Pick<ReturnType<typeof useGhRepository.getState>, "connection" | "remotes">): MenuItem[] {
return s.connection && s.remotes.length > 1 ? CHANGE_REPOSITORY : NONE;
/** The "⋮" menu's own items: suggested account (if any) and Change Repository or Account…. */
export function headerMenu(
s: Pick<ReturnType<typeof useGhRepository.getState>, "connection" | "remotes">,
acct?: GhProjectAccountStatus | null,
): MenuItem[] {
if (!s.connection) return NONE;
const suggested = !acct?.configuredAccount ? (acct?.suggestedAccount ?? null) : null;
const multipleAccounts = (acct?.accounts.length ?? 0) > 1 || !!acct?.configuredAccount;
if (!suggested && s.remotes.length <= 1 && !multipleAccounts) return NONE;
return [
...(suggested
? [
{
label: tx`Use ${suggested} for this project`,
verbatim: true,
run: () => void setProjectGithubAccount(suggested),
},
]
: []),
...CHANGE_REPOSITORY,
];
}
const NONE: MenuItem[] = [];
+28
Переглянути файл
@@ -36,6 +36,34 @@
.tabs {
min-width: 0;
}
.accountBadge {
flex: 0 1 auto;
height: 22px;
min-width: 48px;
max-width: 100px;
padding: 0 6px;
overflow: hidden;
border: 1px solid var(--border);
border-radius: 4px;
background: transparent;
color: var(--fg-secondary);
font-family: var(--font-ui);
font-size: var(--fs-small);
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
}
.accountBadge:hover {
background: var(--bg-hover);
color: var(--fg);
}
.accountInline {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-1-5);
margin-top: 8px;
}
/* Repository selector (several GitHub remotes) */
.selector {
+45 -1
Переглянути файл
@@ -7,9 +7,15 @@ import { provideToolWindowService, useContributions, type ToolWindowService } fr
import { activate } from "../index";
import { setCurrentRepository } from "../api/client";
import type { GHRepository, GHUser } from "../api/types";
import { useGhProjectAccount } from "../data/account";
import * as repositoryData from "../data/repository";
import { useGhRepository } from "../data/repository";
import { PullRequestsTabs, PullRequestsToolWindow } from "./PullRequestsToolWindow";
import {
PullRequestsHeaderActions,
PullRequestsTabs,
PullRequestsToolWindow,
headerMenu,
} from "./PullRequestsToolWindow";
import {
closeTab,
contextPullRequest,
@@ -86,6 +92,7 @@ describe("tool window", () => {
vi.restoreAllMocks();
setCurrentRepository(null);
useGhRepository.setState({ connection: null, availability: null, remotes: [] });
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
resetTabs();
});
@@ -193,4 +200,41 @@ describe("tool window", () => {
await act(async () => openPullRequestTab(4));
expect(screen.getByRole("tab", { name: /#4/ })).toBeTruthy();
});
it("suggests a matching GitHub account in the header menu and shows the active account badge", () => {
const connState = {
connection: {
coordinates: { owner: "org", name: "app" },
repository,
currentUser: { ...me, login: "alice" },
root: null,
remotes: [],
},
remotes: [{ owner: "org", name: "app", remote: "origin", url: "" }],
};
expect(headerMenu(connState, null)).toEqual([]);
const multiStatus = {
ghInstalled: true,
accounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
configuredAccount: "",
effectiveAccount: "alice",
suggestedAccount: "alice-work",
};
expect(headerMenu(connState, multiStatus).map((i) => ("label" in i ? i.label : ""))).toEqual([
"Use alice-work for this project",
"Change Repository or Account…",
]);
useGhRepository.setState({
availability: { kind: "ready", repo: {} as never, login: "alice" },
...connState,
});
useGhProjectAccount.setState({ status: multiStatus });
render(<PullRequestsHeaderActions />);
const badge = screen.getByRole("button", { name: "@alice" });
expect(badge).toHaveAttribute("title", "Use alice-work for this project");
});
});
+16 -1
Переглянути файл
@@ -3,7 +3,7 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-librar
import { emitLocalIdeEvent, type IdeEvent, type RemoteEntry, type Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemoteProgress } from "@/platform/remote";
import { ConnectHost } from "./ConnectDialog";
import { ConnectDialog, ConnectHost } from "./ConnectDialog";
import { closeConnectDialog, openConnectDialog, useConnectDialog } from "./model";
const { list, distros, globalSettings, openRemote, executeAction } = vi.hoisted(() => ({
@@ -153,3 +153,18 @@ it("opens a folder of the chosen WSL distribution, without browsing over SFTP",
await waitFor(() => expect(openRemote).toHaveBeenCalledWith({ kind: "wsl", distro: installed[1] }, "~"));
expect(list).not.toHaveBeenCalled();
});
it("in its own window, hands the connection to its project window and shows its failure", async () => {
const close = vi.fn();
const connect = vi.fn().mockRejectedValueOnce(new Error("Host key mismatch")).mockResolvedValueOnce(true);
render(<ConnectDialog standalone onClose={close} onConnect={connect} />);
expect(screen.queryByRole("dialog")).toBeNull();
await waitFor(() => expect(screen.getByRole("button", { name: "Open" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Open" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Host key mismatch");
expect(close).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Open" }));
await waitFor(() => expect(close).toHaveBeenCalled());
expect(connect).toHaveBeenLastCalledWith({ kind: "ssh", config: "first" }, "~");
expect(openRemote).not.toHaveBeenCalled();
});
+59 -13
Переглянути файл
@@ -1,12 +1,17 @@
/** Picks an SSH configuration and a folder on that host, then opens it in this or a new window. */
import { useEffect, useState } from "react";
/**
* Picks an SSH configuration and a folder on that host, then opens it in this or a new window.
* In the desktop app it has its own window (`connectWindow.tsx`).
*/
import { useEffect, useState, type ReactNode } from "react";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { call, commands, isCancelled, onIdeEvent, type RemoteEntry, type RemoteTarget } from "@/platform/ipc";
import { localGlobalSettings, useRemoteProgress } from "@/platform/remote";
import { sshLabel, type SshConfigValid, validateRemote } from "@/platform/remoteSettings";
import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner } from "@/ui";
import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner, type DialogButton } from "@/ui";
import { openRemoteProject } from "@/workbench/projectWindow";
import { windowBackgroundHex } from "@/workbench/theme";
import { WindowDialogFrame } from "@/workbench/WindowDialogFrame";
import {
browsableFolders,
closeConnectDialog,
@@ -47,7 +52,44 @@ function useLocalSshConfigs(): SshConfigValid[] {
return configs;
}
function ConnectDialog() {
function Frame({
standalone,
onClose,
buttons,
children,
}: {
standalone: boolean;
onClose: () => void;
buttons: readonly DialogButton[];
children: ReactNode;
}) {
const tx = useTx();
if (standalone)
return (
<WindowDialogFrame title="Remote Development" buttons={buttons} onCancel={onClose}>
{children}
</WindowDialogFrame>
);
return (
<Dialog open title={tx("Remote Development")} onClose={onClose} width={560} buttons={buttons}>
{children}
</Dialog>
);
}
/**
* `standalone`: fills the Remote Development window, whose project window connects
* (`onConnect`: true once the project is open).
*/
export function ConnectDialog({
standalone = false,
onClose = closeConnectDialog,
onConnect,
}: {
standalone?: boolean;
onClose?: () => void;
onConnect?: (target: RemoteTarget, path: string) => Promise<boolean>;
}) {
const tx = useTx();
const configs = useLocalSshConfigs();
const [picked, setSsh] = useState("");
@@ -99,7 +141,8 @@ function ConnectDialog() {
setError(null);
setBusy(true);
try {
if (await openRemoteProject(target, path.trim() || "~")) closeConnectDialog();
const dir = path.trim() || "~";
if (await (onConnect ? onConnect(target, dir) : openRemoteProject(target, dir))) onClose();
else setBusy(false);
} catch (e) {
if (!isCancelled(e)) setError(e instanceof Error ? e.message : String(e));
@@ -117,12 +160,15 @@ function ConnectDialog() {
const ready = !!name && !busy && !!path.trim();
const connecting = useRemoteProgress((s) => s.progress !== null);
const configure = () =>
standalone
? void call(commands.windowOpenSettings(SSH_SETTINGS_PAGE, false, windowBackgroundHex())).catch(() => {})
: void executeAction("file.settings", SSH_SETTINGS_PAGE);
return (
<Dialog
open
title={tx("Remote Development")}
onClose={closeConnectDialog}
width={560}
<Frame
standalone={standalone}
onClose={onClose}
buttons={[
{
label: connecting ? "Connecting…" : "Open",
@@ -134,7 +180,7 @@ function ConnectDialog() {
]}
>
<form
className={styles.form}
className={standalone ? `${styles.form} ${styles.windowForm}` : styles.form}
onSubmit={(e) => {
e.preventDefault();
if (ready) void connect();
@@ -185,7 +231,7 @@ function ConnectDialog() {
}}
aria-label={tx("SSH configuration")}
/>
<Button onClick={() => void executeAction("file.settings", SSH_SETTINGS_PAGE)}>{tx("Configure…")}</Button>
<Button onClick={configure}>{tx("Configure…")}</Button>
</div>
</>
)}
@@ -235,7 +281,7 @@ function ConnectDialog() {
</div>
)}
</form>
</Dialog>
</Frame>
);
}
+4
Переглянути файл
@@ -6,6 +6,10 @@
align-items: center;
padding: 14px var(--space-4);
}
/* In the Remote Development window the title above it gives the space. */
.windowForm {
padding-top: 0;
}
.form > * {
grid-column: 1 / -1;
}
+135
Переглянути файл
@@ -0,0 +1,135 @@
/**
* The Remote Development window (`connect-<parent>`): the connect dialog in its own native
* window. The connection is its project window's (the remote project may open in it), so the
* window hands the target over, shows the progress the project window sends back, and closes
* once the project is open; a failure stays in the window, as in the dialog.
*/
import { emitTo } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { Window } from "@tauri-apps/api/window";
import { logError } from "@/platform/errorLog";
import { call, commands, isCancelled, isTauri, type RemoteProgress, type RemoteTarget } from "@/platform/ipc";
import { isRemoteWindow, useRemoteProgress } from "@/platform/remote";
import { closeDialogWindow, useDialogWindow } from "@/workbench/dialogWindow";
import { showError } from "@/workbench/messages";
import { OverlayHost } from "@/workbench/OverlayHost";
import { openRemoteProject } from "@/workbench/projectWindow";
import { useApplyTheme, windowBackgroundHex } from "@/workbench/theme";
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
import { ConnectDialog } from "./ConnectDialog";
import { openConnectDialog, useConnectDialog } from "./model";
const REQUEST = "openidea://connect/request";
const PROGRESS = "openidea://connect/progress";
const RESULT = "openidea://connect/result";
interface ConnectRequest {
id: number;
from: string;
target: RemoteTarget;
path: string;
}
interface ConnectResult {
id: number;
opened: boolean;
error?: string;
}
/** File › Remote Development…: its own window in the desktop app, else a dialog in this page. */
export function showConnect() {
if (!isTauri() || isRemoteWindow()) return openConnectDialog();
void call(commands.windowOpenConnect(windowBackgroundHex())).catch((e: unknown) => {
logError("cannot open the Remote Development window", e);
openConnectDialog();
});
}
/** Connects for the Remote Development window, here in its project window. */
export function installConnectHandoff(): () => void {
if (!isTauri()) return () => {};
let self: ReturnType<typeof getCurrentWebviewWindow>;
try {
self = getCurrentWebviewWindow();
} catch {
return () => {}; // Not a desktop window (tests).
}
let disposed = false;
let off: (() => void) | undefined;
void self
.listen<ConnectRequest>(REQUEST, ({ payload: { id, from, target, path } }) => {
void self.setFocus().catch(() => {});
const relay = useRemoteProgress.subscribe((s) => void emitTo(from, PROGRESS, s.progress).catch(() => {}));
useConnectDialog.setState({ inWindow: true });
const reply = async (result: ConnectResult) => {
if (await Window.getByLabel(from)) return emitTo(from, RESULT, result);
// The window is gone (closed, or with this window's old project): tell it here.
if (result.error) await showError("Cannot connect to the remote host", result.error);
};
void openRemoteProject(target, path)
.then(
(opened) => reply({ id, opened }),
(e: unknown) => reply(isCancelled(e) ? { id, opened: false } : { id, opened: false, error: errorText(e) }),
)
.finally(() => {
relay();
useConnectDialog.setState({ inWindow: false });
});
})
.then((u) => (disposed ? u() : (off = u)));
return () => {
disposed = true;
off?.();
};
}
function errorText(e: unknown) {
return e instanceof Error ? e.message : String(e);
}
let nextId = 0;
/** Asks project window `parent` to connect; true once the project is open, false if it was not. */
async function requestConnect(parent: string, target: RemoteTarget, path: string): Promise<boolean> {
const self = getCurrentWebviewWindow();
const id = ++nextId;
const offs: Array<() => void> = [];
try {
const result = new Promise<ConnectResult>((resolve) => {
void self
.listen<ConnectResult>(RESULT, ({ payload }) => payload.id === id && resolve(payload))
.then((u) => {
offs.push(u);
});
});
offs.push(
await self.listen<RemoteProgress | null>(PROGRESS, ({ payload }) =>
useRemoteProgress.setState({ progress: payload }),
),
);
await emitTo(parent, REQUEST, { id, from: self.label, target, path } satisfies ConnectRequest);
const { opened, error } = await result;
if (error) throw new Error(error);
return opened;
} finally {
offs.forEach((off) => off());
useRemoteProgress.setState({ progress: null });
}
}
export function ConnectWindow() {
useApplyTheme();
const parent = useDialogWindow((s) => s.parent);
const connect = async (target: RemoteTarget, path: string) => {
if (!parent) return false;
const opened = await requestConnect(parent, target, path);
if (opened) closeDialogWindow();
return opened;
};
return (
<>
{parent && <ConnectDialog standalone onClose={closeDialogWindow} onConnect={connect} />}
<OverlayHost />
<WindowResizeHandles />
</>
);
}
+4 -2
Переглянути файл
@@ -11,10 +11,11 @@ import { confirm } from "@/workbench/messages";
import { tx } from "@/platform/i18n";
import { confirmLeaveProject } from "@/platform/project";
import { ConnectHost } from "./ConnectDialog";
import { installConnectHandoff, showConnect } from "./connectWindow";
import { reopenInContainer } from "./container";
import { installDirenvNotifications, reloadEnvironment } from "./environment";
import { RemoteStatus } from "./RemoteStatus";
import { closeConnectDialog, openConnectDialog } from "./model";
import { closeConnectDialog } from "./model";
import { restorePorts, usePorts } from "./ports";
import { installReconnect, reconnectNow } from "./reconnect";
@@ -71,6 +72,7 @@ export function activate(): () => void {
installReconnect(),
installDirenvNotifications(),
registerOverlay({ id: "remote.connect", component: ConnectHost }),
installConnectHandoff(),
registerStatusItem({
id: "remote.location",
title: "Remote Host",
@@ -86,7 +88,7 @@ export function activate(): () => void {
category: "File",
icon: "remote",
keywords: ["ssh", "remote", "server", "gateway", "connect", "host"],
run: () => openConnectDialog(),
run: () => showConnect(),
},
{
id: "remote.reconnect",
+2 -1
Переглянути файл
@@ -2,7 +2,8 @@
import { create } from "zustand";
import type { RemoteEntry, RemoteStage } from "@/platform/ipc";
export const useConnectDialog = create<{ open: boolean }>(() => ({ open: false }));
/** `open`: the dialog in this page. `inWindow`: connecting for the Remote Development window. */
export const useConnectDialog = create<{ open: boolean; inWindow: boolean }>(() => ({ open: false, inWindow: false }));
export function openConnectDialog() {
useConnectDialog.setState({ open: true });
+122
Переглянути файл
@@ -680,3 +680,125 @@ describe("Select First Failed Test When Finished", () => {
expect(testTree.selectFirstFailed).toBe(true);
});
});
describe("Track Running Test", () => {
beforeEach(() => {
localStorage.clear();
onSelect.mockClear();
});
afterEach(() => localStorage.clear());
const onSelect = vi.fn();
function Host({ results, version, running }: { results: TestResults; version: number; running: boolean }) {
const [selected, setSelected] = useState<string | null>(null);
return (
<TestTreeView
results={results}
version={version}
cwd="/p"
selected={selected}
onSelect={(id) => {
onSelect(id);
setSelected(id);
}}
running={running}
/>
);
}
const selectedRows = () => screen.queryAllByRole("treeitem", { selected: true }).map((r) => r.textContent);
const enable = (on = true) =>
localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true, trackRunning: on }));
it("selects each test as it starts, opening its collapsed suites", () => {
enable();
const results = new TestResults();
results.apply([{ type: "start", path: ["ApiTest", "lists()"] }]);
const { rerender } = render(<Host results={results} version={1} running />);
expect(selectedRows()).toEqual(["lists()"]);
expect(results.get(onSelect.mock.lastCall![0])!.name).toBe("lists()");
act(() => testTree.collapseAll!());
results.apply([
{ type: "result", path: ["ApiTest", "lists()"], status: "passed" },
{ type: "start", path: ["ApiTest", "Auth", "Tokens", "refreshes()"] },
]);
rerender(<Host results={results} version={2} running />);
expect(selectedRows()).toEqual(["refreshes()"]);
});
it("selects the latest of several tests that start together and keeps the selection while they finish", () => {
enable();
const results = new TestResults();
results.apply([{ type: "start", path: ["pkg", "TestA"] }]);
const { rerender } = render(<Host results={results} version={1} running />);
results.apply([
{ type: "start", path: ["pkg", "TestB"] },
{ type: "start", path: ["pkg", "TestC"] },
]);
rerender(<Host results={results} version={2} running />);
expect(selectedRows()).toEqual(["TestC"]);
// A test finishing, or one that was already running, doesn't move the selection.
results.apply([{ type: "result", path: ["pkg", "TestC"], status: "passed" }]);
rerender(<Host results={results} version={3} running />);
expect(selectedRows()).toEqual(["TestC"]);
fireEvent.mouseDown(screen.getByText("TestA"));
results.apply([{ type: "result", path: ["pkg", "TestB"], status: "passed" }]);
rerender(<Host results={results} version={4} running />);
expect(selectedRows()).toEqual(["TestA"]);
// The next test to start takes the selection again.
results.apply([{ type: "start", path: ["pkg", "TestD"] }]);
rerender(<Host results={results} version={5} running />);
expect(selectedRows()).toEqual(["TestD"]);
});
it("switched on mid-run, waits for the next test to start", () => {
enable(false);
const results = new TestResults();
results.apply([{ type: "start", path: ["pkg", "TestA"] }]);
const { rerender } = render(<Host results={results} version={1} running />);
act(() => testTree.toggleTrackRunning!());
rerender(<Host results={results} version={2} running />);
expect(selectedRows()).toEqual([]);
results.apply([{ type: "start", path: ["pkg", "TestB"] }]);
rerender(<Host results={results} version={3} running />);
expect(selectedRows()).toEqual(["TestB"]);
});
it("is on by default, as in IDEA, and follows nothing once the run has finished", () => {
let results = new TestResults();
results.apply([{ type: "start", path: ["ApiTest", "lists()"] }]);
const { unmount } = render(<Host results={results} version={1} running />);
expect(selectedRows()).toEqual(["lists()"]);
unmount();
onSelect.mockClear();
enable(false);
results = new TestResults();
results.apply([{ type: "start", path: ["ApiTest", "lists()"] }]);
const off = render(<Host results={results} version={1} running />);
expect(selectedRows()).toEqual([]);
off.unmount();
enable();
results = new TestResults();
results.apply([{ type: "start", path: ["ApiTest", "lists()"] }]);
render(<Host results={results} version={1} running={false} />);
expect(selectedRows()).toEqual([]);
expect(onSelect).not.toHaveBeenCalled();
});
it("the Test Runner Options toggle is remembered across sessions", () => {
const results = new TestResults();
const view = <Host results={results} version={1} running={false} />;
const { unmount } = render(view);
expect(testTree.trackRunning).toBe(true);
act(() => testTree.toggleTrackRunning!());
expect(testTree.trackRunning).toBe(false);
unmount();
expect(testTree.toggleTrackRunning).toBeNull();
render(view);
expect(testTree.trackRunning).toBe(false);
});
});
+47 -1
Переглянути файл
@@ -41,6 +41,7 @@ interface TestFilters {
showIgnored: boolean;
showDurations: boolean;
selectFirstFailed: boolean;
trackRunning: boolean;
sortAlphabetically: boolean;
sortByDuration: boolean;
}
@@ -54,6 +55,7 @@ export function loadTestFilters(): TestFilters {
showIgnored: v.showIgnored !== false,
showDurations: v.showDurations !== false,
selectFirstFailed: v.selectFirstFailed === true,
trackRunning: v.trackRunning !== false,
sortAlphabetically: v.sortAlphabetically === true && v.sortByDuration !== true,
sortByDuration: v.sortByDuration === true,
};
@@ -63,6 +65,7 @@ export function loadTestFilters(): TestFilters {
showIgnored: true,
showDurations: true,
selectFirstFailed: false,
trackRunning: true,
sortAlphabetically: false,
sortByDuration: false,
};
@@ -155,6 +158,19 @@ function suiteIds(nodes: readonly TestNode[], out: Set<string> = new Set()): Set
return out;
}
/** Tests still running, in tree order, with the suites above them. */
function runningTests(
nodes: readonly TestNode[],
ancestors: TestNode[] = [],
out: Array<{ node: TestNode; ancestors: TestNode[] }> = [],
) {
for (const n of nodes) {
if (n.children.length > 0) runningTests(n.children, [...ancestors, n], out);
else if (nodeStatus(n) === "running") out.push({ node: n, ancestors });
}
return out;
}
function filterTree(nodes: readonly TestNode[], keep: (n: TestNode) => boolean): TestNode[] {
const out: TestNode[] = [];
for (const n of nodes) {
@@ -213,7 +229,15 @@ export function TestTreeView({
rerunAutomatically,
}: TestTreeViewProps) {
const [filters, setFilters] = useState(loadTestFilters);
const { showPassed, showIgnored, showDurations, selectFirstFailed, sortAlphabetically, sortByDuration } = filters;
const {
showPassed,
showIgnored,
showDurations,
selectFirstFailed,
trackRunning,
sortAlphabetically,
sortByDuration,
} = filters;
const toggle = (key: keyof TestFilters) =>
setFilters((f) => {
const next = { ...f, [key]: !f[key] };
@@ -345,6 +369,8 @@ export function TestTreeView({
testTree.toggleDurations = () => toggle("showDurations");
testTree.selectFirstFailed = selectFirstFailed;
testTree.toggleSelectFirstFailed = () => toggle("selectFirstFailed");
testTree.trackRunning = trackRunning;
testTree.toggleTrackRunning = () => toggle("trackRunning");
return () => {
testTree.expandAll = null;
testTree.collapseAll = null;
@@ -353,6 +379,8 @@ export function TestTreeView({
testTree.toggleDurations = null;
testTree.selectFirstFailed = null;
testTree.toggleSelectFirstFailed = null;
testTree.trackRunning = null;
testTree.toggleTrackRunning = null;
};
});
@@ -372,6 +400,23 @@ export function TestTreeView({
useEffect(() => {
if (firstFailed) tree.current?.reveal(firstFailed.key);
}, [firstFailed]);
// Track Running Test: while the run is in progress, select each test as it starts, as IDEA does.
const started = useMemo(() => (running ? runningTests(roots) : []), [roots, running]);
const [startedIds, setStartedIds] = useState<ReadonlySet<string>>(new Set());
const [tracked, setTracked] = useState<{ key: string } | null>(null);
if (started.length !== startedIds.size || started.some((t) => !startedIds.has(t.node.id))) {
setStartedIds(new Set(started.map((t) => t.node.id)));
const latest = trackRunning ? started.findLast((t) => !startedIds.has(t.node.id)) : undefined;
if (latest) {
if (latest.ancestors.some((a) => !effectiveExpanded.has(a.id)))
setExpanded(new Set([...effectiveExpanded, ...latest.ancestors.map((a) => a.id)]));
setTracked({ key: latest.node.id });
}
}
useEffect(() => {
if (tracked) tree.current?.reveal(tracked.key);
}, [tracked]);
const hasSuites = roots.some((n) => n.children.length > 0);
// Previous / Next Failed Test (⌘⌥↑ / ⌘⌥↓): like IDEA, stops at the first / last failure instead of wrapping.
@@ -494,6 +539,7 @@ export function TestTreeView({
icon: "settings",
submenu: [
{ kind: "action", action: "run.toggleTestDurations" },
{ kind: "action", action: "run.toggleTrackRunningTest" },
{ kind: "action", action: "run.toggleSelectFirstFailedTest" },
],
},
+9
Переглянути файл
@@ -823,6 +823,15 @@ export function activate(): () => void {
toggled: () => testTree.showDurations === true,
run: () => testTree.toggleDurations?.(),
},
{
id: "run.toggleTrackRunningTest",
title: "Track Running Test",
category: "Run",
when: "projectOpen",
enabled: () => testTree.toggleTrackRunning !== null,
toggled: () => testTree.trackRunning === true,
run: () => testTree.toggleTrackRunning?.(),
},
{
id: "run.toggleSelectFirstFailedTest",
title: "Select First Failed Test When Finished",
+4
Переглянути файл
@@ -11,6 +11,8 @@ export const testTree: {
toggleDurations: (() => void) | null;
selectFirstFailed: boolean | null;
toggleSelectFirstFailed: (() => void) | null;
trackRunning: boolean | null;
toggleTrackRunning: (() => void) | null;
} = {
expandAll: null,
collapseAll: null,
@@ -19,4 +21,6 @@ export const testTree: {
toggleDurations: null,
selectFirstFailed: null,
toggleSelectFirstFailed: null,
trackRunning: null,
toggleTrackRunning: null,
};
+5 -3
Переглянути файл
@@ -243,6 +243,8 @@ export function CombinedDiffView({
const [viewStates] = useState(() => new Map<string, DiffViewState>());
const [entriesCache] = useState<DiffEntriesCache>(() => new Map());
const keys = useMemo(() => entries.map((e) => e.key), [entries]);
// Each diff's own key, hashing its texts: worked out once, not on every scroll frame.
const diffKeys = useMemo(() => items.map((item) => diffInput(item).key), [items]);
// Blocks that stay mounted when scrolled away: the one holding the keyboard focus, so typing still
// reaches it, and with autosave off those with unsaved staged edits, which unmounting would save.
@@ -253,12 +255,12 @@ export function CombinedDiffView({
const slot = scrollRef.current?.contains(active) ? active?.closest<HTMLElement>("[data-index]") : null;
if (slot) shown.add(Number(slot.dataset.index));
if (useProject.getState().settings?.files?.autoSave === false)
items.forEach((item, index) => {
if (ownedStagedDocument(combinedDiffDocumentOwner(tabKey, diffInput(item).key))?.dirty) shown.add(index);
diffKeys.forEach((key, index) => {
if (ownedStagedDocument(combinedDiffDocumentOwner(tabKey, key))?.dirty) shown.add(index);
});
return [...shown].sort((a, b) => a - b);
},
[items, tabKey],
[diffKeys, tabKey],
);
const virtualizer = useVirtualizer({
count: items.length,
+1 -1
Переглянути файл
@@ -172,7 +172,7 @@ describe("Commit dialog diff window (#1863)", () => {
? "[data-testid='diff-view']"
: location === "footer"
? "[data-dialog-footer] button"
: "[data-dialog-titlebar] button",
: "[data-dialog-titlebar]",
)!;
fireEvent.keyDown(target, { key: "w", code: "KeyW", metaKey: true });
expect(closeTab).not.toHaveBeenCalled();
+34 -11
Переглянути файл
@@ -26,34 +26,42 @@
}
.sidebar {
flex: 0 0 200px;
padding: var(--space-2) 0;
padding: var(--space-2) var(--space-1);
border-right: 1px solid var(--border);
background: color-mix(in srgb, var(--bg-dialog, var(--bg-elev)) 96%, var(--fg-strong));
background: var(--bg-island);
overflow: auto;
}
.sourceItem {
min-height: var(--h-row);
height: var(--h-list-row);
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-1) var(--space-3);
padding: 0 var(--space-2);
width: 100%;
border: 0;
background: none;
color: var(--fg-strong);
border-radius: var(--radius-control, 4px);
background: transparent;
color: var(--fg);
font: inherit;
text-align: left;
cursor: default;
}
.sourceItem:hover:not(:disabled) {
background: var(--bg-hover);
}
.sourceItem[data-selected] {
background: var(--bg-tree-selected);
background: var(--bg-list-selected);
color: var(--fg-strong);
}
.sourceItem:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
.sourceName {
min-width: 0;
overflow-wrap: anywhere;
font-weight: 500;
font-size: var(--fs-ui);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.form {
--clone-label-width: 112px;
@@ -190,3 +198,18 @@
display: flex;
flex-direction: column;
}
/* The Get from VCS window: the frame lays out the sources. */
.windowBody {
display: flex;
overflow: hidden;
}
.windowBody .form {
padding-top: 0;
}
.windowSources {
flex: 1;
min-height: 0;
overflow: auto;
padding: 0 var(--space-1) var(--space-2);
}
+293 -159
Переглянути файл
@@ -1,11 +1,31 @@
/** Get from VCS: clone a repository into a new folder and open it as a project. */
import { useEffect, useRef, useState } from "react";
/**
* Get from VCS: clone a repository into a new folder and open it as a project. In the desktop app
* the dialog has its own native window (`clone-<parent>`, see `cloneWindow.tsx`), which hands the
* cloned folder back to its project window to open; remote windows show it in the page.
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Channel } from "@tauri-apps/api/core";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { logError } from "@/platform/errorLog";
import { tx } from "@/platform/i18n";
import { callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { call, callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { openProject } from "@/platform/project";
import { Checkbox, Dialog, Icon, IconButton, Input, ProgressBar, Select, T, showContextMenu } from "@/ui";
import { isRemoteWindow } from "@/platform/remote";
import {
Checkbox,
Dialog,
Icon,
IconButton,
Input,
ProgressBar,
Select,
T,
showContextMenu,
type DialogButton,
} from "@/ui";
import { cloneSourceList, notifications, useCloneSources } from "@/workbench/contributions";
import { windowBackgroundHex } from "@/workbench/theme";
import { WindowDialogFrame } from "@/workbench/WindowDialogFrame";
import { openDialog } from "./dialogs";
import { progressFraction } from "./model";
import logo from "../../../src-tauri/icons/128x128.png";
@@ -106,15 +126,120 @@ async function defaultParent(): Promise<string> {
return "";
}
/** Sent by the Get from VCS window to its project window with the cloned folder. */
export const CLONED = "openidea://clone/cloned";
export function showCloneDialog(initialUrl = "") {
if (!isTauri()) {
notifications().notify({ group: "vcs", level: "warning", title: "Cloning requires the desktop app" });
return;
}
openDialog((close) => <CloneDialog onClose={close} initialUrl={initialUrl} />);
const inPage = () => openDialog((close) => <CloneDialog onClose={close} initialUrl={initialUrl} />);
if (isRemoteWindow()) {
inPage();
return;
}
void call(commands.windowOpenClone(initialUrl || null, windowBackgroundHex())).catch((e: unknown) => {
logError("cannot open the Get from VCS window", e);
inPage();
});
}
function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: string }) {
/** Opens a cloned folder as this window's project. */
async function openCloned(dir: string) {
try {
await openProject(dir);
} catch (e) {
notifications().notify({
group: "vcs",
level: "error",
title: "Cloned, but the project could not be opened",
body: e instanceof Error ? e.message : String(e),
});
}
}
/** Opens what the Get from VCS window cloned, here in its project window. */
export function installCloneHandoff(): () => void {
if (!isTauri()) return () => {};
let self: ReturnType<typeof getCurrentWebviewWindow>;
try {
self = getCurrentWebviewWindow();
} catch {
return () => {}; // Not a desktop window (tests).
}
let disposed = false;
let off: (() => void) | undefined;
void self
.listen<{ dir: string }>(CLONED, ({ payload }) => {
void self.setFocus().catch(() => {});
void openCloned(payload.dir);
})
.then((u) => (disposed ? u() : (off = u)));
return () => {
disposed = true;
off?.();
};
}
interface FrameProps {
standalone: boolean;
onCancel: () => void;
buttons: readonly DialogButton[];
children: ReactNode;
/** The clone sources; the window shows them full height. */
sidebar: ReactNode;
}
function Frame({ standalone, onCancel, buttons, children, sidebar }: FrameProps) {
if (standalone)
return (
<WindowDialogFrame
title="Get from Version Control"
buttons={buttons}
onCancel={onCancel}
sidebar={sidebar}
bodyClassName={styles.windowBody}
>
{children}
</WindowDialogFrame>
);
return (
<Dialog
open
title={
<span className={styles.dialogTitle}>
<img src={logo} alt="" draggable={false} />
<T>Clone Repository</T>
</span>
}
aria-label="Clone Repository"
onClose={onCancel}
width="min(920px, calc(100vw - 48px))"
resizable="both"
className={styles.dialog}
buttons={buttons}
>
{children}
</Dialog>
);
}
/**
* `standalone`: fills the Get from VCS window; the cloned folder goes to `onCloned` (its project
* window) instead of opening here.
*/
export function CloneDialog({
onClose,
initialUrl,
standalone = false,
onCloned,
}: {
onClose: () => void;
initialUrl: string;
standalone?: boolean;
onCloned?: (dir: string) => Promise<void>;
}) {
/** Sidebar selection: "url" (Repository URL) or a contributed source's id; each keeps its own URL. */
const [sourceId, setSourceId] = useState("url");
const [urls, setUrls] = useState<Record<string, string>>({ url: initialUrl });
@@ -188,6 +313,23 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
else void callDesktop("cancel_request", { id });
};
useEffect(() => {
if (!standalone || !isTauri()) return;
// Closing the window stops a clone in progress instead of leaving it running unseen.
let disposed = false;
let off: (() => void) | undefined;
void getCurrentWebviewWindow()
.onCloseRequested(() => {
const id = request.current;
if (id !== null) void callDesktop("cancel_request", { id });
})
.then((u) => (disposed ? u() : (off = u)));
return () => {
disposed = true;
off?.();
};
}, [standalone]);
const clone = async (picked?: string) => {
const cloneUrl = picked ?? url;
const target = (customDir ?? joinPath(parent, cloneDirName(cloneUrl))).trim();
@@ -205,17 +347,12 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel });
writeParent(parentOf(target));
rememberUrl(cloneUrl.trim());
onClose();
try {
await openProject(target);
} catch (e) {
notifications().notify({
group: "vcs",
level: "error",
title: "Cloned, but the project could not be opened",
body: e instanceof Error ? e.message : String(e),
});
if (onCloned) {
await onCloned(target);
return;
}
onClose();
await openCloned(target);
} catch (e) {
if (isCancelled(e)) setError("Clone cancelled");
else setError(e instanceof Error ? e.message : String(e));
@@ -226,165 +363,162 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
}
};
return (
<Dialog
open
title={
<span className={styles.dialogTitle}>
<img src={logo} alt="" draggable={false} />
<T>Clone Repository</T>
</span>
}
aria-label="Clone Repository"
onClose={cancel}
width="min(920px, calc(100vw - 48px))"
resizable="both"
className={styles.dialog}
buttons={[
{ label: "Clone", role: "default", disabled: !!invalid || busy, onClick: () => void clone() },
{ label: "Cancel", role: "cancel", onClick: cancel },
]}
>
<div ref={layout} className={styles.layout} data-compact={compact || undefined}>
<aside className={styles.sidebar} aria-label={tx("Clone source")}>
{[{ id: "url", label: "Repository URL", icon: "branch" }, ...sources].map((s) => (
<button
key={s.id}
type="button"
className={styles.sourceItem}
data-selected={s.id === sourceId ? "" : undefined}
aria-pressed={s.id === sourceId}
disabled={busy}
onClick={() => setSourceId(s.id)}
>
<Icon name={s.icon} size={16} />
<span className={styles.sourceName}>
<T>{s.label}</T>
</span>
</button>
))}
</aside>
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void clone();
}}
const buttons: DialogButton[] = [
{ label: "Clone", role: "default", disabled: !!invalid || busy, onClick: () => void clone() },
{ label: "Cancel", role: "cancel", onClick: cancel },
];
const sourceList = (
<aside className={standalone ? styles.windowSources : styles.sidebar} aria-label={tx("Clone source")}>
{[{ id: "url", label: "Repository URL", icon: "branch" }, ...sources].map((s) => (
<button
key={s.id}
type="button"
className={styles.sourceItem}
data-selected={s.id === sourceId ? "" : undefined}
aria-pressed={s.id === sourceId}
disabled={busy}
onClick={() => setSourceId(s.id)}
>
{source ? (
<div className={styles.sourcePane}>
<source.component url={url} onUrl={setUrl} onClone={(u) => void clone(u)} disabled={busy} />
</div>
) : (
<>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-version">
<T>Version control:</T>
</label>
<Select
id="vcs-clone-version"
aria-label="Version control"
className={styles.versionSelect}
value="git"
options={[{ value: "git", label: "Git" }]}
onChange={() => {}}
disabled={busy}
/>
</div>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-url">
<T>URL:</T>
</label>
<div ref={urlField} className={styles.comboField}>
<Input
id="vcs-clone-url"
data-autofocus
variant="bare"
className={styles.fieldInput}
value={url}
disabled={busy}
placeholder="https://github.com/user/repository.git"
onChange={(e) => setUrl(e.target.value)}
/>
<IconButton
icon="chevron-down"
size="normal"
className={styles.fieldButton}
title={recentUrls.length ? "Recent repository URLs" : "No recent repository URLs"}
disabled={busy || !recentUrls.length}
onClick={showUrlHistory}
/>
</div>
</div>
</>
)}
<Icon name={s.icon} size={16} />
<span className={styles.sourceName}>
<T>{s.label}</T>
</span>
</button>
))}
</aside>
);
const formView = (
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void clone();
}}
>
{source ? (
<div className={styles.sourcePane}>
<source.component url={url} onUrl={setUrl} onClone={(u) => void clone(u)} disabled={busy} />
</div>
) : (
<>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-version">
<T>Version control:</T>
</label>
<Select
id="vcs-clone-version"
aria-label="Version control"
className={styles.versionSelect}
value="git"
options={[{ value: "git", label: "Git" }]}
onChange={() => {}}
disabled={busy}
/>
</div>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-dir">
<T>Directory:</T>
<label htmlFor="vcs-clone-url">
<T>URL:</T>
</label>
<div className={styles.comboField}>
<div ref={urlField} className={styles.comboField}>
<Input
id="vcs-clone-dir"
id="vcs-clone-url"
data-autofocus
variant="bare"
className={styles.fieldInput}
value={dir}
value={url}
disabled={busy}
onChange={(e) => setCustomDir(e.target.value)}
placeholder="https://github.com/user/repository.git"
onChange={(e) => setUrl(e.target.value)}
/>
<IconButton
icon="folder-open"
icon="chevron-down"
size="normal"
className={styles.fieldButton}
title="Browse…"
disabled={busy}
onClick={() => void browse()}
title={recentUrls.length ? "Recent repository URLs" : "No recent repository URLs"}
disabled={busy || !recentUrls.length}
onClick={showUrlHistory}
/>
</div>
</div>
</>
)}
<div className={styles.shallowRow}>
<Checkbox
checked={shallow}
disabled={busy}
onChange={setShallow}
label={<T>Shallow clone with a history truncated to</T>}
/>
<div className={styles.depthGroup}>
<Input
aria-label="Clone depth"
className={styles.depthInput}
type="number"
inputMode="numeric"
min={1}
step={1}
value={depthInput}
disabled={busy || !shallow}
invalid={shallow && depth === null}
onChange={(e) => setDepthInput(e.target.value)}
/>
<T>commits</T>
</div>
</div>
<div className={styles.feedback}>
{busy && (
<div className={styles.progress} aria-live="polite">
<ProgressBar value={progress.fraction} aria-label="Clone progress" />
<span className={styles.hint}>{progress.line || tx("Cloning…")}</span>
</div>
)}
{error && <div className={styles.error}>{error}</div>}
{!busy && !error && url.trim() && invalid && (
<div className={styles.hint}>
<T>{invalid}</T>
</div>
)}
</div>
</form>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-dir">
<T>Directory:</T>
</label>
<div className={styles.comboField}>
<Input
id="vcs-clone-dir"
variant="bare"
className={styles.fieldInput}
value={dir}
disabled={busy}
onChange={(e) => setCustomDir(e.target.value)}
/>
<IconButton
icon="folder-open"
size="normal"
className={styles.fieldButton}
title="Browse…"
disabled={busy}
onClick={() => void browse()}
/>
</div>
</div>
</Dialog>
<div className={styles.shallowRow}>
<Checkbox
checked={shallow}
disabled={busy}
onChange={setShallow}
label={<T>Shallow clone with a history truncated to</T>}
/>
<div className={styles.depthGroup}>
<Input
aria-label="Clone depth"
className={styles.depthInput}
type="number"
inputMode="numeric"
min={1}
step={1}
value={depthInput}
disabled={busy || !shallow}
invalid={shallow && depth === null}
onChange={(e) => setDepthInput(e.target.value)}
/>
<T>commits</T>
</div>
</div>
<div className={styles.feedback}>
{busy && (
<div className={styles.progress} aria-live="polite">
<ProgressBar value={progress.fraction} aria-label="Clone progress" />
<span className={styles.hint}>{progress.line || tx("Cloning…")}</span>
</div>
)}
{error && <div className={styles.error}>{error}</div>}
{!busy && !error && url.trim() && invalid && (
<div className={styles.hint}>
<T>{invalid}</T>
</div>
)}
</div>
</form>
);
return (
<Frame standalone={standalone} onCancel={cancel} buttons={buttons} sidebar={sourceList}>
{standalone ? (
formView
) : (
<div ref={layout} className={styles.layout} data-compact={compact || undefined}>
{sourceList}
{formView}
</div>
)}
</Frame>
);
}
+68
Переглянути файл
@@ -0,0 +1,68 @@
/**
* The Get from VCS window (`clone-<parent>`): the clone dialog in its own native window. The
* cloned folder opens in the parent project window. A later Get from VCS with a URL (a
* `x-github-client` link, say) fills it in here unless a clone is running.
*/
import { create } from "zustand";
import { emitTo } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { commands } from "@/platform/ipc";
import { closeDialogWindow, useDialogWindow } from "@/workbench/dialogWindow";
import { OverlayHost } from "@/workbench/OverlayHost";
import { useApplyTheme } from "@/workbench/theme";
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
import { CLONED, CloneDialog } from "./clone";
/** Same event as `windows::LAUNCH_EVENT`: a pending launch (URL) is waiting. */
const LAUNCH_EVENT = "openidea://launch";
/** The launch's URL, with a key that remounts the form for each new one. */
const useLaunch = create<{ url: string; key: number } | null>(() => null);
/** Takes this window's launches: the first one, then each a later Get from VCS hands over. */
export function activateCloneLaunches(): () => void {
let disposed = false;
let off: (() => void) | undefined;
const take = (first: boolean) =>
void commands
.windowTakeLaunch()
.catch(() => null)
.then((l) => {
const url = l?.cloneUrl ?? "";
if (!disposed && (first || url)) useLaunch.setState((prev) => ({ url, key: (prev?.key ?? 0) + 1 }), true);
});
take(true);
void getCurrentWebviewWindow()
.listen(LAUNCH_EVENT, () => take(false))
.then((u) => (disposed ? u() : (off = u)));
return () => {
disposed = true;
off?.();
};
}
export function CloneWindow() {
useApplyTheme();
const parent = useDialogWindow((s) => s.parent);
const launch = useLaunch();
const cloned = async (dir: string) => {
if (!parent) return;
await emitTo(parent, CLONED, { dir });
closeDialogWindow();
};
return (
<>
{parent && launch && (
<CloneDialog
key={launch.key}
standalone
initialUrl={launch.url}
onClose={closeDialogWindow}
onCloned={cloned}
/>
)}
<OverlayHost />
<WindowResizeHandles />
</>
);
}
+2
Переглянути файл
@@ -46,6 +46,7 @@ import { registerCompareActions } from "./compare";
import { activateDiffViewer } from "./diffViewer";
import { installDiffEditorHost } from "./DiffWindow";
import { VcsDialogHost } from "./dialogs";
import { installCloneHandoff } from "./clone";
import { changeMarkers } from "./gutter";
import { installHunkPopup } from "./HunkPopup";
import { LOCAL_HISTORY_KIND } from "./localHistoryKind";
@@ -285,6 +286,7 @@ export function activate(): () => void {
trackMergeRebaseItem(),
installHunkPopup(),
registerOverlay({ id: "vcs.dialogs", component: VcsDialogHost }),
installCloneHandoff(),
registerOverlay({ id: "vcs.branches", component: BranchesPopupHost }),
registerOverlay({ id: "vcs.syncCommits", component: SyncCommitsPopupHost }),
activateConflictBanner(),
+1 -1
Переглянути файл
@@ -148,7 +148,7 @@ export function WelcomeView() {
const reopening = useSession((s) => s.reopening);
// A remote project connecting with no dialog or list row to show it (a new window's).
const connecting = useRemoteProgress((s) => s.location);
const connectDialog = useConnectDialog((s) => s.open);
const connectDialog = useConnectDialog((s) => s.open || s.inWindow);
const listOpening = useRecent((s) => s.opening);
const opening = useProject((s) => s.opening);
const Plugins = useSettingsPages((s) => s.pages.get(PLUGINS_PAGE)?.component);
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ await initWebRuntime();
await installCommonWindowBoot();
// Auxiliary windows (`settings-<parent>`, `comparison-<parent>-<n>`, `diff-<parent>-<n>`,
// `deployment-<parent>`) load only their own module graph, without Workbench or CodeMirror
// `deployment-<parent>`, `new-project-<parent>`, `clone-<parent>`, `connect-<parent>`) load only their own module graph, without Workbench or CodeMirror
// when not needed.
const aux = auxiliaryWindow();
+16
Переглянути файл
@@ -0,0 +1,16 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { NewProjectWindow } from "./features/app/newProjectWindow";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activateDialogWindow } from "./workbench/dialogWindow";
import { activateList } from "./windowBoot";
/** New Project window of project window `parent`: the wizard only, no workbench. */
export function bootNewProjectWindow(parent: string): ComponentType {
activateList("new project window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["dialog", () => activateDialogWindow(parent)],
]);
return NewProjectWindow;
}
+5 -1
Переглянути файл
@@ -14,9 +14,13 @@ describe("auxiliaryWindow", () => {
expect(auxiliaryWindow("editor-main-0")).toEqual({ kind: "editor", parent: "main" });
expect(auxiliaryWindow("editor-project-2-14")).toEqual({ kind: "editor", parent: "project-2" });
expect(auxiliaryWindow("deployment-project-2")).toEqual({ kind: "deployment", parent: "project-2" });
expect(auxiliaryWindow("new-project-main")).toEqual({ kind: "new-project", parent: "main" });
expect(auxiliaryWindow("new-project-project-2")).toEqual({ kind: "new-project", parent: "project-2" });
expect(auxiliaryWindow("clone-main")).toEqual({ kind: "clone", parent: "main" });
expect(auxiliaryWindow("connect-project-2")).toEqual({ kind: "connect", parent: "project-2" });
});
it.each(["settings", "comparison", "diff", "editor", "deployment"])(
it.each(["settings", "comparison", "diff", "editor", "deployment", "new-project", "clone", "connect"])(
"grants %s windows permission to close",
(kind) => {
expect(capability.windows).toContain(`${kind}-*`);
+24 -4
Переглянути файл
@@ -1,5 +1,6 @@
/**
* Auxiliary windows: Settings, comparison and deployment windows that belong
* Auxiliary windows: Settings, comparison, deployment and dialog windows (New Project, Get from VCS,
* Remote Development) that belong
* to a project window (their parent) and share its project. Labels name the
* kind and the parent (`settings-main`, `comparison-project-2-3`), mirroring
* `windows::auxiliary` in src-tauri/src/windows.rs.
@@ -8,11 +9,30 @@ import { getAllWindows, getCurrentWindow } from "@tauri-apps/api/window";
import { TauriEvent } from "@tauri-apps/api/event";
import { isTauri } from "./ipc";
export type AuxKind = "settings" | "comparison" | "diff" | "editor" | "deployment";
export type AuxKind =
| "settings"
| "comparison"
| "diff"
| "editor"
| "deployment"
| "new-project"
| "clone"
| "connect";
/** Kinds with several windows per parent (`<kind>-<parent>-<n>`); the others have one (`<kind>-<parent>`). */
const MULTIPLE: ReadonlySet<AuxKind> = new Set(["comparison", "diff", "editor"]);
const KINDS: readonly AuxKind[] = ["settings", "comparison", "diff", "editor", "deployment"];
const KINDS: readonly AuxKind[] = [
"settings",
"comparison",
"diff",
"editor",
"deployment",
"new-project",
"clone",
"connect",
];
/** Kinds that show none of the parent's documents (`AuxKind::shares_documents` in windows.rs). */
const WITHOUT_DOCUMENTS: ReadonlySet<AuxKind> = new Set(["settings", "new-project", "clone", "connect"]);
/** An auxiliary window reports to its parent whether it closed, and which documents it released. */
export const AUX_CLOSED = "openidea://auxiliary/closed";
@@ -64,7 +84,7 @@ export async function closeDocumentWindows(): Promise<boolean> {
const parent = getCurrentWindow();
const children = (await getAllWindows()).filter((window) => {
const aux = auxiliaryWindow(window.label);
return aux !== null && aux.kind !== "settings" && aux.parent === parent.label;
return aux !== null && !WITHOUT_DOCUMENTS.has(aux.kind) && aux.parent === parent.label;
});
for (const child of children) {
let finish!: (closed: boolean) => void;
+37 -3
Переглянути файл
@@ -3675,8 +3675,6 @@
"Branch '{branchName}' is already the current branch": "Branch '{branchName}' is already the current branch",
"Checkout '{name}'": "Checkout '{name}'",
"GitHub account": "GitHub account",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.",
"github-username": "github-username",
"Find actions": "Find actions",
"Resize find preview": "Resize find preview",
"Caret": "Caret",
@@ -4176,6 +4174,22 @@
"SQL INSERT": "SQL INSERT",
"SQL UPDATE": "SQL UPDATE",
"SQL DELETE": "SQL DELETE",
"Unsafe query: 'Delete' statement without 'where' clears all data in the table": "Unsafe query: 'Delete' statement without 'where' clears all data in the table",
"Unsafe query: 'Delete' statement clears all data in the table because 'where' condition is always true": "Unsafe query: 'Delete' statement clears all data in the table because 'where' condition is always true",
"Unsafe query: 'Update' statement without 'where' updates all rows in the table": "Unsafe query: 'Update' statement without 'where' updates all rows in the table",
"Unsafe query: 'Update' statement updates all rows in the table because 'where' condition is always true": "Unsafe query: 'Update' statement updates all rows in the table because 'where' condition is always true",
"Unsafe query: 'Truncate' statement clears all data in the table": "Unsafe query: 'Truncate' statement clears all data in the table",
"Unsafe query: 'Drop' statement deletes the table with all its data": "Unsafe query: 'Drop' statement deletes the table with all its data",
"Unsafe query: 'Drop' statement deletes the database with all its data": "Unsafe query: 'Drop' statement deletes the database with all its data",
"Unsafe query: 'Drop' statement deletes the schema with all its objects": "Unsafe query: 'Drop' statement deletes the schema with all its objects",
"Unsafe query: 'Alter' statement drops a column with all its data": "Unsafe query: 'Alter' statement drops a column with all its data",
"Unsafe query: 'Alter' statement drops a partition with all its data": "Unsafe query: 'Alter' statement drops a partition with all its data",
"Unsafe query: 'Alter' statement clears all data in a partition": "Unsafe query: 'Alter' statement clears all data in a partition",
"Unsafe query: 'Alter' statement deletes the history of all rows": "Unsafe query: 'Alter' statement deletes the history of all rows",
"Unsafe query: 'Merge' statement deletes all rows in the table because 'on' condition is always true": "Unsafe query: 'Merge' statement deletes all rows in the table because 'on' condition is always true",
"Unsafe query: 'Merge' statement updates all rows in the table because 'on' condition is always true": "Unsafe query: 'Merge' statement updates all rows in the table because 'on' condition is always true",
"Execute and Suppress": "Execute and Suppress",
"Executed": "Executed",
"SVG editor layout": "SVG editor layout",
"Resize SVG preview": "Resize SVG preview",
"The SVG source is not valid.": "The SVG source is not valid.",
@@ -4187,5 +4201,25 @@
"Install GitHub CLI": "Install GitHub CLI",
"Download manually…": "Download manually…",
"Show Scratches and Consoles": "Show Scratches and Consoles",
"The terminal is not available in this window.": "The terminal is not available in this window."
"The terminal is not available in this window.": "The terminal is not available in this window.",
"{value} (not signed in)": "{value} (not signed in)",
"Add account…": "Add account…",
"Sign In to GitHub CLI": "Sign In to GitHub CLI",
"Copilot CLI default ({login} via GitHub CLI)": "Copilot CLI default ({login} via GitHub CLI)",
"Copilot CLI default ({login})": "Copilot CLI default ({login})",
"Copilot CLI default (not signed in)": "Copilot CLI default (not signed in)",
"Copilot CLI default": "Copilot CLI default",
"GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch and never stored.": "GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch and never stored.",
"Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.": "Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.",
"Download GitHub CLI…": "Download GitHub CLI…",
"Checking sign-in status…": "Checking sign-in status…",
"Sign in above to view and choose models available for this account.": "Sign in above to view and choose models available for this account.",
"Click Apply to load the models available for the selected account.": "Click Apply to load the models available for the selected account.",
"Loading models for this account…": "Loading models for this account…",
"Account": "Account",
"Automatic ({activeLogin})": "Automatic ({activeLogin})",
"Use {suggested} for this project": "Use {suggested} for this project",
"GitHub account: @{activeLogin}": "GitHub account: @{activeLogin}",
"Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.": "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.",
"Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations)."
}
+3 -1
Переглянути файл
@@ -6182,5 +6182,7 @@
"Blocked command pattern": "Patrón de comando bloqueado",
"Mode applies to": "El modo se aplica a",
"Context": "Contexto",
"Allow all optional permissions": "Permitir todos los permisos opcionales"
"Allow all optional permissions": "Permitir todos los permisos opcionales",
"Get from Version Control": "Obtener del control de versiones",
"Cannot connect to the remote host": "No se puede conectar al host remoto"
}
+3 -1
Переглянути файл
@@ -5826,5 +5826,7 @@
"Blocked command pattern": "Motif de commande bloquée",
"Mode applies to": "Le mode s'applique à",
"Context": "Contexte",
"Allow all optional permissions": "Autoriser toutes les autorisations facultatives"
"Allow all optional permissions": "Autoriser toutes les autorisations facultatives",
"Get from Version Control": "Récupérer depuis le contrôle de version",
"Cannot connect to the remote host": "Impossible de se connecter à l’hôte distant"
}
+3 -1
Переглянути файл
@@ -6292,5 +6292,7 @@
"Blocked command pattern": "차단된 명령 패턴",
"Mode applies to": "모드 적용 범위",
"Context": "컨텍스트",
"Allow all optional permissions": "모든 선택 권한 허용"
"Allow all optional permissions": "모든 선택 권한 허용",
"Get from Version Control": "버전 관리에서 가져오기",
"Cannot connect to the remote host": "원격 호스트에 연결할 수 없음"
}
+3 -1
Переглянути файл
@@ -5990,5 +5990,7 @@
"Blocked command pattern": "Wzorzec zablokowanego polecenia",
"Mode applies to": "Tryb dotyczy",
"Context": "Kontekst",
"Allow all optional permissions": "Zezwól na wszystkie opcjonalne uprawnienia"
"Allow all optional permissions": "Zezwól na wszystkie opcjonalne uprawnienia",
"Get from Version Control": "Pobierz z systemu kontroli wersji",
"Cannot connect to the remote host": "Nie można połączyć się z hostem zdalnym"
}
+3 -1
Переглянути файл
@@ -6005,5 +6005,7 @@
"Blocked command pattern": "Padrão de comando bloqueado",
"Mode applies to": "O modo se aplica a",
"Context": "Contexto",
"Allow all optional permissions": "Permitir todas as permissões opcionais"
"Allow all optional permissions": "Permitir todas as permissões opcionais",
"Get from Version Control": "Obter do controle de versão",
"Cannot connect to the remote host": "Não é possível conectar ao host remoto"
}
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more