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
1 change: 1 addition & 0 deletions changelog.d/3114-message-menu.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A message now opens the same menu on a right-click as its hover toolbar, and a person's own line carries Reply and the same Copy/Download menu a reply does; a copy or a download the window cannot do says why in the menu instead of failing silently ([#3114](https://github.com/ThinkFlowLab/FlyBot/issues/3114)).
5,305 changes: 2,679 additions & 2,626 deletions core/client.js

Large diffs are not rendered by default.

68 changes: 10 additions & 58 deletions core/src/client/cells.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { createElement as h, Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
import { inkText } from './inks.js'
import { currentPart, linkMentions, mentionTarget, MENTION_ORIGIN, dayLabel, contentText, stripHeader, stripTrace, botNames, isHiddenTurn, typedBy, heldReplyOf, isRelayContext, relaysBefore, relayPart, commRunOf, toolName, toolArgs, reminderPrompts, cutText, isPluginTool } from './text.js'
import { SmileIcon, ReplyIcon, DotsIcon, CheckIcon, DownloadIcon, CopyIcon, MemoryIcon } from './icons.js'
import { MemoryIcon } from './icons.js'
import { colorOf, lookBotForRemote, toolState, BotMark, PersonMark, RoomAvatar } from './mark.js'
import { botByName, rosterBot } from './sources.js'
import { AnsweredCell, SettledQuestion, PendingQuestion } from './questions.js'
Expand All @@ -15,6 +14,7 @@ import { cleanPeerName, friendBotOwner, normRemoteHandle, ownerNameOf, remoteBot
import { faceBotLabel, faceSeatLabel, faceSeats } from './face-seats.js'
import { fileSize } from './flybot-slots.js'
import { HeldReplyActions } from './held-reply.js'
import { MessageTools, onMessageContextMenu } from './message-tools.js'
import { call } from './api.js'
import { failureLabel } from './diagnostics.js'
import { turnReasoning } from './turn-reasoning.js'
Expand Down Expand Up @@ -75,6 +75,8 @@ export function Bubbles({ texts, roster, selfId, actions, streaming, sessionId,
: null
const reactKey = (index) => (msgKeys ? msgKeys[index] : msgKey)
const reactIndex = (index) => (msgKeys ? 0 : index)
// A right-click on a row opens this menu; the index keeps one row's click out of its neighbours.
const [contextAt, setContextAt] = useState(null)
// #2123: a message with no text is no message — a turn that ended in tool calls only, or whose reply
// a card elsewhere carries, leaves nothing to draw. The empty and whitespace-only shapes are one: the
// row (bubble and its avatar) is drawn only for a text a person can read.
Expand All @@ -86,12 +88,16 @@ export function Bubbles({ texts, roster, selfId, actions, streaming, sessionId,
const picked = key ? (msgKeys ? reactions?.[key] : reactions)?.[reactIndex(index)] ?? [] : []
const last = index === shown.length - 1
const live = streaming && last
return h('div', { key: index, className: 'bt-msg' },
return h('div', {
key: index,
className: 'bt-msg',
onContextMenu: live ? undefined : event => onMessageContextMenu(event, at => setContextAt({ ...at, index })),
},
h('div', { className: 'bt-msg-line' },
lead && last ? lead : null,
h('div', { className: 'bt-bubble' },
h(MarkdownText, { text: linkMentions(text, roster.bots, selfId), streaming: live, labels: mdLabels(), variant: 'compact', fileMentions: mentions })),
live ? null : h(MessageTools, { text, name: roster.byId[selfId]?.name ?? t('Bot'), sessionId, react: key ? emoji => actions.toggleReaction(key, reactIndex(index), emoji) : undefined, actions })),
live ? null : h(MessageTools, { text, name: roster.byId[selfId]?.name ?? t('Bot'), sessionId, react: key ? emoji => actions.toggleReaction(key, reactIndex(index), emoji) : undefined, actions, contextAt: contextAt?.index === index ? contextAt : null })),
picked.length ? h('div', { className: 'bt-reacts' }, picked.map(emoji => h('button', {
key: emoji, type: 'button', className: 'bt-react', 'aria-label': t('Remove reaction {emoji}', { emoji }), onClick: () => actions.toggleReaction(key, reactIndex(index), emoji),
}, emoji))) : null)
Expand All @@ -101,7 +107,6 @@ export function Bubbles({ texts, roster, selfId, actions, streaming, sessionId,
// A held send is shown by its card and the sidebar mark, not by a line in a Face-to-face room's history:
// older rooms still hold this line from when the social plugin posted it for a direct message (#278).
const WAITING_OTHERS_NOTICE = "Waiting for the owner's approval"
const REACTIONS = ['👍', '❤️', '😂', '😮', '😢', '🙏']

// The closed status line already says who left (#1103). Same rule as
// plugins/social/src/face-rooms.js leaveNoticeCoveredByClose: the plugin does not post the short
Expand All @@ -119,59 +124,6 @@ function leaveNoticeCoveredByClose(room, text) {
return false
}

// Closes a popover on a press outside the given elements or on Escape.
function useDismiss(open, close, refs) {
useEffect(() => {
if (!open) return undefined
const onDown = (event) => {
if (refs.some(ref => ref.current?.contains(event.target))) return
close()
}
const onKey = (event) => { if (event.key === 'Escape') { event.stopPropagation(); close() } }
window.addEventListener('mousedown', onDown)
window.addEventListener('keydown', onKey, true)
return () => { window.removeEventListener('mousedown', onDown); window.removeEventListener('keydown', onKey, true) }
}, [open])
}

// The hover toolbar beside a reply bubble: Add reaction, Reply, More.
function MessageTools({ text, name, sessionId, react, actions }) {
const [panel, setPanel] = useState(null)
const [place, setPlace] = useState(null)
const [copied, setCopied] = useState(false)
const tools = useRef(null)
const pop = useRef(null)
const close = () => setPanel(null)
useDismiss(panel !== null, close, [tools, pop])
const open = (kind, event) => {
if (panel === kind) { close(); return }
const rect = event.currentTarget.getBoundingClientRect()
const below = rect.bottom + 220 < window.innerHeight
setPlace(kind === 'react'
? { left: rect.left + rect.width / 2, top: rect.top - 6, '--bt-origin': 'bottom center' }
: { left: Math.min(rect.left, window.innerWidth - 208), ...(below ? { top: rect.bottom + 4 } : { bottom: window.innerHeight - rect.top + 4, '--bt-origin': 'bottom left' }) })
setPanel(kind)
}
const copy = () => {
void navigator.clipboard?.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1000) })
}
const download = () => {
const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' }))
const link = Object.assign(document.createElement('a'), { href: url, download: `${name}-message.md` })
link.click()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}
const item = (label, Icon, run) => h('button', { key: label, type: 'button', role: 'menuitem', onClick: () => { close(); run() } }, h(Icon), label)
return h('div', { ref: tools, className: 'bt-tools', 'data-open': panel !== null || undefined },
react ? h('button', { type: 'button', className: 'bt-tool', 'aria-label': t('Add reaction'), title: t('Add reaction'), 'aria-expanded': panel === 'react', onClick: event => open('react', event) }, h(SmileIcon)) : null,
sessionId ? h('button', { type: 'button', className: 'bt-tool', 'aria-label': t('Reply'), title: t('Reply'), onClick: () => actions.quote(sessionId, text) }, h(ReplyIcon)) : null,
h('button', { type: 'button', className: 'bt-tool', 'aria-label': t('More message actions'), title: t('More'), 'aria-haspopup': 'menu', 'aria-expanded': panel === 'more', onClick: event => open('more', event) }, copied ? h(CheckIcon) : h(DotsIcon)),
panel === 'react' ? createPortal(h('div', { ref: pop, className: 'bt-react-strip', role: 'menu', 'aria-label': t('Reactions'), style: place },
REACTIONS.map(emoji => h('button', { key: emoji, type: 'button', role: 'menuitem', 'aria-label': emoji, onClick: () => { close(); react(emoji) } }, emoji))), document.body) : null,
panel === 'more' ? createPortal(h('div', { ref: pop, className: 'bt-menu', role: 'menu', 'aria-label': t('Message actions'), style: place },
item(t('Copy'), CopyIcon, copy), item(t('Download'), DownloadIcon, download)), document.body) : null)
}

// The first line with something on it, inner runs of whitespace squeezed: a folded row shows it, so
// the row never reads as an empty frame while the text it names sits behind the caret (#1624).
const PEEK_MAX = 160
Expand Down
3 changes: 3 additions & 0 deletions core/src/client/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,9 @@ const ZH = {
Reactions: '表情',
'Message actions': '消息操作',
Download: '下载',
'Clipboard unavailable': '剪贴板不可用,请手动选择文字复制',
'Could not copy message': '未能复制消息,请重试或手动选择文字复制',
'Could not download message': '未能下载消息,请重试或复制正文',
'Thought it through': '思考过程',
'{n} line of reasoning': '{n} 行思考内容',
'{n} lines of reasoning': '{n} 行思考内容',
Expand Down
111 changes: 111 additions & 0 deletions core/src/client/message-tools.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { createElement as h, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { SmileIcon, ReplyIcon, DotsIcon, CheckIcon, DownloadIcon, CopyIcon } from './icons.js'
import { t } from './i18n.js'

export const MESSAGE_REACTIONS = ['👍', '❤️', '😂', '😮', '😢', '🙏']

const hasMessageText = text => String(text ?? '').trim() !== ''

// Only the actions this window can run: a reaction needs a key to store it under, Reply a chat to
// quote into, and a copy or a download the line's own text.
export function messageActionIds({ text, sessionId, canReact = false, canReply = true } = {}) {
if (!hasMessageText(text)) return []
return [
...(canReact ? ['react'] : []),
...(sessionId && canReply ? ['reply'] : []),
'copy', 'download',
]
}

// Closes a popover on a press outside the given elements or on Escape.
export function useDismiss(open, close, refs) {
useEffect(() => {
if (!open) return undefined
const onDown = (event) => {
if (refs.some(ref => ref.current?.contains(event.target))) return
close()
}
const onKey = (event) => { if (event.key === 'Escape') { event.stopPropagation(); close() } }
window.addEventListener('mousedown', onDown)
window.addEventListener('keydown', onKey, true)
return () => { window.removeEventListener('mousedown', onDown); window.removeEventListener('keydown', onKey, true) }
}, [open])
}

function downloadMessage(text, name) {
const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' }))
const link = Object.assign(document.createElement('a'), { href: url, download: `${name}-message.md` })
link.click()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}

// The hover toolbar and the right-click menu for one message: the same actions a reply bubble and a
// person's own line can offer, and a note in the menu when a copy or a download cannot be done.
export function MessageTools({ text, name, sessionId, react, actions, contextAt, className = 'bt-tools' }) {
const [panel, setPanel] = useState(null)
const [place, setPlace] = useState(null)
const [copied, setCopied] = useState(false)
const [note, setNote] = useState('')
const [dismissed, setDismissed] = useState(null)
const tools = useRef(null)
const pop = useRef(null)
const ids = messageActionIds({ text, sessionId, canReact: typeof react === 'function', canReply: typeof actions?.quote === 'function' })
const close = () => { setDismissed(contextAt?.token ?? dismissed); setPanel(null) }
// A right-click sets a new token each time; the menu stays closed once this one is dismissed.
const openedAt = contextAt?.token && contextAt.token !== dismissed ? 'more' : null
const shown = openedAt ?? panel
useDismiss(shown !== null, close, [tools, pop])
const at = (x, y) => {
const width = typeof window === 'undefined' ? 1400 : window.innerWidth
const height = typeof window === 'undefined' ? 800 : window.innerHeight
const below = y + 220 < height
return { left: Math.max(8, Math.min(x, width - 228)), ...(below ? { top: y } : { bottom: height - y + 4, '--bt-origin': 'bottom left' }) }
}
const menuPlace = openedAt ? at(contextAt.x, contextAt.y) : place
const open = (kind, event) => {
if (panel === kind) { close(); return }
const rect = event.currentTarget.getBoundingClientRect()
setPlace(kind === 'react'
? { left: rect.left + rect.width / 2, top: rect.top - 6, '--bt-origin': 'bottom center' }
: at(rect.left, rect.bottom + 4))
setPanel(kind)
}
const copy = async () => {
try {
if (typeof navigator.clipboard?.writeText !== 'function') { setNote(t('Clipboard unavailable')); return }
await navigator.clipboard.writeText(text)
setCopied(true)
setNote(t('Copied'))
setTimeout(() => setCopied(false), 1000)
} catch { setNote(t('Could not copy message')) }
}
const download = () => {
try { downloadMessage(text, name) } catch { setNote(t('Could not download message')) }
}
if (ids.length === 0) return null
const item = (label, Icon, run, keepOpen = false) => h('button', { key: label, type: 'button', role: 'menuitem', onClick: () => { if (!keepOpen) close(); run() } }, h(Icon), label)
return h('div', { ref: tools, className, 'data-open': shown !== null || undefined },
ids.includes('react') ? h('button', { type: 'button', className: 'bt-tool', 'aria-label': t('Add reaction'), title: t('Add reaction'), 'aria-expanded': shown === 'react', onClick: event => open('react', event) }, h(SmileIcon)) : null,
ids.includes('reply') ? h('button', { type: 'button', className: 'bt-tool', 'aria-label': t('Reply'), title: t('Reply'), onClick: () => actions.quote(sessionId, text) }, h(ReplyIcon)) : null,
h('button', { type: 'button', className: 'bt-tool', 'aria-label': t('More message actions'), title: t('More'), 'aria-haspopup': 'menu', 'aria-expanded': shown === 'more', onClick: event => open('more', event) }, copied ? h(CheckIcon) : h(DotsIcon)),
shown === 'react' ? createPortal(h('div', { ref: pop, className: 'bt-react-strip', role: 'menu', 'aria-label': t('Reactions'), style: place },
MESSAGE_REACTIONS.map(emoji => h('button', { key: emoji, type: 'button', role: 'menuitem', 'aria-label': emoji, onClick: () => { close(); react(emoji) } }, emoji))), document.body) : null,
shown === 'more' ? createPortal(h('div', { ref: pop, className: 'bt-menu', role: 'menu', 'aria-label': t('Message actions'), style: menuPlace },
ids.includes('reply') ? item(t('Reply'), ReplyIcon, () => actions.quote(sessionId, text)) : null,
ids.includes('copy') ? item(copied ? t('Copied') : t('Copy'), copied ? CheckIcon : CopyIcon, copy, true) : null,
ids.includes('download') ? item(t('Download'), DownloadIcon, download, true) : null,
note ? h('div', { role: 'status', 'aria-live': 'polite', className: 'bt-menu-hint bt-message-note' }, note) : null), document.body) : null)
}

let contextToken = 0

// A right-click on a message opens the same menu the More button does, at the cursor. Links, inputs
// and an already open menu keep their own right-click; a part still streaming has no menu.
export function onMessageContextMenu(event, setContextAt, { live = false } = {}) {
if (live) return
if (event.target?.closest?.('a[href], input, textarea, [role="menu"]')) return
event.preventDefault()
event.stopPropagation()
setContextAt({ x: event.clientX, y: event.clientY, token: ++contextToken })
}
16 changes: 5 additions & 11 deletions core/src/client/user-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { createElement as h, Fragment, useState } from 'react'
import * as ui from '@deepseek-ai/dsh-client-ui-primitives'
import { mentionSpans } from '../shared/mentions.js'
import { BotMark, PersonMark, markBotForMention } from './mark.js'
import { CheckIcon, CopyIcon } from './icons.js'
import { dateLocale, t } from './i18n.js'
import { cleanPeerName, faceAliases, remoteBotTitle, remoteMentionLabel } from '../shared/remote-label.js'
import { facePeople, faceSeatLabel, faceSeats } from './face-seats.js'
import { MessageTools, onMessageContextMenu } from './message-tools.js'

// -------------------------------------------------------------------------
// The user's own messages. DSH draws every "@word" in them as a file reference, and
Expand Down Expand Up @@ -155,14 +155,6 @@ function Attachments({ attachments, renderMessageImages }) {
}))
}

function CopyButton({ text }) {
const [copied, setCopied] = useState(false)
const copy = () => {
void navigator.clipboard?.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1000) })
}
return h('button', { type: 'button', className: 'bt-tool', 'aria-label': copied ? t('Copied') : t('Copy'), title: copied ? t('Copied') : t('Copy'), onClick: copy }, copied ? h(CheckIcon) : h(CopyIcon))
}

const clock = time => (typeof time === 'number' ? new Date(time).toLocaleTimeString(dateLocale(), { hour: 'numeric', minute: '2-digit' }) : undefined)

// A sent message, or one that joined a running turn ("steering").
Expand All @@ -185,13 +177,15 @@ export function UserMessageCell({ node, sessionId, useRoster, actions, renderMes
// never drawn as held, whatever else in the room waits for approval (#457).
const faceMine = Boolean(room?.origin === 'face-to-face' && !incoming)
const myName = faceMine ? (facePeople(room, roster).find(entry => entry.mine)?.name || cleanPeerName(roster.self?.displayName, '') || author?.name || '') : ''
const [contextAt, setContextAt] = useState(null)
return h('div', {
className: incoming ? 'bt-umsg bt-umsg-other' : 'bt-umsg',
'data-steering': steering || undefined,
'data-face-mine': faceMine || undefined,
'data-author': author?.authorId,
'data-author-kind': author?.authorKind,
'data-author-name': author?.name,
onContextMenu: event => onMessageContextMenu(event, setContextAt),
},
person ? h('span', { className: 'bt-lead', title: author.name }, h(PersonMark, { name: author.name })) : null,
faceMine ? h('span', { className: 'bt-lead', title: myName || undefined }, h(PersonMark, { name: myName || undefined })) : null,
Expand All @@ -203,7 +197,7 @@ export function UserMessageCell({ node, sessionId, useRoster, actions, renderMes
h(UserText, { text, bots: mentionableBots(roster, sessionId, { fromFriend: Boolean(incoming && author.ownerName) }), referenceLabels, skillNames: data.skillNames ?? [], references, actions }),
rest.map((block, index) => (ui.JsonBlock ? h(ui.JsonBlock, { key: index, label: t('Content'), payload: block }) : null))) : null,
referenceLabels.length > 0 ? h('div', { className: 'bt-urefs' }, t('Referenced {labels}', { labels: referenceLabels.join(t(', ')) })) : null),
text === '' ? null : h('div', { className: 'bt-utools' }, h(CopyButton, { text })))
h(MessageTools, { text, name: incoming ? author?.name : t('You'), sessionId, actions, contextAt, className: 'bt-utools' }))
}

export const USER_MESSAGE_CSS = `
Expand All @@ -229,5 +223,5 @@ export const USER_MESSAGE_CSS = `
.bt-ufile-meta{font-size:12px;line-height:15px;color:var(--bt-ink-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.bt-urefs{font-size:13px;line-height:18px;color:var(--bt-ink-3)}
.bt-utools{display:flex;flex:none;gap:2px;opacity:0;visibility:hidden;transition:opacity .12s ease,visibility .12s}
.bt-umsg:hover .bt-utools,.bt-umsg:focus-within .bt-utools{opacity:1;visibility:visible}
.bt-umsg:hover .bt-utools,.bt-umsg:focus-within .bt-utools,.bt-utools[data-open]{opacity:1;visibility:visible}
`
Loading
Loading