Compare commits

..
Author SHA1 Message Date
l0ng-ai bd79458f59 fix(editor): refresh Java inheritance markers after Maven import 2026-11-23 23:19:09 +08:00
25 changed files with 168 additions and 231 deletions

No files matched your search

+2
View File
@@ -324,6 +324,8 @@ 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,15 +228,6 @@ 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)]
@@ -392,7 +383,6 @@ 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,13 +74,6 @@ 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);
+6 -8
View File
@@ -8,6 +8,7 @@
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};
@@ -646,10 +647,8 @@ 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.
/// 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.
/// 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.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -666,10 +665,9 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
}
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
+9 -7
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_semantic_tokens() {
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
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,20 +3175,22 @@ async fn a_project_update_refreshes_java_semantic_tokens() {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
.filter_map(|e| match e {
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
_ => None,
})
.collect::<Vec<_>>()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(refreshes(), 0);
assert!(refreshes().is_empty());
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
// A later import may add tokens and implementation targets to open editors.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == 1).await;
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
}
#[tokio::test(flavor = "multi_thread")]
+2 -1
View File
@@ -12,8 +12,9 @@ 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({
scratchesDir: async () => "/test-app-data/scratches",
dataDir: async () => "/test-app-data",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
-1
View File
@@ -286,7 +286,6 @@ 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
+2 -5
View File
@@ -707,11 +707,6 @@ 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.
@@ -9202,6 +9197,8 @@ 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 or a language server settles: on some servers (jdtls) every
* files change, a language server settles or its classpath changes: 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,11 +119,15 @@ 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 indexing may be incomplete.
onServerSettled(() => {
// Answers (outlines too) given while a server was starting or importing may be incomplete.
const refreshCaches = () => {
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,13 +9,25 @@ 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,
@@ -623,6 +635,59 @@ 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,17 +2,22 @@ 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 { scratchesDir } from "@/platform/scratchesDir";
import { appDataDir } from "@/platform/platformInfo";
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 path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
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}`;
let created = true;
await call(commands.fsCreateFile(path)).catch((e) => {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
ignoreExisting(e);
created = false;
});
return { path, created };
+6 -8
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,13 +116,11 @@ 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 scratchesDir());
if (directory) {
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
const dir = directory ?? `${await appDataDir()}/scratches`;
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,6 +4,12 @@ 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) => {
@@ -13,8 +19,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
call: async (p: Promise<unknown>) => await p,
commands: {
...m.commands,
// The backend reports the scratches folder `/`-separated on every OS.
fsScratchesDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches",
fsCreateDir: async () => null,
fsCreateFile: async () => null,
fsReadText: async () => "",
},
@@ -3,7 +3,6 @@ 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,
@@ -103,8 +102,9 @@ describe("creating scratch files", () => {
opened = [];
carets = [];
backend = {
scratchesDir: async () => "/data/scratches/",
dataDir: async () => "/data/",
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,43 +177,14 @@ 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({
scratchesDir: async () => "/data/scratches",
dataDir: async () => "/data",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [],
open: async () => {},
+2 -14
View File
@@ -5,7 +5,6 @@
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";
@@ -21,15 +20,10 @@ export function activate(): () => void {
let disposed = false;
let unregisterRoot = () => {};
let dir: string | null = null;
let generation = 0;
const registerRoot = () => {
const current = ++generation;
unregisterRoot();
unregisterRoot = () => {};
dir = null;
if (scratchesAvailable())
void scratchesDir()
.then((path) => {
if (disposed || current !== generation) return;
if (disposed) return;
dir = path;
unregisterRoot = registerProjectViewRoot({
id: "scratches",
@@ -41,13 +35,7 @@ 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}/`)) : [];
+30 -12
View File
@@ -1,26 +1,27 @@
/**
* 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.
* 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.
*/
import { call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { scratchesDir as hostScratchesDir } from "@/platform/scratchesDir";
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { editorService, notifications } from "@/workbench/contributions";
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
export interface ScratchBackend {
/** Absolute scratches folder, created. */
scratchesDir(): Promise<string>;
/** Absolute app data dir. */
dataDir(): 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 = {
scratchesDir: hostScratchesDir,
dataDir: appDataDir,
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),
@@ -34,13 +35,30 @@ let backend: ScratchBackend = tauriScratchBackend;
/** Tests swap the backend. */
export function setScratchBackend(b: ScratchBackend) {
backend = b;
dirPromise = null;
}
export const scratchBackend = () => backend;
/** The scratches folder, created if needed. */
export async function scratchesDir(): Promise<string> {
return (await backend.scratchesDir()).replace(/\/+$/, "");
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;
}
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, askpassTitle, useAskpass, type AskpassPrompt } from "./askpass";
import { answerAskpass, askpassAnswer, 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(askpassTitle(p))}
title={tx(p.kind === "secret" ? "SSH Password" : "SSH")}
onClose={cancel}
width={440}
buttons={[
-9
View File
@@ -45,12 +45,3 @@ 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";
}
+1 -13
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, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { answerAskpass, askpassAnswer, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
describe("askpass queue", () => {
@@ -40,18 +40,6 @@ 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 });
+6 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
import { loadPlatformInfo, usePlatform } from "./platformInfo";
import { appDataDir, loadPlatformInfo, usePlatform } from "./platformInfo";
const appInfo = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", () => ({ isTauri: () => true, commands: { appInfo } }));
@@ -24,6 +24,11 @@ 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,6 +41,14 @@ 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,7 +4,6 @@ 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(() => {
@@ -55,33 +54,6 @@ 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);
setInvokeRoute(route);
useRemote.setState({ session, lost: null, reconnecting: false });
setInvokeRoute(route);
}
export function disableRemote() {
-38
View File
@@ -1,38 +0,0 @@
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
@@ -1,25 +0,0 @@
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;
}