Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
5c4454b
feat(chat): highlight-to-chat for file and table selections
mzxchandra Jul 30, 2026
3dac5a8
fix(chat): widen selection code fence so embedded backticks can't tru…
mzxchandra Jul 30, 2026
1551f96
fix(chat): carry the selection chip on a column-header copy
mzxchandra Jul 30, 2026
27dbd17
Merge remote-tracking branch 'origin/staging' into worktree-add-to-ch…
waleedlatif1 Aug 1, 2026
6421994
refactor(chat): clean up highlight-to-chat selections
waleedlatif1 Aug 1, 2026
a80f2e2
refactor(chat): tighten table copy fallback and helper placement
waleedlatif1 Aug 1, 2026
8455da9
fix(chat): apply chip handoffs as one batch; widen table copy chip path
waleedlatif1 Aug 1, 2026
598791e
fix(chat): distinguish a line-less file-selection label from the whol…
waleedlatif1 Aug 1, 2026
7d3d58d
fix(chat): don't revive an aged-out chip handoff when accumulating
waleedlatif1 Aug 1, 2026
f82c44e
fix(chat): reference every selected row in a table chip, not just loa…
waleedlatif1 Aug 1, 2026
9a1da09
docs(chat): scope the table copy 'complete' comment to the text path
waleedlatif1 Aug 1, 2026
231e0a0
fix(chat): compare selection ids as sets, not sequences
waleedlatif1 Aug 1, 2026
b20cfcd
fix(chat): enforce the table selection budget over the whole rendered…
waleedlatif1 Aug 1, 2026
2e5f8f5
fix(chat): don't swallow a paste whose selection chip is already atta…
waleedlatif1 Aug 1, 2026
eff18e6
fix(chat): derive the budget reserve from the same clause it reserves…
waleedlatif1 Aug 1, 2026
d939aea
fix(chat): align MothershipChat's onContextRemove with the surface co…
waleedlatif1 Aug 1, 2026
d3b6878
refactor(chat): apply cleanup pass findings
waleedlatif1 Aug 1, 2026
1392a74
fix(chat): don't attach a selection chip to a copy from a nested input
waleedlatif1 Aug 1, 2026
94eab0d
fix(chat): persist the source names a selection chip renders from
waleedlatif1 Aug 1, 2026
14b9ba6
Merge remote-tracking branch 'origin/staging' into worktree-add-to-ch…
waleedlatif1 Aug 1, 2026
0ff8c7f
refactor(chat): remove a needless alias and correct an eslint-disable…
waleedlatif1 Aug 1, 2026
fafe018
fix(chat): bound the sync copy path by the text limit, not the chip cap
waleedlatif1 Aug 1, 2026
65ddf42
refactor(tables): extract selection-to-chip helpers into utils so the…
waleedlatif1 Aug 1, 2026
dac8313
fix(chat): scope selections to the columns actually picked, and stop …
waleedlatif1 Aug 1, 2026
db183b5
fix(tables): cap the Add-to-Chat label at the rows a chip can carry
waleedlatif1 Aug 1, 2026
3bb5d6c
fix(chat): stop a removed chip lingering when its label prefixes another
waleedlatif1 Aug 1, 2026
714e6d8
fix(chat): include the line range in file-selection equality
waleedlatif1 Aug 1, 2026
7644b8d
fix(tables): drain past the cap so exclusions can't shrink a select-a…
waleedlatif1 Aug 1, 2026
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
DropdownMenuShortcut,
DropdownMenuTrigger,
} from '@sim/emcn'
import { Clipboard, Duplicate, Search, SelectAll } from '@sim/emcn/icons'
import { Blimp, Clipboard, Duplicate, Search, SelectAll } from '@sim/emcn/icons'
import { Scissors } from 'lucide-react'

interface EditorContextMenuProps {
Expand All @@ -23,6 +23,8 @@ interface EditorContextMenuProps {
onPaste: () => void
onSelectAll: () => void
onFind: () => void
/** Adds the current selection to Chat as a reference. Omit to hide the item. */
onAddToChat?: () => void
}

export function EditorContextMenu({
Expand All @@ -37,6 +39,7 @@ export function EditorContextMenu({
onPaste,
onSelectAll,
onFind,
onAddToChat,
}: EditorContextMenuProps) {
return (
<DropdownMenu open={isOpen} onOpenChange={(open) => !open && onClose()} modal={false}>
Expand All @@ -60,6 +63,15 @@ export function EditorContextMenu({
sideOffset={2}
onCloseAutoFocus={(e) => e.preventDefault()}
>
{onAddToChat && (
<>
<DropdownMenuItem disabled={!hasSelection} onSelect={onAddToChat}>
<Blimp />
Add to Chat
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
{canEdit && (
<DropdownMenuItem disabled={!hasSelection} onSelect={onCut}>
<Scissors />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { Blimp } from '@sim/emcn/icons'
import { posToDOMRect } from '@tiptap/core'
import { PluginKey } from '@tiptap/pm/state'
import type { Editor } from '@tiptap/react'
Expand Down Expand Up @@ -54,6 +55,8 @@ interface EditorBubbleMenuProps {
editor: Editor
/** The editor's scrollable viewport, used to keep the toolbar on-screen for selections taller than it. */
scrollContainerRef: React.RefObject<HTMLDivElement | null>
/** Adds the current selection to Chat as a reference. Omit to hide the action. */
onAddToChat?: () => void
}

/**
Expand All @@ -62,7 +65,11 @@ interface EditorBubbleMenuProps {
* live in the `/` slash menu. Active states are read through {@link useEditorState} so the bar
* stays correct without re-rendering the editor on every transaction.
*/
export function EditorBubbleMenu({ editor, scrollContainerRef }: EditorBubbleMenuProps) {
export function EditorBubbleMenu({
editor,
scrollContainerRef,
onAddToChat,
}: EditorBubbleMenuProps) {
const [linkValue, setLinkValue] = useState<string | null>(null)
const linkInputRef = useRef<HTMLInputElement>(null)
const linkRangeRef = useRef<{ from: number; to: number } | null>(null)
Expand Down Expand Up @@ -243,6 +250,17 @@ export function EditorBubbleMenu({ editor, scrollContainerRef }: EditorBubbleMen
</>
) : (
<>
{onAddToChat && (
<>
<ToolbarButton
icon={Blimp}
label='Add to Chat'
isActive={false}
onClick={onAddToChat}
/>
<ToolbarDivider />
</>
)}
<ToolbarButton
icon={Bold}
label='Bold'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { ComponentType, SVGProps } from 'react'
import { cn, Tooltip } from '@sim/emcn'
import type { LucideIcon } from 'lucide-react'

interface ToolbarButtonProps {
icon: LucideIcon
/** Any SVG icon component — Lucide icons and `@sim/emcn/icons` both satisfy this. */
icon: ComponentType<SVGProps<SVGSVGElement>>
label: string
shortcut?: string
isActive?: boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,21 @@ import type { Editor } from '@tiptap/react'
import { EditorContent, useEditor } from '@tiptap/react'
import { useRouter } from 'next/navigation'
import { useSession } from '@/lib/auth/auth-client'
import {
buildFileSelectionLabel,
truncateSelectionText,
} from '@/lib/copilot/chat/selection-context'
import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace'
import { extractEmbeddedFileRef } from '@/lib/uploads/utils/embedded-image-ref'
import { isUntitledName } from '@/app/workspace/[workspaceId]/files/untitled-title'
import { useUploadWorkspaceFile } from '@/hooks/queries/workspace-files'
import { useAddToChat } from '@/hooks/use-add-to-chat'
import type { SaveStatus } from '@/hooks/use-autosave'
import { useFileContentSource } from '@/hooks/use-file-content-source'
import type { ChatContext } from '@/stores/panel'
import { PreviewLoadingFrame } from '../preview-shared'
import { useEditableFileContent } from '../use-editable-file-content'
import { useSelectionCopyBridge } from '../use-selection-copy-bridge'
import {
announceAgentApplying,
clearAgentApplying,
Expand Down Expand Up @@ -1124,6 +1131,36 @@ export function LoadedRichMarkdownEditor({
[]
)

const addToChat = useAddToChat()
/**
* No line range: this editor renders a ProseMirror document, whose block
* boundaries do not correspond to markdown source lines (blank lines between
* paragraphs, list markers, heading prefixes and fenced blocks all shift the
* real line). Reporting a derived count would label the chip — and prompt the
* agent — with line numbers that don't exist in the file.
*/
const buildSelectionContext = useCallback((): ChatContext | null => {
if (!editor) return null
const { from, to } = editor.state.selection
if (from === to) return null
const text = editor.state.doc.textBetween(from, to, '\n')
if (!text.trim()) return null
return {
kind: 'file_selection',
fileId: file.id,
fileName: file.name,
label: buildFileSelectionLabel(file.name),
text: truncateSelectionText(text),
}
Comment thread
cursor[bot] marked this conversation as resolved.
}, [editor, file.id, file.name])

const handleAddSelectionToChat = () => {
const context = buildSelectionContext()
if (context) addToChat(context)
}

useSelectionCopyBridge(containerRef, buildSelectionContext)

// Show the read-only placeholder (the already-fetched markdown) whenever a collaborative doc has not yet
// seeded — including during an agent stream that begins before the seed lands. Streamed diffs are held
// until `collabReady` (see the streaming effect), so before then the editor is empty; the placeholder
Expand All @@ -1135,7 +1172,13 @@ export function LoadedRichMarkdownEditor({
ref={containerRef}
className={cn('flex flex-1 flex-col overflow-y-auto', isEditable && 'cursor-text')}
>
{editor && <EditorBubbleMenu editor={editor} scrollContainerRef={containerRef} />}
{editor && (
<EditorBubbleMenu
editor={editor}
scrollContainerRef={containerRef}
onAddToChat={handleAddSelectionToChat}
/>
)}
{editor && <TableBubbleMenu editor={editor} scrollContainerRef={containerRef} />}
{editor && <LinkHoverCard editor={editor} />}
<input
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@ import type { OnMount } from '@monaco-editor/react'
import { cn } from '@sim/emcn'
import type { editor as MonacoEditorTypes } from 'monaco-editor'
import dynamic from 'next/dynamic'
import {
buildFileSelectionLabel,
truncateSelectionText,
} from '@/lib/copilot/chat/selection-context'
import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace'
import { getFileExtension } from '@/lib/uploads/utils/file-utils'
import { useAddToChat } from '@/hooks/use-add-to-chat'
import type { ChatContext } from '@/stores/panel'
import { EditorContextMenu } from './editor-context-menu'
import type { PreviewMode } from './file-viewer'
import { PreviewPanel, resolvePreviewType } from './preview-panel'
import { PreviewLoadingFrame } from './preview-shared'
import { useEditableFileContent } from './use-editable-file-content'
import { useSelectionCopyBridge } from './use-selection-copy-bridge'

const SIM_DARK_RULES: MonacoEditorTypes.ITokenThemeRule[] = [
{ token: 'comment', foreground: '606060', fontStyle: 'italic' },
Expand Down Expand Up @@ -373,6 +380,38 @@ export const TextEditor = memo(function TextEditor({

const monacoLanguage = resolveMonacoLanguage(file)
const monacoTheme = useMonacoTheme()
const addToChat = useAddToChat()

const buildSelectionContext = useCallback((): ChatContext | null => {
const editor = monacoEditorRef.current
const sel = editor?.getSelection()
const model = editor?.getModel()
if (!editor || !sel || sel.isEmpty() || !model) return null
const text = model.getValueInRange(sel)
if (!text.trim()) return null
const startLine = sel.startLineNumber
// A full-line highlight ends at column 1 of the FOLLOWING line, so that line
// contributed no text — reporting it would claim a range one line longer
// than what was selected, in both the chip label and the agent's prompt.
const endLine =
sel.endColumn === 1 && sel.endLineNumber > startLine
? sel.endLineNumber - 1
: sel.endLineNumber
return {
kind: 'file_selection',
fileId: file.id,
fileName: file.name,
label: buildFileSelectionLabel(file.name, startLine, endLine),
text: truncateSelectionText(text),
startLine,
endLine,
Comment thread
waleedlatif1 marked this conversation as resolved.
}
}, [file.id, file.name])

const handleAddSelectionToChat = () => {
const context = buildSelectionContext()
if (context) addToChat(context)
}

const {
content,
Expand All @@ -394,6 +433,10 @@ export const TextEditor = memo(function TextEditor({
})
contentRef.current = content

// Enable once content has loaded — the container (and Monaco) only mount after
// the `isContentLoading` early return below, so the bridge must (re-)attach then.
useSelectionCopyBridge(containerRef, buildSelectionContext, !isContentLoading)

useEffect(() => {
const editor = monacoEditorRef.current
if (!editor) return
Expand Down Expand Up @@ -650,6 +693,10 @@ export const TextEditor = memo(function TextEditor({
onClose={closeContextMenu}
hasSelection={contextMenu.hasSelection}
canEdit={!isEditorReadOnly}
onAddToChat={() => {
handleAddSelectionToChat()
closeContextMenu()
}}
onCut={() => {
monacoEditorRef.current?.focus()
monacoEditorRef.current?.trigger(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* @vitest-environment jsdom
*/
import { act, createRef, type RefObject } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SIM_SELECTION_MIME } from '@/lib/copilot/chat/selection-clipboard'
import type { ChatContext } from '@/stores/panel'
import { useSelectionCopyBridge } from './use-selection-copy-bridge'

const selection: ChatContext = {
kind: 'file_selection',
fileId: 'f1',
fileName: 'notes.md',
label: 'notes.md:2-4',
text: 'the exact passage',
}

let container: HTMLDivElement
let root: Root
let containerRef: RefObject<HTMLDivElement | null>
let buildContext: ReturnType<typeof vi.fn>

/**
* Mirrors the editors this hook wraps: Monaco's editing surface is a hidden
* textarea, and its find widget is a real input nested in the same container.
*/
function Host() {
useSelectionCopyBridge(containerRef, buildContext as () => ChatContext | null)
return (
<div ref={containerRef}>
<textarea id='editor-surface' />
<input id='find-box' />
</div>
)
}

/** Dispatches a bubbling copy from `id` and returns what was written. */
function dispatchCopy(id: string): Record<string, string> {
const written: Record<string, string> = {}
const event = new Event('copy', { bubbles: true }) as ClipboardEvent
Object.defineProperty(event, 'clipboardData', {
value: {
setData: (type: string, value: string) => {
written[type] = value
},
},
})
act(() => {
container.querySelector(`#${id}`)?.dispatchEvent(event)
})
return written
}

describe('useSelectionCopyBridge', () => {
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
containerRef = createRef<HTMLDivElement>()
buildContext = vi.fn(() => selection)
root = createRoot(container)
act(() => {
root.render(<Host />)
})
})

afterEach(() => {
act(() => root.unmount())
container.remove()
vi.clearAllMocks()
})

it('attaches the selection when copying from the editor surface', () => {
const written = dispatchCopy('editor-surface')

expect(buildContext).toHaveBeenCalled()
expect(written[SIM_SELECTION_MIME]).toContain('file_selection')
})

it('ignores a copy from a nested input such as the find box', () => {
// The document still holds a highlight, so without the guard the chip would
// ride onto text the user never copied.
const written = dispatchCopy('find-box')

expect(buildContext).not.toHaveBeenCalled()
expect(written[SIM_SELECTION_MIME]).toBeUndefined()
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use client'

import { type RefObject, useEffect } from 'react'
import { attachSelectionContextToClipboard } from '@/lib/copilot/chat/selection-clipboard'
import type { ChatContext } from '@/stores/panel'

/**
* Rides a selection {@link ChatContext} onto the editor's native copy so a
* highlighted passage copied with Cmd+C pastes into Chat as a reference chip.
*
* Attached in the BUBBLE phase so it runs after the inner editor's own copy
* handler — Monaco and ProseMirror both `clearData()` before writing
* `text/plain`, so the custom type must be added last to survive.
*
* @param buildContext - Returns null when there is no non-empty selection.
* @param enabled - Re-runs the effect for a container that mounts late (behind a
* loading gate); a ref isn't reactive, so the effect would otherwise bail on the
* first render and never re-attach.
*/
export function useSelectionCopyBridge(
containerRef: RefObject<HTMLElement | null>,
buildContext: () => ChatContext | null,
enabled = true
): void {
useEffect(() => {
const dom = containerRef.current
if (!dom || !enabled) return
const onCopy = (e: ClipboardEvent) => {
// A copy from a field nested in the editor — Monaco's find box being the
// common one — bubbles here while the document still holds a highlight,
// so the selection would be attached to text the user never copied.
//
// Only INPUT is skipped, deliberately: Monaco's own editing surface is a
// hidden TEXTAREA, so excluding textareas (as the table grid does, where
// the cell editors really are form fields) would suppress the chip on the
// main copy path this hook exists for.
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
const context = buildContext()
if (context) attachSelectionContextToClipboard(e.clipboardData, context)
}
Comment thread
waleedlatif1 marked this conversation as resolved.
dom.addEventListener('copy', onCopy)
return () => dom.removeEventListener('copy', onCopy)
}, [containerRef, buildContext, enabled])
}
Loading
Loading