Compare commits

...
Author SHA1 Message Date
l0ng-ai bb3d7d7c51 fix(libraries): scope detected libraries to the open project 2026-11-18 19:10:19 +08:00
4 changed files with 91 additions and 11 deletions

No files matched your search

+9 -4
View File
@@ -149,6 +149,7 @@ export function activate(): () => void {
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
let settled: LibraryGroup[] = [];
let request: RequestId | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
const clear = () => {
disposeRoot();
disposeReadOnly();
@@ -160,8 +161,8 @@ export function activate(): () => void {
const id = ++seq;
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
request = undefined;
if (!useProject.getState().project || useProject.getState().project?.trusted === false || !isTauri())
return clear();
const { project } = useProject.getState();
if (!project || project.trusted === false || !isTauri()) return clear();
let collected: LibraryGroup[] = [];
const show = (groups: LibraryGroup[]) => {
if (id !== seq) return;
@@ -185,6 +186,7 @@ export function activate(): () => void {
};
const channel = new Channel<LibraryGroup[]>();
channel.onmessage = (groups) => {
if (id !== seq) return;
collected = mergeLibraryGroups([...collected, ...groups]);
const reported = new Set(collected.map((g) => g.kind));
show(mergeLibraryGroups([...collected, ...settled.filter((g) => !reported.has(g.kind))]));
@@ -197,7 +199,7 @@ export function activate(): () => void {
show(groups);
})
.catch((e: unknown) => {
if (!isCancelled(e)) console.warn("external libraries: cannot list SDK roots", e);
if (id === seq && !isCancelled(e)) console.warn("external libraries: cannot list SDK roots", e);
})
.finally(() => {
if (request === current) request = undefined;
@@ -208,9 +210,12 @@ export function activate(): () => void {
{ id: "libraries.reload", title: "Reload External Libraries", category: "Go", hidden: true, run: refresh },
]);
const unsub = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) {
clearTimeout(timer);
clear();
}
if (sdkKey(s) !== sdkKey(prev)) refresh();
});
let timer: ReturnType<typeof setTimeout> | undefined;
const unsubFs = onIdeEvent("fsChanged", (e) => {
if (!touchesManifest([...e.created, ...e.modified, ...e.removed])) return;
clearTimeout(timer);
+53 -4
View File
@@ -1,7 +1,9 @@
import { describe, expect, it, vi } from "vitest";
import type { LibraryGroup } from "@/bindings";
const results: LibraryGroup[][] = [];
const results: Array<LibraryGroup[] | Promise<LibraryGroup[]>> = [];
const channels: Array<{ onmessage: (groups: LibraryGroup[]) => void }> = [];
let requestId = 0;
/** Batches the next request streams before it answers. */
const streamed: LibraryGroup[][] = [];
@@ -17,13 +19,15 @@ vi.mock("@/bindings", () => ({
},
}));
vi.mock("@/platform/ipc", () => ({
call: (request: [string, { onmessage: (v: unknown) => void }]) => {
for (const batch of streamed.splice(0)) request[1].onmessage(batch);
call: (request: [string, (typeof channels)[number]]) => {
const channel = request[1];
channels.push(channel);
for (const batch of streamed.splice(0)) channel.onmessage(batch);
return Promise.resolve(results.shift() ?? []);
},
isCancelled: () => false,
isTauri: () => true,
nextRequestId: () => 1,
nextRequestId: () => ++requestId,
onIdeEvent: () => () => {},
}));
@@ -31,6 +35,7 @@ const { activate } = await import("./index");
const { useProject } = await import("@/platform/project");
const { useProjectViewRoots } = await import("@/workbench/contributions");
const { executeAction } = await import("@/platform/actions");
const { isLibraryPath } = await import("@/editor/api");
const rust = (version: string): LibraryGroup => ({
name: "Cargo dependencies",
@@ -39,6 +44,50 @@ const rust = (version: string): LibraryGroup => ({
});
describe("External Libraries refresh", () => {
it("drops the old project's tree and read-only roots before the next project reports any libraries", async () => {
const setRoot = (root: string) =>
useProject.setState({ project: { root, name: root, trusted: true, isGit: false, settings: {} } });
const rootLabel = () =>
useProjectViewRoots.getState().roots.get("externalLibraries")?.children?.[0]?.children?.[0]?.label;
setRoot("/old");
results.push([rust("1.0.19")]);
const dispose = activate();
try {
await vi.waitFor(() => expect(rootLabel()).toBe("itoa 1.0.19"));
expect(isLibraryPath("/cargo/itoa-1.0.19/src/lib.rs")).toBe(true);
let finishOld!: (groups: LibraryGroup[]) => void;
results.push(new Promise((resolve) => (finishOld = resolve)));
await executeAction("libraries.reload");
const old = channels.at(-1)!;
expect(rootLabel()).toBe("itoa 1.0.19");
let finishNew!: (groups: LibraryGroup[]) => void;
results.push(new Promise((resolve) => (finishNew = resolve)));
setRoot("/new");
const current = channels.at(-1)!;
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
expect(isLibraryPath("/cargo/itoa-1.0.19/src/lib.rs")).toBe(false);
old.onmessage([rust("9.0.0")]);
finishOld([rust("9.0.0")]);
await Promise.resolve();
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
current.onmessage([
{ name: "Node", kind: "nodeModules", roots: [{ name: "new", path: "/new/node_modules/new" }] },
]);
expect(rootLabel()).toBe("new");
expect(isLibraryPath("/new/node_modules/new/index.js")).toBe(true);
expect(isLibraryPath("/cargo/itoa-1.0.19/src/lib.rs")).toBe(false);
finishNew([rust("2.0.0")]);
await vi.waitFor(() => expect(rootLabel()).toBe("itoa 2.0.0"));
} finally {
dispose();
useProject.setState({ project: null });
}
});
it("replaces the node in place when the libraries change", async () => {
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
@@ -688,6 +688,31 @@ describe("Settings dialog", () => {
expect(settingsSet).toHaveBeenCalledWith("project", "projectStructure.compilerOutput", '"out/classes"');
});
it("drops the previous project's resolved libraries while discovering the next project's libraries", async () => {
const setRoot = (root: string) =>
useProject.setState({ project: { root, name: root, trusted: true, isGit: false, settings: current } });
vi.stubGlobal("__TAURI_INTERNALS__", { transformCallback: () => 1, invoke: async () => {} });
let finish!: (result: Awaited<ReturnType<typeof commands.sdkProjectLibraries>>) => void;
const discover = vi
.spyOn(commands, "sdkProjectLibraries")
.mockResolvedValueOnce({ status: "ok", data: [{ name: "Old dependencies", kind: "cargo", roots: [] }] })
.mockReturnValueOnce(new Promise((resolve) => (finish = resolve)));
try {
setRoot("/old");
render(<ProjectStructureDialog />);
await act(async () => executeAction("file.projectStructure", "libraries"));
expect(screen.getByText("Old dependencies")).toBeInTheDocument();
act(() => setRoot("/new"));
expect(screen.queryByText("Old dependencies")).not.toBeInTheDocument();
await act(async () => finish({ status: "ok", data: [{ name: "New dependencies", kind: "cargo", roots: [] }] }));
expect(screen.getByText("New dependencies")).toBeInTheDocument();
} finally {
discover.mockRestore();
vi.unstubAllGlobals();
}
});
it("disables Project Structure controls whose settings have no execution support", async () => {
useProject.setState({ project: { name: "demo", root: "/project" } as never });
render(<ProjectStructureDialog />);
@@ -1061,7 +1061,8 @@ function LibrariesSection() {
const [rawLibs, setRawLibs] = useProjectSetting<ProjectLibraryValid[] | undefined>("projectStructure.libraries");
const libs = rawLibs ?? [];
const [selectedIdx, setSelectedIdx] = useState<number>(0);
const [detectedGroups, setDetectedGroups] = useState<LibraryGroup[]>([]);
const [detected, setDetected] = useState<{ root: string; groups: LibraryGroup[] } | null>(null);
const detectedGroups = detected?.root === root ? detected.groups : [];
const nameId = useId();
useEffect(() => {
@@ -1072,12 +1073,12 @@ function LibrariesSection() {
let collected: LibraryGroup[] = [];
channel.onmessage = (groups) => {
collected = mergeLibraryGroups([...collected, ...groups]);
if (live) setDetectedGroups(collected);
if (live) setDetected({ root, groups: collected });
};
call(commands.sdkProjectLibraries(request, channel))
.then((groups) => {
collected = groups;
if (live) setDetectedGroups(groups);
if (live) setDetected({ root, groups });
})
.catch(() => {});
return () => {