Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): @path file references in chat input
tikikun0cdf1f4326f5
diff --git a/web-app/src/components/FilePickerPopover.tsx b/web-app/src/components/FilePickerPopover.tsxnew file mode 100644index 000000000..a8cd01afe--- /dev/null+++ b/web-app/src/components/FilePickerPopover.tsx@@ -0,0 +1,248 @@+/**+ * Fuzzy file/folder picker popover triggered by typing `@` in the chat input.+ *+ * Scoped to the session's working directory. Supports keyboard navigation+ * (arrows, tab to complete, enter to select, esc to dismiss).+ */+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { cn } from '@/lib/utils'+import { Folder, File, FileCode, FileText, ImageIcon, FileJson, FileType } from 'lucide-react'+import type { FilePickerEntry } from '@/types/path-reference'++// ─── File-type icon helper ───────────────────────────────────────────────────+const extIconMap: Record<string, typeof FileCode> = {+ ts: FileCode,+ tsx: FileCode,+ js: FileCode,+ jsx: FileCode,+ rs: FileCode,+ py: FileCode,+ go: FileCode,+ java: FileCode,+ cpp: FileCode,+ c: FileCode,+ h: FileCode,+ json: FileJson,+ yaml: FileJson,+ yml: FileJson,+ toml: FileJson,+ md: FileText,+ txt: FileText,+ pdf: FileText,+ png: ImageIcon,+ jpg: ImageIcon,+ jpeg: ImageIcon,+ gif: ImageIcon,+ svg: ImageIcon,+ css: FileType,+ scss: FileType,+ html: FileType,+ xml: FileType,+}++function FileIcon({ entry }: { entry: FilePickerEntry }) {+ if (entry.kind === 'directory') return <Folder className="size-4 shrink-0 text-amber-500" />+ const ext = entry.extension?.toLowerCase() ?? ''+ const Icon = extIconMap[ext]+ if (Icon) return <Icon className="size-4 shrink-0 text-blue-500" />+ return <File className="size-4 shrink-0 text-muted-foreground" />+}++// ─── Props ───────────────────────────────────────────────────────────────────+type FilePickerPopoverProps = {+ /** List of entries to show */+ entries: FilePickerEntry[]+ /** Search query (the text after `@`) */+ query: string+ /** Whether the picker is visible */+ open: boolean+ /** Position offset relative to the textarea */+ position: { top: number; left: number } | null+ /** Called when a path is selected (tab or enter) */+ onSelect: (entry: FilePickerEntry) => void+ /** Called to dismiss */+ onClose: () => void+ /** Ref for the textarea to position relative to */+ textareaRef: React.RefObject<HTMLTextAreaElement | null>+}++export function FilePickerPopover({+ entries,+ query,+ open,+ position,+ onSelect,+ onClose,+ textareaRef,+}: FilePickerPopoverProps) {+ const [activeIndex, setActiveIndex] = useState(0)+ const listRef = useRef<HTMLDivElement>(null)+ const itemRefs = useRef<Map<number, HTMLDivElement>>(new Map())++ // Reset selection when entries change+ useEffect(() => {+ setActiveIndex(0)+ }, [entries.length])++ // Position the popover relative to textarea cursor+ const popoverStyle = useMemo(() => {+ if (!position || !textareaRef.current) {+ return { top: 0, left: 0, opacity: 0 as const }+ }+ return {+ top: position.top,+ left: position.left,+ }+ }, [position, textareaRef])++ // Scroll active item into view+ useEffect(() => {+ const el = itemRefs.current.get(activeIndex)+ el?.scrollIntoView({ block: 'nearest' })+ }, [activeIndex])++ // Keyboard handling is done in ChatInput, but we expose arrow navigation here+ // We'll handle it through imperative methods+ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (!open) return++ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault()+ e.stopPropagation()+ setActiveIndex((prev) => Math.min(prev + 1, entries.length - 1))+ break+ case 'ArrowUp':+ e.preventDefault()+ e.stopPropagation()+ setActiveIndex((prev) => Math.max(prev - 1, 0))+ break+ case 'Enter':+ case 'Tab':+ if (entries.length > 0 && entries[activeIndex]) {+ e.preventDefault()+ e.stopPropagation()+ onSelect(entries[activeIndex])+ }+ break+ case 'Escape':+ e.preventDefault()+ e.stopPropagation()+ onClose()+ break+ }+ },+ [open, entries, activeIndex, onSelect, onClose]+ )++ if (!open || entries.length === 0) return null++ return (+ <div+ className="absolute z-50 w-[400px] max-h-[300px] overflow-y-auto rounded-xl border border-border bg-popover shadow-popover p-1"+ style={popoverStyle}+ onKeyDown={handleKeyDown}+ role="listbox"+ tabIndex={-1}+ >+ <div className="px-2 py-1.5 text-xs text-muted-foreground border-b border-border/50 mb-1">+ {entries.length === 1+ ? '1 result'+ : `${entries.length} results`}+ {query && (+ <span>+ {' '}for <span className="font-mono font-medium text-foreground/70">@{query}</span>+ </span>+ )}+ <span className="ml-auto text-[10px] opacity-60">+ ↑↓ navigate · Tab/Enter select · Esc dismiss+ </span>+ </div>+ <div ref={listRef}>+ {entries.map((entry, idx) => (+ <div+ key={entry.path}+ ref={(el) => {+ if (el) itemRefs.current.set(idx, el)+ else itemRefs.current.delete(idx)+ }}+ className={cn(+ 'flex items-center gap-2 px-2 py-1.5 rounded-lg cursor-pointer text-sm transition-colors',+ idx === activeIndex+ ? 'bg-primary/10 text-primary-foreground'+ : 'hover:bg-accent'+ )}+ onClick={() => onSelect(entry)}+ onMouseEnter={() => setActiveIndex(idx)}+ role="option"+ aria-selected={idx === activeIndex}+ >+ <FileIcon entry={entry} />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5">+ <span className="font-medium truncate">{entry.name}</span>+ <span className="text-[10px] text-muted-foreground/50 uppercase shrink-0">+ {entry.kind === 'directory' ? 'folder' : entry.extension}+ </span>+ </div>+ <div className="text-[11px] text-muted-foreground/60 truncate">+ {entry.path}+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )+}++// ─── Expose imperative controls for the parent to forward keyboard events ────+export type FilePickerHandle = {+ handleKeyDown: (e: React.KeyboardEvent) => void+ activeIndex: number+ entries: FilePickerEntry[]+}++export function useFilePickerKeyboard(open: boolean) {+ const [activeIndex, setActiveIndex] = useState(0)+ const [entries, setEntries] = useState<FilePickerEntry[]>([])++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (!open || entries.length === 0) return++ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault()+ setActiveIndex((prev) => Math.min(prev + 1, entries.length - 1))+ break+ case 'ArrowUp':+ e.preventDefault()+ setActiveIndex((prev) => Math.max(prev - 1, 0))+ break+ case 'Enter':+ case 'Tab': {+ if (entries[activeIndex]) {+ e.preventDefault()+ return { selected: entries[activeIndex] } as const+ }+ break+ }+ case 'Escape':+ e.preventDefault()+ return { dismissed: true } as const+ }+ return undefined+ },+ [open, entries, activeIndex]+ )++ return {+ activeIndex,+ setActiveIndex,+ entries,+ setEntries,+ handleKeyDown,+ }+}diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 3ce850e8d..c7aad4d0d 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -101,6 +101,16 @@ import JanBrowserExtensionDialog from '@/containers/dialogs/JanBrowserExtensionDimport { useJanBrowserExtension } from '@/hooks/useJanBrowserExtension'import { useAgentMode } from '@/hooks/useAgentMode'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'+import { usePathReferences } from '@/stores/path-references'+import {+ parsePromptForReferences,+ resolvePathReference,+ formatPathReferenceText,+ searchFiles,+ REFERENCE_PATTERN,+ type FilePickerEntry as FileEntry,+} from '@/lib/path-references'+import { FilePickerPopover } from '@/components/FilePickerPopover'type ChatInputProps = {className?: string@@ -187,6 +197,155 @@ const ChatInput = memo(function ChatInput({const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)const setWebSearchEnabled = useWebSearchConfig((s) => s.setWebSearchEnabled)+ // ── @path file reference state ──────────────────────────────────────────+ const pathRefs = usePathReferences((s) => s.references)+ const setPathRefs = usePathReferences((s) => s.setReferences)+ const clearPathRefs = usePathReferences((s) => s.clearReferences)++ const [filePickerOpen, setFilePickerOpen] = useState(false)+ const [filePickerQuery, setFilePickerQuery] = useState('')+ const [filePickerEntries, setFilePickerEntries] = useState<FileEntry[]>([])+ const [filePickerPosition, setFilePickerPosition] = useState<{+ top: number+ left: number+ } | null>(null)+ const [workingDir, setWorkingDir] = useState<string | undefined>(undefined)+ // Textarea cursor position snapshot at the time @ was typed+ const filePickerCursorPos = useRef<number | null>(null)++ // Pre-load working directory+ useEffect(() => {+ const loadWorkingDir = async () => {+ try {+ // Try to get project home directory+ const { homeDir, documentDir } = await import('@tauri-apps/api/path')+ const home = await homeDir()+ setWorkingDir(home)+ } catch {+ setWorkingDir(undefined)+ }+ }+ if (effectiveAgentMode) {+ loadWorkingDir()+ }+ }, [effectiveAgentMode])++ // Detect `@` in the prompt text and open the file picker+ const handlePromptChange = useCallback(+ (value: string) => {+ setPrompt(value)++ // Only enable in agent mode+ if (!effectiveAgentMode) {+ setFilePickerOpen(false)+ return+ }++ const cursorIdx = filePickerCursorPos.current ?? value.length++ // Look backwards from current cursor to find the last word starting with @+ const beforeCursor = value.slice(0, cursorIdx)+ const atMatch = beforeCursor.match(/@([\w.\/-]*)$/)++ if (atMatch) {+ const query = atMatch[1] ?? ''+ setFilePickerQuery(query)++ // If we have a working directory, search files+ if (workingDir) {+ searchFiles(workingDir, query)+ .then((entries) => setFilePickerEntries(entries.slice(0, 50)))+ .catch(() => setFilePickerEntries([]))+ } else {+ setFilePickerEntries([])+ }++ // Position the picker above the text+ if (textareaRef.current) {+ const lineHeight = 22+ const lines = beforeCursor.split('\n').length+ const pos = {+ top: -Math.min(lines * lineHeight + 40, 300),+ left: 0,+ }+ setFilePickerPosition(pos)+ }+ setFilePickerOpen(true)+ } else {+ setFilePickerOpen(false)+ }+ },+ [effectiveAgentMode, workingDir, setPrompt]+ )++ // Insert a selected file reference into the prompt+ const handleFilePickerSelect = useCallback(+ (entry: FileEntry) => {+ if (filePickerCursorPos.current == null) return++ const beforeCursor = prompt.slice(0, filePickerCursorPos.current)+ const afterCursor = prompt.slice(filePickerCursorPos.current)++ // Replace the `@query` with `path/to/file` (the resolved reference)+ const textBefore = beforeCursor.replace(/@[\w.\/-]*$/, '')+ const refText = entry.path+ const newPrompt = textBefore + refText + afterCursor++ setPrompt(newPrompt)+ setFilePickerOpen(false)+ filePickerCursorPos.current = null++ // Focus back on textarea+ setTimeout(() => textareaRef.current?.focus(), 0)+ },+ [prompt, setPrompt]+ )++ const handleFilePickerClose = useCallback(() => {+ setFilePickerOpen(false)+ filePickerCursorPos.current = null+ }, [])++ // Resolve @path references in the prompt text, returning the resolved content+ const resolvePromptReferences = useCallback(+ async (text: string): Promise<{+ text: string+ resolvedContents: string+ }> => {+ const refs = parsePromptForReferences(text)+ if (refs.length === 0) return { text, resolvedContents: '' }++ const parts: string[] = []+ for (const ref of refs) {+ const resolved = await resolvePathReference(ref, workingDir)+ if (resolved) {+ if (resolved.kind === 'file') {+ parts.push(+ `--- File: ${resolved.absolutePath} ---\n${resolved.content}`+ )+ } else if (resolved.kind === 'directory') {+ parts.push(+ `--- Directory: ${resolved.absolutePath} ---\n${resolved.content}`+ )+ }+ } else {+ parts.push(+ `[File not found or too large: ${ref.rawPath}]`+ )+ }+ }++ const resolvedContents = parts.join('\n\n')++ // Remove @ references from the prompt text (they'll be replaced by the+ // resolved contents above so the model sees the content directly)+ const cleanText = text.replace(REFERENCE_PATTERN, '').replace(/\s+/g, ' ').trim()++ return { text: cleanText, resolvedContents }+ },+ [workingDir]+ )+const handleAgentToggle = useCallback(() => {toggleAgentMode(agentModeKey)}, [agentModeKey, toggleAgentMode])@@ -365,7 +524,15 @@ const ChatInput = memo(function ChatInput({setMessage('Please select a model to start chatting.')return}- if (!prompt.trim() && !hasSendableMedia) {++ // Resolve @path references before sending+ const { text: resolvedText, resolvedContents } =+ await resolvePromptReferences(prompt)+ const effectivePrompt = resolvedContents+ ? `${resolvedText}\n\n---\nReferenced file contents:\n\n${resolvedContents}`+ : resolvedText++ if (!effectivePrompt.trim() && !hasSendableMedia) {return}if (ingestingAny) {@@ -374,7 +541,7 @@ const ChatInput = memo(function ChatInput({}setMessage('')- addToHistory(prompt)+ addToHistory(effectivePrompt)// Use onSubmit prop if available (AI SDK), otherwise create thread and navigateif (onSubmit) {@@ -382,7 +549,7 @@ const ChatInput = memo(function ChatInput({if (isStreaming && currentThreadId) {useMessageQueue.getState().enqueue(currentThreadId, {id: generateId(),- text: prompt,+ text: effectivePrompt,createdAt: Date.now(),})setPrompt('')@@ -412,7 +579,7 @@ const ChatInput = memo(function ChatInput({}))const files = [...imageFiles, ...audioFiles, ...videoFiles]- onSubmit(prompt, files.length > 0 ? files : undefined)+ onSubmit(effectivePrompt, files.length > 0 ? files : undefined)setPrompt('')clearAttachmentsForThread(attachmentsKey)} else {@@ -427,7 +594,7 @@ const ChatInput = memo(function ChatInput({)const messagePayload = {- text: prompt,+ text: effectivePrompt,files: [] as Array<{ type: string; mediaType: string; url: string }>,}@@ -1897,9 +2064,27 @@ const ChatInput = memo(function ChatInput({value={prompt}data-testid={'chat-input'}onChange={(e) => {- setPrompt(e.target.value)+ const value = e.target.value+ const cursorIdx = e.target.selectionStart++ // Track when @ is freshly typed+ const prevPrompt = prompt+ handlePromptChange(value)++ // Snapshot cursor position when user types @+ if (value.includes('@') && !prevPrompt.includes('@')) {+ filePickerCursorPos.current = cursorIdx+ } else if (value.endsWith('@') && cursorIdx > 0) {+ filePickerCursorPos.current = cursorIdx+ } else if (!value.includes('@')) {+ filePickerCursorPos.current = null+ } else if (filePickerCursorPos.current == null) {+ // If picker already open, keep tracking cursor+ filePickerCursorPos.current = cursorIdx+ }+// Count the number of newlines to estimate rows- const newRows = (e.target.value.match(/\n/g) || []).length + 1+ const newRows = (value.match(/\n/g) || []).length + 1setRows(Math.min(newRows, maxRows))}}onKeyDown={(e) => {@@ -1936,6 +2121,17 @@ const ChatInput = memo(function ChatInput({navigateHistory('down')}}+ // Tab completes the selected @path file reference+ if (+ e.key === 'Tab' &&+ filePickerOpen &&+ filePickerEntries.length > 0 &&+ !isComposing+ ) {+ e.preventDefault()+ // Select the first entry as the default Tab completion+ handleFilePickerSelect(filePickerEntries[0])+ }}}onPaste={handlePaste}placeholder={t('common:placeholder.chatInput')}@@ -1950,6 +2146,20 @@ const ChatInput = memo(function ChatInput({className)}/>+ {/* @path file reference picker popover */}+ {filePickerOpen && effectiveAgentMode && (+ <div className="relative">+ <FilePickerPopover+ entries={filePickerEntries}+ query={filePickerQuery}+ open={filePickerOpen}+ position={filePickerPosition}+ onSelect={handleFilePickerSelect}+ onClose={handleFilePickerClose}+ textareaRef={textareaRef}+ />+ </div>+ )}</div></div>diff --git a/web-app/src/lib/path-references.ts b/web-app/src/lib/path-references.tsnew file mode 100644index 000000000..35ae2850d--- /dev/null+++ b/web-app/src/lib/path-references.ts@@ -0,0 +1,339 @@+/**+ * Utility for scanning, resolving, and searching @path file/folder references+ * in the chat input.+ *+ * - Typing `@` triggers a fuzzy file search scoped to the working directory.+ * - Selected paths are kept as text references (e.g. `@src/main.ts`) in the prompt.+ * - On submit, each @reference is resolved: files are read as text (with a 1MB cap),+ * directories produce a listing, images produce inline data, and errors surface+ * as inline notices.+ */+import { fs } from '@janhq/core'+import type { PathReference, FilePickerEntry } from '@/types/path-reference'++export type { FilePickerEntry }++// ── Exports ──────────────────────────────────────────────────────────────────++/** Regex matching @path references in text. */+export const REFERENCE_PATTERN = /@([^\s,;:!?'"`)\]}>]+)/g++/** Maximum bytes we'll read from a single file. */+const MAX_FILE_BYTES = 1 * 1024 * 1024++/** Maximum characters in a directory listing sent to the model. */+const MAX_DIR_CHARS = 20_000++/** Image extensions that should be offered as base64 rather than text. */+const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'])++/** Common code/text extensions we prioritise in picker results. */+const CODE_EXTS = new Set([+ 'ts', 'tsx', 'js', 'jsx', 'rs', 'py', 'go', 'java', 'c', 'cpp', 'h',+ 'hpp', 'cs', 'rb', 'php', 'swift', 'kt', 'scala',+ 'json', 'yaml', 'yml', 'toml', 'xml', 'md', 'txt', 'css', 'scss',+ 'html', 'sh', 'bash', 'zsh', 'sql', 'graphql',+])++// ── Parsing references from text ─────────────────────────────────────────────++/**+ * Parse @path references from a prompt string.+ * Returns the raw path strings (e.g. `["src/main.ts", "../README.md"]`).+ */+export function parsePromptForReferences(text: string): string[] {+ const seen = new Set<string>()+ const refs: string[] = []+ let match: RegExpExecArray | null+ while ((match = REFERENCE_PATTERN.exec(text)) !== null) {+ const raw = match[1].trim()+ // Skip obvious non-paths+ if (+ !raw ||+ raw.startsWith('http://') ||+ raw.startsWith('https://') ||+ raw.startsWith('file://') ||+ raw.includes('@') ||+ raw === ''+ )+ continue+ if (!seen.has(raw)) {+ seen.add(raw)+ refs.push(raw)+ }+ }+ return refs+}++/**+ * Format a path as a @reference text for insertion into the prompt.+ */+export function formatPathReferenceText(path: string): string {+ return `@${path}`+}++// ── Fuzzy file search ────────────────────────────────────────────────────────++/**+ * Searches for files/folders in `rootDir` whose path or name matches `query`+ * (case-insensitive substring / fuzzy matching). Returns up to 50 entries+ * suitable for the picker dropdown.+ *+ * If `query` is empty, returns a flat listing of the immediate children of+ * `rootDir` (capped at 100). Otherwise performs a breadth-first walk up to a+ * depth of 4 levels and scores entries by match quality.+ */+export async function searchFiles(+ rootDir: string,+ query: string,+ max_: number = 50+): Promise<FilePickerEntry[]> {+ try {+ // Empty query: return immediate children (fast, no recursion)+ if (!query || query.trim() === '') {+ return listImmediateChildren(rootDir, max_)+ }++ // Non-empty query: walk the tree up to 4 levels+ const results: ScoredEntry[] = []+ const queryLower = query.toLowerCase()+ // If query contains slashes, we search deeper+ const depth = Math.min(query.split('/').length + 2, 4)++ await walkDir(rootDir, queryLower, results, depth, 0)++ // Sort: directories first, then by match quality, then alphabetically+ results.sort((a, b) => {+ // Directories first+ if (a.kind !== b.kind) return a.kind === 'directory' ? -1 : 1+ // Exact name match > starts with > substring > fuzzy+ if (a.score !== b.score) return b.score - a.score+ // Shorter paths first+ return a.path.length - b.path.length+ })++ return results.slice(0, max_).map(({ path, name, kind, ext }) => ({+ path,+ name,+ kind,+ extension: ext,+ }))+ } catch {+ return []+ }+}++// ── Resolving a single reference content ─────────────────────────────────────++/**+ * Resolve a @path reference and return the content to inject into the message.+ *+ * Returns `null` if the reference is missing or errors (caller surfaces inline).+ */+export async function resolvePathReference(+ rawPath: string,+ workingDir?: string+): Promise<{+ kind: 'file' | 'directory'+ absolutePath: string+ content: string+ isImage: boolean+ imageBase64?: string+ imageMimeType?: string+} | null> {+ const absolutePath = rawPath.startsWith('/')+ ? rawPath+ : workingDir+ ? `${workingDir}/${rawPath}`+ : rawPath++ try {+ const stat = await fs.fileStat(absolutePath)+ if (!stat) return null++ const isDir = stat.isDirectory ?? false++ if (isDir) {+ // Directory listing+ const entries = await fs.readdirSync(absolutePath)+ const items = Array.isArray(entries) ? entries : []+ let listing = ''+ for (const item of items) {+ const name = typeof item === 'string' ? item : String(item)+ listing += ` ${name}\n`+ }+ if (listing.length > MAX_DIR_CHARS) {+ listing = listing.slice(0, MAX_DIR_CHARS) + '\n ... (truncated)'+ }+ return { kind: 'directory', absolutePath, content: listing, isImage: false }+ }++ // File+ const size = stat.size ? Number(stat.size) : 0+ if (size > MAX_FILE_BYTES) {+ return null // too large — caller handles+ }++ const ext = rawPath.split('.').pop()?.toLowerCase()+ if (ext && IMAGE_EXTS.has(ext)) {+ const content = await fs.readFileSync(absolutePath)+ const base64 = typeof content === 'string' ? content : String(content)+ const mime = imageMimeFor(ext)+ return {+ kind: 'file',+ absolutePath,+ content: `[Image: ${rawPath}]`,+ isImage: true,+ imageBase64: base64,+ imageMimeType: mime,+ }+ }++ const content = await fs.readFileSync(absolutePath)+ const text = typeof content === 'string' ? content : String(content)+ const truncated =+ text.length > MAX_FILE_BYTES+ ? text.slice(0, MAX_FILE_BYTES) + '\n\n... (truncated)'+ : text++ const header = `--- File: ${rawPath} ---\n`+ const footer = `\n--- End: ${rawPath} ---`+ return { kind: 'file', absolutePath, content: header + truncated + footer, isImage: false }+ } catch {+ return null+ }+}++// ── Internal helpers ─────────────────────────────────────────────────────────++interface ScoredEntry {+ path: string+ name: string+ kind: 'file' | 'directory'+ ext?: string+ score: number+}++function scoreMatch(name: string, queryLower: string): number {+ const lower = name.toLowerCase()+ if (lower === queryLower) return 100 // exact match+ if (lower.startsWith(queryLower)) return 80 // prefix+ if (lower.includes(queryLower)) return 60 // substring+ // Fuzzy: each consecutive matched character adds 5+ let fi = 0+ let score = 0+ for (const ch of queryLower) {+ const idx = lower.indexOf(ch, fi)+ if (idx === -1) return 0+ if (idx === fi) score += 10 // consecutive match+ else score += 2+ fi = idx + 1+ }+ return Math.min(score, 50)+}++async function walkDir(+ dir: string,+ queryLower: string,+ results: ScoredEntry[],+ maxDepth: number,+ depth: number+): Promise<void> {+ if (depth > maxDepth) return++ try {+ const entries: string[] = await fs.readdirSync(dir)+ if (!Array.isArray(entries)) return++ const items: Array<{ path: string; name: string; isDir: boolean }> = []+ for (const entry of entries) {+ const name = typeof entry === 'string' ? entry : String(entry)+ const fullPath = `${dir}/${name}`+ let isDir = false+ try {+ const stat = await fs.fileStat(fullPath)+ isDir = stat?.isDirectory ?? false+ } catch {+ // stat failed, treat as file+ }++ const entryName = name+ const entryScore = scoreMatch(entryName, queryLower)+ if (entryScore > 0) {+ const ext = isDir ? undefined : entryName.split('.').pop()?.toLowerCase()+ results.push({+ path: fullPath,+ name: entryName,+ kind: isDir ? 'directory' : 'file',+ ext,+ score: entryScore,+ })+ }++ items.push({ path: fullPath, name: entryName, isDir })+ }++ // Recurse into directories+ if (depth < maxDepth) {+ for (const item of items) {+ if (item.isDir) {+ await walkDir(item.path, queryLower, results, maxDepth, depth + 1)+ }+ }+ }+ } catch {+ // Silently skip directories we can't read+ }+}++async function listImmediateChildren(+ dir: string,+ max_: number+): Promise<FilePickerEntry[]> {+ try {+ const entries: string[] = await fs.readdirSync(dir)+ if (!Array.isArray(entries)) return []++ const results: FilePickerEntry[] = []+ for (const entry of entries) {+ if (results.length >= max_) break+ const name = typeof entry === 'string' ? entry : String(entry)+ const fullPath = `${dir}/${name}`+ let isDir = false+ try {+ const stat = await fs.fileStat(fullPath)+ isDir = stat?.isDirectory ?? false+ } catch {+ // treat as file+ }+ const ext = isDir ? undefined : name.split('.').pop()?.toLowerCase()+ results.push({ path: fullPath, name, kind: isDir ? 'directory' : 'file', extension: ext })+ }++ // Sort: directories first, then code files, then alphabetically+ results.sort((a, b) => {+ if (a.kind !== b.kind) return a.kind === 'directory' ? -1 : 1+ const aCode = a.extension ? CODE_EXTS.has(a.extension) : false+ const bCode = b.extension ? CODE_EXTS.has(b.extension) : false+ if (aCode !== bCode) return aCode ? -1 : 1+ return a.name.localeCompare(b.name)+ })++ return results+ } catch {+ return []+ }+}++function imageMimeFor(ext: string): string {+ const map: Record<string, string> = {+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ png: 'image/png',+ gif: 'image/gif',+ webp: 'image/webp',+ bmp: 'image/bmp',+ svg: 'image/svg+xml',+ }+ return map[ext] || 'image/png'+}diff --git a/web-app/src/stores/path-references.ts b/web-app/src/stores/path-references.tsnew file mode 100644index 000000000..cd0d2f6a7--- /dev/null+++ b/web-app/src/stores/path-references.ts@@ -0,0 +1,48 @@+/**+ * Store for @path file/folder references in chat input.+ * Maintains an ordered list of active references during a message composition.+ */+import { create } from 'zustand'+import type { PathReference } from '@/types/path-reference'++type PathReferencesState = {+ /** Active references in the current message being composed */+ references: PathReference[]++ /** Set all references (from parsing the prompt text) */+ setReferences: (refs: PathReference[]) => void++ /** Add a single reference */+ addReference: (ref: PathReference) => void++ /** Remove a reference by its raw path */+ removeReference: (rawPath: string) => void++ /** Clear all references */+ clearReferences: () => void++ /** Get the current references */+ getReferences: () => PathReference[]+}++export const usePathReferences = create<PathReferencesState>((set, get) => ({+ references: [],++ setReferences: (refs) => set({ references: refs }),++ addReference: (ref) =>+ set((state) => {+ // Avoid duplicates+ if (state.references.some((r) => r.rawPath === ref.rawPath)) return state+ return { references: [...state.references, ref] }+ }),++ removeReference: (rawPath) =>+ set((state) => ({+ references: state.references.filter((r) => r.rawPath !== rawPath),+ })),++ clearReferences: () => set({ references: [] }),++ getReferences: () => get().references,+}))diff --git a/web-app/src/types/path-reference.ts b/web-app/src/types/path-reference.tsnew file mode 100644index 000000000..a90cfb0b8--- /dev/null+++ b/web-app/src/types/path-reference.ts@@ -0,0 +1,32 @@+/**+ * A resolved @path reference in the chat input+ */+export type PathReference = {+ /** Unique ID for this reference chip */+ id: string+ /** The raw path string as typed/selected by the user */+ rawPath: string+ /** Full absolute path (resolved relative to working directory) */+ absolutePath: string+ /** Whether it's a file or directory */+ kind: 'file' | 'directory'+ /** Display name (basename of the path) */+ name: string+ /** File size in bytes (for files only) */+ size?: number+ /** Whether this reference encountered an error during resolution */+ error?: 'missing' | 'too_large' | 'unreadable'+ /** Error description */+ errorMessage?: string+}++/**+ * Entry shown in the fuzzy file picker+ */+export type FilePickerEntry = {+ path: string+ name: string+ kind: 'file' | 'directory'+ // Optional for display/styling+ extension?: string+}