Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

Composer: @ file mentions in Code, Agent and chat with a folder (U8)

purpleaf7e609c66cf
diff --git a/src/components/chat/ChatFileChip.tsx b/src/components/chat/ChatFileChip.tsx
index 5235d892..97a7bf86 100644
--- a/src/components/chat/ChatFileChip.tsx
+++ b/src/components/chat/ChatFileChip.tsx
@@ -1,4 +1,4 @@
-import { File as FileIcon, X } from 'lucide-react'
+import { AtSign, File as FileIcon, X } from 'lucide-react'
import type { FileAttachment } from '../../types/chat'
import { formatBytes } from '../../lib/formatters'
import { chipCutLabel } from '../../lib/chat-file-fit'
@@ -24,7 +24,7 @@ export function binaryReachLabel(file: FileAttachment, reachesTools?: boolean):
* (without it). It shows a description, never the file: the bytes are not in
* the chat (lib/chat-files.ts), so there is nothing here to open or save.
*/
-export function ChatFileChip({ file, onRemove, testId = 'chat-file-chip', reachesTools }: {
+export function ChatFileChip({ file, onRemove, testId = 'chat-file-chip', reachesTools, mention }: {
file: FileAttachment
/** Composer only: take the file off the draft again. */
onRemove?: () => void
@@ -32,6 +32,8 @@ export function ChatFileChip({ file, onRemove, testId = 'chat-file-chip', reache
/** Composer only: whether a send copies the file into a working folder
* (Agent and Code). Unset in the transcript, where the file says it. */
reachesTools?: boolean
+ /** Composer only: the file came from an `@` mention (lib/file-mentions.ts). */
+ mention?: boolean
}) {
const where = file.absolutePath
? `\nOn this computer: ${file.absolutePath}`
@@ -43,12 +45,13 @@ export function ChatFileChip({ file, onRemove, testId = 'chat-file-chip', reache
return (
<div
data-testid={testId}
+ data-mention={mention ? 'true' : undefined}
title={`${file.name}\n${file.kind}, ${formatBytes(file.size)}${cut ? `\nOnly part of the text reached the model: ${cut}` : ''}\nSHA-256 ${file.sha256}${where}`}
className="flex items-center gap-1.5 max-w-[240px] pl-2 pr-1.5 py-1 rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-white/[0.04] text-left"
>
- <FileIcon size={13} className="shrink-0 text-gray-400" />
+ {mention ? <AtSign size={13} className="shrink-0 text-gray-400" /> : <FileIcon size={13} className="shrink-0 text-gray-400" />}
<span className="min-w-0 flex flex-col leading-tight">
- <span className="truncate t-mono text-gray-800 dark:text-gray-200">{file.name}</span>
+ <span className="truncate t-mono text-gray-800 dark:text-gray-200">{mention ? `@${file.name}` : file.name}</span>
<span className="truncate t-micro text-gray-500 dark:text-gray-400">{file.kind}, {formatBytes(file.size)}</span>
{cut && <span data-testid="chat-file-cut" className="truncate t-micro text-gray-500 dark:text-gray-400">{cut}</span>}
{reach && <span data-testid="chat-file-reach" className="truncate t-micro text-gray-500 dark:text-gray-400">{reach}</span>}
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index da346e30..5f4e1aa9 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -1,7 +1,7 @@
import { useState, useRef, useEffect, useLayoutEffect, useCallback, type ReactNode } from 'react'
import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'
import { SamplingControls } from './SamplingControls'
-import { Send, Square, Paperclip, X, Brain, Gauge, Terminal, Film, Music } from 'lucide-react'
+import { Send, Square, Paperclip, X, Brain, Gauge, Terminal, Film, Music, AtSign, FileText, Folder, Lock } from 'lucide-react'
import { matchAgentCommands, type AgentCommand, type CommandScope } from '../../lib/agent-commands'
import { VoiceButton, type VoiceButtonHandle } from './VoiceButton'
import { ApprovalDialog } from './ApprovalDialog'
@@ -38,6 +38,11 @@ import { useCreateChatReleased } from '../../lib/create/chat-release'
import {
ATTACH_TOO_LARGE, ATTACH_TOO_MANY, addPendingMedia, mediaKindOf, tooLargeToAttach, type PendingMedia,
} from '../../lib/create/chat-attachments'
+import {
+ MAX_MENTIONS, TOO_MANY_MENTIONS_MESSAGE, hasMentionToken, insertMention, loadMention, mentionAt, mentionIndexFor,
+ mentionPath, mentionRootKey, mentionSecretReason, rankMentions, removeMentionToken, secretMentionNote, mentionLabel,
+ type MentionEntry, type MentionIndex, type MentionQuery, type MentionRoot,
+} from '../../lib/file-mentions'
interface Props {
onSend: (content: string, images?: ImageAttachment[], files?: ChatFileInput[], media?: PendingMedia[]) => void
@@ -100,6 +105,12 @@ interface Props {
* (lib/chat-drafts.ts): Chat and Code each keep their own.
*/
draftScope?: string
+ /**
+ * `@` file mentions (U8): the folder the list reads. Undefined turns them
+ * off for this composer; null means mentions are on but no folder is known
+ * yet, and the list says so (hooks/useMentionRoot.ts).
+ */
+ mentionRoot?: MentionRoot | null
}
/**
@@ -144,7 +155,7 @@ interface SendLock {
message: string
}
-export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pendingApproval, onApprove, onReject, disabled, modelReady, slashCommands, composerModel, composerActions, composerAbove, filesReachTools = false, draftScope = 'chat' }: Props) {
+export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pendingApproval, onApprove, onReject, disabled, modelReady, slashCommands, composerModel, composerActions, composerAbove, filesReachTools = false, draftScope = 'chat', mentionRoot }: Props) {
// What this composer held when its view closed last (lib/chat-drafts.ts):
// the draft of the open chat goes straight into the field, the rest into
// `entwuerfe` below. Read once, on mount.
@@ -179,6 +190,20 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const cmdMenuRef = useRef<HTMLDivElement>(null)
const cmdMenuPlatz = usePopoverPlatz(cmdMenuRef, cmdMenu.length > 0, { bevorzugt: 'oben', abstand: 6, deckel: 256 })
const [cmdIndex, setCmdIndex] = useState(0)
+ // `@` file mentions (U8, lib/file-mentions.ts). `mention` is the `@query`
+ // the caret stands in; `mentionShut` remembers the `@` whose list Esc
+ // closed, so it stays closed while that word is typed on.
+ const [mention, setMention] = useState<MentionQuery | null>(null)
+ const [mentionShut, setMentionShut] = useState<number | null>(null)
+ const [mentionIndex, setMentionIndex] = useState<{ key: string; index: MentionIndex | null } | null>(null)
+ const [mentionSel, setMentionSel] = useState(0)
+ const mentionMenuRef = useRef<HTMLDivElement>(null)
+ const mentionsOn = mentionRoot !== undefined
+ const mentionOpen = mentionsOn && mention !== null
+ const mentionMenuPlatz = usePopoverPlatz(mentionMenuRef, mentionOpen, { bevorzugt: 'oben', abstand: 6, deckel: 256 })
+ const mentionKey = mentionRootKey(mentionRoot)
+ const mentionLoaded = mentionIndex && mentionIndex.key === mentionKey ? mentionIndex : null
+ const mentionRows: MentionEntry[] = mentionOpen && mentionLoaded?.index ? rankMentions(mentionLoaded.index.entries, mention.query) : []
/**
* Ein Entwurf gehoert dem Gespraech, in dem er getippt wurde.
*
@@ -278,6 +303,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
// draft they were picked for; they are not carried across conversations.
setMedia([])
setCmdMenu([])
+ setMention(null)
}
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
@@ -411,7 +437,9 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
notices.show('file-attach', 'Still reading the previous files. Add these again in a moment.', 'ruhig', CHAT_NOTICE_MS)
return
}
- const slots = MAX_CHAT_FILES - files.length
+ // `@` mentions have their own limit and take no slot of a dropped file.
+ const ownFiles = files.filter((f) => !f.mention).length
+ const slots = MAX_CHAT_FILES - ownFiles
if (slots <= 0) {
notices.show('file-attach', TOO_MANY_FILES_MESSAGE, 'ruhig', CHAT_NOTICE_MS)
return
@@ -431,7 +459,12 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
}
// The draft belongs to the conversation it was started in.
if (useChatStore.getState().activeConversationId !== startedIn) return
- if (ready.length) setFiles((prev) => [...prev, ...ready].slice(0, MAX_CHAT_FILES))
+ if (ready.length) {
+ setFiles((prev) => {
+ const room = MAX_CHAT_FILES - prev.filter((f) => !f.mention).length
+ return room > 0 ? [...prev, ...ready.slice(0, room)] : prev
+ })
+ }
if (problems.length) notices.show('file-attach', problems[0], 'ruhig', CHAT_NOTICE_MS)
else notices.dismiss('file-attach')
// A PDF or Word file attaches like any other, but the model gets far
@@ -455,7 +488,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
job.busy = false
setPreparingFiles(false)
}
- }, [files.length, conversationId, filesReachTools])
+ }, [files, conversationId, filesReachTools])
const addFiles = useCallback(async (picked: FileList | File[]) => {
const all = Array.from(picked)
@@ -556,6 +589,9 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const removeFile = (index: number) => {
const left = files.filter((_, i) => i !== index)
setFiles(left)
+ // The chip of a mention goes with its token in the text.
+ const gone = files[index]?.mention
+ if (gone) setInput((value) => removeMentionToken(value, gone))
if (!left.some(({ attachment }) => isBinaryAttachment(attachment))) useChatNoticeStore.getState().dismiss('binary-summary-only')
}
useEffect(() => {
@@ -596,12 +632,14 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
// A message is sent: the note about a stop has been seen.
dismissComputerStop()
const text = trimmed || (images.length > 0 ? '(image)' : FILE_ONLY_TEXT)
+ // A mention whose token is no longer in the text is not sent.
+ const sendFiles = files.filter((f) => !f.mention || hasMentionToken(trimmed, f.mention))
const pictures = images.length > 0 ? images : undefined
// The third argument only exists for a message that carries files, so a
// send without them reaches its handler exactly as it always did.
// And the fourth only for one that carries a clip or a sound track.
- if (media.length > 0) onSend(trimmed || '(attachment)', pictures, files.length > 0 ? files : undefined, media)
- else if (files.length > 0) onSend(text, pictures, files)
+ if (media.length > 0) onSend(trimmed || '(attachment)', pictures, sendFiles.length > 0 ? sendFiles : undefined, media)
+ else if (sendFiles.length > 0) onSend(text, pictures, sendFiles)
else onSend(text, pictures)
// Sent while dictating: the words in the field went out, the take ends
// here and leaves nothing to fill the emptied field again.
@@ -611,6 +649,8 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
setFiles([])
setMedia([])
setCmdMenu([])
+ setMention(null)
+ setMentionShut(null)
}
// Update the input + the slash-command typeahead together. The menu shows
@@ -632,6 +672,66 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const matches = slashCommands ? matchAgentCommands(value, slashCommands) : []
setCmdMenu(matches)
setCmdIndex(0)
+ // The `@` list follows the caret; a chip goes when its token is deleted.
+ if (mentionsOn) {
+ const at = matches.length === 0 ? mentionAt(value, caret ?? value.length) : null
+ const open = at && at.start !== mentionShut ? at : null
+ setMention(open)
+ if (!at) setMentionShut(null)
+ setMentionSel(0)
+ if (files.some((f) => f.mention && !hasMentionToken(value, f.mention))) {
+ setFiles((prev) => prev.filter((f) => !f.mention || hasMentionToken(value, f.mention)))
+ }
+ }
+ }
+
+ // The file list of the working folder, read when the `@` list opens and
+ // again after a few seconds (lib/file-mentions.ts caches it).
+ const wantMentionIndex = mentionOpen && !!mentionKey
+ useEffect(() => {
+ if (!wantMentionIndex || !mentionRoot) return
+ let alive = true
+ const key = mentionRootKey(mentionRoot)
+ mentionIndexFor(mentionRoot).then(
+ (index) => { if (alive) setMentionIndex({ key, index }) },
+ () => { if (alive) setMentionIndex({ key, index: null }) },
+ )
+ return () => { alive = false }
+ }, [wantMentionIndex, mentionRoot])
+
+ // A pick: the typed `@query` becomes the token, then the file is read and
+ // joins the draft as an attachment, the same way a dropped file does.
+ const pickMention = (entry: MentionEntry) => {
+ const at = mention
+ setMention(null)
+ if (!at || !mentionRoot) return
+ const notices = useChatNoticeStore.getState()
+ const rel = mentionPath(entry)
+ const why = mentionSecretReason(entry)
+ if (why) {
+ notices.show('file-mention', secretMentionNote(mentionLabel(rel), why), 'ruhig', CHAT_NOTICE_MS)
+ return
+ }
+ const already = files.some((f) => f.mention === rel)
+ if (!already && files.filter((f) => f.mention).length >= MAX_MENTIONS) {
+ notices.show('file-mention', TOO_MANY_MENTIONS_MESSAGE, 'ruhig', CHAT_NOTICE_MS)
+ return
+ }
+ const caret = textareaRef.current?.selectionStart ?? at.start + 1 + at.query.length
+ const next = insertMention(input, at, caret, rel)
+ caretRef.current = next.caret
+ setInput(next.text)
+ textareaRef.current?.focus()
+ if (already) return
+ const startedIn = conversationId
+ void loadMention(mentionRoot, entry).then((result) => {
+ if (useChatStore.getState().activeConversationId !== startedIn) return
+ if (!result.ok) {
+ notices.show('file-mention', result.note, 'ruhig', CHAT_NOTICE_MS)
+ return
+ }
+ setFiles((prev) => (prev.some((f) => f.mention === rel) ? prev : [...prev, result.input]))
+ })
}
// Fill the input with the chosen command (trailing space so args can follow)
@@ -678,6 +778,32 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
return
}
}
+ // The `@` file list, the same keys as the command menu.
+ if (mentionOpen) {
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ setMentionShut(mention.start)
+ setMention(null)
+ return
+ }
+ if (mentionRows.length > 0) {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault()
+ setMentionSel((i) => (i + 1) % mentionRows.length)
+ return
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault()
+ setMentionSel((i) => (i - 1 + mentionRows.length) % mentionRows.length)
+ return
+ }
+ if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing)) {
+ e.preventDefault()
+ pickMention(mentionRows[Math.min(mentionSel, mentionRows.length - 1)])
+ return
+ }
+ }
+ }
if (composerSends({ key: e.key, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, isComposing: e.nativeEvent.isComposing }, enterMode)) {
e.preventDefault()
// While the last words are still being transcribed, Enter waits for
@@ -781,6 +907,62 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
</div>
)}
+ {/* `@` file list (U8): same place and look as the command menu. */}
+ {mentionOpen && (
+ <div
+ ref={mentionMenuRef}
+ data-testid="mention-menu"
+ role="listbox"
+ aria-label="Files"
+ style={mentionMenuPlatz.style}
+ className={`absolute left-0 right-0 z-50 overflow-y-auto scrollbar-thin rounded-lg lu-elevated py-1 ${mentionMenuPlatz.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5'}`}
+ >
+ <div className="px-2.5 py-1 flex items-center gap-1 text-[0.5rem] uppercase tracking-widest text-gray-400 dark:text-gray-600">
+ <AtSign size={9} /> Files
+ </div>
+ {!mentionRoot ? (
+ <div className="px-2.5 py-1 t-micro text-gray-500 dark:text-gray-400">No working folder yet, so there are no files to mention.</div>
+ ) : !mentionLoaded ? (
+ <div className="px-2.5 py-1 t-micro text-gray-500 dark:text-gray-400">Reading the folder…</div>
+ ) : !mentionLoaded.index ? (
+ <div className="px-2.5 py-1 t-micro text-gray-500 dark:text-gray-400">The folder could not be read.</div>
+ ) : mentionRows.length === 0 ? (
+ <div className="px-2.5 py-1 t-micro text-gray-500 dark:text-gray-400">{mention.query ? 'No file matches.' : 'This folder is empty.'}</div>
+ ) : (
+ mentionRows.map((entry, i) => {
+ const slash = entry.rel.lastIndexOf('/')
+ const dir = slash >= 0 ? entry.rel.slice(0, slash + 1) : ''
+ const base = slash >= 0 ? entry.rel.slice(slash + 1) : entry.rel
+ const secret = !!mentionSecretReason(entry)
+ const Icon = secret ? Lock : entry.isDir ? Folder : FileText
+ return (
+ <button
+ key={entry.rel}
+ role="option"
+ aria-selected={i === mentionSel}
+ data-testid="mention-row"
+ onMouseDown={(e) => { e.preventDefault(); pickMention(entry) }}
+ onMouseEnter={() => setMentionSel(i)}
+ className={`w-full text-left px-2.5 py-1 flex items-center gap-1.5 min-w-0 transition-colors ${
+ i === mentionSel ? 'bg-gray-100 dark:bg-white/[0.07]' : 'hover:bg-gray-50 dark:hover:bg-white/[0.04]'
+ }`}
+ >
+ <Icon size={11} className="shrink-0 text-gray-400 dark:text-gray-500" />
+ <span className="min-w-0 truncate text-[0.72rem]">
+ <span className="font-medium text-gray-800 dark:text-gray-100">{base}{entry.isDir ? '/' : ''}</span>
+ {dir && <span className="ml-1.5 t-micro text-gray-400 dark:text-gray-500">{dir}</span>}
+ </span>
+ {secret && <span className="t-micro text-gray-400 dark:text-gray-500 shrink-0 ml-auto">private</span>}
+ </button>
+ )
+ })
+ )}
+ {mentionLoaded?.index?.truncated && mentionRows.length > 0 && (
+ <div className="px-2.5 pt-1 t-micro text-gray-400 dark:text-gray-500">Large folder: only part of it is searched.</div>
+ )}
+ </div>
+ )}
+
{/* The standing goal sits above everything else in the composer, so an
instruction that steers every turn is never invisible. */}
{composerAbove}
@@ -851,6 +1033,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
file={attachment}
testId="composer-file-chip"
reachesTools={filesReachTools}
+ mention={!!files[i].mention}
onRemove={() => removeFile(i)}
/>
))}
@@ -904,7 +1087,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
value={input}
onChange={(e) => updateInput(e.target.value, e.target.selectionStart)}
onKeyDown={handleKeyDown}
- onBlur={() => setTimeout(() => setCmdMenu([]), 120)}
+ onBlur={() => setTimeout(() => { setCmdMenu([]); setMention(null) }, 120)}
onPaste={handlePaste}
placeholder={disabled ? "Unavailable" : isDragOver ? "Drop files here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : composerPlaceholder(enterMode, isMacOS())}
disabled={disabled}
diff --git a/src/components/chat/ChatNotices.tsx b/src/components/chat/ChatNotices.tsx
index ff511584..8640440d 100644
--- a/src/components/chat/ChatNotices.tsx
+++ b/src/components/chat/ChatNotices.tsx
@@ -11,7 +11,7 @@
* fuer Anmerkungen und Fehler vorschreibt: eine Zeile, kein Kasten, ruhiges
* Grau oder Rot, und ein x, das sie wegnimmt.
*/
-import { Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, Scissors } from 'lucide-react'
+import { AtSign, Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, Scissors } from 'lucide-react'
import { Hinweis } from '../ui/Hinweis'
import { useChatNoticeStore, CONVERSATION_BOUND, type ChatNoticeId } from '../../stores/chatNoticeStore'
import { COMPOSER_MAX_W } from './composer-width'
@@ -32,6 +32,7 @@ const ICON: Record<ChatNoticeId, typeof Paperclip> = {
'agent-outside-workspace': FolderOpen,
'agent-for-local-files': Bot,
'create-save': Download,
+ 'file-mention': AtSign,
}
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 4b7766af..50b9d605 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -57,6 +57,7 @@ import { useIsQueuedForLocalLane, useLocalLaneQueuePosition, useLocalLaneHolderW
import { useRemoteStore } from '../../stores/remoteStore'
import { modelDisplayLabel } from '../../lib/model-label'
import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'
+import { useMentionRoot } from '../../hooks/useMentionRoot'
/** Was die Eingangsseite sagt und anbietet, je nach Lage. */
interface Landing {
@@ -193,6 +194,9 @@ export function ChatView() {
activeConversationId ? s.agentModeActive[activeConversationId] ?? false : false
)
const isComparing = useCompareStore((s) => s.isComparing)
+ // `@` file mentions (U8): Agent mode reads its working folder, plain chat
+ // only a real folder pinned on the chat or set as default.
+ const mentionRoot = useMentionRoot(isAgentActive ? 'agent' : 'chat')
// Remote-chat state: show a reactivate banner when the user is viewing a
// Remote conversation whose server has been stopped.
@@ -844,6 +848,7 @@ export function ChatView() {
// Agent mode copies attached files into the working folder;
// plain chat hands the model a summary of them.
filesReachTools={isAgentActive}
+ mentionRoot={mentionRoot}
composerModel={
/* What this chat's answers were written by rides on the
picker itself now, as a dot plus a tooltip, instead of a
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index d23516dc..221bd06e 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -60,6 +60,7 @@ import { Hinweis } from '../ui/Hinweis'
import { HINWEIS_TEXT } from '../../lib/hinweis'
import { stripModelNoise } from '../../lib/strip-model-noise'
import { useIsQueuedForLocalLane, useLocalLaneQueuePosition } from '../../lib/run-idle'
+import { useMentionRoot } from '../../hooks/useMentionRoot'
// Code always drives a tool loop, so the aggressive tier applies here.
const stripChannelTags = (text: string) => stripModelNoise(text, { aggressive: true })
@@ -110,6 +111,8 @@ export function CodexView() {
// the same function). Handed to the send, which never runs looser (A37).
const codexDefaultMode = useSettingsStore((s) => s.settings.codexDefaultMode)
const shownMode = useCodexStore((s) => s.nextSendMode(activeConversationId, codexDefaultMode))
+ // `@` file mentions (U8) read the folder this run works in.
+ const mentionRoot = useMentionRoot('code')
const conversation = conversations.find(c => c.id === activeConversationId)
const messages = conversation?.messages || []
@@ -787,6 +790,7 @@ export function CodexView() {
waitingForLocalLane={queuedForLocalLane}
slashCommands="agent"
filesReachTools
+ mentionRoot={mentionRoot}
draftScope="code"
composerModel={<ModelSelector openUpward surface="code" />}
// Ask / Bypass / Plan sits here, in the CODE composer only (plan
diff --git a/src/components/chat/__tests__/composer-file-mentions.test.tsx b/src/components/chat/__tests__/composer-file-mentions.test.tsx
new file mode 100644
index 00000000..92a4f759
--- /dev/null
+++ b/src/components/chat/__tests__/composer-file-mentions.test.tsx
@@ -0,0 +1,171 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * U8: `@` file mentions in the composer that Chat, Agent and Code share.
+ * Typing `@` opens the file list of the working folder, the arrow keys move,
+ * Enter or Tab picks, Esc closes. A pick puts `@path` into the text and a chip
+ * into the attachment row; the send hands the file on as an ordinary
+ * attachment, and a secret file is refused with a note above the thread.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/composer-file-mentions.test.tsx
+ */
+import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
+
+const tree: Record<string, string> = {
+ 'src/math.ts': 'export const add = (a: number, b: number) => a + b\n',
+ 'src/main.ts': 'import { add } from "./math"\n',
+ 'README.md': '# demo\n',
+ '.env': 'API_KEY=secret\n',
+ 'node_modules/left-pad/index.js': 'module.exports = 1\n',
+}
+
+vi.mock('../../../api/backend', async (importOriginal) => {
+ const real = await importOriginal<typeof import('../../../api/backend')>()
+ return {
+ ...real,
+ backendCall: vi.fn(async (command: string, args: Record<string, unknown>) => {
+ const path = String(args.path)
+ const rel = path === '.' ? '' : path.replace(/^\/proj\/?/, '')
+ if (command === 'fs_list') {
+ const prefix = rel ? `${rel}/` : ''
+ const seen = new Map<string, boolean>()
+ for (const key of Object.keys(tree)) {
+ if (!key.startsWith(prefix)) continue
+ const [first, ...more] = key.slice(prefix.length).split('/')
+ seen.set(first, more.length > 0)
+ }
+ return { entries: [...seen].map(([name, isDir]) => ({ name, path: `/proj/${prefix}${name}`, isDir, size: tree[`${prefix}${name}`]?.length ?? 0, modified: 0 })) }
+ }
+ if (command === 'fs_read') return { encoding: 'utf8', content: tree[rel] }
+ throw new Error(`unexpected ${command}`)
+ }),
+ }
+})
+
+import { ChatInput } from '../ChatInput'
+import { useChatNoticeStore } from '../../../stores/chatNoticeStore'
+import { useSettingsStore } from '../../../stores/settingsStore'
+import { __clearMentionCache } from '../../../lib/file-mentions'
+import type { ChatFileInput } from '../../../lib/chat-files'
+
+beforeEach(() => {
+ __clearMentionCache()
+ useChatNoticeStore.getState().clear()
+ useSettingsStore.getState().updateSettings({ emojiAutoReplace: false })
+})
+afterEach(() => cleanup())
+
+function composer(onSend: (text: string, files?: ChatFileInput[]) => void = () => {}, root: { workingDirectory: string } | null = { workingDirectory: '/proj' }) {
+ const view = render(
+ <ChatInput
+ onSend={(text, _images, files) => onSend(text, files)}
+ onStop={() => {}}
+ isGenerating={false}
+ modelReady={() => true}
+ filesReachTools
+ mentionRoot={root}
+ />,
+ )
+ const field = view.container.querySelector('textarea[data-lu-composer]') as HTMLTextAreaElement
+ const type = (value: string) => {
+ field.setSelectionRange?.(field.value.length, field.value.length)
+ fireEvent.change(field, { target: { value, selectionStart: value.length } })
+ }
+ return { view, field, type }
+}
+
+const rows = (view: ReturnType<typeof render>) => Array.from(view.container.querySelectorAll('[data-testid="mention-row"]'))
+
+describe('@ file mentions in the composer', () => {
+ it('opens the list on @, filters it, and leaves node_modules out', async () => {
+ const { view, type } = composer()
+ type('@')
+ expect(view.getByTestId('mention-menu')).toBeTruthy()
+ await waitFor(() => expect(rows(view).length).toBeGreaterThan(0))
+ expect(rows(view).some((r) => r.textContent?.includes('node_modules'))).toBe(false)
+ type('@math')
+ await waitFor(() => expect(rows(view)[0]?.textContent).toContain('math.ts'))
+ expect(rows(view)[0].getAttribute('aria-selected')).toBe('true')
+ })
+
+ it('moves with the arrow keys, picks with Enter, and the send carries the file', async () => {
+ const sent: { text: string; files?: ChatFileInput[] }[] = []
+ const { view, field, type } = composer((text, files) => sent.push({ text, files }))
+ type('look at @ma')
+ await waitFor(() => expect(rows(view).length).toBe(2))
+ const names = rows(view).map((r) => r.textContent ?? '')
+ fireEvent.keyDown(field, { key: 'ArrowDown' })
+ expect(rows(view)[1].getAttribute('aria-selected')).toBe('true')
+ fireEvent.keyDown(field, { key: 'ArrowUp' })
+ fireEvent.keyDown(field, { key: 'ArrowUp' })
+ expect(rows(view)[1].getAttribute('aria-selected')).toBe('true')
+ const picked = names[1].includes('math.ts') ? 'src/math.ts' : 'src/main.ts'
+ // Enter picks and does not send.
+ fireEvent.keyDown(field, { key: 'Enter' })
+ expect(sent).toEqual([])
+ expect(field.value).toBe(`look at @${picked} `)
+ expect(view.queryByTestId('mention-menu')).toBeNull()
+ await waitFor(() => expect(view.container.querySelector('[data-mention="true"]')?.textContent).toContain(`@${picked}`))
+
+ type(`look at @${picked} what does it do?`)
+ fireEvent.keyDown(field, { key: 'Enter' })
+ expect(sent).toHaveLength(1)
+ expect(sent[0].text).toBe(`look at @${picked} what does it do?`)
+ const file = sent[0].files![0]
+ expect(file.attachment.workspacePath).toBe(picked)
+ expect(file.attachment.summary).toContain(tree[picked].trim())
+ })
+
+ it('picks with Tab and closes with Esc, which stays closed for that word', async () => {
+ const { view, field, type } = composer()
+ type('@READ')
+ await waitFor(() => expect(rows(view).length).toBe(1))
+ fireEvent.keyDown(field, { key: 'Escape' })
+ expect(view.queryByTestId('mention-menu')).toBeNull()
+ type('@READM')
+ expect(view.queryByTestId('mention-menu')).toBeNull()
+ type('@READM @READ')
+ await waitFor(() => expect(rows(view).length).toBe(1))
+ fireEvent.keyDown(field, { key: 'Tab' })
+ expect(field.value).toBe('@READM @README.md ')
+ })
+
+ it('refuses a secret file with a note and adds no chip', async () => {
+ const { view, field, type } = composer()
+ type('@.env')
+ await waitFor(() => expect(rows(view)[0]?.textContent).toContain('private'))
+ fireEvent.keyDown(field, { key: 'Enter' })
+ const notice = useChatNoticeStore.getState().notices.find((n) => n.id === 'file-mention')
+ expect(notice?.text).toBe('.env stays private: it holds environment secrets (.env). LU never sends secret files to a model.')
+ expect(view.container.querySelector('[data-mention="true"]')).toBeNull()
+ })
+
+ it('takes the chip away when its token is deleted, and the token when the chip is removed', async () => {
+ const { view, field, type } = composer()
+ type('@README')
+ await waitFor(() => expect(rows(view).length).toBe(1))
+ fireEvent.keyDown(field, { key: 'Enter' })
+ await waitFor(() => expect(view.container.querySelector('[data-mention="true"]')).not.toBeNull())
+ type('')
+ expect(view.container.querySelector('[data-mention="true"]')).toBeNull()
+
+ type('fix @README')
+ await waitFor(() => expect(rows(view).length).toBe(1))
+ fireEvent.keyDown(field, { key: 'Enter' })
+ await waitFor(() => expect(view.container.querySelector('[data-mention="true"]')).not.toBeNull())
+ await act(async () => { fireEvent.click(view.getByLabelText('Remove README.md')) })
+ expect(field.value).toBe('fix ')
+ })
+
+ it('says so when no working folder is known, and stays off where mentions are off', () => {
+ const { view, type } = composer(() => {}, null)
+ type('@')
+ expect(view.getByTestId('mention-menu').textContent).toContain('No working folder yet')
+ cleanup()
+ const off = render(<ChatInput onSend={() => {}} onStop={() => {}} isGenerating={false} modelReady={() => true} />)
+ const field = off.container.querySelector('textarea[data-lu-composer]') as HTMLTextAreaElement
+ fireEvent.change(field, { target: { value: '@' } })
+ expect(off.queryByTestId('mention-menu')).toBeNull()
+ })
+})
diff --git a/src/hooks/useMentionRoot.ts b/src/hooks/useMentionRoot.ts
new file mode 100644
index 00000000..04fef237
--- /dev/null
+++ b/src/hooks/useMentionRoot.ts
@@ -0,0 +1,50 @@
+import { useMemo } from 'react'
+import { resolveWorkspace, resolveWorkspacePath } from '../api/agents/workspace-resolve'
+import { resolveCodexWorkspace } from './codex/workspace-precedence'
+import { useAgentModeStore } from '../stores/agentModeStore'
+import { useChatStore } from '../stores/chatStore'
+import { useCodexStore } from '../stores/codexStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import type { MentionRoot } from '../lib/file-mentions'
+
+/**
+ * Which folder the `@` list of a composer reads (U8). The SAME precedence the
+ * run uses, so the list never shows files of a folder the model does not
+ * work in:
+ *
+ * Code tab: hooks/codex/workspace-precedence.ts (Explorer pick first).
+ * Chat: api/agents/workspace-resolve.ts (folder pinned on this chat,
+ * then the default folder).
+ *
+ * Without a real folder, Agent mode and Code fall back to the per-chat
+ * sandbox once a run of this chat has named it (the slug is pinned then);
+ * looking never creates one. Plain chat offers mentions only when a real
+ * folder is known: it has no sandbox of its own.
+ *
+ * Returns null when nothing can be listed (the popup says so) and undefined
+ * when this surface has no mentions at all.
+ */
+export function useMentionRoot(surface: 'code' | 'agent' | 'chat'): MentionRoot | null | undefined {
+ const conversationId = useChatStore((s) => s.activeConversationId)
+ const perChat = useAgentModeStore((s) => (conversationId ? s.workspaces[conversationId] : undefined))
+ const slug = useAgentModeStore((s) => (conversationId ? s.workspaceSlugs?.[conversationId] : undefined))
+ const defaultWorkspace = useSettingsStore((s) => s.settings.defaultWorkspace)
+ const threadDir = useCodexStore((s) => (conversationId ? s.threads[conversationId]?.workingDirectory : undefined))
+ const storeDir = useCodexStore((s) => s.workingDirectory)
+
+ return useMemo(() => {
+ if (surface === 'code') {
+ const { workDir } = resolveCodexWorkspace({
+ threadWorkingDirectory: threadDir,
+ codexWorkspace: resolveWorkspace({ perChat, defaultWorkspace }),
+ storeWorkingDirectory: storeDir,
+ })
+ if (workDir && workDir !== '.') return { workingDirectory: workDir }
+ return slug ? { chatId: slug } : null
+ }
+ const folder = resolveWorkspacePath({ perChat, defaultWorkspace })
+ if (folder) return { workingDirectory: folder }
+ if (surface === 'agent') return slug ? { chatId: slug } : null
+ return undefined
+ }, [surface, threadDir, perChat, defaultWorkspace, storeDir, slug])
+}
diff --git a/src/lib/__tests__/file-mentions.test.ts b/src/lib/__tests__/file-mentions.test.ts
new file mode 100644
index 00000000..ac9cddeb
--- /dev/null
+++ b/src/lib/__tests__/file-mentions.test.ts
@@ -0,0 +1,185 @@
+/**
+ * U8: `@` file mentions. The trigger, the filter, the walk of the folder and
+ * what a pick turns into: the same attachment a dropped file is, so the text
+ * reaches the model as one delimited file block while the bubble keeps what
+ * was typed. Secret files and binaries are refused with a short note.
+ *
+ * Run: npx vitest run src/lib/__tests__/file-mentions.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import {
+ MENTION_TEXT_CAP, buildMentionIndex, hasMentionToken, insertMention, loadMention, mentionAt, mentionIndexFor,
+ mentionScore, rankMentions, removeMentionToken, __clearMentionCache,
+ type FsCall, type MentionEntry,
+} from '../file-mentions'
+import { fileMessageFields, placeChatFiles } from '../chat-files'
+
+/** A folder in memory, the way fs_list and fs_read answer for it. */
+function fakeFs(tree: Record<string, string | null>, root = '/proj'): { fs: FsCall; calls: string[] } {
+ const calls: string[] = []
+ const fs = (async (command: string, args: Record<string, unknown>) => {
+ const path = String(args.path)
+ const abs = path === '.' ? root : path
+ calls.push(`${command} ${abs}`)
+ if (command === 'fs_list') {
+ const prefix = `${abs}/`
+ const names = new Map<string, boolean>()
+ for (const key of Object.keys(tree)) {
+ const full = `${root}/${key}`
+ if (!full.startsWith(prefix)) continue
+ const rest = full.slice(prefix.length)
+ const [first, ...more] = rest.split('/')
+ names.set(first, more.length > 0 || tree[key] === null)
+ }
+ return { entries: [...names].map(([name, isDir]) => ({ name, path: `${prefix}${name}`, isDir, size: isDir ? 0 : (tree[`${abs.slice(root.length + 1) ? `${abs.slice(root.length + 1)}/` : ''}${name}`] ?? '').length, modified: 0 })) }
+ }
+ if (command === 'fs_read') {
+ const rel = abs.slice(root.length + 1)
+ const content = tree[rel]
+ if (typeof content !== 'string') throw new Error('not found')
+ if (content.startsWith('BINARY')) return { encoding: 'binary', bytes: 10 }
+ return { encoding: 'utf8', content }
+ }
+ throw new Error(`unexpected ${command}`)
+ }) as FsCall
+ return { fs, calls }
+}
+
+const entry = (rel: string, isDir = false, depth = rel.split('/').length, modified = 0): MentionEntry =>
+ ({ rel, abs: `/proj/${rel}`, isDir, size: 1, modified, depth })
+
+beforeEach(() => __clearMentionCache())
+
+describe('the trigger', () => {
+ it('opens at the start and after whitespace, never inside a word', () => {
+ expect(mentionAt('@', 1)).toEqual({ start: 0, query: '' })
+ expect(mentionAt('look at @src/ma', 15)).toEqual({ start: 8, query: 'src/ma' })
+ expect(mentionAt('(@mat', 5)).toEqual({ start: 1, query: 'mat' })
+ expect(mentionAt('mail [email protected]', 16)).toBeNull()
+ expect(mentionAt('@src/math.ts done', 17)).toBeNull()
+ expect(mentionAt('plain text', 10)).toBeNull()
+ })
+
+ it('follows the caret, not the end of the text', () => {
+ expect(mentionAt('@ab then more', 3)).toEqual({ start: 0, query: 'ab' })
+ })
+
+ it('puts the token and a space in place of the typed query', () => {
+ const at = mentionAt('see @ma please', 7)!
+ expect(insertMention('see @ma please', at, 7, 'src/math.ts')).toEqual({ text: 'see @src/math.ts please', caret: 17 })
+ const end = mentionAt('@m', 2)!
+ expect(insertMention('@m', end, 2, 'my notes.md').text).toBe('@"my notes.md" ')
+ })
+
+ it('knows whether a token still stands, and takes it out', () => {
+ expect(hasMentionToken('fix @src/math.ts now', 'src/math.ts')).toBe(true)
+ expect(hasMentionToken('fix @src/math.ts.', 'src/math.ts')).toBe(true)
+ expect(hasMentionToken('fix @src/math.tsx', 'src/math.ts')).toBe(false)
+ expect(hasMentionToken('fix src/math.ts', 'src/math.ts')).toBe(false)
+ expect(removeMentionToken('fix @src/math.ts now', 'src/math.ts')).toBe('fix now')
+ })
+})
+
+describe('the filter', () => {
+ it('ranks a name match above a fuzzy path match, and drops what does not match', () => {
+ expect(mentionScore('math', 'src/math.ts')!).toBeGreaterThan(mentionScore('math', 'src/my-app/thing.ts') ?? -1)
+ expect(mentionScore('xyz', 'src/math.ts')).toBeNull()
+ expect(mentionScore('smt', 'src/math.ts')).not.toBeNull()
+ })
+
+ it('shows shallow and recent first without a query, and at most the limit', () => {
+ const rows = rankMentions([entry('a/b/c/deep.ts', false, 4), entry('README.md', false, 1, 5), entry('index.ts', false, 1, 9)], '')
+ expect(rows.map((r) => r.rel)).toEqual(['index.ts', 'README.md', 'a/b/c/deep.ts'])
+ const many = Array.from({ length: 120 }, (_, i) => entry(`f${i}.ts`))
+ expect(rankMentions(many, 'f')).toHaveLength(50)
+ })
+})
+
+describe('reading the folder', () => {
+ it('walks breadth first and never lists node_modules, .git or dist', async () => {
+ const { fs, calls } = fakeFs({
+ 'src/math.ts': 'x', 'src/lib/deep.ts': 'y', 'README.md': 'r',
+ 'node_modules/react/index.js': 'z', '.git/HEAD': 'h', 'dist/app.js': 'd',
+ })
+ const index = await buildMentionIndex({ workingDirectory: '/proj' }, fs)
+ const rels = index.entries.map((e) => e.rel)
+ expect(rels).toEqual(expect.arrayContaining(['src', 'src/math.ts', 'src/lib', 'src/lib/deep.ts', 'README.md']))
+ expect(rels.some((r) => /node_modules|\.git|dist/.test(r))).toBe(false)
+ expect(calls.some((c) => c.includes('node_modules'))).toBe(false)
+ expect(index.entries.find((e) => e.rel === 'README.md')!.depth).toBeLessThan(index.entries.find((e) => e.rel === 'src/lib/deep.ts')!.depth)
+ })
+
+ it('reads a root once while the cache is fresh', async () => {
+ const { fs, calls } = fakeFs({ 'a.ts': 'a' })
+ await mentionIndexFor({ workingDirectory: '/proj' }, fs, 1000)
+ await mentionIndexFor({ workingDirectory: '/proj' }, fs, 2000)
+ expect(calls.filter((c) => c.startsWith('fs_list'))).toHaveLength(1)
+ })
+})
+
+describe('a pick becomes an attachment', () => {
+ const root = { workingDirectory: '/proj' }
+
+ it('carries path and content to the model, while the bubble shows what was typed', async () => {
+ const { fs } = fakeFs({ 'src/math.ts': 'export const add = (a, b) => a + b\n' })
+ const result = await loadMention(root, entry('src/math.ts'), fs)
+ expect(result.ok).toBe(true)
+ if (!result.ok) return
+ expect(result.input.mention).toBe('src/math.ts')
+ expect(result.input.attachment).toMatchObject({ name: 'src/math.ts', workspacePath: 'src/math.ts', textChars: 35 })
+ // Already in the folder: the send never copies it again.
+ const placed = await placeChatFiles([result.input], { chatId: 'c1' })
+ expect(placed.failed).toEqual([])
+ const fields = fileMessageFields('@src/math.ts why is this slow?', placed.files, 'workspace')
+ expect(fields.displayContent).toBe('@src/math.ts why is this slow?')
+ expect(fields.content).toContain('[Attached file: src/math.ts]')
+ expect(fields.content).toContain('Path in your working folder: src/math.ts')
+ expect(fields.content).toContain('export const add = (a, b) => a + b')
+ expect(fields.content).toContain('[End of attached file: src/math.ts]')
+ expect(fields.files![0].name).toBe('src/math.ts')
+ })
+
+ it('cuts a long text at the cap and says so', async () => {
+ const big = 'a'.repeat(MENTION_TEXT_CAP + 500)
+ const { fs } = fakeFs({ 'big.txt': big })
+ const result = await loadMention(root, entry('big.txt'), fs)
+ if (!result.ok) throw new Error('expected ok')
+ expect(result.input.attachment.includedChars).toBe(MENTION_TEXT_CAP)
+ expect(result.input.attachment.textChars).toBe(big.length)
+ expect(result.input.attachment.summary).toMatch(/^Only the first 65,536 of 66,036 characters/)
+ })
+
+ it('refuses a binary with a short note', async () => {
+ const { fs, calls } = fakeFs({ 'logo.png': 'BINARY', 'blob.dat': 'BINARY', 'nul.txt': 'a\u0000b' })
+ expect(await loadMention(root, entry('logo.png'), fs)).toEqual({ ok: false, note: 'logo.png is not a text file, so it was not attached. Use the clip to attach it instead.' })
+ // By its ending: not even read.
+ expect(calls).toEqual([])
+ expect((await loadMention(root, entry('blob.dat'), fs)).ok).toBe(false)
+ expect((await loadMention(root, entry('nul.txt'), fs)).ok).toBe(false)
+ })
+
+ it('refuses secret files with the C59 rules, before anything is read', async () => {
+ const { fs, calls } = fakeFs({ '.env': 'KEY=1', 'config/.env.local': 'K=2', 'certs/server.pem': 'x', '.ssh/id_rsa': 'k', '.env.example': 'KEY=' })
+ for (const rel of ['.env', 'config/.env.local', 'certs/server.pem', '.ssh/id_rsa']) {
+ const result = await loadMention(root, entry(rel), fs)
+ expect(result.ok).toBe(false)
+ if (!result.ok) expect(result.note).toMatch(/stays private: it holds .+\. LU never sends secret files to a model\./)
+ }
+ expect(calls).toEqual([])
+ // The examples projects ship are fine.
+ expect((await loadMention(root, entry('.env.example'), fs)).ok).toBe(true)
+ })
+
+ it('turns a folder into a short listing, without the ignored folders and secret files', async () => {
+ const { fs } = fakeFs({ 'src/math.ts': 'x', 'src/util/a.ts': 'y', 'src/node_modules/z.js': 'z', 'src/.env': 'K=1' })
+ const result = await loadMention(root, entry('src', true), fs)
+ if (!result.ok) throw new Error('expected ok')
+ expect(result.input.mention).toBe('src/')
+ expect(result.input.attachment).toMatchObject({ name: 'src/', kind: 'Folder listing', workspacePath: 'src/' })
+ const summary = result.input.attachment.summary
+ expect(summary).toContain('util/')
+ expect(summary).toContain('math.ts (1 bytes)')
+ expect(summary).not.toContain('node_modules')
+ expect(summary).not.toContain('.env')
+ })
+})
diff --git a/src/lib/chat-files.ts b/src/lib/chat-files.ts
index 55373222..8c7fb59c 100644
--- a/src/lib/chat-files.ts
+++ b/src/lib/chat-files.ts
@@ -87,6 +87,9 @@ export interface ChatFileInput {
file?: File
/** One sentence for the user when the file could not be read the way it should be. Not stored. */
notice?: string
+ /** Set for an `@` mention (lib/file-mentions.ts): the path in the working
+ * folder whose token stands in the text. The chip goes with the token. */
+ mention?: string
}
/** Reads the text of a PDF or a Word file. Handed in by the phone, which has the reader of the documents of a chat. */
diff --git a/src/lib/file-mentions.ts b/src/lib/file-mentions.ts
new file mode 100644
index 00000000..670366f3
--- /dev/null
+++ b/src/lib/file-mentions.ts
@@ -0,0 +1,411 @@
+/**
+ * `@` file mentions in the composer (U8, like Claude Code, Cursor and Zed).
+ *
+ * Typing `@` at the start of the field or after a space opens a list of the
+ * files of the working folder. A picked file becomes a token in the text
+ * (`@src/math.ts`) and a chip in the attachment row, and it travels the SAME
+ * way as a file dropped onto the composer: one `ChatFileInput` in the draft,
+ * one block in the user message (lib/chat-files.ts, `fileBlock`). There is no
+ * second path to the model.
+ *
+ * What is different from a dropped file: the file is already in the working
+ * folder, so the attachment carries its `workspacePath` from the start and
+ * `placeChatFiles` never copies it. A mention is text only: a binary file is
+ * refused with a short note (the clip is the way for those), and a secret
+ * file (.env, keys, tokens) is refused by the same rules that stop the
+ * agent's own tools (lib/secret-paths.ts, C59).
+ *
+ * The folder is read with `fs_list` one level at a time, the way the Explorer
+ * does, so node_modules and friends are skipped before they are listed: a
+ * recursive listing stops at 500 entries, and one npm install fills that on
+ * its own.
+ */
+import { backendCall } from '../api/backend'
+import type { FsListResult, FsReadResult } from '../types/bridge'
+import type { FileAttachment } from '../types/chat'
+import type { ChatFileInput } from './chat-files'
+import { cutTextSummary, wholeTextSummary } from './chat-files'
+import { EXPLORER_IGNORED, FS_LIST_CAP } from './explorer-tree'
+import { detectFileKind } from './file-magic'
+import { secretPathReason } from './secret-paths'
+
+/** Where the files of a mention come from, in the words the fs commands take. */
+export interface MentionRoot {
+ /** The real project folder (Code tab, a pinned Agent folder). */
+ workingDirectory?: string
+ /** The per-chat sandbox, when no real folder is set. */
+ chatId?: string
+}
+
+/** One file or folder of the working folder, as the popup lists it. */
+export interface MentionEntry {
+ /** Path inside the working folder, forward slashes, no leading `./`. */
+ rel: string
+ /** The path the backend named; handed back verbatim when it is read. */
+ abs: string
+ isDir: boolean
+ size: number
+ /** Unix seconds, 0 when unknown. */
+ modified: number
+ depth: number
+}
+
+export interface MentionIndex {
+ entries: MentionEntry[]
+ /** The walk stopped at one of its limits, so the list is not the whole folder. */
+ truncated: boolean
+}
+
+/** A text mention goes out up to this many characters, the rest is cut with a note. */
+export const MENTION_TEXT_CAP = 64 * 1024
+/** Rows the popup shows at most. */
+export const MENTION_MENU_MAX = 50
+/** Mentions one message may carry. Dropped files have their own limit. */
+export const MAX_MENTIONS = 5
+/** Lines of a folder listing at most. */
+export const MENTION_FOLDER_MAX = 200
+
+/** The walk's limits: files collected, folders listed, depth. */
+const WALK_MAX_FILES = 5000
+const WALK_MAX_DIRS = 400
+const WALK_MAX_DEPTH = 8
+
+/**
+ * Folders nobody means when they type `@`: the Explorer's list
+ * (lib/explorer-tree.ts) plus the caches and environments of other stacks.
+ */
+export const MENTION_IGNORED: ReadonlySet<string> = new Set([
+ ...EXPLORER_IGNORED,
+ '.next', '.nuxt', '.svelte-kit', '.turbo', '.cache', '.parcel-cache', 'coverage',
+ '.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', '.tox',
+ '.gradle', '.idea', '.DS_Store', 'Thumbs.db',
+])
+
+/** Endings that are never text, refused before a byte is read. */
+const BINARY_ENDINGS = new Set([
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'icns', 'tif', 'tiff', 'psd', 'heic',
+ 'mp3', 'wav', 'flac', 'ogg', 'm4a', 'mp4', 'mov', 'mkv', 'webm', 'avi',
+ 'zip', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar', 'tar', 'dmg', 'iso', 'jar',
+ 'exe', 'dll', 'so', 'dylib', 'bin', 'o', 'a', 'class', 'wasm', 'pyc',
+ 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt',
+ 'ttf', 'otf', 'woff', 'woff2', 'sqlite', 'db', 'safetensors', 'gguf', 'ckpt', 'pt', 'onnx',
+])
+
+/* ---------- the trigger ---------- */
+
+export interface MentionQuery {
+ /** Index of the `@` in the text. */
+ start: number
+ /** What was typed after the `@`, up to the caret. */
+ query: string
+}
+
+/**
+ * The mention the caret is in, or null. An `@` counts at the start of the
+ * text or after whitespace or an opening bracket, so `[email protected]` never
+ * opens the list. The query ends at the caret and holds no whitespace.
+ */
+export function mentionAt(text: string, caret: number | null | undefined): MentionQuery | null {
+ const end = caret == null ? text.length : Math.max(0, Math.min(caret, text.length))
+ let i = end - 1
+ while (i >= 0 && !/\s/.test(text[i]) && text[i] !== '@') i--
+ if (i < 0 || text[i] !== '@') return null
+ const before = i === 0 ? '' : text[i - 1]
+ if (before && !/[\s([{]/.test(before)) return null
+ const query = text.slice(i + 1, end)
+ if (query.includes('@')) return null
+ return { start: i, query }
+}
+
+/** The path a pick stands for in the field: a folder ends in `/`. */
+export function mentionPath(entry: Pick<MentionEntry, 'rel' | 'isDir'>): string {
+ return entry.isDir ? `${entry.rel.replace(/\/+$/, '')}/` : entry.rel
+}
+
+/** The text of a mention as it stands in the field. Paths with spaces are quoted. */
+export function mentionToken(rel: string): string {
+ return /\s/.test(rel) ? `@"${rel}"` : `@${rel}`
+}
+
+const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+
+/** Whether the field still holds the token of `rel` as a word of its own. */
+export function hasMentionToken(text: string, rel: string): boolean {
+ const re = new RegExp(`(^|[\\s([{])${escapeRe(mentionToken(rel))}(?=$|[\\s,;:!?)\\]}'"]|\\.(?:\\s|$))`)
+ return re.test(text)
+}
+
+/** The field without the token of `rel` (the chip's x takes both away). */
+export function removeMentionToken(text: string, rel: string): string {
+ const re = new RegExp(`(^|[\\s([{])${escapeRe(mentionToken(rel))} ?`)
+ return text.replace(re, '$1')
+}
+
+/**
+ * The field after a pick: the typed `@query` becomes the token plus a space,
+ * and the caret goes behind it.
+ */
+export function insertMention(text: string, at: MentionQuery, caret: number, rel: string): { text: string; caret: number } {
+ const token = `${mentionToken(rel)} `
+ const tail = text.slice(Math.max(caret, at.start)).replace(/^\S*/, '').replace(/^ /, '')
+ const head = text.slice(0, at.start)
+ return { text: head + token + tail, caret: head.length + token.length }
+}
+
+/* ---------- the filter ---------- */
+
+/** A score for `query` against `rel`; higher is better, null is no match. */
+export function mentionScore(query: string, rel: string): number | null {
+ const q = query.toLowerCase().replace(/^\.\//, '')
+ if (!q) return 0
+ const path = rel.toLowerCase()
+ const base = path.replace(/\/$/, '').split('/').pop() ?? path
+ if (base === q || path === q) return 1000
+ if (base.startsWith(q)) return 800 - base.length
+ if (path.startsWith(q)) return 700 - path.length
+ const inBase = base.indexOf(q)
+ if (inBase >= 0) return 600 - inBase
+ const inPath = path.indexOf(q)
+ if (inPath >= 0) return 500 - inPath
+ // Fuzzy: every character in order. A run of matches and a match at the
+ // start of a segment count more; gaps count against.
+ let score = 300
+ let at = -1
+ let run = 0
+ for (const ch of q) {
+ const next = path.indexOf(ch, at + 1)
+ if (next < 0) return null
+ if (next === at + 1) run++
+ else { score -= Math.min(next - at - 1, 20); run = 0 }
+ if (next === 0 || path[next - 1] === '/' || path[next - 1] === '.' || path[next - 1] === '-' || path[next - 1] === '_') score += 4
+ score += run * 2
+ at = next
+ }
+ return score
+}
+
+/**
+ * The rows for the popup: matching entries, best first. Without a query the
+ * shallow and the recently changed come first, so `@` alone shows the top of
+ * the project instead of a deep file nobody looks for.
+ */
+export function rankMentions(entries: readonly MentionEntry[], query: string, limit = MENTION_MENU_MAX): MentionEntry[] {
+ const scored: { e: MentionEntry; s: number }[] = []
+ for (const e of entries) {
+ const s = mentionScore(query, e.isDir ? `${e.rel}/` : e.rel)
+ if (s !== null) scored.push({ e, s })
+ }
+ scored.sort((a, b) =>
+ b.s - a.s
+ || a.e.depth - b.e.depth
+ || b.e.modified - a.e.modified
+ || a.e.rel.length - b.e.rel.length
+ || a.e.rel.localeCompare(b.e.rel))
+ return scored.slice(0, limit).map((x) => x.e)
+}
+
+/* ---------- reading the folder ---------- */
+
+export type FsCall = <T>(command: string, args: Record<string, unknown>) => Promise<T>
+
+const defaultFs: FsCall = (command, args) => backendCall(command, args)
+
+/** A stable key for a root, for the cache and for React. */
+export function mentionRootKey(root: MentionRoot | null | undefined): string {
+ if (!root) return ''
+ return root.workingDirectory ? `dir:${root.workingDirectory}` : root.chatId ? `chat:${root.chatId}` : ''
+}
+
+/**
+ * Walk the working folder breadth first, one `fs_list` per folder, skipping
+ * the ignored folders before they are listed. Stops at its limits and says so.
+ */
+export async function buildMentionIndex(root: MentionRoot, fs: FsCall = defaultFs): Promise<MentionIndex> {
+ const entries: MentionEntry[] = []
+ let truncated = false
+ let listed = 0
+ const queue: { path: string; rel: string; depth: number }[] = [{ path: '.', rel: '', depth: 0 }]
+ while (queue.length > 0) {
+ if (listed >= WALK_MAX_DIRS || entries.length >= WALK_MAX_FILES) { truncated = true; break }
+ const dir = queue.shift()!
+ listed++
+ let data: FsListResult | null
+ try {
+ data = await fs<FsListResult>('fs_list', { path: dir.path, recursive: false, pattern: null, ...root })
+ } catch (err) {
+ // The root itself unreadable is an error for the caller; a subfolder is skipped.
+ if (dir.depth === 0) throw err
+ continue
+ }
+ const raw = Array.isArray(data?.entries) ? data!.entries : []
+ if (raw.length >= FS_LIST_CAP) truncated = true
+ for (const item of raw) {
+ const name = typeof item?.name === 'string' ? item.name : ''
+ if (!name || name === '.' || name === '..' || MENTION_IGNORED.has(name)) continue
+ const rel = dir.rel ? `${dir.rel}/${name}` : name
+ const depth = dir.depth + 1
+ const entry: MentionEntry = {
+ rel,
+ abs: typeof item.path === 'string' && item.path ? item.path : rel,
+ isDir: !!item.isDir,
+ size: typeof item.size === 'number' ? item.size : 0,
+ modified: typeof item.modified === 'number' ? item.modified : 0,
+ depth,
+ }
+ entries.push(entry)
+ if (entry.isDir && depth < WALK_MAX_DEPTH) queue.push({ path: entry.abs, rel, depth })
+ if (entries.length >= WALK_MAX_FILES) { truncated = true; break }
+ }
+ }
+ return { entries, truncated }
+}
+
+const CACHE_MS = 15_000
+const cache = new Map<string, { at: number; index: Promise<MentionIndex> }>()
+
+/** The index of a root, read again after a few seconds so new files show up. */
+export function mentionIndexFor(root: MentionRoot, fs: FsCall = defaultFs, now = Date.now()): Promise<MentionIndex> {
+ const key = mentionRootKey(root)
+ const hit = cache.get(key)
+ if (hit && now - hit.at < CACHE_MS) return hit.index
+ const index = buildMentionIndex(root, fs)
+ cache.set(key, { at: now, index })
+ index.catch(() => cache.delete(key))
+ return index
+}
+
+/** Only for tests. */
+export function __clearMentionCache(): void {
+ cache.clear()
+}
+
+/* ---------- a pick becomes an attachment ---------- */
+
+export type MentionResult =
+ | { ok: true; input: ChatFileInput }
+ | { ok: false; note: string }
+
+/** One path as a harmless label: no control characters, no brackets that could end the block early. */
+export function mentionLabel(rel: string): string {
+ const clean = Array.from(rel, (c) => (c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f ? ' ' : c))
+ .join('')
+ .replace(/[[\]]/g, '_')
+ .trim()
+ if (!clean) return 'file'
+ return clean.length > 160 ? `...${clean.slice(-157)}` : clean
+}
+
+/** Why a mention may not be sent, or null. Checks the path in the folder and the path the backend named. */
+export function mentionSecretReason(entry: Pick<MentionEntry, 'rel' | 'abs'>): string | null {
+ return secretPathReason(entry.rel) ?? secretPathReason(entry.abs)
+}
+
+export function secretMentionNote(rel: string, why: string): string {
+ return `${rel} stays private: it holds ${why}. LU never sends secret files to a model.`
+}
+
+export function binaryMentionNote(rel: string): string {
+ return `${rel} is not a text file, so it was not attached. Use the clip to attach it instead.`
+}
+
+export function unreadableMentionNote(rel: string): string {
+ return `${rel} could not be read.`
+}
+
+export const TOO_MANY_MENTIONS_MESSAGE = `You can mention up to ${MAX_MENTIONS} files per message.`
+
+const ending = (rel: string) => /\.([a-z0-9]+)$/i.exec(rel)?.[1]?.toLowerCase() ?? ''
+
+/** Text that came out of a binary: a NUL, or many replacement characters. */
+export function looksBinaryText(text: string): boolean {
+ if (text.includes('\u0000')) return true
+ const sample = text.slice(0, 8192)
+ if (!sample) return false
+ let bad = 0
+ for (const ch of sample) if (ch === '�') bad++
+ return bad / sample.length > 0.02
+}
+
+async function sha256Text(text: string): Promise<string> {
+ const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')
+}
+
+/** Pure: the summary of a text mention, whole or cut at the cap with a note. */
+export function mentionTextFields(text: string): Pick<FileAttachment, 'summary' | 'textChars' | 'includedChars'> {
+ if (text.length === 0) return { summary: 'The file is empty.' }
+ if (text.length <= MENTION_TEXT_CAP) return { summary: wholeTextSummary(text), textChars: text.length }
+ const held = text.slice(0, MENTION_TEXT_CAP)
+ return { summary: cutTextSummary(held, text.length, 'size'), textChars: text.length, includedChars: held.length }
+}
+
+/** Pure: the listing of a folder as the model reads it. */
+export function folderListing(rel: string, items: readonly { name: string; isDir: boolean; size: number }[]): string {
+ const shown = items.slice(0, MENTION_FOLDER_MAX)
+ const lines = shown.map((i) => (i.isDir ? `${i.name}/` : `${i.name} (${i.size} bytes)`))
+ const more = items.length > shown.length ? `\n(${items.length - shown.length} more entries not shown.)` : ''
+ return `The folder ${rel}/ in the working folder, one level, ${items.length} entries:\n${lines.join('\n')}${more}`
+}
+
+/**
+ * Read a picked entry and turn it into the attachment a dropped file would
+ * be. Never throws: a refusal comes back as one short sentence for the user.
+ */
+export async function loadMention(root: MentionRoot, entry: MentionEntry, fs: FsCall = defaultFs): Promise<MentionResult> {
+ const rel = entry.isDir ? entry.rel.replace(/\/+$/, '') : entry.rel
+ const label = mentionLabel(rel)
+ const why = mentionSecretReason(entry)
+ if (why) return { ok: false, note: secretMentionNote(label, why) }
+
+ if (entry.isDir) {
+ let data: FsListResult | null
+ try {
+ data = await fs<FsListResult>('fs_list', { path: entry.abs, recursive: false, pattern: null, ...root })
+ } catch {
+ return { ok: false, note: unreadableMentionNote(label) }
+ }
+ const items = (Array.isArray(data?.entries) ? data!.entries : [])
+ .filter((i) => typeof i?.name === 'string' && i.name && !MENTION_IGNORED.has(i.name))
+ // A secret file is not named in a listing either.
+ .filter((i) => !secretPathReason(`${rel}/${i.name}`))
+ .map((i) => ({ name: i.name, isDir: !!i.isDir, size: typeof i.size === 'number' ? i.size : 0 }))
+ .sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1))
+ const summary = folderListing(label, items)
+ return {
+ ok: true,
+ input: {
+ // The size is that of the listing the model gets, not of the folder.
+ attachment: { name: `${label}/`, size: new TextEncoder().encode(summary).length, kind: 'Folder listing', sha256: await sha256Text(summary), summary, workspacePath: `${rel}/` },
+ mention: mentionPath(entry),
+ },
+ }
+ }
+
+ if (BINARY_ENDINGS.has(ending(rel))) return { ok: false, note: binaryMentionNote(label) }
+ let read: FsReadResult | null
+ try {
+ read = await fs<FsReadResult>('fs_read', { path: entry.abs, ...root })
+ } catch {
+ return { ok: false, note: unreadableMentionNote(label) }
+ }
+ if (!read || read.encoding !== 'utf8' || typeof read.content !== 'string') return { ok: false, note: binaryMentionNote(label) }
+ const text = read.content
+ if (looksBinaryText(text)) return { ok: false, note: binaryMentionNote(label) }
+ const bytes = new TextEncoder().encode(text)
+ const kind = detectFileKind(bytes.subarray(0, 64 * 1024), rel)
+ if (!kind.isText && bytes.length > 0) return { ok: false, note: binaryMentionNote(label) }
+ return {
+ ok: true,
+ input: {
+ attachment: {
+ name: label,
+ size: bytes.length,
+ kind: bytes.length === 0 ? 'Empty file' : kind.label,
+ sha256: await sha256Text(text),
+ ...mentionTextFields(text),
+ workspacePath: rel,
+ },
+ mention: rel,
+ },
+ }
+}
diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.ts
index a4793e5c..7dcccf21 100644
--- a/src/stores/chatNoticeStore.ts
+++ b/src/stores/chatNoticeStore.ts
@@ -34,7 +34,7 @@ import { useChatStore } from './chatStore'
/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst
* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */
-export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save'
+export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention'
export interface ChatNotice {
id: ChatNoticeId