дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
3
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
66a373ad4d | ||
|
|
1634386129 | ||
|
|
4780bf9950 |
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("remote project opening stays inside its project tab with progress and Cancel", async ({ workbench: page }) => {
|
||||
await page.evaluate(async () => {
|
||||
const projectMod = "/src/platform/project.ts";
|
||||
const remoteMod = "/src/platform/remote.ts";
|
||||
const windowGroupsMod = "/src/platform/windowGroups.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectMod);
|
||||
const { useRemoteProgress } = await import(/* @vite-ignore */ remoteMod);
|
||||
const { useWindowGroup } = await import(/* @vite-ignore */ windowGroupsMod);
|
||||
const location = "ssh://[email protected]/Users/mac/repo/idea";
|
||||
useWindowGroup.setState({
|
||||
tabs: [
|
||||
{ label: "main", name: "idea", root: "/Users/me/idea", current: false },
|
||||
{ label: "project-1", name: "opengui", root: "/Users/me/opengui", current: false },
|
||||
{
|
||||
label: "project-2",
|
||||
name: "idea",
|
||||
root: location,
|
||||
current: true,
|
||||
remoteHost: "[email protected]",
|
||||
},
|
||||
],
|
||||
});
|
||||
useProject.setState({ project: null, opening: true, openingPath: location });
|
||||
useRemoteProgress.setState({
|
||||
location,
|
||||
progress: { stage: "uploading", fraction: 0.68 },
|
||||
});
|
||||
});
|
||||
|
||||
const opening = page.locator("[data-project-opening]");
|
||||
await expect(opening).toBeVisible();
|
||||
await expect(opening.getByText("Welcome to OpenIDEA")).toHaveCount(0);
|
||||
await expect(opening.getByRole("button", { name: "idea", exact: true })).toBeVisible();
|
||||
await expect(opening.locator('[data-project-tab="project-1"]')).toBeVisible();
|
||||
await expect(opening.locator('[data-project-tab="project-2"]')).toBeVisible();
|
||||
await expect(opening.getByText("Opening idea…")).toBeVisible();
|
||||
await expect(opening.getByText("Installing the IDE backend on the host… 68%")).toBeVisible();
|
||||
await expect(opening.getByText("SSH: [email protected] — /Users/mac/repo/idea")).toBeVisible();
|
||||
|
||||
const bar = opening.getByRole("progressbar");
|
||||
await expect(bar).toHaveAttribute("aria-valuenow", "68");
|
||||
const fillWidthRatio = await bar.evaluate((el) => {
|
||||
const track = el.getBoundingClientRect().width;
|
||||
const fill = el.firstElementChild?.getBoundingClientRect().width ?? 0;
|
||||
return track > 0 ? fill / track : 0;
|
||||
});
|
||||
expect(fillWidthRatio).toBeGreaterThan(0.6);
|
||||
expect(fillWidthRatio).toBeLessThan(0.75);
|
||||
|
||||
// Verify opening body stays within viewport at the minimum window width (400px).
|
||||
await page.setViewportSize({ width: 400, height: 500 });
|
||||
const status = opening.getByRole("status");
|
||||
const overflow = await status.evaluate((el) => el.scrollWidth > el.clientWidth + 1);
|
||||
expect(overflow).toBe(false);
|
||||
|
||||
// Clicking Cancel clears the opening state.
|
||||
await opening.getByRole("button", { name: "Cancel" }).click();
|
||||
await expect(opening).toHaveCount(0);
|
||||
});
|
||||
@@ -15,17 +15,26 @@ use tauri::{AppHandle, State, WebviewWindow, Window};
|
||||
|
||||
/// 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.
|
||||
/// `files` then open in that project's editor.
|
||||
/// `files` then open in that project's editor. When `in_tab` is true, the opened
|
||||
/// or focused window joins this window's tab group directly without flashing as
|
||||
/// a separate window.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_project(
|
||||
app: AppHandle,
|
||||
window: WebviewWindow,
|
||||
path: PathBuf,
|
||||
new_window: bool,
|
||||
files: Vec<PathBuf>,
|
||||
in_tab: bool,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
windows::open_project_window(&app, &path, new_window, files)
|
||||
let tab_anchor = in_tab.then(|| window.label());
|
||||
let outcome = windows::open_project_window(&app, &path, new_window, files, tab_anchor)?;
|
||||
if tab_anchor.is_some() && !matches!(outcome, OpenOutcome::Current) {
|
||||
crate::window_groups::persist(&app).await?;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Loose `files` opened from a window without a local project: a file inside a local project
|
||||
@@ -64,11 +73,18 @@ pub async fn window_open_file_in_new_window(
|
||||
#[specta::specta]
|
||||
pub async fn window_open_remote(
|
||||
app: AppHandle,
|
||||
window: WebviewWindow,
|
||||
target: crate::remote_dev::RemoteTarget,
|
||||
path: String,
|
||||
new_window: bool,
|
||||
in_tab: bool,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
windows::open_remote_window(&app, &target, &path, new_window)
|
||||
let tab_anchor = in_tab.then(|| window.label());
|
||||
let outcome = windows::open_remote_window(&app, &target, &path, new_window, tab_anchor)?;
|
||||
if tab_anchor.is_some() && !matches!(outcome, OpenOutcome::Current) {
|
||||
crate::window_groups::persist(&app).await?;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Opens an empty (welcome) window; returns its label.
|
||||
|
||||
@@ -225,6 +225,11 @@ impl Connections {
|
||||
true
|
||||
}
|
||||
|
||||
/// Invalidates an in-flight connect attempt without dropping an already-active connection.
|
||||
pub fn cancel(&self, window: &str) {
|
||||
self.bump(window);
|
||||
}
|
||||
|
||||
pub fn disconnect(&self, window: &str) {
|
||||
// Invalidate an attempt that has not published yet, or it would put the
|
||||
// connection back after this disconnect.
|
||||
@@ -837,7 +842,6 @@ pub async fn remote_connect(
|
||||
if !server_path(&root) {
|
||||
return Err(IdeError::invalid(format!("openidea-server opened an unexpected project folder: {root}")));
|
||||
}
|
||||
let _ = window.set_title(&format!("{} [{title_tag}]", project.display_name));
|
||||
let connection = Arc::new(Connection {
|
||||
peer,
|
||||
stopping: AtomicBool::new(false),
|
||||
@@ -868,6 +872,7 @@ pub async fn remote_connect(
|
||||
connection.forwards.lock().clear();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let _ = window.set_title(&format!("{} [{title_tag}]", project.display_name));
|
||||
state.host.close_project(&label);
|
||||
state.host.mcp_reports.set_remote(&label, std::path::PathBuf::from(&connection.root));
|
||||
crate::window_groups::notify_changed(window.app_handle());
|
||||
@@ -1343,6 +1348,14 @@ pub async fn remote_stop_forwarding(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cancels an in-flight `remote_connect` attempt without dropping an already-active remote session.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn remote_cancel_connect(window: Window, state: State<'_, AppState>) {
|
||||
state.remote_dev.cancel(AppState::owner_window(window.label()));
|
||||
}
|
||||
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -1757,6 +1770,25 @@ mod tests {
|
||||
newer.peer.kill();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_a_connect_attempt_keeps_an_existing_connection() {
|
||||
let connections = Connections::default();
|
||||
let active_attempt = connections.begin("main");
|
||||
let active = Arc::new(connected(RemoteTarget::Ssh { config: "a".into() }, "/srv/a"));
|
||||
assert!(connections.publish("main", active_attempt, active.clone()));
|
||||
|
||||
let replacement_attempt = connections.begin("main");
|
||||
connections.cancel("main");
|
||||
assert!(Arc::ptr_eq(&connections.get("main").unwrap(), &active));
|
||||
|
||||
let replacement = Arc::new(connected(RemoteTarget::Ssh { config: "b".into() }, "/srv/b"));
|
||||
assert!(!connections.publish("main", replacement_attempt, replacement.clone()));
|
||||
assert!(Arc::ptr_eq(&connections.get("main").unwrap(), &active));
|
||||
|
||||
active.peer.kill();
|
||||
replacement.peer.kill();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_server_does_not_decide_trust_for_commands_run_here() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1821,6 +1853,7 @@ mod tests {
|
||||
|
||||
ide_command::desktop_domain!(
|
||||
remote_bootstrap_list,
|
||||
remote_cancel_connect,
|
||||
remote_connect,
|
||||
remote_current,
|
||||
remote_devcontainer_check_requirements,
|
||||
|
||||
@@ -309,7 +309,7 @@ pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Opt
|
||||
.next()
|
||||
.filter(|n| !n.is_empty() && *n != "~")
|
||||
.map(str::to_owned);
|
||||
return Ok(Some(create_window_for(app, title, launch, true)?));
|
||||
return Ok(Some(create_window_for(app, title, launch, true, None)?));
|
||||
}
|
||||
if let Some(w) = find_project_window(app, path) {
|
||||
return Ok(Some(w));
|
||||
@@ -1210,7 +1210,7 @@ pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
|
||||
|
||||
/// Creates a new project window; `project` is opened by its frontend on load.
|
||||
pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<WebviewWindow> {
|
||||
create_window_with(app, project, Vec::new(), false)
|
||||
create_window_with(app, project, Vec::new(), false, None)
|
||||
}
|
||||
|
||||
/// [`create_window`] that also opens `files` (without `project`: in LightEdit).
|
||||
@@ -1219,26 +1219,43 @@ fn create_window_with(
|
||||
project: Option<PathBuf>,
|
||||
files: Vec<PathBuf>,
|
||||
restoring: bool,
|
||||
tab_anchor: Option<&str>,
|
||||
) -> IdeResult<WebviewWindow> {
|
||||
let title = project.as_deref().or(files.first().map(PathBuf::as_path)).and_then(Path::file_name);
|
||||
let title = title.map(|n| n.to_string_lossy().into_owned());
|
||||
let files = files.into_iter().map(Into::into).collect();
|
||||
create_window_for(app, title, Launch { project: project.map(Into::into), files, ..Default::default() }, restoring)
|
||||
create_window_for(
|
||||
app,
|
||||
title,
|
||||
Launch { project: project.map(Into::into), files, ..Default::default() },
|
||||
restoring,
|
||||
tab_anchor,
|
||||
)
|
||||
}
|
||||
|
||||
/// Restoring a saved group preserves its membership and selected tab.
|
||||
pub fn create_restored_window(app: &AppHandle, project: PathBuf) -> IdeResult<WebviewWindow> {
|
||||
create_window_with(app, Some(project), Vec::new(), true)
|
||||
create_window_with(app, Some(project), Vec::new(), true, None)
|
||||
}
|
||||
|
||||
fn create_window_for(
|
||||
app: &AppHandle,
|
||||
title: Option<String>,
|
||||
launch: Launch,
|
||||
_restoring: bool,
|
||||
restoring: bool,
|
||||
tab_anchor: Option<&str>,
|
||||
) -> IdeResult<WebviewWindow> {
|
||||
let explicit_tab = if restoring { None } else { tab_anchor.and_then(|label| app.get_webview_window(label)) };
|
||||
#[cfg(target_os = "macos")]
|
||||
let tab_target = if _restoring { None } else { crate::macos::new_project_tab_target(app, &launch)? };
|
||||
let tab_target = if restoring {
|
||||
None
|
||||
} else if explicit_tab.is_some() {
|
||||
explicit_tab
|
||||
} else {
|
||||
crate::macos::new_project_tab_target(app, &launch)?
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let tab_target = explicit_tab;
|
||||
// The label is free only until the window exists, so concurrent opens take turns.
|
||||
let creating = CREATING.lock();
|
||||
let windows = app.webview_windows();
|
||||
@@ -1259,11 +1276,12 @@ fn create_window_for(
|
||||
config.center = false;
|
||||
}
|
||||
app.state::<WindowsState>().set_launch(&label, launch);
|
||||
#[cfg(target_os = "macos")]
|
||||
if tab_target.is_some() {
|
||||
#[cfg(target_os = "macos")]
|
||||
JOINING_GROUP.lock().push(label.clone());
|
||||
// Selecting it in the group shows it; shown before, a window opened over a fullscreen
|
||||
// group lands on the desktop and takes the screen there.
|
||||
// group lands on the desktop and takes the screen there, and an explicit New Tab would
|
||||
// briefly flash as a standalone window before joining the group.
|
||||
config.visible = false;
|
||||
}
|
||||
let window = build_project_window(app, config);
|
||||
@@ -1275,7 +1293,6 @@ fn create_window_for(
|
||||
let _ = app.run_on_main_thread(move || JOINING_GROUP.lock().retain(|l| *l != joined));
|
||||
}
|
||||
let window = window?;
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(target) = tab_target {
|
||||
match crate::window_groups::join(app, target.label(), window.label()) {
|
||||
Ok(()) => {
|
||||
@@ -1293,6 +1310,10 @@ fn create_window_for(
|
||||
if window.show().is_err() {
|
||||
return Err(error);
|
||||
}
|
||||
if tab_anchor.is_some() {
|
||||
focus(&window);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1314,11 +1335,11 @@ fn spawn_window_with(app: &AppHandle, project: Option<PathBuf>, files: Vec<PathB
|
||||
|
||||
fn open_launch_window(app: &AppHandle, title: Option<String>, launch: Launch, wait: bool) -> IdeResult<()> {
|
||||
if wait {
|
||||
return create_window_for(app, title, launch, false).map(|_| ());
|
||||
return create_window_for(app, title, launch, false, None).map(|_| ());
|
||||
}
|
||||
let app = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(e) = create_window_for(&app, title, launch, false) {
|
||||
if let Err(e) = create_window_for(&app, title, launch, false, None) {
|
||||
tracing::warn!("cannot open window: {}", e.message);
|
||||
}
|
||||
});
|
||||
@@ -1338,21 +1359,30 @@ pub enum OpenOutcome {
|
||||
}
|
||||
|
||||
/// Opens folder `path` as a project and then `files` in its editor; see [`OpenOutcome`]
|
||||
/// (`Current`: the caller opens both itself).
|
||||
/// (`Current`: the caller opens both itself). When `tab_anchor` is set, the opened or
|
||||
/// already-open project window joins that window's tab group before it is shown.
|
||||
pub fn open_project_window(
|
||||
app: &AppHandle,
|
||||
path: &Path,
|
||||
new_window: bool,
|
||||
files: Vec<PathBuf>,
|
||||
tab_anchor: Option<&str>,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
// Before touching the share: a stat on `\\wsl.localhost` is what makes it slow.
|
||||
if let Some(remote) = wsl_launch(path) {
|
||||
return open_remote_window(app, &remote.target, &remote.path, new_window);
|
||||
return open_remote_window(app, &remote.target, &remote.path, new_window, tab_anchor);
|
||||
}
|
||||
let root = dunce::canonicalize(path).map_err(|e| IdeError::not_found(format!("{}: {e}", path.display())))?;
|
||||
tracing::info!("open_project_window {} new_window={new_window}", root.display());
|
||||
tracing::info!("open_project_window {} new_window={new_window} tab_anchor={tab_anchor:?}", root.display());
|
||||
if let Some(w) = find_project_window(app, &root) {
|
||||
if files.is_empty() {
|
||||
if let Some(anchor) = tab_anchor
|
||||
&& w.label() != anchor
|
||||
{
|
||||
crate::window_groups::join(app, anchor, w.label())?;
|
||||
if !files.is_empty() {
|
||||
send_files(app, &w, files);
|
||||
}
|
||||
} else if files.is_empty() {
|
||||
focus(&w);
|
||||
} else {
|
||||
send_files(app, &w, files);
|
||||
@@ -1362,7 +1392,7 @@ pub fn open_project_window(
|
||||
if !new_window {
|
||||
return Ok(OpenOutcome::Current);
|
||||
}
|
||||
let window = create_window_with(app, Some(root), files, false)?;
|
||||
let window = create_window_with(app, Some(root), files, false, tab_anchor)?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
@@ -1372,7 +1402,7 @@ pub fn open_project_window(
|
||||
/// detach an editor tab out of its window.
|
||||
pub fn open_file_in_new_window(app: &AppHandle, project: Option<PathBuf>, file: PathBuf) -> IdeResult<OpenOutcome> {
|
||||
tracing::info!("open_file_in_new_window {} project={:?}", file.display(), project);
|
||||
let window = create_window_with(app, project, vec![file], false)?;
|
||||
let window = create_window_with(app, project, vec![file], false, None)?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
@@ -1391,12 +1421,19 @@ pub fn open_remote_window(
|
||||
target: &RemoteTarget,
|
||||
path: &str,
|
||||
new_window: bool,
|
||||
tab_anchor: Option<&str>,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
tracing::info!("open_remote_window {target:?}:{path} new_window={new_window}");
|
||||
tracing::info!("open_remote_window {target:?}:{path} new_window={new_window} tab_anchor={tab_anchor:?}");
|
||||
let windows = app.webview_windows();
|
||||
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(target, path));
|
||||
if let Some(w) = open.and_then(|label| windows.get(&label)) {
|
||||
focus(w);
|
||||
if let Some(anchor) = tab_anchor
|
||||
&& w.label() != anchor
|
||||
{
|
||||
crate::window_groups::join(app, anchor, w.label())?;
|
||||
} else {
|
||||
focus(w);
|
||||
}
|
||||
return Ok(OpenOutcome::Focused { label: w.label().to_owned() });
|
||||
}
|
||||
if !new_window {
|
||||
@@ -1404,7 +1441,8 @@ pub fn open_remote_window(
|
||||
}
|
||||
let title = path.trim_end_matches('/').rsplit('/').next().filter(|n| !n.is_empty() && *n != "~").map(str::to_owned);
|
||||
let remote = RemoteLaunch { target: target.clone(), path: path.to_owned() };
|
||||
let window = create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() }, false)?;
|
||||
let window =
|
||||
create_window_for(app, title, Launch { remote: Some(remote), ..Default::default() }, false, tab_anchor)?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
|
||||
@@ -669,6 +669,7 @@ refactor_move_files always project_host bin
|
||||
refactor_python_mention_edits always project_host bindings async
|
||||
refactor_undo_file_move always project_host bindings async
|
||||
remote_bootstrap_list always desktop bindings async
|
||||
remote_cancel_connect always desktop bindings sync
|
||||
remote_connect always desktop bindings async
|
||||
remote_current always desktop bindings sync
|
||||
remote_delete trusted project_host bindings async
|
||||
|
||||
@@ -1939,6 +1939,8 @@ export const commands = {
|
||||
refactorUndoFileMove: (id: number) => typedError<UndoOutcome, IdeError>(__TAURI_INVOKE("refactor_undo_file_move", { id })),
|
||||
/** Browse before connecting, using the desktop's SSH configuration even in a remote window. */
|
||||
remoteBootstrapList: (ssh: string, path: string) => typedError<RemoteEntry[], IdeError>(__TAURI_INVOKE("remote_bootstrap_list", { ssh, path })),
|
||||
/** Cancels an in-flight `remote_connect` attempt without dropping an already-active remote session. */
|
||||
remoteCancelConnect: () => __TAURI_INVOKE<void>("remote_cancel_connect"),
|
||||
/**
|
||||
* File › Remote Development: opens `path` on `target` (an SSH host, a WSL distribution, or a
|
||||
* dev container, whose project folder is the container's own) in this window (installs /
|
||||
@@ -3046,16 +3048,18 @@ export const commands = {
|
||||
/**
|
||||
* 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.
|
||||
* `files` then open in that project's editor.
|
||||
* `files` then open in that project's editor. When `in_tab` is true, the opened
|
||||
* or focused window joins this window's tab group directly without flashing as
|
||||
* a separate window.
|
||||
*/
|
||||
windowOpenProject: (path: string, newWindow: boolean, files: string[]) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_project", { path, newWindow, files })),
|
||||
windowOpenProject: (path: string, newWindow: boolean, files: string[], inTab: boolean) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_project", { path, newWindow, files, inTab })),
|
||||
/** Projects open in project windows, in window order (title bar project widget). */
|
||||
windowOpenProjects: () => typedError<OpenProject[], IdeError>(__TAURI_INVOKE("window_open_projects")),
|
||||
/**
|
||||
* [`window_open_project`] for folder `path` of `target` (an SSH host or a WSL distribution;
|
||||
* Remote Development); a new window connects itself.
|
||||
*/
|
||||
windowOpenRemote: (target: RemoteTarget, path: string, newWindow: boolean) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_remote", { target, path, newWindow })),
|
||||
windowOpenRemote: (target: RemoteTarget, path: string, newWindow: boolean, inTab: boolean) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_remote", { target, path, newWindow, inTab })),
|
||||
/**
|
||||
* Opens this window's Settings window on `page` (or focuses it and navigates);
|
||||
* `new_projects` edits the global layer only ("Settings for New Projects").
|
||||
|
||||
@@ -150,7 +150,7 @@ describe("openProjectInWindow", () => {
|
||||
it("opens in this window when the backend says `current`", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectInWindow("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", false, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", false, [], false);
|
||||
expect(openProject).toHaveBeenCalledWith("/p/a");
|
||||
});
|
||||
|
||||
@@ -172,7 +172,7 @@ describe("openProjectInWindow", () => {
|
||||
useProject.setState(projectState("/p/b") as never);
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
await openProjectInWindow("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true, [], false);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -180,7 +180,7 @@ describe("openProjectInWindow", () => {
|
||||
useProject.setState({ lightEdit: true });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
await openProjectInWindow("/p/a", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/a", true, [], false);
|
||||
});
|
||||
|
||||
it("does nothing locally when another window was focused", async () => {
|
||||
@@ -230,7 +230,7 @@ describe("replacing a project in this window", () => {
|
||||
vi.mocked(isRemoteWindow).mockReturnValue(true);
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectWithPolicy("/same");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/same", false, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/same", false, [], false);
|
||||
expect(openProject).toHaveBeenCalledWith("/same");
|
||||
});
|
||||
});
|
||||
@@ -246,7 +246,7 @@ describe("a recent project opened with a modifier key", () => {
|
||||
useProject.setState({ ...projectState("/p/a"), settings: { general: { openProjectIn: policy } } } as never);
|
||||
windowOpenProject.mockResolvedValue(ok(newWindow ? { kind: "opened", label: "project-2" } : { kind: "current" }));
|
||||
await openProjectWithPolicy("/p/b", [], override);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", newWindow, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", newWindow, [], false);
|
||||
expect(ask).not.toHaveBeenCalled();
|
||||
// Only the current window takes the project here; a new one leaves this project alone.
|
||||
expect(openProject.mock.calls).toEqual(newWindow ? [] : [["/p/b"]]);
|
||||
@@ -255,7 +255,7 @@ describe("a recent project opened with a modifier key", () => {
|
||||
it("opens a new window from a window that has no project", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-2" }));
|
||||
await openProjectWithPolicy("/p/b", [], "new");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, [], false);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -272,16 +272,16 @@ describe("a recent project opened with a modifier key", () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-2" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openRecentProject")!;
|
||||
await action.run({ arg: { path: "/p/b", window: "new" } } as never);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", true, []);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", true, [], false);
|
||||
await action.run({ arg: "/p/b" } as never);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", false, []);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", false, [], false);
|
||||
});
|
||||
|
||||
it("opens a Remote Development project from Open Recent on its host (#6124)", async () => {
|
||||
windowOpenRemote.mockResolvedValue(ok({ kind: "focused" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openRecentProject")!;
|
||||
await action.run({ arg: "wsl://Ubuntu/home/me/api" } as never);
|
||||
expect(windowOpenRemote).toHaveBeenCalledWith({ kind: "wsl", distro: "Ubuntu" }, "/home/me/api", false);
|
||||
expect(windowOpenRemote).toHaveBeenCalledWith({ kind: "wsl", distro: "Ubuntu" }, "/home/me/api", false, false);
|
||||
expect(windowOpenProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -334,7 +334,7 @@ describe("loose files (LightEdit)", () => {
|
||||
useProject.setState({ settings: { general: { openProjectIn: "new" } } } as never);
|
||||
await openPaths(["/x/a.txt", "/work/app"], async (p) => p === "/work/app");
|
||||
expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/work/app", true, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/work/app", true, [], false);
|
||||
});
|
||||
|
||||
it("opens a dropped folder alone exactly as before", async () => {
|
||||
@@ -374,7 +374,7 @@ describe("Open Containing Folder as Project", () => {
|
||||
activePath = "/x/notes/a.txt";
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
await openLightEditFileAsProject();
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/x/notes", true, ["/x/notes/a.txt"]);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/x/notes", true, ["/x/notes/a.txt"], false);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -383,7 +383,7 @@ describe("Open Containing Folder as Project", () => {
|
||||
activePath = "/x/notes/a.txt";
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openLightEditFileAsProject();
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/x/notes", false, ["/x/notes/a.txt"]);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/x/notes", false, ["/x/notes/a.txt"], false);
|
||||
expect(openProject).toHaveBeenCalledWith("/x/notes");
|
||||
expect(useProject.getState()).toMatchObject({ lightEdit: false, project: { root: "/x/notes" } });
|
||||
expect(opened).toEqual(["/x/notes/a.txt (focus)"]);
|
||||
@@ -439,6 +439,18 @@ describe("launch", () => {
|
||||
expect(opened).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not report an error when a remote launch is cancelled", async () => {
|
||||
windowTakeLaunch.mockResolvedValueOnce({
|
||||
remote: { target: { kind: "ssh", config: "box" }, path: "/srv/idea" },
|
||||
});
|
||||
vi.mocked(connectRemote).mockRejectedValueOnce(
|
||||
new IpcError({ kind: "cancelled", message: "Remote connection cancelled" }),
|
||||
);
|
||||
await consumeLaunch();
|
||||
expect(connectRemote).toHaveBeenCalledWith({ kind: "ssh", config: "box" }, "/srv/idea");
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("serializes launch events while their project is opening", async () => {
|
||||
const openedProject = deferred();
|
||||
openProject.mockImplementationOnce(async (path) => {
|
||||
@@ -807,14 +819,14 @@ describe("Attach", () => {
|
||||
});
|
||||
|
||||
describe("Project tabs", () => {
|
||||
it("opens the project in its own window and joins that window into this window's group", async () => {
|
||||
it("opens the project directly into this window's tab group", async () => {
|
||||
useProject.setState(projectState("/p/a"));
|
||||
vi.mocked(ask).mockResolvedValueOnce({ button: "tab", checked: false });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "main-2" }));
|
||||
await openProjectWithPolicy("/p/b", ["/p/b/file.txt"]);
|
||||
expect(confirmProjectTrust).toHaveBeenCalledWith("/p/b", "local");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, ["/p/b/file.txt"]);
|
||||
expect(windowGroupJoin).toHaveBeenCalledWith("main-2");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, ["/p/b/file.txt"], true);
|
||||
expect(windowGroupJoin).not.toHaveBeenCalled();
|
||||
// The new window opens its own files, and this window keeps its project.
|
||||
expect(opened).toEqual([]);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
@@ -825,13 +837,12 @@ describe("Project tabs", () => {
|
||||
vi.mocked(ask).mockResolvedValueOnce({ button: "tab", checked: false });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "focused", label: "main-3" }));
|
||||
await openProjectWithPolicy("/p/b");
|
||||
expect(windowGroupJoin).toHaveBeenCalledWith("main-3");
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, [], true);
|
||||
});
|
||||
it("reports a window it could not group", async () => {
|
||||
useProject.setState(projectState("/p/a"));
|
||||
vi.mocked(ask).mockResolvedValueOnce({ button: "tab", checked: false });
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "main-2" }));
|
||||
windowGroupJoin.mockRejectedValueOnce(new Error("Window closed"));
|
||||
windowOpenProject.mockRejectedValueOnce(new Error("Window closed"));
|
||||
await openProjectWithPolicy("/p/b");
|
||||
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "Window closed" }));
|
||||
});
|
||||
@@ -964,7 +975,7 @@ describe("explicit project-window requests", () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openProjectPath")!;
|
||||
await action.run({ arg: { path: "/p/new", newWindow: false } } as never);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/new", false, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/new", false, [], false);
|
||||
expect(openProject).toHaveBeenCalledWith("/p/new");
|
||||
});
|
||||
it("opens a new window without replacing the current project", async () => {
|
||||
@@ -972,7 +983,7 @@ describe("explicit project-window requests", () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "project-1" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openProjectPath")!;
|
||||
await action.run({ arg: { path: "/p/new", newWindow: true } } as never);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/new", true, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/new", true, [], false);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
expect(useProject.getState().project?.root).toBe("/p/old");
|
||||
});
|
||||
@@ -1011,7 +1022,7 @@ describe("trust is asked before a new project window opens", () => {
|
||||
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
windowOpenProject.mock.invocationCallOrder[0]!,
|
||||
);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, [], false);
|
||||
});
|
||||
|
||||
it.each(newWindowEntries)("%s opens no window when the user chooses Don't Open", async (_, open) => {
|
||||
@@ -1035,7 +1046,7 @@ describe("trust is asked before a new project window opens", () => {
|
||||
it("asks once this window takes the project, before leaving its current one", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectInWindow("/p/b", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, [], false);
|
||||
expect(confirmProjectTrust).toHaveBeenCalledOnce();
|
||||
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
|
||||
|
||||
@@ -152,9 +152,9 @@ export async function openPaths(
|
||||
* show its Welcome screen under the question. A WSL folder opens as a remote project, whose
|
||||
* window asks about the distribution's folder itself.
|
||||
*/
|
||||
async function openProjectWindow(path: string, newWindow: boolean, files: readonly string[] = []) {
|
||||
async function openProjectWindow(path: string, newWindow: boolean, files: readonly string[] = [], inTab = false) {
|
||||
if (newWindow && !(await commands.wslResolve(path).catch(() => null))) await confirmProjectTrust(path, "local");
|
||||
return call(commands.windowOpenProject(path, newWindow, [...files]));
|
||||
return call(commands.windowOpenProject(path, newWindow, [...files], inTab));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -212,7 +212,7 @@ export async function openProjectWithPolicy(
|
||||
}
|
||||
try {
|
||||
// A window that already has the project is focused instead.
|
||||
const outcome = await call(commands.windowOpenProject(path, false, [...files]));
|
||||
const outcome = await call(commands.windowOpenProject(path, false, [...files], false));
|
||||
if (outcome.kind === "current" && (await openHere(path))) await openInEditor(files);
|
||||
} catch {
|
||||
if (await openHere(path)) await openInEditor(files);
|
||||
@@ -293,11 +293,7 @@ function skipped(path: string, key: string) {
|
||||
/** Opens `path` as a new project tab of this window: a window of its own, joined into this window's group. */
|
||||
async function openProjectTab(path: string, files: readonly string[]): Promise<void> {
|
||||
try {
|
||||
// `new_window` always answers with the window holding the project, focused or just created;
|
||||
// either way that window becomes this window's tab.
|
||||
const outcome = await openProjectWindow(path, true, files);
|
||||
if (outcome.kind === "current") return;
|
||||
await call(commands.windowGroupJoin(outcome.label));
|
||||
await openProjectWindow(path, true, files, true);
|
||||
} catch (e) {
|
||||
openFailed(path, e);
|
||||
}
|
||||
@@ -364,14 +360,7 @@ async function consumePendingLaunch(): Promise<void> {
|
||||
} else if (files.length) await openFilesHere(files, positions);
|
||||
else if (launch.remote) {
|
||||
const { target, path } = launch.remote;
|
||||
await connectRemote(target, path).catch((e) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.window.openFailed", { name: basename(path) }),
|
||||
body: errorText(e),
|
||||
key: `app.open:${path}`,
|
||||
}),
|
||||
);
|
||||
await connectRemote(target, path).catch((e) => openFailed(path, e));
|
||||
}
|
||||
if (launch.diff && !launch.diffBeforeFiles) await openCliDiff(launch.diff);
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** File › Remote Development…: state of the connect dialog and the folder browser helpers. */
|
||||
import { create } from "zustand";
|
||||
import type { RemoteEntry, RemoteStage } from "@/platform/ipc";
|
||||
import type { RemoteEntry } from "@/platform/ipc";
|
||||
export { remoteStageLabel as stageLabel } from "@/platform/remote";
|
||||
|
||||
/** `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 }));
|
||||
@@ -34,23 +35,3 @@ export function listedDirectory(requested: string, entries: readonly RemoteEntry
|
||||
const first = entries[0];
|
||||
return first ? remoteParent(first.path) : requested;
|
||||
}
|
||||
|
||||
/** What the window is waiting for at each stage of connecting. */
|
||||
export function stageLabel(stage: RemoteStage): string {
|
||||
switch (stage) {
|
||||
case "connecting":
|
||||
return "Connecting to the host…";
|
||||
case "container":
|
||||
return "Starting the dev container…";
|
||||
case "checking":
|
||||
return "Checking the IDE backend on the host…";
|
||||
case "downloading":
|
||||
return "Downloading the IDE backend…";
|
||||
case "uploading":
|
||||
return "Installing the IDE backend on the host…";
|
||||
case "starting":
|
||||
return "Starting the IDE backend…";
|
||||
case "opening":
|
||||
return "Opening the project…";
|
||||
}
|
||||
}
|
||||
@@ -669,7 +669,7 @@ it.each(["focused", "failed"])("opens a checked-out SSH branch without retrying
|
||||
mocks.executeAction.mockClear();
|
||||
mocks.notify.mockClear();
|
||||
await checkoutBranch(local("feature/wt"));
|
||||
expect(mocks.windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, path, true);
|
||||
expect(mocks.windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, path, true, false);
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.executeAction).not.toHaveBeenCalledWith("file.openProjectPath", expect.anything());
|
||||
if (outcome === "failed") {
|
||||
|
||||
@@ -271,7 +271,7 @@ it.each([
|
||||
fireEvent.mouseDown(row);
|
||||
if (entry === "toolbar") fireEvent.click(screen.getByRole("button", { name: "Open in New Window" }));
|
||||
else fireEvent.doubleClick(row);
|
||||
await waitFor(() => expect(windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, "/work/app", true));
|
||||
await waitFor(() => expect(windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, "/work/app", true, false));
|
||||
expect(useProject.getState().project?.root).toBe("/work/app-feature");
|
||||
});
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ export async function openWorktree(path: string, newWindow = false): Promise<voi
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await call(commands.windowOpenRemote(target, path, true));
|
||||
await call(commands.windowOpenRemote(target, path, true, false));
|
||||
} catch (error) {
|
||||
if (isCancelled(error)) return;
|
||||
notifications().notify({
|
||||
|
||||
@@ -84,7 +84,7 @@ export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
|
||||
if (e.kind === "action") void executeAction(e.id);
|
||||
// An open project goes to its window.
|
||||
else if (e.open && !parseRemoteLocation(e.m.project.path))
|
||||
void call(commands.windowOpenProject(e.m.project.path, false, [])).catch(() => undefined);
|
||||
void call(commands.windowOpenProject(e.m.project.path, false, [], false)).catch(() => undefined);
|
||||
// Opening a remote location focuses the window already connected to it.
|
||||
else void openRecent(e.m.project, override);
|
||||
};
|
||||
|
||||
@@ -204,7 +204,7 @@ export function recentMenu(project: RecentProject, onOpened?: () => void, onRemo
|
||||
label: "Open in New Window",
|
||||
icon: "folder-open",
|
||||
run: () =>
|
||||
void call(commands.windowOpenRemote(remote.target, remote.path, true))
|
||||
void call(commands.windowOpenRemote(remote.target, remote.path, true, false))
|
||||
.then(() => onOpened?.())
|
||||
.catch(() => undefined),
|
||||
}
|
||||
|
||||
@@ -132,4 +132,28 @@ describe("reopenLastProject", () => {
|
||||
await promise;
|
||||
expect(closeProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears reopening immediately when a remote reconnect is cancelled from the workbench", async () => {
|
||||
const { cancelRemoteConnect, useRemoteProgress } = await import("@/platform/remote");
|
||||
localStorage.setItem("openidea.session.openProject", "ssh://box/srv/idea");
|
||||
let rejectConnect!: (err: unknown) => void;
|
||||
connectRemote.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((_, reject) => {
|
||||
rejectConnect = reject;
|
||||
useRemoteProgress.setState({
|
||||
location: "ssh://box/srv/idea",
|
||||
progress: { stage: "connecting", fraction: null },
|
||||
});
|
||||
}),
|
||||
);
|
||||
provideStartupLaunch(Promise.resolve());
|
||||
const promise = reopenLastProject();
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(useSession.getState().reopening).toBe("ssh://box/srv/idea");
|
||||
cancelRemoteConnect();
|
||||
expect(useSession.getState().reopening).toBeNull();
|
||||
rejectConnect({ kind: "cancelled", message: "Remote connection cancelled" });
|
||||
await promise;
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,13 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { create } from "zustand";
|
||||
import { commands, isCancelled, isTauri, type Settings } from "@/platform/ipc";
|
||||
import { closeProject, openProject, startupLaunchHandled, useProject } from "@/platform/project";
|
||||
import { connectRemote, projectLocation, resolveRemoteLocation, useRemoteProgress } from "@/platform/remote";
|
||||
import {
|
||||
cancelRemoteConnect,
|
||||
connectRemote,
|
||||
onRemoteConnectCancel,
|
||||
projectLocation,
|
||||
resolveRemoteLocation,
|
||||
} from "@/platform/remote";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
const SESSION_KEY = "openidea.session.openProject";
|
||||
@@ -84,6 +90,14 @@ export function lastSessionProject(): string | null {
|
||||
let attempted = false;
|
||||
let reopenEpoch = 0;
|
||||
|
||||
onRemoteConnectCancel(() => {
|
||||
if (!useSession.getState().reopening) return;
|
||||
reopenEpoch++;
|
||||
write(SESSION_KEY, null);
|
||||
windowProject(null);
|
||||
useSession.setState({ reopening: null });
|
||||
});
|
||||
|
||||
/** Cancels an in-flight startup project reopen or remote connection and returns to the Welcome screen. */
|
||||
export function cancelReopen() {
|
||||
reopenEpoch++;
|
||||
@@ -91,11 +105,7 @@ export function cancelReopen() {
|
||||
windowProject(null);
|
||||
useSession.setState({ reopening: null });
|
||||
// A local open can't be interrupted; `reopen` closes it again once it finishes.
|
||||
if (useRemoteProgress.getState().location) {
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useProject.setState({ opening: false, openingPath: null });
|
||||
if (isTauri()) void commands.remoteDisconnect().catch(() => {});
|
||||
}
|
||||
cancelRemoteConnect();
|
||||
}
|
||||
|
||||
/** On startup: reopens the project that was open at exit. Robust against a missing folder. */
|
||||
|
||||
+161
-35
@@ -17,12 +17,13 @@ import {
|
||||
type RemoteProgress,
|
||||
type RemoteProject,
|
||||
type RemoteSession,
|
||||
type RemoteStage,
|
||||
type RemoteTarget,
|
||||
} from "./ipc";
|
||||
import { isClientSetting, overlayClientSettings } from "./clientSettings";
|
||||
import type { Settings } from "./ipc";
|
||||
import { usePlatform } from "./platformInfo";
|
||||
import { useProject } from "./project";
|
||||
import { basename, useProject } from "./project";
|
||||
|
||||
interface RemoteState {
|
||||
session: RemoteSession | null;
|
||||
@@ -200,42 +201,128 @@ export const useRemoteProgress = create<{ progress: RemoteProgress | null; locat
|
||||
location: null,
|
||||
}));
|
||||
|
||||
/** What the window is waiting for at each stage of connecting to a remote host. */
|
||||
export function remoteStageLabel(stage: RemoteStage): string {
|
||||
switch (stage) {
|
||||
case "connecting":
|
||||
return "Connecting to the host…";
|
||||
case "container":
|
||||
return "Starting the dev container…";
|
||||
case "checking":
|
||||
return "Checking the IDE backend on the host…";
|
||||
case "downloading":
|
||||
return "Downloading the IDE backend…";
|
||||
case "uploading":
|
||||
return "Installing the IDE backend on the host…";
|
||||
case "starting":
|
||||
return "Starting the IDE backend…";
|
||||
case "opening":
|
||||
return "Opening the project…";
|
||||
}
|
||||
}
|
||||
|
||||
const cancelListeners = new Set<() => void>();
|
||||
|
||||
/** Runs `listener` whenever an in-flight remote connection is cancelled via {@link cancelRemoteConnect}. */
|
||||
export function onRemoteConnectCancel(listener: () => void): () => void {
|
||||
cancelListeners.add(listener);
|
||||
return () => {
|
||||
cancelListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Cancels any in-flight remote connection in this window. */
|
||||
export function cancelRemoteConnect(): void {
|
||||
const { location } = useRemoteProgress.getState();
|
||||
if (!location) return;
|
||||
// When replacing an already-open remote project in This Window, keep its active session alive
|
||||
// and only invalidate the in-flight connect attempt on the backend.
|
||||
const keepExisting = isRemoteWindow() && !attachingRemote;
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useProject.setState((s) => (s.openingPath === location || s.opening ? { opening: false, openingPath: null } : s));
|
||||
for (const listener of cancelListeners) listener();
|
||||
if (isTauri()) {
|
||||
const stop = keepExisting ? commands.remoteCancelConnect() : commands.remoteDisconnect();
|
||||
void stop.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes this window to the server `remoteConnect` answered with and shows its project. */
|
||||
async function attachRemote(r: RemoteProject, path: string): Promise<void> {
|
||||
enableRemote({
|
||||
target: r.target,
|
||||
root: r.root,
|
||||
host: r.host,
|
||||
os: r.os,
|
||||
commands: r.commands,
|
||||
idlePolicy: r.idlePolicy,
|
||||
});
|
||||
if (takeLegacyRemoteTrust(r.target, path, r.host)) {
|
||||
const status = await call(commands.projectTrustStatus(r.root));
|
||||
if (!status.decided) await call(commands.projectTrustSet(r.root, true, false));
|
||||
if (!(await call(commands.remoteTrustStatus())).decided) await call(commands.remoteTrustSet(true, false));
|
||||
}
|
||||
async function attachRemote(
|
||||
r: RemoteProject,
|
||||
path: string,
|
||||
guard?: {
|
||||
isCurrent: () => boolean;
|
||||
isSuperseded: () => boolean;
|
||||
previousSession: RemoteSession | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
const checkCurrent = () => {
|
||||
if (!guard || guard.isCurrent()) return;
|
||||
if (!guard.isSuperseded()) {
|
||||
if (isTauri()) void commands.remoteDisconnect().catch(() => {});
|
||||
if (guard.previousSession) {
|
||||
routed = new Set();
|
||||
setInvokeRoute(null);
|
||||
useRemote.setState({
|
||||
session: guard.previousSession,
|
||||
lost: guard.previousSession.host,
|
||||
takenOver: false,
|
||||
reconnecting: false,
|
||||
});
|
||||
} else {
|
||||
disableRemote();
|
||||
}
|
||||
}
|
||||
throw new IpcError({ kind: "cancelled", message: "Remote connection cancelled" });
|
||||
};
|
||||
checkCurrent();
|
||||
attachingRemote = true;
|
||||
try {
|
||||
await confirmProjectTrust(r.root);
|
||||
} catch (error) {
|
||||
await commands.closeProject();
|
||||
disableRemote();
|
||||
throw error;
|
||||
enableRemote({
|
||||
target: r.target,
|
||||
root: r.root,
|
||||
host: r.host,
|
||||
os: r.os,
|
||||
commands: r.commands,
|
||||
idlePolicy: r.idlePolicy,
|
||||
});
|
||||
if (takeLegacyRemoteTrust(r.target, path, r.host)) {
|
||||
const status = await call(commands.projectTrustStatus(r.root));
|
||||
checkCurrent();
|
||||
if (!status.decided) await call(commands.projectTrustSet(r.root, true, false));
|
||||
checkCurrent();
|
||||
if (!(await call(commands.remoteTrustStatus())).decided) await call(commands.remoteTrustSet(true, false));
|
||||
checkCurrent();
|
||||
}
|
||||
try {
|
||||
await confirmProjectTrust(r.root);
|
||||
} catch (error) {
|
||||
await commands.closeProject();
|
||||
disableRemote();
|
||||
throw error;
|
||||
}
|
||||
checkCurrent();
|
||||
const current = await commands.projectCurrent();
|
||||
checkCurrent();
|
||||
if (current) r.project = current;
|
||||
r.project.settings = await clientSettings(r.project.settings);
|
||||
checkCurrent();
|
||||
useProject.setState({ project: r.project, settings: r.project.settings });
|
||||
rememberRemote({
|
||||
target: r.target,
|
||||
path: r.root,
|
||||
name: r.project.displayName || r.project.name,
|
||||
host: r.host,
|
||||
openedAtMs: Date.now(),
|
||||
});
|
||||
} finally {
|
||||
attachingRemote = false;
|
||||
}
|
||||
const current = await commands.projectCurrent();
|
||||
if (current) r.project = current;
|
||||
r.project.settings = await clientSettings(r.project.settings);
|
||||
useProject.setState({ project: r.project, settings: r.project.settings });
|
||||
rememberRemote({
|
||||
target: r.target,
|
||||
path: r.root,
|
||||
name: r.project.displayName || r.project.name,
|
||||
host: r.host,
|
||||
openedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
let connectAttempt = 0;
|
||||
let attachingRemote = false;
|
||||
|
||||
let backendBusyPrompt: ((target: RemoteTarget) => Promise<boolean>) | null = null;
|
||||
|
||||
@@ -263,11 +350,13 @@ async function connectOrReplace(target: RemoteTarget, path: string, onProgress:
|
||||
* project folder is the one in the container: `path` is then only a label.
|
||||
*/
|
||||
export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
useProject.setState({ opening: true });
|
||||
const location = remoteLocation(target, path);
|
||||
const previousSession = useRemote.getState().session;
|
||||
useProject.setState({ opening: true, openingPath: location });
|
||||
// Two connects to one location (a double click) share `location`; only the latest attaches.
|
||||
const attempt = ++connectAttempt;
|
||||
const current = () => attempt === connectAttempt && useRemoteProgress.getState().location === location;
|
||||
const isSuperseded = () => attempt !== connectAttempt;
|
||||
const onProgress = new Channel<RemoteProgress>();
|
||||
onProgress.onmessage = (progress) => {
|
||||
if (current()) useRemoteProgress.setState({ progress });
|
||||
@@ -279,15 +368,29 @@ export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
try {
|
||||
const r = await connectOrReplace(target, path, onProgress);
|
||||
// Another connect replaced this one, or the user cancelled. Disconnecting here
|
||||
// would drop the connection that replacement published. Cancel already disconnects.
|
||||
// would drop the connection that replacement published.
|
||||
if (!current()) {
|
||||
// If the user cancelled right after the backend published `r` over an existing remote
|
||||
// session, `remoteCancelConnect` only bumped the attempt counter — drop `r` and mark the
|
||||
// displaced session lost instead of routing the old project's IPC to `r`'s server.
|
||||
if (!isSuperseded() && previousSession) {
|
||||
if (isTauri()) void commands.remoteDisconnect().catch(() => {});
|
||||
routed = new Set();
|
||||
setInvokeRoute(null);
|
||||
useRemote.setState({
|
||||
session: previousSession,
|
||||
lost: previousSession.host,
|
||||
takenOver: false,
|
||||
reconnecting: false,
|
||||
});
|
||||
}
|
||||
throw new IpcError({ kind: "cancelled", message: "Remote connection cancelled" });
|
||||
}
|
||||
await attachRemote(r, path);
|
||||
await attachRemote(r, path, { isCurrent: current, isSuperseded, previousSession });
|
||||
return r;
|
||||
} finally {
|
||||
if (current()) {
|
||||
useProject.setState({ opening: false });
|
||||
useProject.setState({ opening: false, openingPath: null });
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
}
|
||||
}
|
||||
@@ -335,6 +438,29 @@ export async function shutdownRemoteBackend() {
|
||||
|
||||
const SCHEMES = { ssh: "ssh://", wsl: "wsl://", devContainer: "devcontainer://" } as const;
|
||||
|
||||
const REMOTE_KIND_LABEL: Record<RemoteTarget["kind"], string> = {
|
||||
ssh: "SSH",
|
||||
wsl: "WSL",
|
||||
devContainer: "Dev Container",
|
||||
};
|
||||
|
||||
/** Project name for a local path or remote location (`ssh://…`, `wsl://…`, `devcontainer://…`). */
|
||||
export function openingDisplayName(path: string): string {
|
||||
const parsed = parseRemoteLocation(path);
|
||||
const raw = (parsed ? parsed.path : path).replace(/\/+$/, "");
|
||||
return basename(raw) || raw || path;
|
||||
}
|
||||
|
||||
/** Human-readable path for a local folder or remote location. */
|
||||
export function openingDisplayPath(path: string): string {
|
||||
const parsed = parseRemoteLocation(path);
|
||||
if (!parsed) return path;
|
||||
const host =
|
||||
recentRemotes().find((x) => sameTarget(x.target, parsed.target) && x.path === parsed.path)?.host ||
|
||||
targetName(parsed.target);
|
||||
return `${REMOTE_KIND_LABEL[parsed.target.kind]}: ${host} — ${parsed.path}`;
|
||||
}
|
||||
|
||||
/** The SSH configuration id, the WSL distribution name or the dev container's local folder. */
|
||||
export function targetName(target: RemoteTarget): string {
|
||||
switch (target.kind) {
|
||||
|
||||
@@ -3,11 +3,13 @@ import { CLIENT_SETTINGS_KEYS } from "./clientSettings";
|
||||
import { commands, call, type Settings } from "./ipc";
|
||||
import { loadSettings, useProject } from "./project";
|
||||
import {
|
||||
cancelRemoteConnect,
|
||||
connectRemote,
|
||||
disableRemote,
|
||||
enableRemote,
|
||||
isRemoteWindow,
|
||||
localGlobalSettings,
|
||||
remoteLocation,
|
||||
remoteRouting,
|
||||
useRemote,
|
||||
useRemoteProgress,
|
||||
@@ -63,7 +65,7 @@ beforeEach(() => {
|
||||
});
|
||||
afterEach(() => {
|
||||
disableRemote();
|
||||
useProject.setState({ opening: false, settings: null });
|
||||
useProject.setState({ project: null, opening: false, openingPath: null, settings: null });
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
});
|
||||
|
||||
@@ -286,6 +288,123 @@ describe("remote client settings", () => {
|
||||
await expect(newer).resolves.toMatchObject({ root: "/srv/app" });
|
||||
expect(useRemote.getState().session?.root).toBe("/srv/app");
|
||||
expect(useRemoteProgress.getState()).toEqual({ progress: null, location: null });
|
||||
expect(useProject.getState()).toMatchObject({ opening: false, openingPath: null });
|
||||
});
|
||||
it("sets openingPath to the remote location while connecting and clears it on cancel", async () => {
|
||||
disableRemote();
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useProject.setState({ project: null, opening: false, openingPath: null });
|
||||
let release: (value: unknown) => void = () => {};
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd !== "remote_connect") return cmd === "remote_invoke" ? "null" : local;
|
||||
return new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
});
|
||||
const target = { kind: "ssh" as const, config: "box" };
|
||||
const location = remoteLocation(target, "/srv/idea");
|
||||
const pending = connectRemote(target, "/srv/idea");
|
||||
expect(useProject.getState()).toMatchObject({ opening: true, openingPath: location });
|
||||
cancelRemoteConnect();
|
||||
expect(useProject.getState()).toMatchObject({ opening: false, openingPath: null });
|
||||
expect(useRemoteProgress.getState()).toEqual({ progress: null, location: null });
|
||||
release({
|
||||
target,
|
||||
root: "/srv/idea",
|
||||
host: "box",
|
||||
os: "linux",
|
||||
commands: [...served],
|
||||
project: { root: "/srv/idea", name: "idea", displayName: "idea", settings: remote },
|
||||
});
|
||||
await expect(pending).rejects.toMatchObject({ kind: "cancelled" });
|
||||
});
|
||||
it("keeps the existing remote session alive when cancelling a This Window remote open", async () => {
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useProject.setState({
|
||||
project: { root: "/remote", name: "remote", displayName: "remote", settings: remote } as never,
|
||||
opening: false,
|
||||
openingPath: null,
|
||||
});
|
||||
let rejectConnect: (reason?: unknown) => void = () => {};
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd !== "remote_connect") return cmd === "remote_invoke" ? "null" : local;
|
||||
return new Promise((_, reject) => {
|
||||
rejectConnect = reject;
|
||||
});
|
||||
});
|
||||
const pending = connectRemote({ kind: "ssh", config: "other" }, "/srv/other");
|
||||
cancelRemoteConnect();
|
||||
expect(invoke.mock.calls.filter(([cmd]) => cmd === "remote_cancel_connect")).toHaveLength(1);
|
||||
expect(invoke.mock.calls.filter(([cmd]) => cmd === "remote_disconnect")).toHaveLength(0);
|
||||
rejectConnect({ kind: "cancelled", message: "Remote connection cancelled" });
|
||||
await expect(pending).rejects.toMatchObject({ kind: "cancelled" });
|
||||
expect(useRemote.getState()).toMatchObject({ session: { root: "/remote", host: "test" }, lost: null });
|
||||
expect(useProject.getState()).toMatchObject({
|
||||
project: { root: "/remote" },
|
||||
opening: false,
|
||||
openingPath: null,
|
||||
});
|
||||
});
|
||||
it("drops a newly published replacement and marks the displaced session lost if cancel raced with publish", async () => {
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useProject.setState({
|
||||
project: { root: "/remote", name: "remote", displayName: "remote", settings: remote } as never,
|
||||
opening: false,
|
||||
openingPath: null,
|
||||
});
|
||||
let release: (value: unknown) => void = () => {};
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd !== "remote_connect") return cmd === "remote_invoke" ? "null" : local;
|
||||
return new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
});
|
||||
const target = { kind: "ssh" as const, config: "other" };
|
||||
const pending = connectRemote(target, "/srv/other");
|
||||
cancelRemoteConnect();
|
||||
release({
|
||||
target,
|
||||
root: "/srv/other",
|
||||
host: "other",
|
||||
os: "linux",
|
||||
commands: [...served],
|
||||
project: { root: "/srv/other", name: "other", displayName: "other", settings: remote },
|
||||
});
|
||||
await expect(pending).rejects.toMatchObject({ kind: "cancelled" });
|
||||
expect(invoke.mock.calls.filter(([cmd]) => cmd === "remote_disconnect")).toHaveLength(1);
|
||||
expect(useRemote.getState()).toMatchObject({ session: { root: "/remote", host: "test" }, lost: "test" });
|
||||
expect(useProject.getState().project?.root).toBe("/remote");
|
||||
});
|
||||
it("does not attach a remote project if cancelled while attachRemote is awaiting", async () => {
|
||||
disableRemote();
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useProject.setState({ project: null, opening: false, openingPath: null });
|
||||
let releaseCurrent: (value: string) => void = () => {};
|
||||
const target = { kind: "ssh" as const, config: "box" };
|
||||
const project = { root: "/srv/idea", name: "idea", displayName: "idea", settings: remote };
|
||||
invoke.mockImplementation(async (cmd: string, args?: { cmd?: string }) => {
|
||||
if (cmd === "remote_connect") {
|
||||
return { target, root: "/srv/idea", host: "box", os: "linux", commands: [...served], project };
|
||||
}
|
||||
if (cmd === "remote_invoke" && args?.cmd === "project_current") {
|
||||
return new Promise<string>((resolve) => {
|
||||
releaseCurrent = resolve;
|
||||
});
|
||||
}
|
||||
return cmd === "remote_invoke" ? "null" : local;
|
||||
});
|
||||
const pending = connectRemote(target, "/srv/idea");
|
||||
await vi.waitFor(() =>
|
||||
expect(invoke.mock.calls.some(([cmd, args]) => cmd === "remote_invoke" && args?.cmd === "project_current")).toBe(
|
||||
true,
|
||||
),
|
||||
);
|
||||
cancelRemoteConnect();
|
||||
releaseCurrent(JSON.stringify(project));
|
||||
await expect(pending).rejects.toMatchObject({ kind: "cancelled" });
|
||||
expect(useProject.getState()).toMatchObject({ project: null, opening: false, openingPath: null });
|
||||
expect(useRemote.getState().session).toBeNull();
|
||||
expect(invoke.mock.calls.filter(([cmd]) => cmd === "remote_disconnect").length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
it("overlays the project snapshot used by the settings window", async () => {
|
||||
invoke.mockImplementation(async (cmd: string) =>
|
||||
|
||||
@@ -4,7 +4,8 @@ import clsx from "clsx";
|
||||
import { useActions } from "@/platform/actions";
|
||||
import { isWebMode } from "@/platform/webBridge";
|
||||
import { shortcutLabel, useKeymap } from "@/platform/keymap";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { openingDisplayName, openingDisplayPath } from "@/platform/remote";
|
||||
import { BarButton, Icon, IconButton, Menu, type MenuItem, showContextMenu, T } from "@/ui";
|
||||
import { useChromeIconSize } from "@/ui/density";
|
||||
import { useContributions, useWorkbenchSlots, type TitleItemContribution } from "./contributions";
|
||||
@@ -61,9 +62,10 @@ function TitleItem({ item }: { item: TitleItemContribution }) {
|
||||
|
||||
function ProjectButton() {
|
||||
const name = useProject((s) =>
|
||||
s.openingPath ? basename(s.openingPath) || s.openingPath : s.project?.displayName || s.project?.name,
|
||||
s.openingPath ? openingDisplayName(s.openingPath) : s.project?.displayName || s.project?.name,
|
||||
);
|
||||
const root = useProject((s) => s.openingPath ?? s.project?.root);
|
||||
const tooltip = root ? openingDisplayPath(root) : undefined;
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
const actions = useActions((s) => s.actions);
|
||||
@@ -83,7 +85,7 @@ function ProjectButton() {
|
||||
ref={ref}
|
||||
variant="title"
|
||||
className={styles.widget}
|
||||
tooltip={root}
|
||||
tooltip={tooltip}
|
||||
data-toolbar-icon-dropdown=""
|
||||
aria-label={label}
|
||||
aria-haspopup={Popup ? "dialog" : "menu"}
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
flex-direction: column;
|
||||
background: var(--bg-island);
|
||||
}
|
||||
.root > [data-window-group] {
|
||||
background: var(--bg-frame);
|
||||
padding-top: var(--island-gap);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useWorkbenchSlots } from "./contributions";
|
||||
import { ErrorBoundary, Slot } from "./ErrorBoundary";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { TitleBar } from "./TitleBar";
|
||||
import { WindowGroupTabs } from "./WindowGroupTabs";
|
||||
import styles from "./Welcome.module.css";
|
||||
|
||||
function WelcomeFallback() {
|
||||
@@ -55,6 +56,7 @@ export function Welcome() {
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<TitleBar minimal title="Welcome to OpenIDEA" />
|
||||
<WindowGroupTabs />
|
||||
<main className={styles.main}>
|
||||
{Provided ? (
|
||||
<ErrorBoundary name="welcome view" fallback={<WelcomeFallback />}>
|
||||
|
||||
@@ -76,11 +76,21 @@
|
||||
transform-origin: left;
|
||||
animation: opening-progress var(--splash-progress-duration) var(--splash-progress-easing) both;
|
||||
}
|
||||
.openingRemoteProgress {
|
||||
width: min(320px, 100%);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.openingTitle {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.openingStage {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg);
|
||||
}
|
||||
.openingPath {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
@@ -533,6 +533,126 @@ describe("workbench shell", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows remote download progress inside the new tab instead of the welcome chrome", async () => {
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { useRemoteProgress } = await import("@/platform/remote");
|
||||
const { useWindowGroup } = await import("@/platform/windowGroups");
|
||||
const { Workbench } = await import("./Workbench");
|
||||
const location = "ssh://[email protected]/Users/mac/repo/idea";
|
||||
useProject.setState({ project: null, opening: true, openingPath: location });
|
||||
useRemoteProgress.setState({
|
||||
location,
|
||||
progress: { stage: "uploading", fraction: 0.68 },
|
||||
});
|
||||
useWindowGroup.setState({
|
||||
tabs: [
|
||||
{ label: "main", name: "opengui", root: "/Users/me/opengui", current: false },
|
||||
{ label: "project-2", name: "idea", root: location, current: true },
|
||||
],
|
||||
});
|
||||
const { container, unmount } = render(<Workbench />);
|
||||
try {
|
||||
const opening = container.querySelector<HTMLElement>("[data-project-opening]")!;
|
||||
expect(opening).not.toBeNull();
|
||||
expect(within(opening).queryByText("Welcome to OpenIDEA")).toBeNull();
|
||||
expect(screen.getByText("Welcome to OpenIDEA").closest("[inert]")).not.toBeNull();
|
||||
expect(within(opening).getByRole("status", { name: "Opening idea…" })).toBeVisible();
|
||||
expect(within(opening).getByRole("button", { name: "idea" })).toBeInTheDocument();
|
||||
expect(within(opening).getByRole("tab", { name: "opengui" })).toBeInTheDocument();
|
||||
expect(within(opening).getByRole("tab", { name: /idea/ })).toHaveAttribute("aria-selected", "true");
|
||||
expect(within(opening).getByText("Installing the IDE backend on the host… 68%")).toBeVisible();
|
||||
expect(within(opening).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "68");
|
||||
expect(within(opening).getByText("SSH: [email protected] — /Users/mac/repo/idea")).toBeVisible();
|
||||
fireEvent.click(within(opening).getByRole("button", { name: "Cancel" }));
|
||||
expect(useRemoteProgress.getState()).toEqual({ progress: null, location: null });
|
||||
expect(useProject.getState()).toMatchObject({ opening: false, openingPath: null });
|
||||
} finally {
|
||||
unmount();
|
||||
useProject.setState({ project: null, opening: false, openingPath: null });
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useWindowGroup.setState({ tabs: [] });
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps project tabs visible if a grouped tab falls back to the welcome view", async () => {
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { useWindowGroup } = await import("@/platform/windowGroups");
|
||||
const { Workbench } = await import("./Workbench");
|
||||
useProject.setState({ project: null, opening: false, openingPath: null });
|
||||
useWindowGroup.setState({
|
||||
tabs: [
|
||||
{ label: "main", name: "opengui", root: "/Users/me/opengui", current: false },
|
||||
{ label: "project-2", name: "idea", root: "ssh://box/srv/idea", current: true },
|
||||
],
|
||||
});
|
||||
const { unmount } = render(<Workbench />);
|
||||
try {
|
||||
expect(screen.getByRole("tab", { name: "opengui" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("tab", { name: /idea/ })).toHaveAttribute("aria-selected", "true");
|
||||
} finally {
|
||||
unmount();
|
||||
useWindowGroup.setState({ tabs: [] });
|
||||
}
|
||||
});
|
||||
|
||||
it("closes an empty grouped tab when cancelling a remote open, but keeps a window with an open project", async () => {
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { useRemoteProgress } = await import("@/platform/remote");
|
||||
const { useWindowGroup } = await import("@/platform/windowGroups");
|
||||
const { Workbench } = await import("./Workbench");
|
||||
const invoke = vi.fn().mockResolvedValue(null);
|
||||
const tauriWindow = window as unknown as { __TAURI_INTERNALS__?: Record<string, unknown> };
|
||||
const previousTauri = tauriWindow.__TAURI_INTERNALS__;
|
||||
tauriWindow.__TAURI_INTERNALS__ = {
|
||||
invoke,
|
||||
metadata: { currentWindow: { label: "project-2" }, currentWebview: { windowLabel: "project-2" } },
|
||||
};
|
||||
const location = "ssh://box/srv/idea";
|
||||
useWindowGroup.setState({
|
||||
tabs: [
|
||||
{ label: "main", name: "opengui", root: "/Users/me/opengui", current: false },
|
||||
{ label: "project-2", name: "idea", root: location, current: true },
|
||||
],
|
||||
});
|
||||
useProject.setState({ project: null, opening: true, openingPath: location });
|
||||
useRemoteProgress.setState({ location, progress: { stage: "downloading", fraction: 0.4 } });
|
||||
const { container, unmount } = render(<Workbench />);
|
||||
try {
|
||||
fireEvent.click(
|
||||
within(container.querySelector<HTMLElement>("[data-project-opening]")!).getByRole("button", { name: "Cancel" }),
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(invoke).toHaveBeenCalledWith(
|
||||
"plugin:window|close",
|
||||
expect.objectContaining({ label: "project-2" }),
|
||||
undefined,
|
||||
),
|
||||
);
|
||||
invoke.mockClear();
|
||||
act(() => {
|
||||
useProject.setState({
|
||||
project: { root: "/Users/me/opengui", name: "opengui", trusted: true, isGit: false, settings: {} },
|
||||
opening: true,
|
||||
openingPath: location,
|
||||
});
|
||||
useRemoteProgress.setState({ location, progress: { stage: "downloading", fraction: 0.4 } });
|
||||
});
|
||||
fireEvent.click(
|
||||
within(container.querySelector<HTMLElement>("[data-project-opening]")!).getByRole("button", { name: "Cancel" }),
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(invoke).not.toHaveBeenCalledWith("plugin:window|close", expect.anything(), expect.anything());
|
||||
expect(useProject.getState().project?.root).toBe("/Users/me/opengui");
|
||||
} finally {
|
||||
unmount();
|
||||
if (previousTauri === undefined) delete tauriWindow.__TAURI_INTERNALS__;
|
||||
else tauriWindow.__TAURI_INTERNALS__ = previousTauri;
|
||||
useProject.setState({ project: null, opening: false, openingPath: null });
|
||||
useRemoteProgress.setState({ progress: null, location: null });
|
||||
useWindowGroup.setState({ tabs: [] });
|
||||
}
|
||||
});
|
||||
|
||||
it("renders the welcome view without a project and the frame with one", async () => {
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { Workbench } = await import("./Workbench");
|
||||
|
||||
@@ -8,10 +8,20 @@ import { useSyncExternalStore } from "react";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { Breadcrumbs } from "@/editor/core";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { remoteLocation, useRemote } from "@/platform/remote";
|
||||
import {
|
||||
cancelRemoteConnect,
|
||||
openingDisplayName,
|
||||
openingDisplayPath,
|
||||
remoteLocation,
|
||||
remoteStageLabel,
|
||||
useRemote,
|
||||
useRemoteProgress,
|
||||
} from "@/platform/remote";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { useWindowGroup } from "@/platform/windowGroups";
|
||||
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
|
||||
import { useT } from "@/platform/i18n";
|
||||
import { ProgressBar } from "@/ui";
|
||||
import { useT, useTx } from "@/platform/i18n";
|
||||
import { Button, ProgressBar, T } from "@/ui";
|
||||
import logo from "@/assets/openidea-logo.png";
|
||||
import { useDistractionFree } from "./distractionFree";
|
||||
import { EditorArea } from "./EditorArea";
|
||||
@@ -61,7 +71,21 @@ function LightEditFrame({ title }: { title?: string }) {
|
||||
|
||||
function ProjectOpening({ path }: { path: string }) {
|
||||
const t = useT();
|
||||
const label = t("app.project.opening", { name: basename(path) || path });
|
||||
const tx = useTx();
|
||||
const remoteProgress = useRemoteProgress((s) => (s.location === path ? s.progress : null));
|
||||
const label = t("app.project.opening", { name: openingDisplayName(path) });
|
||||
const displayPath = openingDisplayPath(path);
|
||||
const stageText = remoteProgress
|
||||
? tx(remoteStageLabel(remoteProgress.stage)) +
|
||||
(remoteProgress.fraction == null ? "" : ` ${Math.round(remoteProgress.fraction * 100)}%`)
|
||||
: null;
|
||||
const onCancel = () => {
|
||||
const closeTab = !useProject.getState().project && useWindowGroup.getState().tabs.length > 1;
|
||||
cancelRemoteConnect();
|
||||
if (closeTab && isTauri()) {
|
||||
void import("@tauri-apps/api/window").then(({ getCurrentWindow }) => getCurrentWindow().close()).catch(() => {});
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className={styles.opening} data-project-opening>
|
||||
<TitleBar />
|
||||
@@ -71,11 +95,25 @@ function ProjectOpening({ path }: { path: string }) {
|
||||
<img className={styles.openingLogo} src={logo} alt="" draggable={false} />
|
||||
<span>OpenIDEA</span>
|
||||
</div>
|
||||
<ProgressBar className={styles.openingProgress} aria-label={label} />
|
||||
{remoteProgress ? (
|
||||
<ProgressBar
|
||||
value={remoteProgress.fraction}
|
||||
className={styles.openingRemoteProgress}
|
||||
aria-label={stageText ?? label}
|
||||
/>
|
||||
) : (
|
||||
<ProgressBar className={styles.openingProgress} aria-label={label} />
|
||||
)}
|
||||
<div className={styles.openingTitle}>{label}</div>
|
||||
<div className={styles.openingPath} title={path}>
|
||||
{path}
|
||||
{stageText && <div className={styles.openingStage}>{stageText}</div>}
|
||||
<div className={styles.openingPath} title={displayPath}>
|
||||
{displayPath}
|
||||
</div>
|
||||
{remoteProgress && (
|
||||
<Button size="small" onClick={onCancel}>
|
||||
<T>Cancel</T>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -96,7 +134,7 @@ export function Workbench() {
|
||||
const statusBar = useAppearanceFlag("showStatusBar");
|
||||
const navBarPosition = useNavigationBarPosition();
|
||||
const frame = project ? styles.framed : lightEdit || standaloneTitle ? styles.lightEditFrame : undefined;
|
||||
const tintName = openingPath ? basename(openingPath) || openingPath : project?.name;
|
||||
const tintName = openingPath ? openingDisplayName(openingPath) : project?.name;
|
||||
const tintRoot = openingPath ?? (remoteTarget && root ? remoteLocation(remoteTarget, root) : root);
|
||||
|
||||
return (
|
||||
|
||||
@@ -106,8 +106,9 @@ describe("a recent project opened with a modifier key", () => {
|
||||
const here = vi.fn(async () => {});
|
||||
useProject.setState({ settings: { general: { openProjectIn: "tab" } } as never });
|
||||
expect(await openRemoteProject(target, "/home/me/app", here)).toBe(true);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true);
|
||||
expect(windowGroupJoin).toHaveBeenCalledWith("w2");
|
||||
expect(windowOpenRemote).toHaveBeenNthCalledWith(1, target, "/home/me/app", false, false);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true, true);
|
||||
expect(windowGroupJoin).not.toHaveBeenCalled();
|
||||
expect(here).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -116,11 +117,11 @@ describe("a recent project opened with a modifier key", () => {
|
||||
const here = vi.fn(async () => {});
|
||||
useProject.setState({ settings: { general: { openProjectIn: "same" } } as never });
|
||||
expect(await openRemoteProject(target, "/home/me/app", here, "new")).toBe(true);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true, false);
|
||||
expect(here).not.toHaveBeenCalled();
|
||||
useProject.setState({ settings: { general: { openProjectIn: "new" } } as never });
|
||||
expect(await openRemoteProject(target, "/home/me/app", here, "same")).toBe(true);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", false);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", false, false);
|
||||
expect(here).toHaveBeenCalledOnce();
|
||||
expect(ask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -91,13 +91,11 @@ export async function openRemoteProject(
|
||||
here: () => Promise<unknown> = () => connectRemote(target, path),
|
||||
override?: ProjectWindowOverride | null,
|
||||
): Promise<boolean> {
|
||||
if ((await call(commands.windowOpenRemote(target, path, false))).kind === "focused") return true;
|
||||
if ((await call(commands.windowOpenRemote(target, path, false, false))).kind === "focused") return true;
|
||||
const mode = override ?? (await chooseProjectWindow(path.replace(/\/+$/, "").split("/").pop() || path, false));
|
||||
if (!mode) return false;
|
||||
if (mode === "new" || mode === "tab") {
|
||||
const outcome = await call(commands.windowOpenRemote(target, path, true));
|
||||
// As a local project tab: the window holding the project, new or focused, joins this one's group.
|
||||
if (mode === "tab" && outcome.kind !== "current") await call(commands.windowGroupJoin(outcome.label));
|
||||
await call(commands.windowOpenRemote(target, path, true, mode === "tab"));
|
||||
return true;
|
||||
}
|
||||
// The remote host's project doesn't take this window's untitled buffers.
|
||||
|
||||
Reference in new issue
Заблокувати користувача