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
20 changed files with 213 additions and 77 deletions

No files matched your search

+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);
+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
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.
@@ -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;
}