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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Table as TableIcon,
Task,
TerminalWindow,
TextQuote,
Workflow,
Workspaces,
} from '@sim/emcn/icons'
Expand Down Expand Up @@ -68,6 +69,10 @@ export const CHAT_CONTEXT_KIND_REGISTRY: Record<ChatContextKind, ChatContextKind
label: 'Terminal',
renderIcon: ({ className }) => <TerminalWindow className={className} />,
},
chat_quote: {
label: 'Quote',
renderIcon: ({ className }) => <TextQuote className={className} />,
},
workflow: { label: 'Workflow', renderIcon: renderWorkflowIcon },
current_workflow: { label: 'Current workflow', renderIcon: renderWorkflowIcon },
workflow_block: { label: 'Block', renderIcon: renderWorkflowIcon },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ import {
useState,
} from 'react'
import {
Chip,
type ClipboardContent,
cn,
overflowFadeSizeClass,
scrollFadeAttributes,
scrollFadeClass,
useScrollEdges,
} from '@sim/emcn'
import { Calendar, Clock } from '@sim/emcn/icons'
import { Calendar, Clock, TextQuote } from '@sim/emcn/icons'
import { useQueryClient } from '@tanstack/react-query'
import { defaultRangeExtractor, type Range, useVirtualizer } from '@tanstack/react-virtual'
import { useParams } from 'next/navigation'
Expand All @@ -30,6 +31,7 @@ import {
} from '@/components/assistant-actions'
import { SMOOTH_CHASE_RATE } from '@/lib/core/utils/smooth-bottom-chase'
import { parseAutomatedTurn } from '@/lib/mothership/chat/automated-turn'
import { isLiveAssistantMessageId } from '@/lib/mothership/chat/live-message-id'
import type { TurnOrigin } from '@/lib/mothership/generated/protocol'
import { inter } from '@/app/_styles/fonts/inter/inter'
import { FindBar } from '@/app/workspace/[workspaceId]/components/find-bar'
Expand Down Expand Up @@ -57,8 +59,10 @@ import {
prepareCopyableMarkdown,
toCopyableMarkdown,
} from '@/app/workspace/[workspaceId]/home/components/mothership-chat/copyable-markdown'
import { quoteSourceAttributes } from '@/app/workspace/[workspaceId]/home/components/mothership-chat/quote-selection'
import { nextSizerFloor } from '@/app/workspace/[workspaceId]/home/components/mothership-chat/sizer-floor'
import { useChatFind } from '@/app/workspace/[workspaceId]/home/components/mothership-chat/use-chat-find'
import { useQuoteSelection } from '@/app/workspace/[workspaceId]/home/components/mothership-chat/use-quote-selection'
import { QueuedMessages } from '@/app/workspace/[workspaceId]/home/components/queued-messages'
import {
UserInput,
Expand Down Expand Up @@ -207,6 +211,22 @@ interface UserMessageRowProps {
rowClassName: string
bubbleClassName: string
attachmentWidthClassName: string
/** Index of each loaded message by id, to tell whether a quote's source can be shown. */
messageIndexById: ReadonlyMap<string, number>
onQuoteSelect: (sourceMessageId: string) => void
}

type SentQuote = ChatMessageContext & { text: string; sourceMessageId: string }

function isSentQuote(context: ChatMessageContext): context is SentQuote {
return context.kind === 'chat_quote' && Boolean(context.text && context.sourceMessageId)
}

/** Label every quote carries into the composer; repeats are numbered on insert. */
const QUOTE_LABEL = 'Quote'

function preventSelectionLoss(event: React.PointerEvent) {
event.preventDefault()
}

function describeAutomatedTurn(
Expand Down Expand Up @@ -270,10 +290,32 @@ const UserMessageRow = memo(function UserMessageRow({
rowClassName,
bubbleClassName,
attachmentWidthClassName,
messageIndexById,
onQuoteSelect,
}: UserMessageRowProps) {
const hasAttachments = Boolean(attachments?.length)
const quotes = contexts?.filter(isSentQuote) ?? []
return (
<div className={rowClassName}>
{quotes.map((quote) => {
const canShowSource = messageIndexById.has(quote.sourceMessageId)
return (
<button
key={quote.label}
type='button'
disabled={!canShowSource}
onClick={() => onQuoteSelect(quote.sourceMessageId)}
className={cn(
'flex min-w-0 items-start gap-1.5 text-left text-[var(--text-muted)] text-caption transition-colors',
canShowSource && 'cursor-pointer hover-hover:text-[var(--text-body)]',
attachmentWidthClassName
)}
>
<TextQuote className='mt-[3px] size-[12px] shrink-0 text-[var(--text-icon)]' />
<span className='line-clamp-2 min-w-0 break-words'>{quote.text}</span>
</button>
)
})}
{hasAttachments && (
<ChatMessageAttachments
attachments={attachments ?? []}
Expand Down Expand Up @@ -775,7 +817,10 @@ export function MothershipChat({
scrollElementRef,
virtualizer,
})
const { ref: autoScrollRef } = useAutoScroll(isStreamActive || lastRowAnimating, find.isOpen)
const { ref: autoScrollRef, release: releaseAutoScroll } = useAutoScroll(
isStreamActive || lastRowAnimating,
find.isOpen
)
const setScrollElement = useCallback(
(el: HTMLDivElement | null) => {
scrollElementRef.current = el
Expand Down Expand Up @@ -856,6 +901,40 @@ export function MothershipChat({
return handleEditQueued(tail.id)
}, [handleEditQueued])

/** Keyed on ids alone so streamed content never rebuilds the index or re-renders user rows. */
const messageIdsKey = messages.map((message) => message.id).join('\u0000')
const messageIndexById = useMemo(
() =>
new Map(messageIdsKey ? messageIdsKey.split('\u0000').map((id, index) => [id, index]) : []),
[messageIdsKey]
)
const showQuoteSource = useCallback(
(sourceMessageId: string) => {
const index = messageIndexById.get(sourceMessageId)
if (index === undefined) return
releaseAutoScroll()
virtualizer.scrollToIndex(index, { align: 'start' })
},
[messageIndexById, releaseAutoScroll, virtualizer]
)

/** Quotes attach to the default composer; a surface that brings its own composer opts out. */
const { pendingQuote, clearPendingQuote, replyChipRef } = useQuoteSelection({
enabled: !composer && !isLoading,
sizerRef,
scrollElementRef,
})
const handleReplyToSelection = () => {
if (!pendingQuote) return
userInputRef.current?.attachQuote({
kind: 'chat_quote',
label: QUOTE_LABEL,
...pendingQuote.quote,
})
window.getSelection()?.removeAllRanges()
clearPendingQuote()
}

/**
* A drag-selection that overshoots a message's last line crosses the row
* wrappers' block boundaries, which the clipboard serializer renders as
Expand Down Expand Up @@ -988,10 +1067,17 @@ export function MothershipChat({
const index = virtualItem.index
const msg = messages[index]
const isLast = index === lastIndex
// A live reply's id is client-only until the refetch swaps in the
// persisted one, so a quote taken from it could never find its source.
const isQuotable =
msg.role === 'assistant'
? !isLiveAssistantMessageId(msg.id)
: !msg.origin && !interactionPairing.hiddenUserByIndex[index]
return (
<div
key={virtualItem.key}
data-index={index}
{...(isQuotable ? quoteSourceAttributes(msg) : {})}
ref={virtualizer.measureElement}
/* Positioned with a real `top`, NOT `top-0` + translateY:
text selection maps a drag's start point to a text
Expand Down Expand Up @@ -1029,6 +1115,8 @@ export function MothershipChat({
rowClassName={cn(styles.userRow, styles.rowGap)}
bubbleClassName={styles.userBubble}
attachmentWidthClassName={styles.attachmentWidth}
messageIndexById={messageIndexById}
onQuoteSelect={showQuoteSource}
/>
)
) : (
Expand All @@ -1053,6 +1141,22 @@ export function MothershipChat({
</div>
)
})}
{pendingQuote && (
<Chip
ref={replyChipRef}
variant='border-shadow'
leftIcon={TextQuote}
onPointerDown={preventSelectionLoss}
onClick={handleReplyToSelection}
className={cn(
'-translate-x-1/2 absolute z-10 select-none',
pendingQuote.side === 'above' && '-translate-y-full'
)}
style={{ top: pendingQuote.y, left: pendingQuote.left }}
>
Reply
</Chip>
)}
</div>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/**
* @vitest-environment jsdom
*/
import { afterEach, describe, expect, it } from 'vitest'
import { resolveQuoteSelection } from '@/app/workspace/[workspaceId]/home/components/mothership-chat/quote-selection'

function renderTranscript(): HTMLElement {
const root = document.createElement('div')
root.innerHTML = [
'<div data-quote-source="user-1" data-quote-role="user"><p id="ask">Which index?</p></div>',
'<div data-quote-source="assistant-1" data-quote-role="assistant">',
'<p id="first">Use a partial index.</p><p id="second">It keeps writes cheap.</p>',
'</div>',
'<div><p id="automated">Background task finished</p></div>',
'<div data-quote-source="assistant-2" data-quote-role="assistant"><p id="later">Done.</p></div>',
].join('')
document.body.appendChild(root)
return root
}

function select(start: Node, startOffset: number, end: Node, endOffset: number) {
const range = document.createRange()
range.setStart(start, startOffset)
range.setEnd(end, endOffset)
const selection = window.getSelection()
if (!selection) throw new Error('jsdom has no selection')
selection.removeAllRanges()
selection.addRange(range)
return selection
}

/** jsdom serializes a selection with its unselectable text, as some browsers do. */
function replyChip(): HTMLButtonElement {
const chip = document.createElement('button')
chip.textContent = 'Reply'
return chip
}

function textOf(root: HTMLElement, id: string): Text {
const node = root.querySelector(`#${id}`)?.firstChild
if (!(node instanceof Text)) throw new Error(`Missing text in #${id}`)
return node
}

afterEach(() => {
window.getSelection()?.removeAllRanges()
document.body.innerHTML = ''
})

describe('resolveQuoteSelection', () => {
it('quotes a passage across paragraphs of one message with its source id and role', () => {
const root = renderTranscript()
const selection = select(textOf(root, 'first'), 4, textOf(root, 'second'), 8)

expect(resolveQuoteSelection(selection, root)?.quote).toEqual({
sourceMessageId: 'assistant-1',
sourceRole: 'assistant',
text: expect.stringMatching(/^a partial index\.\s*It keeps$/),
})
})

it('keeps a selection that overshoots into the next message only by whitespace', () => {
const root = renderTranscript()
const next = root.querySelector('[data-quote-source="assistant-1"]')
if (!next) throw new Error('Missing assistant-1 row')
next.prepend('\n')
const selection = select(textOf(root, 'ask'), 0, next.firstChild as Text, 1)

expect(resolveQuoteSelection(selection, root)?.quote).toEqual({
sourceMessageId: 'user-1',
sourceRole: 'user',
text: 'Which index?',
})
})

it('quotes a triple-click that runs on past the Reply chip, measuring only the quoted text', () => {
const root = renderTranscript()
const last = root.querySelector('[data-quote-source="assistant-2"]')
if (!last) throw new Error('Missing assistant-2 row')
last.append('\n ')
const chip = replyChip()
root.appendChild(chip)
const composer = document.createElement('p')
composer.textContent = 'Composer draft'
document.body.appendChild(composer)
const selection = select(textOf(root, 'later'), 0, composer.firstChild as Text, 0)

const resolved = resolveQuoteSelection(selection, root, chip)
expect(resolved?.quote).toEqual({
sourceMessageId: 'assistant-2',
sourceRole: 'assistant',
text: 'Done.',
})
expect(resolved?.range.toString()).toBe('Done.')
expect(resolveQuoteSelection(selection, root)).toBeNull()
})

it('leaves the Reply chip out of the quote when the selection starts before it', () => {
const root = renderTranscript()
const chip = replyChip()
root.prepend(chip)
const selection = select(root, 0, textOf(root, 'ask'), 12)

expect(resolveQuoteSelection(selection, root, chip)?.quote.text).toBe('Which index?')
})

it.each([
['spans two messages', 'ask', 6, 'first', 3],
['takes text from an unquotable automated row', 'automated', 0, 'later', 5],
])('offers no quote when the selection %s', (_name, startId, startOffset, endId, endOffset) => {
const root = renderTranscript()
const selection = select(textOf(root, startId), startOffset, textOf(root, endId), endOffset)

expect(resolveQuoteSelection(selection, root)).toBeNull()
})

it('offers no quote for a collapsed caret, whitespace, or a selection that runs out of the transcript', () => {
const root = renderTranscript()
const outside = document.createElement('p')
outside.textContent = 'Composer draft'
document.body.appendChild(outside)
const whitespace = document.createElement('p')
whitespace.textContent = ' '
root.querySelector('[data-quote-source="assistant-2"]')?.appendChild(whitespace)

const ask = textOf(root, 'ask')
expect(resolveQuoteSelection(select(ask, 2, ask, 2), root)).toBeNull()
const blank = whitespace.firstChild as Text
expect(resolveQuoteSelection(select(blank, 0, blank, 3), root)).toBeNull()
const draft = outside.firstChild as Text
expect(resolveQuoteSelection(select(textOf(root, 'later'), 0, draft, 8), root)).toBeNull()
})
})
Loading
Loading