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-folding.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A long chat message now opens as a whole-line preview with one **Show more** control in the bubble: the whole reply is one press away, **Show less** folds it back, and a reply still streaming or under the cap is never folded ([#3114](https://github.com/ThinkFlowLab/FlyBot/issues/3114)).
5,241 changes: 2,678 additions & 2,563 deletions core/client.js

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion core/src/client/cells.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ 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 { foldBody, foldingOf } from './message-fold.js'
import { call } from './api.js'
import { failureLabel } from './diagnostics.js'
import { turnReasoning } from './turn-reasoning.js'
Expand Down Expand Up @@ -58,6 +59,7 @@ function bubbleLinkClick({ actions, subject }) {
// `lead` (a sender avatar in group chats) sits beside the last bubble, in the same
// row, so it lines up with the bubble whether or not reactions hang below it.
export function Bubbles({ texts, roster, selfId, actions, streaming, sessionId, msgKey, msgKeys, useUi, lead, mentions }) {
const folding = foldingOf(roster?.prefs)
const openLink = bubbleLinkClick({ actions, subject: selfId ?? sessionId })
const onClick = (event) => {
if (openLink(event)) return
Expand Down Expand Up @@ -96,7 +98,7 @@ export function Bubbles({ texts, roster, selfId, actions, streaming, sessionId,
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 })),
foldBody({ text, folding, streaming: live, draw: shown => h(MarkdownText, { text: linkMentions(shown, 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, 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),
Expand Down
122 changes: 122 additions & 0 deletions core/src/client/message-fold.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// Long-message folding in a chat bubble: the thresholds, the whole-line preview,
// and the one control that opens the whole reply. The document card and the
// folding preference are a later slice; foldingOf() is the read it will write.

import { createElement as h, useEffect, useState } from 'react'
import { t } from './i18n.js'

export const FOLD_MODES = ['compact', 'standard', 'none']

// A message folds when it exceeds either cap for the chosen mode; the preview is
// the shorter of "first N lines" and "first M characters", ending on a line or
// word boundary. Equal-to-the-cap messages stay open — only values over it fold.
export const FOLD_THRESHOLDS = {
compact: { lines: 4, chars: 240 },
standard: { lines: 12, chars: 800 },
}

export const DEFAULT_FOLDING = { mode: 'standard' }

const MODE_SET = new Set(FOLD_MODES)

export function foldingOf(prefs) {
const raw = prefs?.folding
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ...DEFAULT_FOLDING }
return { mode: MODE_SET.has(raw.mode) ? raw.mode : DEFAULT_FOLDING.mode }
}

function clipWord(line, max) {
if (line.length <= max) return line
const slice = line.slice(0, max)
let breakAt = -1
for (const mark of [' ', '\t', ',', '。', '、', ';', ':', ',', '.', ';', ':', '!', '?', '!', '?']) {
breakAt = Math.max(breakAt, slice.lastIndexOf(mark))
}
if (breakAt >= Math.min(8, Math.floor(max * 0.4))) return slice.slice(0, breakAt)
return slice
}

// An odd number of code-block markers means the preview opened a block it did not
// close: cut before that opener when there is still prose, else close the block.
function closeCodeBlock(preview) {
let block = null
let offset = 0
for (const line of preview.split('\n')) {
const match = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)
if (match) {
const mark = match[1]
if (!block) block = { char: mark[0], length: mark.length, offset }
else if (mark[0] === block.char && mark.length >= block.length && match[2].trim() === '') block = null
}
offset += line.length + 1
}
if (!block) return preview
if (preview.slice(0, block.offset).trim()) return preview.slice(0, block.offset).trimEnd()
return `${preview}\n${block.char.repeat(block.length)}`
}

export function exceedsThreshold(text, cap) {
if (!cap) return false
const raw = String(text ?? '')
if (raw.length > cap.chars) return true
return raw.split('\n').length > cap.lines
}

export function previewOf(text, mode) {
const cap = FOLD_THRESHOLDS[mode]
const raw = String(text ?? '')
if (!cap) return raw
const lines = raw.split('\n')
const out = []
let chars = 0
for (let i = 0; i < lines.length && out.length < cap.lines; i++) {
const line = lines[i]
// The first line may be over the character cap on its own; cut it at a word.
const extra = (out.length === 0 ? 0 : 1) + line.length
if (out.length === 0 && line.length > cap.chars) {
out.push(clipWord(line, cap.chars))
break
}
if (out.length > 0 && chars + extra > cap.chars) {
const budget = cap.chars - chars - 1
if (budget > 0) out.push(clipWord(line, budget))
break
}
out.push(line)
chars += extra
}
return closeCodeBlock(out.join('\n'))
}

export function shouldFold(text, mode) {
const cap = FOLD_THRESHOLDS[mode]
if (!cap) return false
const raw = String(text ?? '')
if (!exceedsThreshold(raw, cap)) return false
return previewOf(raw, mode) !== raw
}

// A reply at or under the cap, or one still streaming, is drawn by the caller
// straight away; only a longer one is handed to FoldedContent.
export function foldBody({ text, folding, streaming = false, draw }) {
const mode = folding?.mode ?? DEFAULT_FOLDING.mode
const raw = String(text ?? '')
if (streaming || !shouldFold(raw, mode)) return draw ? draw(raw) : null
return h(FoldedContent, { text: raw, folding, draw })
}

// One control under the preview: open draws the whole reply and becomes Show less.
export function FoldedContent({ text, folding, draw }) {
const [open, setOpen] = useState(false)
const mode = folding?.mode ?? DEFAULT_FOLDING.mode
useEffect(() => { setOpen(false) }, [mode, text])
const shown = open ? text : previewOf(text, mode)
return h('div', { className: 'bt-fold', 'data-folded': open ? undefined : '' },
h('div', { className: 'bt-fold-body' }, draw ? draw(shown) : null),
h('button', {
type: 'button',
className: 'bt-fold-toggle',
'aria-expanded': open,
onClick: (event) => { event.preventDefault(); event.stopPropagation(); setOpen(value => !value) },
}, t(open ? 'Show less' : 'Show more')))
}
6 changes: 6 additions & 0 deletions core/src/client/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,12 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-event.bt-not-sent{gap:6px;color:var(--bt-ink-3)}
.bt-msg:not(:first-child)>.bt-msg-line>.bt-bubble{border-start-start-radius:6px}
.bt-msg:not(:last-child)>.bt-msg-line>.bt-bubble{border-end-start-radius:6px}
.bt-fold{display:flex;flex-direction:column;align-items:flex-start;gap:2px}
.bt-fold-toggle{border:0;background:none;padding:0;font:inherit;font-size:12px;line-height:16px;color:var(--bt-ink-2);cursor:pointer;border-radius:6px}
.bt-fold-toggle:hover{color:var(--bt-ink)}
.bt-fold-toggle:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.bt-fold[data-folded] .bt-fold-body>:first-child{margin-top:0}
.bt-fold[data-folded] .bt-fold-body>:last-child{margin-bottom:0}
.bt-bubble [class*="_markdown"]>*+*{margin-top:10px}
.bt-bubble [class*="_markdown"]{color:inherit!important;font-size:inherit!important;line-height:inherit!important}
.bt-bubble p{margin:0}
Expand Down
3 changes: 2 additions & 1 deletion core/src/client/user-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ 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'
import { foldBody, foldingOf } from './message-fold.js'

// -------------------------------------------------------------------------
// The user's own messages. DSH draws every "@word" in them as a file reference, and
Expand Down Expand Up @@ -194,7 +195,7 @@ export function UserMessageCell({ node, sessionId, useRoster, actions, renderMes
: author && (incoming || multiHuman) ? h('span', { className: 'bt-uauthor' }, author.name, author.ownerName ? h('span', { className: 'bt-chip' }, t('Friend\'s Bot')) : null) : null,
attachments.length > 0 ? h(Attachments, { attachments, renderMessageImages }) : null,
text !== '' || rest.length > 0 ? h('div', { className: 'bt-ubody', title: clock(data.time) },
h(UserText, { text, bots: mentionableBots(roster, sessionId, { fromFriend: Boolean(incoming && author.ownerName) }), referenceLabels, skillNames: data.skillNames ?? [], references, actions }),
foldBody({ text, folding: foldingOf(roster.prefs), draw: shown => h(UserText, { text: shown, 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),
h(MessageTools, { text, name: incoming ? author?.name : t('You'), sessionId, actions, contextAt, className: 'bt-utools' }))
Expand Down
147 changes: 147 additions & 0 deletions core/test/message-fold.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// #3114: a long reply is drawn as a whole-line preview under one Show more control,
// and a streaming reply or a short one is never folded. The draw is checked in a
// bubble, where a person reads it, with the same React mock as the other cell
// tests: a component runs as a plain function and a fold is one hook slot.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { fileURLToPath } from 'node:url'
import { runInNewContext } from 'node:vm'
import { build } from 'esbuild'

const { outputFiles } = await build({
stdin: {
contents: [
"export { Bubbles } from './src/client/cells.js'",
"export { FOLD_THRESHOLDS, foldingOf, previewOf, shouldFold } from './src/client/message-fold.js'",
].join('\n'),
resolveDir: fileURLToPath(new URL('..', import.meta.url)),
},
bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent',
external: ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives'],
})

const h = (type, props, ...children) => ({ type, props: { ...props, children: children.flat(Infinity) } })
// One slot per hook call, started over by each draw: the bubble's context menu is
// slot 0, the fold comes after it, and pressing the control draws the bubble again.
const slots = []
let slot = 0
const react = {
createElement: h, Fragment: Symbol('Fragment'),
useEffect() {}, useLayoutEffect() {}, useMemo: make => make(), useRef: current => ({ current }),
useState: (initial) => {
const at = slot++
if (!(at in slots)) slots[at] = typeof initial === 'function' ? initial() : initial
return [slots[at], next => { slots[at] = typeof next === 'function' ? next(slots[at]) : next }]
},
}
const module = { exports: {} }
runInNewContext(outputFiles[0].text, {
module, exports: module.exports,
document: { hidden: false }, setTimeout, clearTimeout,
require: (name) => {
if (name === 'react') return react
if (name === 'react-dom') return { createPortal: node => node }
if (name === '@deepseek-ai/dsh-client-ui-primitives') return { MarkdownText: ({ text }) => text }
throw new Error(`Unexpected platform module ${name}`)
},
})
const { Bubbles, FOLD_THRESHOLDS, foldingOf, previewOf, shouldFold } = module.exports

// The tool cells' generic expander hands a component its props and nothing else,
// so every element runs as a function of its properties here too.
const expand = (node) => {
if (node === null || node === undefined || typeof node === 'boolean') return null
if (Array.isArray(node)) return node.map(expand)
if (typeof node !== 'object') return node
if (typeof node.type === 'function') return expand(node.type(node.props))
return { ...node, props: { ...node.props, children: expand(node.props.children) } }
}
const walk = (node, match) => {
if (node === null || node === undefined || typeof node !== 'object') return []
if (Array.isArray(node)) return node.flatMap(child => walk(child, match))
return [...(match(node) ? [node] : []), ...walk(node.props.children, match)]
}
const text = (node) => {
if (node === null || node === undefined) return ''
if (Array.isArray(node)) return node.map(text).join('')
return typeof node === 'object' ? text(node.props.children) : String(node)
}
const classed = (node, cls) => walk(node, item => String(item.props?.className ?? '').split(/\s+/).includes(cls))

const chief = { id: 'chief', name: 'Chief', color: 'green' }
const roster = { bots: [chief], byId: { chief }, rooms: [], roomsById: {}, exchangeTurns: {}, questions: {}, secretRequests: {}, secrets: [] }
const actions = { quote: () => {}, toggleReaction: () => {}, openSession: () => {} }

const lines = (count, width = 'This is a line of a longer reply.') => Array.from({ length: count }, () => width).join('\n')
const numbered = (count) => Array.from({ length: count }, (_, index) => `Line ${index + 1} of the reply`).join('\n')

// One draw of one bubble: a fold left in its slot survives the next draw, so the control works.
const bubble = (over = {}) => {
slot = 0
return expand(Bubbles({ texts: [over.text ?? numbered(20)], roster, selfId: chief.id, actions, sessionId: 'chat', msgKey: 'chat:turn:1', ...over }))
}
const fresh = (over = {}) => { slots.length = 0; return bubble(over) }
const toggles = (drawn) => classed(drawn, 'bt-fold-toggle')
const press = (drawn) => toggles(drawn)[0].props.onClick({ preventDefault() {}, stopPropagation() {} })

test('#3114: a message over the cap folds, one at the cap stays open', () => {
const { compact, standard } = FOLD_THRESHOLDS
assert.equal(compact.lines, 4)
assert.equal(standard.lines, 12)
assert.equal(foldingOf(undefined).mode, 'standard')
assert.equal(shouldFold(lines(standard.lines), 'standard'), false, '12 lines stay open')
assert.equal(shouldFold(lines(standard.lines + 1), 'standard'), true, '13 lines fold')
assert.equal(shouldFold('x'.repeat(compact.chars), 'compact'), false, '240 characters stay open')
assert.equal(shouldFold('x'.repeat(standard.chars), 'standard'), false, '800 characters stay open')
assert.equal(shouldFold('x'.repeat(standard.chars + 1), 'standard'), true, '801 characters fold')
assert.equal(shouldFold(lines(20), 'none'), false, "mode:'none' never folds")
})

test('#3114: the preview is whole lines, and no code block is left open', () => {
const reply = lines(20)
const preview = previewOf(reply, 'standard')
assert.equal(preview.split('\n').length, 12, 'the preview is exactly 12 whole lines')
assert.ok(reply.startsWith(preview), 'the preview is a prefix of the reply')
const code = '```js\n' + 'const n = 1\n'.repeat(40) + '```'
const cut = previewOf(code, 'standard')
const markers = cut.match(/^ {0,3}(`{3,}|~{3,})/gm) ?? []
assert.equal(markers.length % 2, 0, 'the preview closes the code block it opens')
assert.equal(previewOf('a short line', 'standard'), 'a short line', 'nothing is cut below the cap')
assert.equal(previewOf('intro line\n\n' + code, 'standard'), 'intro line', 'prose before an open block keeps the preview short')
})

// The bubble carries the control and only the preview: no second fold mark, and
// no line past the twelfth.
test('#3114: a long reply draws its preview and one Show more control', () => {
const drawn = fresh({ text: numbered(20) })
const found = toggles(drawn)
assert.equal(found.length, 1, 'the bubble carries a fold control')
assert.equal(classed(drawn, 'bt-fold').length, 1)
assert.equal(found[0].props['aria-expanded'], false)
assert.equal(text(found[0]), 'Show more')
assert.ok(text(drawn).includes('Line 12 of the reply'), 'the preview reaches line 12')
assert.ok(!text(drawn).includes('Line 20 of the reply'), 'the reply stops at the preview')
})

test('#3114: Show more draws the whole reply, and Show less folds it back', () => {
press(fresh({ text: numbered(20) }))
const opened = bubble({ text: numbered(20) })
const open = toggles(opened)[0]
assert.equal(open.props['aria-expanded'], true)
assert.equal(text(open), 'Show less')
assert.ok(text(opened).includes('Line 20 of the reply'), 'the whole reply is drawn')
press(opened)
const folded = bubble({ text: numbered(20) })
assert.equal(toggles(folded)[0].props['aria-expanded'], false)
assert.ok(!text(folded).includes('Line 20 of the reply'), 'the preview is drawn again')
})

test('#3114: a streaming reply and a short one are never folded', () => {
const streaming = fresh({ text: numbered(20), streaming: true })
assert.equal(toggles(streaming).length, 0, 'a streaming reply has no fold control')
assert.ok(text(streaming).includes('Line 20 of the reply'), 'and every line is drawn')
const short = fresh({ text: 'A short reply.' })
assert.equal(text(short), 'A short reply.', 'the short reply is drawn whole')
assert.equal(toggles(short).length, 0, 'a short message has no fold control')
assert.ok(text(short).includes('A short reply.'))
})
Loading
Loading