Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 83a00449c8 Add React Scan composer menu recordings
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:29:20 +00:00
Cursor AgentandJulius Marminge 669d274bf9 Format composer menu highlight helper
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:26:07 +00:00
Cursor AgentandJulius Marminge 3666f713e4 Avoid composer menu highlight sync effect
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:24:40 +00:00
7 changed files with 193 additions and 197 deletions

No files matched your search

@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import fsPromises from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import { it, afterEach, describe, expect, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -13,7 +13,7 @@ import { ServerConfig } from "../../config.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
import { makeWorkspaceEntries, WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
const TestLayer = Layer.empty.pipe(
@@ -29,28 +29,6 @@ const TestLayer = Layer.empty.pipe(
Layer.provideMerge(NodeServices.layer),
);
const makeWorkspaceEntriesWithFileSystem = (
makeFileSystem: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* makeWorkspaceEntries.pipe(
Effect.provideService(FileSystem.FileSystem, makeFileSystem(fileSystem)),
);
});
const makeWorkspaceEntriesWithReadDirectory = (
onReadDirectory: (
path: string,
run: () => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) =>
makeWorkspaceEntriesWithFileSystem((fileSystem) => ({
...fileSystem,
readDirectory: (inputPath, options) =>
onReadDirectory(inputPath, () => fileSystem.readDirectory(inputPath, options)),
}));
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
const fileSystem = yield* FileSystem.FileSystem;
const dir = yield* fileSystem.makeTempDirectoryScoped({
@@ -102,6 +80,10 @@ const appendSeparator = (input: string) =>
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
afterEach(() => {
vi.restoreAllMocks();
});
describe("search", () => {
it.effect("returns files and directories relative to cwd", () =>
Effect.gen(function* () {
@@ -245,22 +227,26 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
yield* writeTextFile(cwd, "src/components/Composer.tsx");
let rootReadCount = 0;
const rootReadGate = yield* Deferred.make<void>();
const workspaceEntries = yield* makeWorkspaceEntriesWithReadDirectory((inputPath, run) =>
inputPath === cwd
? Effect.gen(function* () {
rootReadCount += 1;
yield* Deferred.await(rootReadGate);
return yield* run();
})
: run(),
);
let releaseRootRead: (() => void) | undefined;
const rootReadGate = new Promise<void>((resolve) => {
releaseRootRead = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
if (args[0] === cwd) {
rootReadCount += 1;
await rootReadGate;
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const searches = yield* Effect.all(
[
workspaceEntries.search({ cwd, query: "", limit: 100 }),
workspaceEntries.search({ cwd, query: "comp", limit: 100 }),
workspaceEntries.search({ cwd, query: "src", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
],
{ concurrency: "unbounded" },
).pipe(Effect.forkScoped);
@@ -270,10 +256,10 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
}
yield* Effect.yieldNow;
}
yield* Deferred.succeed(rootReadGate, undefined);
releaseRootRead?.();
yield* Fiber.join(searches);
assert.equal(rootReadCount, 1);
expect(rootReadCount).toBe(1);
}),
);
@@ -288,37 +274,41 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
let activeReads = 0;
let peakReads = 0;
const readsGate = yield* Deferred.make<void>();
const workspaceEntries = yield* makeWorkspaceEntriesWithReadDirectory((inputPath, run) =>
inputPath !== cwd && inputPath.startsWith(cwd)
? Effect.gen(function* () {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
yield* Deferred.await(readsGate);
return yield* run().pipe(
Effect.ensuring(
Effect.sync(() => {
activeReads -= 1;
}),
),
);
})
: run(),
);
let releaseReads: (() => void) | undefined;
const readsGate = new Promise<void>((resolve) => {
releaseReads = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await readsGate;
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const search = yield* workspaceEntries
.search({ cwd, query: "", limit: 200 })
.pipe(Effect.forkScoped);
const search = yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }).pipe(
Effect.forkScoped,
);
for (let attempt = 0; attempt < 50; attempt += 1) {
if (activeReads > 0) {
break;
}
yield* Effect.yieldNow;
}
yield* Deferred.succeed(readsGate, undefined);
releaseReads?.();
yield* Fiber.join(search);
assert.isAtMost(peakReads, 32);
expect(peakReads).toBeLessThanOrEqual(32);
}),
);
});
@@ -1,14 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as OS from "node:os";
import fsPromises from "node:fs/promises";
import type { Dirent } from "node:fs";
import * as Cache from "effect/Cache";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
@@ -56,11 +56,6 @@ interface SearchableWorkspaceEntry extends ProjectEntry {
normalizedName: string;
}
interface DirectoryEntry {
readonly name: string;
readonly kind: ProjectEntry["kind"];
}
type RankedWorkspaceEntry = RankedSearchResult<SearchableWorkspaceEntry>;
function toPosixPath(input: string): string {
@@ -185,7 +180,6 @@ const resolveBrowseTarget = (
});
export const makeWorkspaceEntries = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry;
const workspacePaths = yield* WorkspacePaths;
@@ -275,64 +269,30 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
},
);
const readDirectoryEntry = Effect.fn("WorkspaceEntries.readDirectoryEntry")(function* (
absoluteDir: string,
name: string,
): Effect.fn.Return<Option.Option<DirectoryEntry>, never> {
const absolutePath = path.join(absoluteDir, name);
const linkTarget = yield* fileSystem.readLink(absolutePath).pipe(Effect.option);
if (Option.isSome(linkTarget)) {
return Option.none();
}
return yield* fileSystem.stat(absolutePath).pipe(
Effect.map((info) =>
info.type === "Directory"
? Option.some({ name, kind: "directory" as const })
: info.type === "File"
? Option.some({ name, kind: "file" as const })
: Option.none<DirectoryEntry>(),
),
Effect.catch(() => Effect.succeed(Option.none<DirectoryEntry>())),
);
});
const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* (
cwd: string,
relativeDir: string,
): Effect.fn.Return<
{
readonly relativeDir: string;
readonly entries: Option.Option<ReadonlyArray<DirectoryEntry>>;
},
{ readonly relativeDir: string; readonly dirents: Dirent[] | null },
WorkspaceEntriesError
> {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
return yield* fileSystem.readDirectory(absoluteDir).pipe(
Effect.flatMap((names) =>
Effect.forEach(
names.toSorted((left, right) => left.localeCompare(right)),
(name) => readDirectoryEntry(absoluteDir, name),
{ concurrency: "unbounded" },
),
),
Effect.map((entries) => ({
relativeDir,
entries: Option.some(entries.filter(Option.isSome).map((entry) => entry.value)),
})),
Effect.mapError(
(cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause.message,
cause,
}),
),
return yield* Effect.tryPromise({
try: async () => {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true });
return { relativeDir, dirents };
},
catch: (cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause instanceof Error ? cause.message : String(cause),
cause,
}),
}).pipe(
Effect.catchIf(
() => relativeDir.length > 0,
() =>
Effect.succeed({ relativeDir, entries: Option.none<ReadonlyArray<DirectoryEntry>>() }),
() => Effect.succeed({ relativeDir, dirents: null }),
),
);
});
@@ -357,26 +317,29 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
);
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
const { relativeDir, entries } = directoryEntry;
if (Option.isNone(entries))
return [] as Array<{ entry: DirectoryEntry; relativePath: string }>;
const { relativeDir, dirents } = directoryEntry;
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
const candidates: Array<{ entry: DirectoryEntry; relativePath: string }> = [];
for (const entry of entries.value) {
if (!entry.name || entry.name === "." || entry.name === "..") {
dirents.sort((left, right) => left.name.localeCompare(right.name));
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
for (const dirent of dirents) {
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
continue;
}
if (entry.kind === "directory" && IGNORED_DIRECTORY_NAMES.has(entry.name)) {
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
continue;
}
if (!dirent.isDirectory() && !dirent.isFile()) {
continue;
}
const relativePath = toPosixPath(
relativeDir ? path.join(relativeDir, entry.name) : entry.name,
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
);
if (isPathInIgnoredDirectory(relativePath)) {
continue;
}
candidates.push({ entry, relativePath });
candidates.push({ dirent, relativePath });
}
return candidates;
});
@@ -396,12 +359,12 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const entry = toSearchableWorkspaceEntry({
path: candidate.relativePath,
kind: candidate.entry.kind,
kind: candidate.dirent.isDirectory() ? "directory" : "file",
parentPath: parentPathOf(candidate.relativePath),
});
entries.push(entry);
if (candidate.entry.kind === "directory") {
if (candidate.dirent.isDirectory()) {
pendingDirectories.push(candidate.relativePath);
}
@@ -479,40 +442,33 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const entries = yield* fileSystem.readDirectory(parentPath).pipe(
Effect.flatMap((names) =>
Effect.forEach(names, (name) => readDirectoryEntry(parentPath, name), {
concurrency: "unbounded",
const dirents = yield* Effect.tryPromise({
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
}),
),
Effect.map((entries) => entries.filter(Option.isSome).map((entry) => entry.value)),
Effect.mapError(
(cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause.message}`,
cause,
}),
),
);
});
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
return {
parentPath,
entries: entries
entries: dirents
.filter(
(entry) =>
entry.kind === "directory" &&
entry.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !entry.name.startsWith(".")),
(dirent) =>
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith(".")),
)
.map((entry) => ({
name: entry.name,
fullPath: path.join(parentPath, entry.name),
.map((dirent) => ({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
}))
.toSorted((left, right) => left.name.localeCompare(right.name)),
};
+12 -40
View File
@@ -68,7 +68,10 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import {
resolveComposerMenuActiveItemId,
resolveComposerMenuNudgedItemId,
} from "./composerMenuHighlight";
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
import {
getComposerProviderState,
@@ -1134,35 +1137,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts, composerTerminalContextsRef]);
// ------------------------------------------------------------------
// Composer menu highlight sync
// ------------------------------------------------------------------
useEffect(() => {
if (!composerMenuOpen) {
setComposerHighlightedItemId(null);
setComposerHighlightedSearchKey(null);
return;
}
const nextActiveItemId = resolveComposerMenuActiveItemId({
items: composerMenuItems,
highlightedItemId: composerHighlightedItemId,
currentSearchKey: composerMenuSearchKey,
highlightedSearchKey: composerHighlightedSearchKey,
});
setComposerHighlightedItemId((existing) =>
existing === nextActiveItemId ? existing : nextActiveItemId,
);
setComposerHighlightedSearchKey((existing) =>
existing === composerMenuSearchKey ? existing : composerMenuSearchKey,
);
}, [
composerHighlightedItemId,
composerHighlightedSearchKey,
composerMenuItems,
composerMenuOpen,
composerMenuSearchKey,
]);
const lastSyncedPendingInputRef = useRef<{
requestId: string | null;
questionId: string | null;
@@ -1576,18 +1550,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const nudgeComposerMenuHighlight = useCallback(
(key: "ArrowDown" | "ArrowUp") => {
if (composerMenuItems.length === 0) return;
const highlightedIndex = composerMenuItems.findIndex(
(item) => item.id === composerHighlightedItemId,
setComposerHighlightedItemId(
resolveComposerMenuNudgedItemId({
items: composerMenuItems,
activeItemId: activeComposerMenuItem?.id ?? null,
direction: key === "ArrowDown" ? "next" : "previous",
}),
);
const normalizedIndex =
highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0;
const offset = key === "ArrowDown" ? 1 : -1;
const nextIndex =
(normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length;
const nextItem = composerMenuItems[nextIndex];
setComposerHighlightedItemId(nextItem?.id ?? null);
setComposerHighlightedSearchKey(composerMenuSearchKey);
},
[composerHighlightedItemId, composerMenuItems],
[activeComposerMenuItem?.id, composerMenuItems, composerMenuSearchKey],
);
const blurMobileComposerAfterSend = useCallback(() => {
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import {
resolveComposerMenuActiveItemId,
resolveComposerMenuNudgedItemId,
} from "./composerMenuHighlight";
describe("resolveComposerMenuActiveItemId", () => {
const items = [{ id: "top" }, { id: "second" }, { id: "third" }] as const;
@@ -49,3 +52,61 @@ describe("resolveComposerMenuActiveItemId", () => {
).toBe("top");
});
});
describe("resolveComposerMenuNudgedItemId", () => {
const items = [{ id: "top" }, { id: "second" }, { id: "third" }] as const;
it("moves from the active item", () => {
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "second",
direction: "next",
}),
).toBe("third");
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "second",
direction: "previous",
}),
).toBe("top");
});
it("wraps around at either edge", () => {
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "third",
direction: "next",
}),
).toBe("top");
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "top",
direction: "previous",
}),
).toBe("third");
});
it("starts from the first visible item when active state is stale", () => {
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "missing",
direction: "next",
}),
).toBe("top");
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "missing",
direction: "previous",
}),
).toBe("third");
});
});
@@ -18,3 +18,20 @@ export function resolveComposerMenuActiveItemId(input: {
return input.items[0]?.id ?? null;
}
export function resolveComposerMenuNudgedItemId(input: {
items: ReadonlyArray<{ id: string }>;
activeItemId: string | null;
direction: "next" | "previous";
}): string | null {
if (input.items.length === 0) {
return null;
}
const activeIndex = input.items.findIndex((item) => item.id === input.activeItemId);
const normalizedIndex = activeIndex >= 0 ? activeIndex : input.direction === "next" ? -1 : 0;
const offset = input.direction === "next" ? 1 : -1;
const nextIndex = (normalizedIndex + offset + input.items.length) % input.items.length;
return input.items[nextIndex]?.id ?? null;
}