fix(todo): drop the previous project's scan results after switching projects (#7318)

A scan of the old project still running after a project switch kept writing its files into the new project's TODO index. On a project change the index now bumps the scan counters (plus a new projectGen for file rescans), drops refreshes queued for the old project and resets the spinners.

Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
audichuang authored and GitHub committed 2026-12-02 10:35:47 +08:00
1 джерело 97add1f448
коміт 3cfbf80e26
2 files changed
+139

No files matched your search

+127
Переглянути файл
@@ -0,0 +1,127 @@
import { afterEach, expect, it, vi } from "vitest";
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks";
import type { Channel } from "@tauri-apps/api/core";
import type { FileMatches, SearchEvent } from "@/platform/ipc";
const backend = vi.hoisted(() => ({
searchStart: vi.fn(),
cancelRequest: vi.fn(async () => ({ status: "ok", data: null })),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, ...backend }, isTauri: () => true, onIdeEvent: () => () => {} };
});
import { useProject } from "@/platform/project";
import { installTodoIndex, queueRefresh, rescanFiles, scanProject, scanScope, useTodos } from "./store";
const todo = (path: string): FileMatches => ({
path,
relPath: path.split("/").at(-1)!,
matches: [{ line: 0, text: "// TODO one", textOffset: 0, ranges: [[3, 7]] }],
});
const done = { type: "done", summary: { cancelled: false, limitHit: false } } as SearchEvent;
const project = (root: string | null) => useProject.setState({ project: root ? ({ root } as never) : null });
const channels: Channel<SearchEvent>[] = [];
const dispose: (() => void)[] = [];
function setup(root: string) {
mockIPC(() => null);
backend.searchStart.mockImplementation((_id, _q, stream: Channel<SearchEvent>) => {
channels.push(stream);
return new Promise(() => {});
});
project(root);
dispose.push(installTodoIndex(), clearMocks);
}
afterEach(async () => {
// End scans left running, so the next test starts with a free slot.
channels.splice(0).forEach((c) => c.onmessage(done));
await Promise.resolve();
dispose.splice(0).forEach((f) => f());
project(null);
vi.clearAllMocks();
vi.useRealTimers();
useTodos.setState({ scanned: new Map(), scanning: false, scoped: new Map(), scopedScanning: false });
});
it("drops the previous project's scan after the project changes", async () => {
setup("/old");
const old = scanProject();
expect(useTodos.getState().scanning).toBe(true);
project("/new");
channels[0]!.onmessage({ type: "file", file: todo("/old/a.ts") });
channels[0]!.onmessage(done);
await old;
expect([...useTodos.getState().scanned.keys()]).toEqual([]);
expect(useTodos.getState().scanning).toBe(false);
});
it("drops the previous project's file rescan after the project changes", async () => {
setup("/old");
const old = rescanFiles(["/old/a.ts"]);
project("/new");
channels[0]!.onmessage({ type: "file", file: todo("/old/a.ts") });
channels[0]!.onmessage(done);
await old;
expect([...useTodos.getState().scanned.keys()]).toEqual([]);
});
it("an old file rescan doesn't touch the index after switching away and back", async () => {
vi.useFakeTimers();
setup("/a");
backend.searchStart.mockImplementation(async (_id, _q, stream: Channel<SearchEvent>) => {
channels.push(stream);
return { status: "ok", data: null };
});
const old = rescanFiles(["/a/x.ts"]);
project("/b");
project("/a");
const scan = scanProject();
channels[1]!.onmessage({ type: "file", file: todo("/a/x.ts") });
channels[1]!.onmessage(done);
await scan;
// The cancelled rescan settles last, through its fallback timeout.
await vi.advanceTimersByTimeAsync(2000);
await old;
expect([...useTodos.getState().scanned.keys()]).toEqual(["/a/x.ts"]);
});
it("a save in the new project still waits for the running scan", async () => {
setup("/a");
void scanProject();
project("/b");
void rescanFiles(["/b/x.ts"]);
expect(backend.searchStart).toHaveBeenCalledOnce();
});
it("drops the previous project's Scope Based scan after the project changes", async () => {
setup("/a");
const old = scanScope("project", { kind: "project" });
project("/b");
expect(useTodos.getState().scopedScanning).toBe(false);
channels[0]!.onmessage({ type: "file", file: todo("/a/x.ts") });
channels[0]!.onmessage(done);
await old;
expect([...useTodos.getState().scoped.keys()]).toEqual([]);
expect(useTodos.getState().scopedScanning).toBe(false);
});
it("forgets refreshes queued for the previous project", async () => {
vi.useFakeTimers();
setup("/old");
queueRefresh(["/old/a.ts"]);
project("/new");
await vi.advanceTimersByTimeAsync(1000);
expect(backend.searchStart).not.toHaveBeenCalled();
});
it("still keeps a scan of the same project", async () => {
setup("/p");
const scan = scanProject();
channels[0]!.onmessage({ type: "file", file: todo("/p/a.ts") });
channels[0]!.onmessage(done);
await scan;
expect([...useTodos.getState().scanned.keys()]).toEqual(["/p/a.ts"]);
});
+12
Переглянути файл
@@ -90,6 +90,8 @@ function run(
}
let scanSeq = 0;
/** Bumped when the project changes: scans started before belong to the old project. */
let projectGen = 0;
/** Rescans the whole project. */
export async function scanProject(): Promise<void> {
@@ -147,12 +149,14 @@ export async function rescanFiles(paths: string[], removed: string[] = []): Prom
if (removed.length) dropPaths(removed);
const query = buildTodoQuery(useTodoSettings.getState(), { kind: "files", paths });
if (!query || !paths.length) return;
const gen = projectGen;
const found = new Map<string, TodoItem[]>();
try {
await run(query, (path, items) => found.set(path, items));
} catch {
return;
}
if (gen !== projectGen) return;
useTodos.setState((s) => {
const scanned = new Map(s.scanned);
for (const p of paths) {
@@ -253,13 +257,21 @@ export function installTodoIndex(): () => void {
const r = s.project?.root ?? null;
if (r === root) return;
root = r;
// The old project's scans and queued refreshes must not fill the new project's index.
projectGen++;
scanSeq++;
scopeSeq++;
pending.clear();
pendingRemoved.clear();
useTodos.setState({
scanned: new Map(),
live: new Map(),
scanning: false,
scannedOnce: false,
error: null,
scoped: new Map(),
scopedKey: null,
scopedScanning: false,
});
if (r) start();
});