Compare commits

...
Author SHA1 Message Date
Cursor Agent 82715e839c fix: integrate prompt-building helpers in onSend and resolve dual highlight conflict
- Add extractTaggedPaths() to parse @path tokens from prompt text
- Use buildPromptInput() for structured model input with 'Referenced paths:' block
- Use buildUserVisiblePrompt() for readable user-facing message display
- Pass autoHighlight={false} to Command in composer palette to prevent
  conflict between autocomplete's internal highlight and composerMenuIndex state
2026-02-17 19:19:52 +00:00
Julius Marminge 3109d1a7f0 Respect .gitignore in workspace search and inline @path mentions
- Build workspace index from `git ls-files` when in a Git repo, excluding ignored paths
- Skip configured ignored top-level directories during filesystem fallback indexing
- Update chat composer to insert `@path` directly in prompt and remove separate tagged-path chips
- Keep command menu navigation visible by scrolling the active/next item into view
2026-02-17 11:00:06 -08:00
Julius Marminge f634a12b89 Add composer path tagging with workspace entry search
- add `projects.searchEntries` API, contracts, and server-side indexed workspace search
- add composer trigger logic for `@` path suggestions and `/model` command completion
- include tagged paths in sent prompt/user-visible text and cover behavior with server/web tests
2026-02-17 09:45:48 -08:00
12 changed files with 979 additions and 7 deletions

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { afterEach, describe, expect, it } from "vitest";
import { searchWorkspaceEntries } from "./workspaceEntries";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
function writeFile(cwd: string, relativePath: string, contents = ""): void {
const absolutePath = path.join(cwd, relativePath);
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
fs.writeFileSync(absolutePath, contents, "utf8");
}
function runGit(cwd: string, args: string[]): void {
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
if (result.status !== 0) {
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
}
}
describe("searchWorkspaceEntries", () => {
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("returns files and directories relative to cwd", async () => {
const cwd = makeTempDir("t3code-workspace-entries-");
writeFile(cwd, "src/components/Composer.tsx");
writeFile(cwd, "src/index.ts");
writeFile(cwd, "README.md");
writeFile(cwd, ".git/HEAD");
writeFile(cwd, "node_modules/pkg/index.js");
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
const paths = result.entries.map((entry) => entry.path);
expect(paths).toContain("src");
expect(paths).toContain("src/components");
expect(paths).toContain("src/components/Composer.tsx");
expect(paths).toContain("README.md");
expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false);
expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false);
expect(result.truncated).toBe(false);
});
it("filters and ranks entries by query", async () => {
const cwd = makeTempDir("t3code-workspace-query-");
writeFile(cwd, "src/components/Composer.tsx");
writeFile(cwd, "src/components/composePrompt.ts");
writeFile(cwd, "docs/composition.md");
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
expect(result.entries.length).toBeGreaterThan(0);
expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true);
expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe(true);
});
it("excludes gitignored paths for git repositories", async () => {
const cwd = makeTempDir("t3code-workspace-gitignore-");
runGit(cwd, ["init"]);
writeFile(cwd, ".gitignore", ".convex/\nignored.txt\n");
writeFile(cwd, "src/keep.ts", "export {};");
writeFile(cwd, "ignored.txt", "ignore me");
writeFile(cwd, ".convex/local-storage/data.json", "{}");
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
const paths = result.entries.map((entry) => entry.path);
expect(paths).toContain("src");
expect(paths).toContain("src/keep.ts");
expect(paths).not.toContain("ignored.txt");
expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
});
});
+286
View File
@@ -0,0 +1,286 @@
import fs from "node:fs/promises";
import path from "node:path";
import { runProcess } from "./processRunner";
import {
projectSearchEntriesInputSchema,
type ProjectEntry,
type ProjectSearchEntriesInput,
type ProjectSearchEntriesResult,
} from "@t3tools/contracts";
const WORKSPACE_CACHE_TTL_MS = 15_000;
const WORKSPACE_CACHE_MAX_KEYS = 4;
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const IGNORED_DIRECTORY_NAMES = new Set([
".git",
"node_modules",
".next",
".turbo",
"dist",
"build",
"out",
".cache",
]);
interface WorkspaceIndex {
scannedAt: number;
entries: ProjectEntry[];
truncated: boolean;
}
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
function toPosixPath(input: string): string {
return input.split(path.sep).join("/");
}
function parentPathOf(input: string): string | undefined {
const separatorIndex = input.lastIndexOf("/");
if (separatorIndex === -1) {
return undefined;
}
return input.slice(0, separatorIndex);
}
function basenameOf(input: string): string {
const separatorIndex = input.lastIndexOf("/");
if (separatorIndex === -1) {
return input;
}
return input.slice(separatorIndex + 1);
}
function normalizeQuery(input: string): string {
return input.trim().replace(/^[@./]+/, "").toLowerCase();
}
function scoreEntry(entry: ProjectEntry, query: string): number {
if (!query) {
return entry.kind === "directory" ? 0 : 1;
}
const normalizedPath = entry.path.toLowerCase();
const normalizedName = basenameOf(normalizedPath);
if (normalizedName === query) return 0;
if (normalizedPath === query) return 1;
if (normalizedName.startsWith(query)) return 2;
if (normalizedPath.startsWith(query)) return 3;
if (normalizedPath.includes(`/${query}`)) return 4;
return 5;
}
function isPathInIgnoredDirectory(relativePath: string): boolean {
const firstSegment = relativePath.split("/")[0];
if (!firstSegment) return false;
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
}
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
// If output was truncated, the final token can be partial.
if (truncated && parts[parts.length - 1]?.length) {
parts.pop();
}
return parts.filter((value) => value.length > 0);
}
function directoryAncestorsOf(relativePath: string): string[] {
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
if (segments.length <= 1) return [];
const directories: string[] = [];
for (let index = 1; index < segments.length; index += 1) {
directories.push(segments.slice(0, index).join("/"));
}
return directories;
}
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxBufferBytes: 4_096,
}).catch(() => null);
if (!insideWorkTree || insideWorkTree.code !== 0 || insideWorkTree.stdout.trim() !== "true") {
return null;
}
const listedFiles = await runProcess(
"git",
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
{
cwd,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxBufferBytes: 16 * 1024 * 1024,
outputMode: "truncate",
},
).catch(() => null);
if (!listedFiles || listedFiles.code !== 0) {
return null;
}
const filePaths = splitNullSeparatedPaths(listedFiles.stdout, Boolean(listedFiles.stdoutTruncated))
.map((entry) => toPosixPath(entry))
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
const directorySet = new Set<string>();
for (const filePath of filePaths) {
for (const directoryPath of directoryAncestorsOf(filePath)) {
if (!isPathInIgnoredDirectory(directoryPath)) {
directorySet.add(directoryPath);
}
}
}
const directoryEntries: ProjectEntry[] = [...directorySet]
.sort((left, right) => left.localeCompare(right))
.map((directoryPath) => ({
path: directoryPath,
kind: "directory",
parentPath: parentPathOf(directoryPath),
}));
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
.sort((left, right) => left.localeCompare(right))
.map((filePath) => ({
path: filePath,
kind: "file",
parentPath: parentPathOf(filePath),
}));
const entries = [...directoryEntries, ...fileEntries];
return {
scannedAt: Date.now(),
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
truncated:
Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
};
}
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
if (gitIndexed) {
return gitIndexed;
}
let pendingDirectories: string[] = [""];
const entries: ProjectEntry[] = [];
let truncated = false;
while (pendingDirectories.length > 0 && !truncated) {
const currentDirectories = pendingDirectories;
pendingDirectories = [];
const directoryEntries = await Promise.all(
currentDirectories.map(async (relativeDir) => {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
try {
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
return { relativeDir, dirents };
} catch (error) {
if (!relativeDir) {
throw new Error(
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
{ cause: error },
);
}
return { relativeDir, dirents: null };
}
}),
);
for (const directoryEntry of directoryEntries) {
const { relativeDir, dirents } = directoryEntry;
if (!dirents) {
continue;
}
dirents.sort((left, right) => left.name.localeCompare(right.name));
for (const dirent of dirents) {
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
continue;
}
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
continue;
}
if (!dirent.isDirectory() && !dirent.isFile()) {
continue;
}
const relativePath = toPosixPath(
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
);
if (isPathInIgnoredDirectory(relativePath)) {
continue;
}
const entry: ProjectEntry = {
path: relativePath,
kind: dirent.isDirectory() ? "directory" : "file",
parentPath: parentPathOf(relativePath),
};
entries.push(entry);
if (dirent.isDirectory()) {
pendingDirectories.push(relativePath);
}
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
truncated = true;
break;
}
}
if (truncated) {
break;
}
}
}
return {
scannedAt: Date.now(),
entries,
truncated,
};
}
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
const cached = workspaceIndexCache.get(cwd);
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
return cached;
}
const next = await buildWorkspaceIndex(cwd);
workspaceIndexCache.set(cwd, next);
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
const oldestKey = workspaceIndexCache.keys().next().value;
if (!oldestKey) break;
workspaceIndexCache.delete(oldestKey);
}
return next;
}
export async function searchWorkspaceEntries(
input: ProjectSearchEntriesInput,
): Promise<ProjectSearchEntriesResult> {
const parsed = projectSearchEntriesInputSchema.parse(input);
const index = await getWorkspaceIndex(parsed.cwd);
const normalizedQuery = normalizeQuery(parsed.query);
const candidates = normalizedQuery
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
: index.entries;
const ranked = candidates.toSorted((left, right) => {
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
if (scoreDelta !== 0) return scoreDelta;
return left.path.localeCompare(right.path);
});
return {
entries: ranked.slice(0, parsed.limit),
truncated: index.truncated || ranked.length > parsed.limit,
};
}
+32
View File
@@ -766,6 +766,38 @@ describe("WebSocket Server", () => {
expect(afterRemove.result).toEqual([]);
});
it("supports projects.searchEntries", async () => {
const workspace = makeTempDir("t3code-ws-workspace-entries-");
fs.mkdirSync(path.join(workspace, "src", "components"), { recursive: true });
fs.writeFileSync(path.join(workspace, "src", "components", "Composer.tsx"), "export {};", "utf8");
fs.writeFileSync(path.join(workspace, "README.md"), "# test", "utf8");
fs.mkdirSync(path.join(workspace, ".git"), { recursive: true });
fs.writeFileSync(path.join(workspace, ".git", "HEAD"), "ref: refs/heads/main\n", "utf8");
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
cwd: workspace,
query: "comp",
limit: 10,
});
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
entries: expect.arrayContaining([
expect.objectContaining({ path: "src/components", kind: "directory" }),
expect.objectContaining({ path: "src/components/Composer.tsx", kind: "file" }),
]),
truncated: false,
});
});
it("supports git methods over websocket", async () => {
const repoCwd = makeTempDir("t3code-ws-git-project-");
+4
View File
@@ -32,6 +32,7 @@ import {
} from "./git";
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -319,6 +320,9 @@ export function createServer(options: ServerOptions) {
projectRegistry.remove(request.params as never);
return undefined;
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
cwd: string;
+295 -7
View File
@@ -1,6 +1,7 @@
import {
EDITORS,
type EditorId,
type ProjectEntry,
ModelSlug,
type NativeApi,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
@@ -31,6 +32,13 @@ import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
import { isElectron } from "../env";
import { buildBootstrapInput } from "../historyBootstrap";
import {
buildPromptInput,
buildUserVisiblePrompt,
detectComposerTrigger,
extractTaggedPaths,
replaceTextRange,
} from "../composer-logic";
import {
DEFAULT_MODEL,
DEFAULT_REASONING,
@@ -69,6 +77,8 @@ import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import {
ChevronDownIcon,
CircleAlertIcon,
FileIcon,
FolderIcon,
FolderClosedIcon,
InfoIcon,
LockIcon,
@@ -83,6 +93,7 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
import { CursorIcon, Icon } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Command, CommandItem, CommandList } from "./ui/command";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -103,6 +114,12 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
return "text-muted-foreground/40";
}
function basenameOfPath(pathValue: string): string {
const slashIndex = pathValue.lastIndexOf("/");
if (slashIndex === -1) return pathValue;
return pathValue.slice(slashIndex + 1);
}
type SessionContinuityState = "resumed" | "new" | "fallback_new";
interface EnsuredSessionInfo {
@@ -121,6 +138,29 @@ interface ExpandedImagePreview {
name: string;
}
type ComposerCommandItem =
| {
id: string;
type: "path";
path: string;
pathKind: ProjectEntry["kind"];
label: string;
description: string;
}
| {
id: string;
type: "slash-command";
label: string;
description: string;
}
| {
id: string;
type: "model";
model: ModelSlug;
label: string;
description: string;
};
function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -158,10 +198,14 @@ export default function ChatView() {
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerCursor, setComposerCursor] = useState(0);
const [composerMenuIndex, setComposerMenuIndex] = useState(0);
const messagesScrollRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerMenuRef = useRef<HTMLDivElement>(null);
const previousComposerMenuIndexRef = useRef(0);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -268,11 +312,77 @@ export default function ChatView() {
sandboxMode: "workspace-write",
} as const);
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
const composerTrigger = useMemo(
() => detectComposerTrigger(prompt, composerCursor),
[prompt, composerCursor],
);
const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
const keybindingsQuery = useQuery({
...serverConfigQueryOptions(api),
select: (config) => config.keybindings,
});
const workspaceEntriesQuery = useQuery({
queryKey: [
"composer-workspace-entries",
gitCwd,
composerTrigger?.kind === "path" ? composerTrigger.query : "",
],
enabled: Boolean(api && gitCwd && composerTrigger?.kind === "path"),
staleTime: 15_000,
queryFn: async () => {
if (!api || !gitCwd || composerTrigger?.kind !== "path") {
return { entries: [], truncated: false };
}
return api.projects.searchEntries({
cwd: gitCwd,
query: composerTrigger.query,
limit: 80,
});
},
});
const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {
if (!composerTrigger) return [];
if (composerTrigger.kind === "path") {
return (workspaceEntriesQuery.data?.entries ?? []).map((entry) => ({
id: `path:${entry.kind}:${entry.path}`,
type: "path",
path: entry.path,
pathKind: entry.kind,
label: basenameOfPath(entry.path),
description: entry.parentPath ?? (entry.kind === "directory" ? "Folder" : "File"),
}));
}
if (composerTrigger.kind === "slash-command") {
if (!"model".includes(composerTrigger.query.toLowerCase())) {
return [];
}
return [
{
id: "slash:model",
type: "slash-command",
label: "/model",
description: "Switch response model for this thread",
},
];
}
return MODEL_OPTIONS.filter(({ slug, name }) => {
const query = composerTrigger.query.trim().toLowerCase();
if (!query) return true;
return slug.toLowerCase().includes(query) || name.toLowerCase().includes(query);
}).map(({ slug, name }) => ({
id: `model:${slug}`,
type: "model",
model: slug,
label: name,
description: slug,
}));
}, [composerTrigger, workspaceEntriesQuery.data?.entries]);
const composerMenuOpen = Boolean(composerTrigger);
const activeComposerMenuItem =
composerMenuItems[Math.min(composerMenuIndex, Math.max(0, composerMenuItems.length - 1))] ??
null;
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
@@ -436,6 +546,32 @@ export default function ChatView() {
setExpandedWorkGroups({});
}, [activeThread?.id]);
useEffect(() => {
setComposerMenuIndex(0);
}, [composerTrigger?.kind, composerTrigger?.query, composerMenuItems.length]);
useEffect(() => {
if (!composerMenuOpen || composerMenuItems.length === 0) {
return;
}
const clampedIndex = Math.min(composerMenuIndex, composerMenuItems.length - 1);
const previousIndex = previousComposerMenuIndexRef.current;
const direction = clampedIndex - previousIndex;
previousComposerMenuIndexRef.current = clampedIndex;
const aheadIndex =
direction > 0
? Math.min(clampedIndex + 1, composerMenuItems.length - 1)
: direction < 0
? Math.max(clampedIndex - 1, 0)
: clampedIndex;
const node = composerMenuRef.current?.querySelector<HTMLElement>(
`[data-composer-menu-index="${aheadIndex}"]`,
);
node?.scrollIntoView({ block: "nearest" });
}, [composerMenuIndex, composerMenuItems, composerMenuOpen]);
useEffect(() => {
if (!activeThread?.id || activeThread.terminalOpen) return;
const frame = window.requestAnimationFrame(() => {
@@ -455,6 +591,8 @@ export default function ChatView() {
revokePreviewUrls(existing);
return [];
});
setComposerCursor(0);
setComposerMenuIndex(0);
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
@@ -773,6 +911,9 @@ export default function ChatView() {
const trimmed = prompt.trim();
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
const { cleanText, paths: taggedPaths } = extractTaggedPaths(trimmed);
const userVisibleText = buildUserVisiblePrompt(cleanText, taggedPaths);
const modelText = buildPromptInput(cleanText, taggedPaths);
const composerImagesSnapshot = [...composerImages];
// On first message: lock in branch + create worktree if needed.
@@ -835,12 +976,14 @@ export default function ChatView() {
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
text: userVisibleText,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
const previousMessages = activeThread.messages;
setPrompt("");
setComposerImages([]);
setComposerCursor(0);
setComposerMenuIndex(0);
const sessionInfo = await ensureSession(sessionCwd);
if (!sessionInfo) return;
@@ -861,14 +1004,14 @@ export default function ChatView() {
const shouldBootstrap =
previousMessages.length > 0 &&
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
const latestPromptForBootstrap = trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT;
const latestPromptForBootstrap = modelText || IMAGE_ONLY_BOOTSTRAP_PROMPT;
const input = shouldBootstrap
? buildBootstrapInput(
previousMessages,
latestPromptForBootstrap,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
).text
: trimmed || undefined;
: modelText || undefined;
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
...(input ? { input } : {}),
@@ -947,7 +1090,71 @@ export default function ChatView() {
[scheduleComposerFocus],
);
const applyPromptReplacement = useCallback(
(rangeStart: number, rangeEnd: number, replacement: string) => {
setPrompt((existing) => {
const next = replaceTextRange(existing, rangeStart, rangeEnd, replacement);
window.requestAnimationFrame(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.focus();
textarea.setSelectionRange(next.cursor, next.cursor);
setComposerCursor(next.cursor);
});
return next.text;
});
},
[],
);
const onSelectComposerItem = useCallback(
(item: ComposerCommandItem) => {
if (!composerTrigger) return;
if (item.type === "path") {
applyPromptReplacement(
composerTrigger.rangeStart,
composerTrigger.rangeEnd,
`@${item.path} `,
);
return;
}
if (item.type === "slash-command") {
applyPromptReplacement(composerTrigger.rangeStart, composerTrigger.rangeEnd, "/model ");
return;
}
onModelSelect(item.model);
applyPromptReplacement(composerTrigger.rangeStart, composerTrigger.rangeEnd, "");
},
[applyPromptReplacement, composerTrigger, onModelSelect],
);
const onPromptChange = useCallback((nextPrompt: string, nextCursor: number) => {
setPrompt(nextPrompt);
setComposerCursor(nextCursor);
}, []);
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (composerMenuOpen && composerMenuItems.length > 0) {
if (e.key === "ArrowDown") {
e.preventDefault();
setComposerMenuIndex((existing) => Math.min(existing + 1, composerMenuItems.length - 1));
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setComposerMenuIndex((existing) => Math.max(existing - 1, 0));
return;
}
if (e.key === "Tab" || e.key === "Enter") {
const selectedItem = activeComposerMenuItem ?? composerMenuItems[0];
if (selectedItem) {
e.preventDefault();
onSelectComposerItem(selectedItem);
return;
}
}
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void onSend(e as unknown as FormEvent);
@@ -1043,7 +1250,66 @@ export default function ChatView() {
onDrop={onComposerDrop}
>
{/* Textarea area */}
<div className="px-4 pt-4 pb-2">
<div className="relative px-4 pt-4 pb-2">
{composerMenuOpen && (
<div className="absolute inset-x-0 bottom-full z-20 mb-2 px-1">
<Command autoHighlight={false}>
<div
ref={composerMenuRef}
className="overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<CommandList className="max-h-64">
{composerMenuItems.map((item, index) => (
<CommandItem
key={item.id}
value={item.id}
data-composer-menu-index={index}
className={cn(
"gap-2",
index === composerMenuIndex && "bg-accent text-accent-foreground",
)}
onMouseEnter={() => setComposerMenuIndex(index)}
onMouseDown={(event) => {
event.preventDefault();
onSelectComposerItem(item);
}}
>
{item.type === "path" ? (
item.pathKind === "directory" ? (
<FolderIcon className="size-4 text-muted-foreground/80" />
) : (
<FileIcon className="size-4 text-muted-foreground/80" />
)
) : null}
{item.type === "slash-command" ? (
<CursorIcon className="size-4 text-muted-foreground/80" />
) : null}
{item.type === "model" ? (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
model
</Badge>
) : null}
<span className="truncate">{item.label}</span>
<span className="truncate text-muted-foreground/70 text-xs">
{item.description}
</span>
</CommandItem>
))}
</CommandList>
{composerMenuItems.length === 0 && (
<p className="px-3 py-2 text-muted-foreground/70 text-xs">
{workspaceEntriesQuery.isLoading
? "Searching workspace files..."
: composerTrigger?.kind === "path"
? "No matching files or folders."
: "No matching command."}
</p>
)}
</div>
</Command>
</div>
)}
{composerImages.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages.map((image) => (
@@ -1083,13 +1349,33 @@ export default function ChatView() {
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
rows={2}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onChange={(event) =>
onPromptChange(
event.target.value,
event.target.selectionStart ?? event.target.value.length,
)
}
onKeyDown={onKeyDown}
onKeyUp={(event) =>
setComposerCursor(
event.currentTarget.selectionStart ?? event.currentTarget.value.length,
)
}
onClick={(event) =>
setComposerCursor(
event.currentTarget.selectionStart ?? event.currentTarget.value.length,
)
}
onSelect={(event) =>
setComposerCursor(
event.currentTarget.selectionStart ?? event.currentTarget.value.length,
)
}
onPaste={onComposerPaste}
placeholder={
phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, or attach images..."
: "Ask anything, @tag files/folders, or use /model"
}
disabled={isSending || isConnecting}
/>
@@ -1157,7 +1443,9 @@ export default function ChatView() {
type="submit"
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
disabled={
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
isSending ||
isConnecting ||
(!prompt.trim() && composerImages.length === 0)
}
aria-label={
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import {
buildPromptInput,
buildUserVisiblePrompt,
detectComposerTrigger,
replaceTextRange,
} from "./composer-logic";
describe("detectComposerTrigger", () => {
it("detects @path trigger at cursor", () => {
const text = "Please check @src/com";
const trigger = detectComposerTrigger(text, text.length);
expect(trigger).toEqual({
kind: "path",
query: "src/com",
rangeStart: "Please check ".length,
rangeEnd: text.length,
});
});
it("detects slash command token while typing command name", () => {
const text = "/mo";
const trigger = detectComposerTrigger(text, text.length);
expect(trigger).toEqual({
kind: "slash-command",
query: "mo",
rangeStart: 0,
rangeEnd: text.length,
});
});
it("detects slash model query after /model", () => {
const text = "/model spark";
const trigger = detectComposerTrigger(text, text.length);
expect(trigger).toEqual({
kind: "slash-model",
query: "spark",
rangeStart: 0,
rangeEnd: text.length,
});
});
});
describe("replaceTextRange", () => {
it("replaces a text range and returns new cursor", () => {
const replaced = replaceTextRange("hello @src", 6, 10, "");
expect(replaced).toEqual({
text: "hello ",
cursor: 6,
});
});
});
describe("tagged path prompt helpers", () => {
it("builds model input with tagged paths", () => {
const result = buildPromptInput("Fix this", ["src/app.tsx", "src/app.tsx", "README.md"]);
expect(result).toContain("Fix this");
expect(result).toContain("Referenced paths:");
expect(result).toContain("- src/app.tsx");
expect(result).toContain("- README.md");
expect(result).not.toContain("- src/app.tsx\n- src/app.tsx");
});
it("builds user-visible prompt from tags only", () => {
const result = buildUserVisiblePrompt(" ", ["src/app.tsx", "README.md"]);
expect(result).toBe("@src/app.tsx @README.md");
});
});
+137
View File
@@ -0,0 +1,137 @@
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
export interface ComposerTrigger {
kind: ComposerTriggerKind;
query: string;
rangeStart: number;
rangeEnd: number;
}
function clampCursor(text: string, cursor: number): number {
if (!Number.isFinite(cursor)) return text.length;
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
}
function isWhitespace(char: string): boolean {
return char === " " || char === "\n" || char === "\t" || char === "\r";
}
function tokenStartForCursor(text: string, cursor: number): number {
let index = cursor - 1;
while (index >= 0 && !isWhitespace(text[index] ?? "")) {
index -= 1;
}
return index + 1;
}
function dedupePaths(paths: string[]): string[] {
const unique = new Set<string>();
for (const rawPath of paths) {
const normalized = rawPath.trim();
if (!normalized) continue;
unique.add(normalized);
}
return [...unique];
}
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
const cursor = clampCursor(text, cursorInput);
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
const linePrefix = text.slice(lineStart, cursor);
if (linePrefix.startsWith("/")) {
const commandMatch = /^\/(\S*)$/.exec(linePrefix);
if (commandMatch) {
const commandQuery = commandMatch[1] ?? "";
if (commandQuery.toLowerCase() === "model") {
return {
kind: "slash-model",
query: "",
rangeStart: lineStart,
rangeEnd: cursor,
};
}
if ("model".startsWith(commandQuery.toLowerCase())) {
return {
kind: "slash-command",
query: commandQuery,
rangeStart: lineStart,
rangeEnd: cursor,
};
}
return null;
}
const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix);
if (modelMatch) {
return {
kind: "slash-model",
query: (modelMatch[1] ?? "").trim(),
rangeStart: lineStart,
rangeEnd: cursor,
};
}
}
const tokenStart = tokenStartForCursor(text, cursor);
const token = text.slice(tokenStart, cursor);
if (!token.startsWith("@")) {
return null;
}
return {
kind: "path",
query: token.slice(1),
rangeStart: tokenStart,
rangeEnd: cursor,
};
}
export function replaceTextRange(
text: string,
rangeStart: number,
rangeEnd: number,
replacement: string,
): { text: string; cursor: number } {
const safeStart = Math.max(0, Math.min(text.length, rangeStart));
const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
return { text: nextText, cursor: safeStart + replacement.length };
}
export function buildPromptInput(text: string, taggedPaths: string[]): string {
const trimmedPrompt = text.trim();
const normalizedPaths = dedupePaths(taggedPaths);
if (normalizedPaths.length === 0) {
return trimmedPrompt;
}
const tagBlock = `Referenced paths:\n${normalizedPaths.map((entry) => `- ${entry}`).join("\n")}`;
if (!trimmedPrompt) {
return tagBlock;
}
return `${trimmedPrompt}\n\n${tagBlock}`;
}
export function extractTaggedPaths(text: string): { cleanText: string; paths: string[] } {
const paths: string[] = [];
const cleanText = text.replace(/@(\S+)/g, (_match, path: string) => {
paths.push(path);
return "";
});
return { cleanText: cleanText.replace(/\s{2,}/g, " ").trim(), paths };
}
export function buildUserVisiblePrompt(text: string, taggedPaths: string[]): string {
const trimmedPrompt = text.trim();
const normalizedPaths = dedupePaths(taggedPaths);
if (normalizedPaths.length === 0) {
return trimmedPrompt;
}
const tagsSummary = normalizedPaths.map((entry) => `@${entry}`).join(" ");
if (!trimmedPrompt) {
return tagsSummary;
}
return `${trimmedPrompt}\n\n${tagsSummary}`;
}
+1
View File
@@ -98,6 +98,7 @@ export function createWsNativeApi(): NativeApi {
list: () => transport.request(WS_METHODS.projectsList),
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
},
shell: {
openInEditor: (cwd, editor) =>
+3
View File
@@ -29,6 +29,8 @@ import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
ProjectRemoveInput,
} from "./project";
import type { ServerConfig } from "./server";
@@ -90,6 +92,7 @@ export interface NativeApi {
list: () => Promise<ProjectListResult>;
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
remove: (input: ProjectRemoveInput) => Promise<void>;
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
};
shell: {
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
+36
View File
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import {
projectAddInputSchema,
projectAddResultSchema,
projectSearchEntriesInputSchema,
projectSearchEntriesResultSchema,
projectListResultSchema,
projectRemoveInputSchema,
} from "./project";
@@ -46,4 +48,38 @@ describe("project contracts", () => {
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
expect(parsed.id).toBe("project-1");
});
it("parses workspace entry search input with defaults", () => {
const parsed = projectSearchEntriesInputSchema.parse({
cwd: " /tmp/project ",
query: " src ",
});
expect(parsed).toEqual({
cwd: "/tmp/project",
query: "src",
limit: 80,
});
});
it("parses workspace entry search result", () => {
const parsed = projectSearchEntriesResultSchema.parse({
entries: [
{
path: "src/components",
kind: "directory",
parentPath: "src",
},
{
path: "src/components/Button.tsx",
kind: "file",
parentPath: "src/components",
},
],
truncated: false,
});
expect(parsed.entries).toHaveLength(2);
expect(parsed.entries[0]?.kind).toBe("directory");
});
});
+25
View File
@@ -23,8 +23,33 @@ export const projectRemoveInputSchema = z.object({
id: z.string().min(1),
});
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
export const projectSearchEntriesInputSchema = z.object({
cwd: z.string().trim().min(1),
query: z.string().trim().max(256).default(""),
limit: z.number().int().min(1).max(PROJECT_SEARCH_ENTRIES_MAX_LIMIT).default(80),
});
export const projectEntryKindSchema = z.enum(["file", "directory"]);
export const projectEntrySchema = z.object({
path: z.string().min(1),
kind: projectEntryKindSchema,
parentPath: z.string().optional(),
});
export const projectSearchEntriesResultSchema = z.object({
entries: z.array(projectEntrySchema),
truncated: z.boolean(),
});
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
+1
View File
@@ -15,6 +15,7 @@ export const WS_METHODS = {
projectsList: "projects.list",
projectsAdd: "projects.add",
projectsRemove: "projects.remove",
projectsSearchEntries: "projects.searchEntries",
// Shell methods
shellOpenInEditor: "shell.openInEditor",