Compare commits

..
Author SHA1 Message Date
l0ng-ai 59b71295b2 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH 2026-11-23 22:27:04 +08:00
Bert Verhelstandbertyhell 5eff75cab5 fix(remote): keep scratches and generated requests on the host that writes them (#5439)
In a remote (SSH/WSL) window, Generate Request in HTTP Client failed with Permission denied: the scratches folder was resolved on the desktop and its path sent to the remote host. Scratches and generated HTTP requests now live in the data directory of the host that writes them (created on demand, rechecked on later calls), and remote IPC routing is installed before session listeners run.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:23 +08:00
25 changed files with 231 additions and 168 deletions

No files matched your search

-2
View File
@@ -324,8 +324,6 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
+10
View File
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
ide_vfs::create_dir(&path)
}
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
/// keeps its scratches on the server, where its file commands run.
#[command(trust = always)]
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
let dir = host.data_dir.join("scratches");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
#[command(trust = always)]
@@ -383,6 +392,7 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+7
View File
@@ -74,6 +74,13 @@ async fn serves_projects_files_documents_search_and_runs() {
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
let scratch_path = base.join("data/scratches");
assert!(!scratch_path.exists());
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
assert!(scratch_path.is_dir());
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
+8 -6
View File
@@ -8,7 +8,6 @@
use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::ErrorKind;
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -647,8 +646,10 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Open editors may have cached empty tokens or inheritance results during the import.
/// Attach generated Maven sources before refreshing either, so both see the new classpath.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -665,9 +666,10 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
}
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
+7 -9
View File
@@ -3166,7 +3166,7 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
async fn a_project_update_refreshes_java_semantic_tokens() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
@@ -3175,22 +3175,20 @@ async fn a_project_update_refreshes_java_tokens_and_inheritance() {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
_ => None,
})
.collect::<Vec<_>>()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(refreshes().is_empty());
assert_eq!(refreshes(), 0);
// A later import may add tokens and implementation targets to open editors.
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
eventually(|| refreshes() == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
+1 -2
View File
@@ -12,9 +12,8 @@ test("the scratch language chooser fits short windows and keeps recents separate
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
const { rememberLanguage } = await import(/* @vite-ignore */ store);
setScratchBackend({
dataDir: async () => "/test-app-data",
scratchesDir: async () => "/test-app-data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
+1
View File
@@ -286,6 +286,7 @@ fs_read_range always project_host bin
fs_read_text always project_host bindings async
fs_rename always project_host bindings async
fs_resolve_reference always project_host bindings async
fs_scratches_dir always project_host bindings sync
fs_set_writable always project_host bindings sync
fs_synchronize_directories always project_host bindings async
fs_undo_delete always project_host bindings async
+5 -2
View File
@@ -707,6 +707,11 @@ export const commands = {
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/**
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
* keeps its scratches on the server, where its file commands run.
*/
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
/**
* Toggle Read-only Attribute: sets the writable bit (and the open document's
* state). Returns whether the file is read-only now.
@@ -9197,8 +9202,6 @@ export type LogcatLine = {
};
export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" |
/** An import or classpath update may have changed inheritance search results. */
"inheritance" |
/** The Dart server published a document's Flutter outline. */
"flutterOutline";
@@ -11,7 +11,7 @@
* of the file in batches; results are cached per document text, and markers
* follow their lines in between.
* The cache outlives the editor view (switching tabs remounts it) until other
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
* files change or a language server settles: on some servers (jdtls) every
* implementation search walks the whole workspace, so asking again is costly.
* Library sources ask no inheritors from the server (`isLibrarySource`).
*/
@@ -119,15 +119,11 @@ function watchChanges() {
// documents: re-render them instead of waiting for an edit or a settling server.
for (const plugin of live) plugin.refreshSoon();
});
// Answers (outlines too) given while a server was starting or importing may be incomplete.
const refreshCaches = () => {
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
onServerSettled(() => {
docMarkers.clear();
forgetInheritanceGraph();
for (const plugin of live) plugin.refreshSoon();
};
onServerSettled(refreshCaches);
onIdeEvent("lspRefresh", (e) => {
if (e.kind === "inheritance") refreshCaches();
});
// Go to Declaration and the like go first: in-flight marker requests are cancelled and
// asked again once the navigation is done.
-65
View File
@@ -9,25 +9,13 @@ import {
commands,
type ClassInheritance,
type HierarchyItem,
type IdeEvent,
type Location,
type OutlineItem,
type Pos,
type SymbolKind,
} from "@/platform/ipc";
import { setInvokeRoute } from "@/platform/tauriCore";
const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi.fn() }));
const ideListeners = vi.hoisted(() => new Map<string, Set<(event: IdeEvent) => void>>());
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
onIdeEvent: (type: string, listener: (event: IdeEvent) => void) => {
let listeners = ideListeners.get(type);
if (!listeners) ideListeners.set(type, (listeners = new Set()));
listeners.add(listener);
return () => listeners.delete(listener);
},
}));
vi.mock("@/editor/lsp/navigation", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
@@ -635,59 +623,6 @@ describe("clicking a marker", () => {
});
describe("inheritance gutter", () => {
it.each([
{ type: "interface", source: SHAPE, outline: SHAPE_OUTLINE },
{ type: "abstract class", source: BASE, outline: BASE_OUTLINE },
])(
"refreshes implementation and override markers when a Java project update finishes ($type)",
async ({ source, outline }) => {
vi.useFakeTimers();
let indexed = false;
const target = "/p/service/target/generated-sources/example/ServiceImpl.java";
const queries = vi.fn<MarkerDeps["implementations"]>(async (positions) =>
positions.map(({ line }) => (indexed ? [loc(target, line + 2)] : [])),
);
setInvokeRoute(async (command, args) => {
if (command === "doc_outline") return outline;
if (command === "lsp_type_hierarchy") {
throw { kind: "unavailable", message: "no type hierarchy", data: null };
}
if (command === "lsp_implementations") return queries((args as { positions: Pos[] }).positions);
return null;
});
const ctx = { doc: 12, path: `/p/api/${outline[0]!.name}.java`, language: "java", uiMode: null, readOnly: false };
const view = new EditorView({
doc: Text.of(source),
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
const kinds = () =>
[...view.dom.querySelectorAll<HTMLElement>('[class*="cm-openidea-lineMarker-"]')].map((el) => el.dataset.kind);
const emit = (event: IdeEvent) => {
for (const listener of ideListeners.get(event.type) ?? []) listener(event);
};
try {
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
expect(kinds()).toEqual([]);
indexed = true;
emit({ type: "lspRefresh", server: 1, kind: "semanticTokens" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
emit({ type: "lspRefresh", server: 1, kind: "inheritance" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(2);
expect(kinds()).toEqual(["implemented", "implemented", "overridden"]);
} finally {
view.destroy();
setInvokeRoute(null);
vi.useRealTimers();
}
},
);
it.each([
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
{ kind: "overridden", language: "java", declaration: "@Data" },
@@ -2,22 +2,17 @@ import { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { scratchesDir } from "@/platform/scratchesDir";
import { editorService } from "@/workbench/contributions";
import { appendRequests } from "./spring/request";
export const GENERATED_REQUESTS = "generated-requests.http";
async function scratchFile(): Promise<{ path: string; created: boolean }> {
const dir = `${await appDataDir()}/scratches`;
const ignoreExisting = (e: unknown) => {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
};
await call(commands.fsCreateDir(dir)).catch(ignoreExisting);
const path = `${dir}/${GENERATED_REQUESTS}`;
const path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
let created = true;
await call(commands.fsCreateFile(path)).catch((e) => {
ignoreExisting(e);
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
created = false;
});
return { path, created };
+8 -6
View File
@@ -8,8 +8,8 @@
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { scratchesDir } from "@/platform/scratchesDir";
import {
editorService,
notifications,
@@ -116,11 +116,13 @@ function directoryArg(arg: unknown): string | null {
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
async function newRequest(directory?: string) {
try {
const dir = directory ?? `${await appDataDir()}/scratches`;
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
const dir = directory ?? (await scratchesDir());
if (directory) {
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
}
const names = new Set((await call(commands.fsReadDir(dir))).map((e) => e.name.toLowerCase()));
let name = "requests.http";
@@ -4,12 +4,6 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co
import { springControllers } from "./endpoints";
import { generateRequests } from "./editor";
// The backend reports the user data directory `/`-separated on every OS.
vi.mock("@/platform/platformInfo", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/platformInfo")>()),
appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea",
}));
// No backend here: the file commands answer like a project without Spring
// configuration files (empty configs, the files the body lookup probes missing).
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -19,7 +13,8 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
call: async (p: Promise<unknown>) => await p,
commands: {
...m.commands,
fsCreateDir: async () => null,
// The backend reports the scratches folder `/`-separated on every OS.
fsScratchesDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches",
fsCreateFile: async () => null,
fsReadText: async () => "",
},
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { getAction } from "@/platform/actions";
import { onIdeEvent } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { useProjectViewRoots } from "@/workbench/contributions";
import {
chooserRows,
@@ -102,9 +103,8 @@ describe("creating scratch files", () => {
opened = [];
carets = [];
backend = {
dataDir: async () => "/data/",
scratchesDir: async () => "/data/scratches/",
listNames: async (dir) => [...files].filter((f) => f.startsWith(dir + "/")).map((f) => f.slice(dir.length + 1)),
createDir: async () => {},
createFile: async (p, text) => {
files.add(p);
contents.set(p, text);
@@ -177,14 +177,43 @@ describe("creating scratch files", () => {
});
});
describe("scratches of a remote window", () => {
afterEach(() => {
useRemote.setState({ session: null });
setScratchBackend(tauriScratchBackend);
});
it("moves the Scratches root to the server's folder when the window attaches to it in place", async () => {
const remote = () => useRemote.getState().session !== null;
setScratchBackend({
scratchesDir: async () => (remote() ? "/home/me/.openidea/data/scratches" : "C:/Users/me/AppData/scratches"),
listNames: async () => [],
createFile: async () => {},
languages: async () => [],
open: async () => {},
});
const root = () => useProjectViewRoots.getState().roots.get("scratches")?.path;
const dispose = activate();
try {
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
useRemote.setState({ session: { root: "/home/me/project" } as never });
await vi.waitFor(() => expect(root()).toBe("/home/me/.openidea/data/scratches"));
useRemote.setState({ session: null });
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
} finally {
dispose();
}
expect(root()).toBeUndefined();
});
});
describe("deleting scratch files", () => {
afterEach(() => setScratchBackend(tauriScratchBackend));
it("reports deletions inside the scratches folder as file system changes", async () => {
setScratchBackend({
dataDir: async () => "/data",
scratchesDir: async () => "/data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [],
open: async () => {},
+14 -2
View File
@@ -5,6 +5,7 @@
import { registerActions } from "@/platform/actions";
import { onFileOperation } from "@/platform/fileOps";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { registerMenuGroup, registerOverlay, registerProjectViewRoot } from "@/workbench/contributions";
import { ScratchChooserHost } from "./ScratchChooser";
import { openChooser } from "./store";
@@ -20,10 +21,15 @@ export function activate(): () => void {
let disposed = false;
let unregisterRoot = () => {};
let dir: string | null = null;
if (scratchesAvailable())
let generation = 0;
const registerRoot = () => {
const current = ++generation;
unregisterRoot();
unregisterRoot = () => {};
dir = null;
void scratchesDir()
.then((path) => {
if (disposed) return;
if (disposed || current !== generation) return;
dir = path;
unregisterRoot = registerProjectViewRoot({
id: "scratches",
@@ -35,7 +41,13 @@ export function activate(): () => void {
});
})
.catch((e: unknown) => console.warn("scratch files: no scratches folder", e));
};
if (scratchesAvailable()) registerRoot();
const disposers = [
// Attaching to (or leaving) a remote server moves the scratches to that host.
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session && scratchesAvailable()) registerRoot();
}),
// The file watcher covers the project only: deleted scratches close their editors like watched files.
onFileOperation((op) => {
const removed = dir && op.kind === "deleted" ? op.paths.filter((p) => p === dir || p.startsWith(`${dir}/`)) : [];
+12 -30
View File
@@ -1,27 +1,26 @@
/**
* Scratch files live in the app data dir (`<appData>/scratches`), not in the
* project, like IDEA's config-dir scratches. Creating one picks the next free
* `scratch[_n].<ext>` name and opens it as a normal document.
* Scratch files live in the user data dir (`<data>/scratches`) of the host that runs the
* window's file commands (the server in a remote window), not in the project, like IDEA's
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
* it as a normal document.
*/
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { scratchesDir as hostScratchesDir } from "@/platform/scratchesDir";
import { editorService, notifications } from "@/workbench/contributions";
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
export interface ScratchBackend {
/** Absolute app data dir. */
dataDir(): Promise<string>;
/** Absolute scratches folder, created. */
scratchesDir(): Promise<string>;
listNames(dir: string): Promise<string[]>;
createDir(dir: string): Promise<void>;
createFile(path: string, text: string): Promise<void>;
languages(): Promise<ScratchLanguage[]>;
open(path: string, caret: { line: number; col: number } | null): Promise<void>;
}
export const tauriScratchBackend: ScratchBackend = {
dataDir: appDataDir,
scratchesDir: hostScratchesDir,
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
createFile: async (path, text) =>
void (await call(
text ? commands.fsCreateFileBytes(path, [...new TextEncoder().encode(text)]) : commands.fsCreateFile(path),
@@ -35,30 +34,13 @@ let backend: ScratchBackend = tauriScratchBackend;
/** Tests swap the backend. */
export function setScratchBackend(b: ScratchBackend) {
backend = b;
dirPromise = null;
}
export const scratchBackend = () => backend;
let dirPromise: Promise<string> | null = null;
/** `<appData>/scratches`, created on first use. */
export function scratchesDir(): Promise<string> {
if (!dirPromise) {
dirPromise = (async () => {
const dir = `${(await backend.dataDir()).replace(/\/+$/, "")}/scratches`;
try {
await backend.createDir(dir);
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
return dir;
})();
dirPromise.catch(() => {
dirPromise = null;
});
}
return dirPromise;
/** The scratches folder, created if needed. */
export async function scratchesDir(): Promise<string> {
return (await backend.scratchesDir()).replace(/\/+$/, "");
}
export const scratchesAvailable = () => isTauri() || backend !== tauriScratchBackend;
+2 -2
View File
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTx } from "@/platform/i18n";
import { Checkbox, Dialog, Input } from "@/ui";
import { answerAskpass, askpassAnswer, useAskpass, type AskpassPrompt } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, useAskpass, type AskpassPrompt } from "./askpass";
import styles from "./Ssh.module.css";
export function AskpassHost() {
@@ -39,7 +39,7 @@ function AskpassDialog({ prompt: p }: { prompt: AskpassPrompt }) {
return (
<Dialog
open
title={tx(p.kind === "secret" ? "SSH Password" : "SSH")}
title={tx(askpassTitle(p))}
onClose={cancel}
width={440}
buttons={[
+9
View File
@@ -45,3 +45,12 @@ export function answerAskpass(
// on success and drops it again when authentication fails.
void send(p.id, answer, remember).catch(() => {});
}
/** The dialog title: git asks for HTTPS credentials (any host, e.g. a token as the password) as well as ssh. */
export function askpassTitle(
p: Pick<AskpassPrompt, "kind" | "prompt">,
): "Password" | "Username" | "SSH Password" | "SSH" {
const https = /\bhttps?:\/\//i.test(p.prompt);
if (p.kind === "secret") return https ? "Password" : "SSH Password";
return https ? "Username" : "SSH";
}
+13 -1
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SSH_CONFIG, type SshConfigValid } from "@/platform/remoteSettings";
import { answerAskpass, askpassAnswer, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
describe("askpass queue", () => {
@@ -40,6 +40,18 @@ describe("askpass queue", () => {
});
});
describe("askpass title", () => {
it("names git HTTPS credentials without calling them SSH", () => {
expect(askpassTitle({ kind: "secret", prompt: "Password for 'https://[email protected]': " })).toBe("Password");
expect(askpassTitle({ kind: "text", prompt: "Username for 'https://cnb.cool': " })).toBe("Username");
});
it("keeps the SSH titles for ssh prompts", () => {
expect(askpassTitle({ kind: "secret", prompt: "dev@host's password: " })).toBe("SSH Password");
expect(askpassTitle({ kind: "text", prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': " })).toBe("SSH");
});
});
describe("Start SSH Session chooser", () => {
const config = (patch: Partial<SshConfigValid>): SshConfigValid => ({ ...DEFAULT_SSH_CONFIG, ...patch });
+1 -6
View File
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
import { appDataDir, loadPlatformInfo, usePlatform } from "./platformInfo";
import { loadPlatformInfo, usePlatform } from "./platformInfo";
const appInfo = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", () => ({ isTauri: () => true, commands: { appInfo } }));
@@ -24,11 +24,6 @@ it("keeps platform defaults when the query fails", async () => {
expect(usePlatform.getState()).toEqual(initialPlatform);
});
it("takes the user data directory from the backend, which may have moved it", async () => {
appInfo.mockResolvedValue({ platform: "windows", dataDir: "E:/OpenIDEA/ai.l0ng.openidea/" });
expect(await appDataDir()).toBe("E:/OpenIDEA/ai.l0ng.openidea");
});
it.each([
[
{ left: ["close", "maximize", "minimize"], right: [] },
-8
View File
@@ -41,14 +41,6 @@ export const usePlatform = create<PlatformInfo>(() => {
};
});
let dataDir: Promise<string> | undefined;
/** The user data directory (scratches, plugins, Local History), which `OPENIDEA_DATA_DIR` can move. */
export function appDataDir(): Promise<string> {
dataDir ??= commands.appInfo().then((info) => info.dataDir.replace(/\/+$/, ""));
return dataDir;
}
export async function loadPlatformInfo() {
if (!isTauri()) return;
try {
+28
View File
@@ -4,6 +4,7 @@ import { call, commands, type ChannelFrame, type ExecutionEvent, type ProjectInf
import { useProject } from "./project";
import { disableRemote, enableRemote, useRemote } from "./remote";
import { encodeArgs, remoteRouting } from "./remote";
import { scratchesDir } from "./scratchesDir";
describe("remote invoke", () => {
beforeAll(() => {
@@ -54,6 +55,33 @@ describe("remote invoke", () => {
}
});
it("routes a scratch folder lookup made as soon as the remote session is published", async () => {
const invoke = vi.fn(async (command: string, args: { cmd: string }) => {
expect(command).toBe("remote_invoke");
expect(args.cmd).toBe("fs_scratches_dir");
return JSON.stringify("/home/me/.openidea/data/scratches");
});
vi.stubGlobal("__TAURI_INTERNALS__", { invoke, transformCallback: () => 1 });
const unsubscribe = useRemote.subscribe(({ session }) => {
if (session) void scratchesDir();
});
try {
enableRemote({
target: { kind: "ssh", config: "test" },
root: "/home/me/project",
host: "test",
os: "linux",
commands: ["fs_scratches_dir"],
});
await expect(scratchesDir()).resolves.toBe("/home/me/.openidea/data/scratches");
expect(invoke).toHaveBeenCalledOnce();
} finally {
unsubscribe();
disableRemote();
vi.unstubAllGlobals();
}
});
it("routes served commands, keeps opening / closing local and sets global settings on both sides", () => {
const served = new Set([
"vcs_add_to_ignore",
+1 -1
View File
@@ -153,8 +153,8 @@ const route: InvokeRoute = (cmd, args, options) => {
*/
export function enableRemote(session: RemoteSession) {
routed = new Set(session.commands);
useRemote.setState({ session, lost: null, reconnecting: false });
setInvokeRoute(route);
useRemote.setState({ session, lost: null, reconnecting: false });
}
export function disableRemote() {
+38
View File
@@ -0,0 +1,38 @@
import { afterEach, expect, it, vi } from "vitest";
import { useRemote } from "./remote";
import { scratchesDir } from "./scratchesDir";
// Routed like every file command: the server answers in a remote window.
const fsScratchesDir = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (importOriginal) => {
const m = await importOriginal<typeof import("@/platform/ipc")>();
return { ...m, call: async (p: Promise<unknown>) => await p, commands: { ...m.commands, fsScratchesDir } };
});
afterEach(() => useRemote.setState({ session: null }));
it("asks the host again once the window attaches to or leaves a remote server", async () => {
fsScratchesDir.mockResolvedValue("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches/");
const pending = scratchesDir();
expect(scratchesDir()).toBe(pending);
expect(await pending).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
expect(await scratchesDir()).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
expect(fsScratchesDir).toHaveBeenCalledTimes(2);
fsScratchesDir.mockResolvedValue("/home/me/.openidea/data/scratches");
useRemote.setState({ session: { root: "/home/me/project" } as never });
expect(await scratchesDir()).toBe("/home/me/.openidea/data/scratches");
fsScratchesDir.mockResolvedValue("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
useRemote.setState({ session: null });
expect(await scratchesDir()).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
expect(fsScratchesDir).toHaveBeenCalledTimes(4);
});
it("asks again after a failure", async () => {
useRemote.setState({ session: { root: "/p" } as never });
fsScratchesDir.mockRejectedValueOnce(new Error("disconnected"));
await expect(scratchesDir()).rejects.toThrow("disconnected");
fsScratchesDir.mockResolvedValue("/home/me/.openidea/data/scratches");
expect(await scratchesDir()).toBe("/home/me/.openidea/data/scratches");
});
+25
View File
@@ -0,0 +1,25 @@
import { call, commands } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
let dir: Promise<string> | null = null;
// A window attaches to (or leaves) a remote server in place: the folder is then another host's.
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session) dir = null;
});
/**
* The scratch files' folder (`<user data>/scratches`) of the host that runs this window's file
* commands: the server in a remote window, this machine otherwise. Ensures the folder exists.
*/
export function scratchesDir(): Promise<string> {
if (!dir) {
const pending = call(commands.fsScratchesDir())
.then((path) => path.replace(/\/+$/, ""))
.finally(() => {
if (dir === pending) dir = null;
});
dir = pending;
}
return dir;
}