Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions console/web/src/components/chat/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { ChatBackend } from '@/lib/backend'
import { predictedUserEntryId } from '@/lib/backend/harness-send'
import type { CompactResult } from '@/lib/backend/types'
import { useConversationsCtxOptional } from '@/lib/conversations-context'
import { expandFileMentions, parseFileMentions } from '@/lib/file-mentions'
import { formatStopReason } from '@/lib/format-stop-reason'
import { newMessageId } from '@/lib/session-id'
import { cn } from '@/lib/utils'
Expand Down Expand Up @@ -357,6 +358,42 @@ export function ChatView({
return
}

// Expand `#file(...)` mentions into attachment blocks (real backend
// with a working dir only). Failures never block the send — a failed
// mention becomes a placeholder block plus a warn notice.
let attachedBlocks: string[] | undefined
const workingDir = conversation.workingDir
const mentionPaths =
backend.id === 'real' && workingDir
? parseFileMentions(payload.text)
: []
if (workingDir && mentionPaths.length > 0) {
const expanded = await expandFileMentions(workingDir, mentionPaths)
attachedBlocks = expanded.blocks
if (expanded.attachments.length > 0) {
onPatchMessage(conversationId, userMsg.id, {
attachments: [
...(userMsg.attachments ?? []),
...expanded.attachments.map((a) => ({
id: `mention-${a.path}`,
name: a.path,
size: a.size,
type: 'text/x-file-mention',
})),
],
})
}
for (const failure of expanded.failures) {
onAppendMessage(
conversationId,
makeSystemNotice(
`could not attach ${failure.path} — ${failure.reason}`,
'warn',
),
)
}
}

const controller = new AbortController()
abortRef.current = controller
setIsStreaming(true)
Expand All @@ -380,6 +417,9 @@ export function ChatView({
thinkingLevel,
workingDir: conversation.workingDir,
approvalGateAvailable: approvalEnabled,
...(attachedBlocks && attachedBlocks.length > 0
? { attachedBlocks }
: {}),
},
)) {
switch (event.kind) {
Expand Down
1 change: 1 addition & 0 deletions console/web/src/components/chat/Composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ export function Composer({
disabled={inputDisabled}
initialContent={initialContent}
functionEntries={functionEntries}
workingDir={workingDir}
/>
</div>

Expand Down
12 changes: 11 additions & 1 deletion console/web/src/components/chat/LexicalShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import {
} from 'lexical'
import { useEffect, useMemo, useRef } from 'react'
import type { FunctionEntry } from '@/lib/functions'
import { FileMentionNode } from './lexical/FileMentionNode'
import { FileMentionsPlugin } from './lexical/FileMentionsPlugin'
import { FileMentionTransformPlugin } from './lexical/FileMentionTransformPlugin'
import { FunctionMentionNode } from './lexical/FunctionMentionNode'
import { FunctionMentionTransformPlugin } from './lexical/FunctionMentionTransformPlugin'
import { MentionsPlugin } from './lexical/MentionsPlugin'
Expand All @@ -32,7 +35,7 @@ const baseConfig = {
/* no theme classes — surface inherits Chivo Mono from <body> */
theme: {},
/* Decorator nodes must be registered up-front so importJSON/restore work. */
nodes: [FunctionMentionNode],
nodes: [FunctionMentionNode, FileMentionNode],
onError(error: Error) {
console.error(error)
},
Expand Down Expand Up @@ -126,6 +129,8 @@ interface LexicalShellExtendedProps extends LexicalShellProps {
/** Optional one-shot initializer that runs once on mount inside the editor. */
initialContent?: (editor: LexicalEditor) => void
functionEntries?: FunctionEntry[]
/** Enables the `#` file-mention typeahead, scoped to this directory. */
workingDir?: string | null
}

export function LexicalShell({
Expand All @@ -136,6 +141,7 @@ export function LexicalShell({
clearToken,
initialContent,
functionEntries,
workingDir,
}: LexicalShellExtendedProps) {
/* LexicalComposer reads initialConfig once on mount; lock it behind useMemo
so the initializer callback identity doesn't trigger a remount on re-render. */
Expand Down Expand Up @@ -178,8 +184,12 @@ export function LexicalShell({
menuOpenRef={menuOpenRef}
functionEntries={functionEntries}
/>
{workingDir ? (
<FileMentionsPlugin menuOpenRef={menuOpenRef} workingDir={workingDir} />
) : null}
<SlashCommandsPlugin menuOpenRef={menuOpenRef} />
<FunctionMentionTransformPlugin />
<FileMentionTransformPlugin />
</LexicalComposer>
)
}
261 changes: 261 additions & 0 deletions console/web/src/components/chat/lexical/FileMentionNode.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { useLexicalNodeSelection } from '@lexical/react/useLexicalNodeSelection'
import {
$getNodeByKey,
CLICK_COMMAND,
COMMAND_PRIORITY_LOW,
DecoratorNode,
type DOMConversion,
type DOMConversionMap,
type DOMConversionOutput,
type DOMExportOutput,
type EditorConfig,
KEY_BACKSPACE_COMMAND,
KEY_DELETE_COMMAND,
type LexicalNode,
mergeRegister,
type NodeKey,
type SerializedLexicalNode,
type Spread,
} from 'lexical'
import { type JSX, type RefObject, useEffect, useRef } from 'react'
import { cn } from '@/lib/utils'

export type SerializedFileMentionNode = Spread<
{ path: string },
SerializedLexicalNode
>

/**
* An inline pill representing a `#file(<path>)` mention. Rendered through
* Lexical's `decorate()` so React owns the visuals (file glyph + relative
* path + panel background), while `getTextContent()` returns the plain-text
* `#file(<path>)` form so the existing OnChange lift in LexicalShell keeps
* working. The markdown renderer detects the same `#file(<path>)` token and
* reuses the presentational pill (`FileMentionPill`) below.
*/
export class FileMentionNode extends DecoratorNode<JSX.Element> {
__path: string

static getType(): string {
return 'file-mention'
}

static clone(node: FileMentionNode): FileMentionNode {
return new FileMentionNode(node.__path, node.__key)
}

static importJSON(serialized: SerializedFileMentionNode): FileMentionNode {
return $createFileMentionNode(serialized.path)
}

/* Recreate the pill on HTML paste (cross-editor or external apps).
`exportDOM` already stamps the `data-lexical-file-mention` flag and
a `data-file-path` attribute, so the round-trip is symmetrical. */
static importDOM(): DOMConversionMap | null {
return {
span: (el: HTMLElement): DOMConversion<HTMLElement> | null => {
if (el.getAttribute('data-lexical-file-mention') !== 'true') {
return null
}
return {
conversion: convertFileMentionElement,
priority: 1,
}
},
}
}

constructor(path: string, key?: NodeKey) {
super(key)
this.__path = path
}

exportJSON(): SerializedFileMentionNode {
return {
type: FileMentionNode.getType(),
version: 1,
path: this.__path,
}
}

exportDOM(): DOMExportOutput {
const element = document.createElement('span')
element.setAttribute('data-lexical-file-mention', 'true')
element.setAttribute('data-file-path', this.__path)
element.textContent = this.getTextContent()
return { element }
}

createDOM(_config: EditorConfig): HTMLElement {
/* Lexical needs a host DOM node; React's decorate() output mounts inside. */
const span = document.createElement('span')
span.style.display = 'inline-block'
span.style.verticalAlign = 'middle'
return span
}

updateDOM(): false {
return false
}

isInline(): true {
return true
}

isKeyboardSelectable(): true {
return true
}

getTextContent(): string {
return `#file(${this.__path})`
}

getPath(): string {
return this.__path
}

decorate(): JSX.Element {
return <EditableFileMentionPill path={this.__path} nodeKey={this.__key} />
}
}

function convertFileMentionElement(el: HTMLElement): DOMConversionOutput {
const path = el.getAttribute('data-file-path') ?? ''
if (!path) return { node: null }
return { node: $createFileMentionNode(path) }
}

interface PillProps {
path: string
/** Visible-selected state. Defaults to false; only the Lexical decorator
wrapper passes a real value. Markdown renders never set this. */
selected?: boolean
/** Click-target ref; only the Lexical wrapper supplies one (so its
`CLICK_COMMAND` handler can scope hit-tests to the pill). Markdown
renders leave this unset and the pill behaves as pure decoration. */
pillRef?: RefObject<HTMLSpanElement | null>
}

/**
* The inserted-token visual. Hairline file glyph in accent, relative path in
* ink, on a panel background. Rectilinear; no rounded corners; monospace;
* tight inline-block sizing so it flows with text. When `selected` is true
* the border swaps to accent and the surface lifts one step to `paper-2` —
* same 1px footprint, no layout shift. No DOM-level click handler lives
* here; the Lexical wrapper drives selection via `CLICK_COMMAND` so the pill
* stays a static, accessible inline element in both editor and markdown.
*/
export function FileMentionPill({ path, selected, pillRef }: PillProps) {
return (
<span
ref={pillRef}
contentEditable={false}
data-file-path={path}
className={cn(
'inline-flex items-center gap-1 px-1.5 h-[20px] -mt-[2px] border align-middle font-mono text-[13px] text-ink select-none transition-colors',
selected
? 'bg-paper-2 border-accent cursor-pointer'
: 'bg-panel border-rule',
pillRef && 'cursor-pointer',
)}
>
<span aria-hidden className="text-accent leading-none shrink-0">
{/* tiny "file" glyph: hairline rectangle with a corner fold */}
<svg
width="9"
height="11"
viewBox="0 0 10 12"
fill="none"
stroke="currentColor"
strokeWidth="1"
aria-hidden="true"
>
<path d="M1 1H6L9 4V11H1V1Z" />
<path d="M6 1V4H9" />
</svg>
</span>
<span className="leading-none truncate max-w-[280px]">{path}</span>
</span>
)
}

interface EditablePillProps {
path: string
nodeKey: NodeKey
}

/**
* Lexical-decorator wrapper: tracks selection via `useLexicalNodeSelection`
* and listens for `CLICK_COMMAND` / `KEY_BACKSPACE_COMMAND` /
* `KEY_DELETE_COMMAND` so the user can select the pill, then cut/copy/paste
* or delete it. Click-with-shift toggles the selection; plain click replaces
* the current selection.
*/
function EditableFileMentionPill({ path, nodeKey }: EditablePillProps) {
const [editor] = useLexicalComposerContext()
const [isSelected, setSelected, clearSelection] =
useLexicalNodeSelection(nodeKey)
const pillRef = useRef<HTMLSpanElement | null>(null)

useEffect(() => {
const removeIfSelected = (event: KeyboardEvent): boolean => {
if (!isSelected) return false
event.preventDefault()
editor.update(() => {
const node = $getNodeByKey(nodeKey)
if (node) node.remove()
})
return true
}
return mergeRegister(
editor.registerCommand(
CLICK_COMMAND,
(event: MouseEvent) => {
const target = event.target as Node | null
if (
!pillRef.current ||
!target ||
!pillRef.current.contains(target)
) {
return false
}
/* preventDefault keeps the caret from landing inside the decorator
host; Lexical would otherwise place selection just before/after
the pill and fight our node selection. */
event.preventDefault()
if (event.shiftKey) {
setSelected(!isSelected)
} else {
clearSelection()
setSelected(true)
}
return true
},
COMMAND_PRIORITY_LOW,
),
editor.registerCommand(
KEY_BACKSPACE_COMMAND,
removeIfSelected,
COMMAND_PRIORITY_LOW,
),
editor.registerCommand(
KEY_DELETE_COMMAND,
removeIfSelected,
COMMAND_PRIORITY_LOW,
),
)
}, [editor, nodeKey, isSelected, setSelected, clearSelection])

return <FileMentionPill path={path} selected={isSelected} pillRef={pillRef} />
}

export function $createFileMentionNode(path: string): FileMentionNode {
return new FileMentionNode(path)
}

export function $isFileMentionNode(
node: LexicalNode | null | undefined,
): node is FileMentionNode {
return node instanceof FileMentionNode
}
Loading
Loading