From 9d1200b9b96cbe5cafec571961cb16a4973e6a17 Mon Sep 17 00:00:00 2001 From: vaakx-dev Date: Wed, 25 Nov 2026 20:56:44 +1100 Subject: [PATCH] fix(chat): thread links open their thread, drawn one way Links that streamed into a reply lost their click once more text arrived. Each render of the reply owned its nodes' listeners, and the next render disposed them while morph kept the old nodes on screen. Every markdown build now lives as long as one of its nodes is shown. A thread link is now always its thread's row card. In a sentence or a bullet the words stay where they are and the card follows the text; a link that starts a line is the card itself, with any note after it. The chat plugin's second thread link renderer is gone, and sidebar rows keep their offscreen speedup on a wrapper so a card in a list lines up with its bullet. --- bun.lock | 3 +- package.json | 2 +- plugins/ui/chat/chat/package.json | 1 - plugins/ui/chat/chat/src/index.ts | 3 - plugins/ui/chat/chat/src/links.ts | 10 --- plugins/ui/chat/chat/test/web/sandbox.ts | 11 ++- plugins/ui/chat/chat/test/web/thread-link.ts | 63 +++++++++++++++ plugins/ui/chat/markdown/src/blocks/index.ts | 2 +- plugins/ui/chat/markdown/src/blocks/list.ts | 4 +- plugins/ui/chat/markdown/src/contract.ts | 5 +- plugins/ui/chat/markdown/src/inline/index.ts | 15 ++-- plugins/ui/chat/markdown/src/inline/links.ts | 81 +++++++++++-------- plugins/ui/chat/markdown/src/nodes.ts | 2 + plugins/ui/chat/markdown/src/schemes.ts | 9 +-- plugins/ui/chat/markdown/src/scope.ts | 6 +- .../chat/transcript/src/integrations/morph.ts | 10 ++- .../transcript/src/integrations/streamed.ts | 30 ++++++- plugins/ui/shell/shell/src/rows.ts | 6 +- plugins/ui/threads/home/src/index.ts | 3 +- plugins/ui/threads/home/src/links.ts | 26 +----- 20 files changed, 184 insertions(+), 108 deletions(-) delete mode 100644 plugins/ui/chat/chat/src/links.ts create mode 100644 plugins/ui/chat/chat/test/web/thread-link.ts diff --git a/bun.lock b/bun.lock index 23407d2e3..54f173ebc 100644 --- a/bun.lock +++ b/bun.lock @@ -27,7 +27,7 @@ }, "apps/sand": { "name": "sand", - "version": "0.1.0-beta.6", + "version": "0.1.0-beta.7", "bin": { "sand": "./src/main.ts", }, @@ -2567,7 +2567,6 @@ "@sand/changes": "workspace:*", "@sand/chats": "workspace:*", "@sand/composer": "workspace:*", - "@sand/markdown": "workspace:*", "@sand/model-panel": "workspace:*", "@sand/picker": "workspace:*", "@sand/reactive": "workspace:*", diff --git a/package.json b/package.json index 78d3ab16b..b89c28cd8 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "bench:gate": "bun apps/bench/src/gate/main.ts", "test": "bun test --parallel=4 --timeout 60000 ./apps ./packages ./plugins", "test:upgrade": "bun test --timeout 1200000 ./plugins/host/daemon/test/upgrade/upgrade.ts", - "test:phone": "bun test --parallel --timeout 30000 ./plugins/ui/look/kit/test/gallery/gallery.ts ./plugins/ui/shell/shell/test/phone/window.ts ./plugins/ui/shell/shell/test/phone/drawers.ts ./plugins/ui/shell/shell/test/phone/keyboard.ts ./plugins/core/features/test/web/matrix.ts ./plugins/ui/chat/chat/test/web/follow.ts ./plugins/ui/chat/chat/test/web/catch-up.ts ./plugins/ui/chat/chat/test/web/draft.ts ./plugins/ui/chat/chat/test/web/early.ts ./plugins/ui/chat/chat/test/web/reply.ts ./plugins/ui/chat/chat/test/web/upload.ts ./plugins/ui/chat/chat/test/web/app.ts ./plugins/bots/views/test/web/history.ts ./plugins/bots/views/test/web/tabs.ts ./plugins/core/server/test/web/hello.ts ./plugins/ui/shell/shell/test/web/parts.ts ./plugins/ui/chat/html/test/web/zoom.ts" + "test:phone": "bun test --parallel --timeout 30000 ./plugins/ui/look/kit/test/gallery/gallery.ts ./plugins/ui/shell/shell/test/phone/window.ts ./plugins/ui/shell/shell/test/phone/drawers.ts ./plugins/ui/shell/shell/test/phone/keyboard.ts ./plugins/core/features/test/web/matrix.ts ./plugins/ui/chat/chat/test/web/follow.ts ./plugins/ui/chat/chat/test/web/catch-up.ts ./plugins/ui/chat/chat/test/web/draft.ts ./plugins/ui/chat/chat/test/web/early.ts ./plugins/ui/chat/chat/test/web/reply.ts ./plugins/ui/chat/chat/test/web/upload.ts ./plugins/ui/chat/chat/test/web/thread-link.ts ./plugins/ui/chat/chat/test/web/app.ts ./plugins/bots/views/test/web/history.ts ./plugins/bots/views/test/web/tabs.ts ./plugins/core/server/test/web/hello.ts ./plugins/ui/shell/shell/test/web/parts.ts ./plugins/ui/chat/html/test/web/zoom.ts" }, "devDependencies": { "@sand/boot": "workspace:*", diff --git a/plugins/ui/chat/chat/package.json b/plugins/ui/chat/chat/package.json index 492459fdc..1e8dc435c 100644 --- a/plugins/ui/chat/chat/package.json +++ b/plugins/ui/chat/chat/package.json @@ -16,7 +16,6 @@ "@sand/changes": "workspace:*", "@sand/chats": "workspace:*", "@sand/composer": "workspace:*", - "@sand/markdown": "workspace:*", "@sand/picker": "workspace:*", "@sand/reactive": "workspace:*", "@sand/scripts": "workspace:*", diff --git a/plugins/ui/chat/chat/src/index.ts b/plugins/ui/chat/chat/src/index.ts index a396e67f0..6f503e02e 100644 --- a/plugins/ui/chat/chat/src/index.ts +++ b/plugins/ui/chat/chat/src/index.ts @@ -1,5 +1,4 @@ import { composer, type Composer } from '@sand/composer/contract' -import { markdownLinks } from '@sand/markdown/contract' import { modelTargets } from '@sand/model-panel/contract' import { pulse } from '@sand/reactive' import { shell } from '@sand/ui-shell/contract' @@ -8,7 +7,6 @@ import { sig } from '@vaakx-dev/vrui' import { definePlugin } from 'drydock' import { inject } from './context' import { draftRoute, threadOwners, threadRoute, threadView, waitLines } from './contract' -import { threadLinks } from './links' import { mergedCheck } from './live/merged' import { threadRoutes } from './route' import { followStart } from './route/select' @@ -37,7 +35,6 @@ export default definePlugin({ ctx.provide(waitLines, createWaitLines()) const view = threadViewService(ctx, screens) ctx.provide(threadView, view) - ctx.watch(markdownLinks, found => found?.scheme(threadLinks(ctx.kit, view))) ctx.watch(shell, found => found && threadRoutes(ctx, found, { screens, view, changes })) ctx.watch(shell, found => found?.subject(({ kind, id }) => { diff --git a/plugins/ui/chat/chat/src/links.ts b/plugins/ui/chat/chat/src/links.ts deleted file mode 100644 index 860e67fb9..000000000 --- a/plugins/ui/chat/chat/src/links.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { threadScheme } from '@sand/chats/contract' -import type { LinkScheme } from '@sand/markdown/contract' -import type { Kit } from '@sand/ui-kit/contract' -import type { ThreadView } from './contract' - -export const threadLinks = (kit: Kit, view: ThreadView): LinkScheme => ({ - scheme: threadScheme, - order: 1, - render: (thread, label) => kit.plainButton({ class: 'underline hover:text-neutral-400', onClick: () => view.open(thread) }, ...label), -}) diff --git a/plugins/ui/chat/chat/test/web/sandbox.ts b/plugins/ui/chat/chat/test/web/sandbox.ts index 1a50dff31..e54e8feba 100644 --- a/plugins/ui/chat/chat/test/web/sandbox.ts +++ b/plugins/ui/chat/chat/test/web/sandbox.ts @@ -18,9 +18,16 @@ const printed = (out: string, pattern: RegExp) => { return found } -export type Reply = { text: string; hold?: boolean } +export type Reply = { text: string | string[]; hold?: boolean } -const replyToml = ({ text, hold }: Reply) => `[{ type = "text", text = ${JSON.stringify(text)} }${hold ? ', { type = "hold" }' : ''}]` +const CHUNK_GAP_MS = 300 + +const textToml = (text: string) => `{ type = "text", text = ${JSON.stringify(text)} }` + +const replyToml = ({ text, hold }: Reply) => { + const chunks = [text].flat().map(textToml).join(`, { type = "wait", ms = ${CHUNK_GAP_MS} }, `) + return `[${chunks}${hold ? ', { type = "hold" }' : ''}]` +} export const startSandbox = async (replies: Reply[]) => { const home = mkdtempSync(join(tmpdir(), 'sand-chat-')) diff --git a/plugins/ui/chat/chat/test/web/thread-link.ts b/plugins/ui/chat/chat/test/web/thread-link.ts new file mode 100644 index 000000000..d3016819f --- /dev/null +++ b/plugins/ui/chat/chat/test/web/thread-link.ts @@ -0,0 +1,63 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test' +import { chromium, type Browser, type BrowserContextOptions, type Page } from 'playwright' +import { newChat, startSandbox } from './sandbox' + +const linked = 'made-up-subagent-thread' +const reply = [`The tracks are merged; see [the merge](thread:${linked}) for details.\n\n`, 'Rebuilding ', 'now.'] +const sizes: { name: string; options: BrowserContextOptions }[] = [ + { name: 'desktop', options: { viewport: { width: 1440, height: 900 } } }, + { name: 'phone', options: { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, deviceScaleFactor: 2 } }, +] + +let sand: Awaited> +let browser: Browser +let state: string +let driver: Page +let thread: string + +const send = async (text: string) => { + const box = driver.getByRole('textbox').first() + await box.fill(text) + await box.press('Enter') +} + +beforeAll(async () => { + sand = await startSandbox([{ text: 'Ready.' }, ...sizes.map(() => ({ text: reply, hold: true }))]) + browser = await chromium.launch() + const pairing = await browser.newContext(sizes[0]!.options) + driver = await pairing.newPage() + driver.setDefaultTimeout(10_000) + await driver.goto(sand.url) + await newChat(driver) + await Bun.sleep(1000) + state = JSON.stringify(await pairing.storageState()) + await send('start') + await driver.waitForURL(/view=thread/) + await driver.getByText('Ready.').waitFor() + thread = driver.url() +}, 90_000) + +afterAll(async () => { + await browser?.close() + await sand?.stop() +}) + +describe.each(sizes)('$name', ({ options }) => { + test('a thread link in a sentence keeps the sentence whole, and its card opens the thread after the reply streams in and ends', async () => { + const page = await (await browser.newContext({ ...options, storageState: JSON.parse(state) })).newPage() + page.setDefaultTimeout(10_000) + await page.goto(thread) + await page.getByText('Ready.').waitFor({ state: 'attached' }) + await send('merge them') + const sentence = page.locator('[data-quote] p').filter({ hasText: 'The tracks are merged' }).last() + const card = sentence.getByRole('button', { name: 'the merge' }) + await page.getByText('Rebuilding now.').waitFor() + expect(await sentence.innerText()).toStartWith('The tracks are merged; see the merge for details.') + await driver.getByRole('button', { name: 'Stop' }).click() + await page.getByRole('button', { name: 'Stop' }).waitFor({ state: 'detached' }) + if (options.hasTouch) await card.tap() + else await card.click() + await page.waitForURL(new RegExp(linked)) + await page.close() + }, 60_000) +}) diff --git a/plugins/ui/chat/markdown/src/blocks/index.ts b/plugins/ui/chat/markdown/src/blocks/index.ts index 0f385ac7f..27934a919 100644 --- a/plugins/ui/chat/markdown/src/blocks/index.ts +++ b/plugins/ui/chat/markdown/src/blocks/index.ts @@ -87,7 +87,7 @@ const plain: Parser = (lines, start, scope) => { index++ } const text = body.join('\n').trimEnd() - return { node: paragraph(inline(text, scope.tight ? scope : { ...scope, paragraph: text })), next: index } + return { node: paragraph(inline(text, scope)), next: index } } const parsers: Parser[] = [fenced, mathBlock, atxHeading, ruled, table, list, quoted, indentedCode, plain] diff --git a/plugins/ui/chat/markdown/src/blocks/list.ts b/plugins/ui/chat/markdown/src/blocks/list.ts index 27fe466b9..e228184ae 100644 --- a/plugins/ui/chat/markdown/src/blocks/list.ts +++ b/plugins/ui/chat/markdown/src/blocks/list.ts @@ -41,10 +41,10 @@ const unwrap = (node: Node) => (node.nodeName === 'P' ? [...node.childNodes] : [ const itemView = (body: string[], loose: boolean, scope: Scope, parse: Parse) => { const task = taskMark.exec(body[0]!) if (!task) { - const children = parse(body, { ...scope, tight: !loose }) + const children = parse(body, scope) return listItem(loose ? children : children.flatMap(unwrap)) } - const [first, ...rest] = parse([body[0]!.slice(task[0].length), ...body.slice(1)], { ...scope, tight: true }) + const [first, ...rest] = parse([body[0]!.slice(task[0].length), ...body.slice(1)], scope) return taskItem(task[1] !== ' ', [...(first ? unwrap(first) : []), ...(loose ? rest : rest.flatMap(unwrap))]) } diff --git a/plugins/ui/chat/markdown/src/contract.ts b/plugins/ui/chat/markdown/src/contract.ts index 7d4848d3d..c45218788 100644 --- a/plugins/ui/chat/markdown/src/contract.ts +++ b/plugins/ui/chat/markdown/src/contract.ts @@ -30,12 +30,9 @@ export interface Markdown { export const markdown = service('markdown') -export type LinkPlace = 'block' | 'inline' - export interface LinkScheme { scheme: string - order?: number - render(target: string, label: (Node | string)[], place: LinkPlace): Node + render(target: string, label: (Node | string)[]): Node } export interface MarkdownLinks { diff --git a/plugins/ui/chat/markdown/src/inline/index.ts b/plugins/ui/chat/markdown/src/inline/index.ts index 64b3c8d36..fbf6c6067 100644 --- a/plugins/ui/chat/markdown/src/inline/index.ts +++ b/plugins/ui/chat/markdown/src/inline/index.ts @@ -1,7 +1,7 @@ import { tildeHome } from '@sand/util' import { inlineMath } from '../math/inline' import { inlineCode, lineBreak, type Inline } from '../nodes' -import type { Scope } from '../scope' +import type { InlineScope, Scope } from '../scope' import { delimiter, resolveEmphasis, type Item } from './emphasis' import { decodeEntity } from './entities' import { autolinkAt, bracketed } from './links' @@ -12,7 +12,7 @@ interface Token { end: number } -type Parser = (source: string, index: number, scope: Scope) => Token | undefined +type Parser = (source: string, index: number, scope: InlineScope) => Token | undefined const lineEnd = / *\n */y @@ -43,7 +43,7 @@ const emphasisRun: Parser = (source, index) => { } const bracket: Parser = (source, index, scope) => - source[index] === '[' || source.startsWith('![', index) ? bracketed(source, index, scope, inline) : undefined + source[index] === '[' || source.startsWith('![', index) ? bracketed(source, index, scope, parseInline) : undefined const autolink: Parser = (source, index, scope) => (source[index] === '<' || source[index] === 'h' ? autolinkAt(source, index, scope) : undefined) @@ -61,7 +61,7 @@ const lineBreakAt: Parser = (source, index) => { const parsers: Parser[] = [inlineMath, escapedBreak, escaped, codeSpan, emphasisRun, bracket, autolink, entity, lineBreakAt] -const tokenAt = (source: string, index: number, scope: Scope): Token => { +const tokenAt = (source: string, index: number, scope: InlineScope): Token => { for (const parser of parsers) { const token = parser(source, index, scope) if (token) return token @@ -69,7 +69,7 @@ const tokenAt = (source: string, index: number, scope: Scope): Token => { return { item: source[index]!, end: index + 1 } } -export const inline = (source: string, scope: Scope): Inline[] => { +const parseInline = (source: string, scope: InlineScope): Inline[] => { const items: Item[] = [] let pending = '' for (let index = 0; index < source.length; ) { @@ -86,3 +86,8 @@ export const inline = (source: string, scope: Scope): Inline[] => { if (pending) items.push(tildeHome(pending)) return resolveEmphasis(items) } + +export const inline = (source: string, scope: Scope): Inline[] => { + const cards: Node[] = [] + return [...parseInline(source, { ...scope, cards }), ...cards] +} diff --git a/plugins/ui/chat/markdown/src/inline/links.ts b/plugins/ui/chat/markdown/src/inline/links.ts index 5089b4ba7..10acc1e48 100644 --- a/plugins/ui/chat/markdown/src/inline/links.ts +++ b/plugins/ui/chat/markdown/src/inline/links.ts @@ -1,16 +1,30 @@ import { label } from '../blocks/refs' -import type { LinkPlace } from '../contract' -import { anchor, linkLabel, type Inline } from '../nodes' -import type { Scope } from '../scope' +import { anchor, labelText, linkLabel, type Inline } from '../nodes' +import type { InlineScope, Scope } from '../scope' import { closingBracket, inlineDestination, matchAt } from './syntax' -type Parse = (source: string, scope: Scope) => Inline[] +type Parse = (source: string, scope: InlineScope) => Inline[] + +interface Link { + href: string + children: Inline[] + title?: string +} + +interface Span { + source: string + start: number + end: number +} const allowed = new Set(['http:', 'https:', 'mailto:']) const autolink = /<([a-zA-Z][a-zA-Z\d+.-]{1,31}:[^\s<>]*)>/y const emailAutolink = /<([\w.!#$%&'*+/=?^`{|}~-]+@[a-zA-Z\d](?:[a-zA-Z\d-]*[a-zA-Z\d])?(?:\.[a-zA-Z\d](?:[a-zA-Z\d-]*[a-zA-Z\d])?)*)>/y const bareUrl = /https?:\/\/[^\s<]+/y const reference = /\[([^\]]*)\]/y +const schemed = /^([a-zA-Z][a-zA-Z\d+.-]*):(.*)$/s +const lineStart = /(?:^|\n)[ \t]*$/ +const noteBreak = /[ \t]*(?:[:—–-]|$)[ \t]*/my const safeUrl = (raw: string) => { try { @@ -21,32 +35,39 @@ const safeUrl = (raw: string) => { } } -const schemed = /^([a-zA-Z][a-zA-Z\d+.-]*):(.*)$/s - -interface Link { - href: string - children: Inline[] - place: LinkPlace - title?: string +const schemeCard = ({ href, children }: Link, scope: Scope) => { + const [, name = '', target = ''] = schemed.exec(href.trim()) ?? [] + const found = name && scope.scheme(name.toLowerCase()) + return found ? found.render(target, children) : undefined } -const placeOf = (source: string, start: number, end: number, scope: Scope): LinkPlace => - scope.paragraph === source && start === 0 && end === source.length ? 'block' : 'inline' - -const link = ({ href, children, place, title }: Link, scope: Scope): Node => { +const plainLink = ({ href, children, title }: Link, scope: Scope): Node => { const url = safeUrl(href) if (url) return anchor(url, title, children) - const [, name = '', target = ''] = schemed.exec(href.trim()) ?? [] - const found = name && scope.scheme(name.toLowerCase()) - if (found) return found.render(target, children, place) return scope.files?.link(href.trim(), children) ?? linkLabel(href, children) } -const imageLink = (src: string, alt: string, place: LinkPlace, scope: Scope, title?: string) => - link({ href: src, children: [`▣ ${alt || 'image'}`], place, title: title ?? src }, scope) +const standaloneEnd = ({ source, start, end }: Span) => { + if (!lineStart.test(source.slice(0, start))) return undefined + const found = matchAt(noteBreak, source, end) + return found ? end + found[0].length : undefined +} + +const placeCard = (card: Node, children: Inline[], span: Span, scope: InlineScope) => { + const cardEnd = standaloneEnd(span) + if (cardEnd !== undefined) return { item: card, end: cardEnd } + scope.cards.push(card) + return { item: labelText(children), end: span.end } +} + +const linkToken = (link: Link, span: Span, scope: InlineScope) => { + const card = schemeCard(link, scope) + return card ? placeCard(card, link.children, span, scope) : { item: plainLink(link, scope), end: span.end } +} -const picture = (src: string, alt: string, place: LinkPlace, scope: Scope, title?: string) => - scope.image?.(src, alt) ?? imageLink(src, alt, place, scope, title) +const imageLink = (src: string, alt: string, scope: Scope, title?: string) => plainLink({ href: src, children: [`▣ ${alt || 'image'}`], title: title ?? src }, scope) + +const picture = (src: string, alt: string, scope: Scope, title?: string) => scope.image?.(src, alt) ?? imageLink(src, alt, scope, title) const trimUrl = (url: string) => { let trimmed = url.replace(/[?!.,:;*_~'"]+$/, '') @@ -54,17 +75,14 @@ const trimUrl = (url: string) => { return trimmed } -export const bracketed = (source: string, start: number, scope: Scope, parse: Parse) => { +export const bracketed = (source: string, start: number, scope: InlineScope, parse: Parse) => { const image = source[start] === '!' const open = image ? start + 1 : start const close = closingBracket(source, open, scope) if (close < 0) return undefined const inner = source.slice(open + 1, close) - const build = (url: string, end: number, title?: string) => { - const place = placeOf(source, start, end, scope) - const item = image ? picture(url, inner, place, scope, title) : link({ href: url, children: parse(inner, scope), place, title }, scope) - return { item, end } - } + const build = (url: string, end: number, title?: string) => + image ? { item: picture(url, inner, scope, title), end } : linkToken({ href: url, children: parse(inner, scope), title }, { source, start, end }, scope) if (source[close + 1] === '(') { const target = inlineDestination(source, close + 1) if (target) return build(target.url, target.end, target.title) @@ -74,11 +92,8 @@ export const bracketed = (source: string, start: number, scope: Scope, parse: Pa return found && build(found.url, close + 1 + (named?.[0].length ?? 0), found.title) } -export const autolinkAt = (source: string, index: number, scope: Scope) => { - const token = (href: string, text: string, length: number) => { - const end = index + length - return { item: link({ href, children: [text], place: placeOf(source, index, end, scope) }, scope), end } - } +export const autolinkAt = (source: string, index: number, scope: InlineScope) => { + const token = (href: string, text: string, length: number) => linkToken({ href, children: [text] }, { source, start: index, end: index + length }, scope) const auto = matchAt(autolink, source, index) if (auto) return token(auto[1]!, auto[1]!, auto[0].length) const email = matchAt(emailAutolink, source, index) diff --git a/plugins/ui/chat/markdown/src/nodes.ts b/plugins/ui/chat/markdown/src/nodes.ts index ff0b525b0..308e262ed 100644 --- a/plugins/ui/chat/markdown/src/nodes.ts +++ b/plugins/ui/chat/markdown/src/nodes.ts @@ -67,3 +67,5 @@ export const anchor = (href: string, title: string | undefined, children: Inline a({ class: 'underline hover:text-neutral-400', href, target: '_blank', rel: 'noopener noreferrer', referrerPolicy: 'no-referrer', ...(title && { title }) }, children) export const linkLabel = (href: string, children: Inline[]) => span({ title: href }, children) + +export const labelText = (children: Inline[]) => span(children) diff --git a/plugins/ui/chat/markdown/src/schemes.ts b/plugins/ui/chat/markdown/src/schemes.ts index a209c5979..e86b939a4 100644 --- a/plugins/ui/chat/markdown/src/schemes.ts +++ b/plugins/ui/chat/markdown/src/schemes.ts @@ -9,13 +9,6 @@ export const linkSchemes = (): MarkdownLinks & { find: FindScheme } => { registered.add(entry) return () => void registered.delete(entry) }, - find(name) { - let best: LinkScheme | undefined - for (const entry of registered) { - if (entry.scheme.toLowerCase() !== name || (best && (best.order ?? 0) <= (entry.order ?? 0))) continue - best = entry - } - return best - }, + find: name => [...registered].find(entry => entry.scheme.toLowerCase() === name), } } diff --git a/plugins/ui/chat/markdown/src/scope.ts b/plugins/ui/chat/markdown/src/scope.ts index 4879beec4..241e4cfeb 100644 --- a/plugins/ui/chat/markdown/src/scope.ts +++ b/plugins/ui/chat/markdown/src/scope.ts @@ -18,6 +18,8 @@ export interface Scope extends Renderers { files?: MarkdownFiles size?: MarkdownSize streaming?: boolean - paragraph?: string - tight?: boolean +} + +export interface InlineScope extends Scope { + cards: Node[] } diff --git a/plugins/ui/chat/transcript/src/integrations/morph.ts b/plugins/ui/chat/transcript/src/integrations/morph.ts index e1db96740..3cd5d7e15 100644 --- a/plugins/ui/chat/transcript/src/integrations/morph.ts +++ b/plugins/ui/chat/transcript/src/integrations/morph.ts @@ -6,16 +6,18 @@ const sameShell = (a: Node, b: Node) => { const leaf = (node: Node) => node.nodeType === Node.TEXT_NODE || node.nodeType === Node.COMMENT_NODE -export const morph = (parent: Node, next: Node[], offset = 0) => { - next.forEach((node, index) => { +export const morph = (parent: Node, next: Node[], offset = 0): Node[] => { + const adopted = next.flatMap((node, index) => { const old = parent.childNodes[offset + index] - if (!old) return void parent.appendChild(node) + if (!old) return [parent.appendChild(node)] if (leaf(old) && old.nodeType === node.nodeType) { if (old.nodeValue !== node.nodeValue) old.nodeValue = node.nodeValue - return + return [] } if (sameShell(old, node)) return morph(old, [...node.childNodes]) parent.replaceChild(node, old) + return [node] }) while (parent.childNodes.length > offset + next.length) parent.lastChild!.remove() + return adopted } diff --git a/plugins/ui/chat/transcript/src/integrations/streamed.ts b/plugins/ui/chat/transcript/src/integrations/streamed.ts index c080bbbe7..a505f552b 100644 --- a/plugins/ui/chat/transcript/src/integrations/streamed.ts +++ b/plugins/ui/chat/transcript/src/integrations/streamed.ts @@ -1,21 +1,43 @@ import type { Markdown, NodeOptions } from '@sand/markdown/contract' +import { collectScope, disposeAll, scoped, type Disposer } from '@vaakx-dev/vrui' import { morph } from './morph' +interface Build { + adopted: Node[] + scope: Disposer[] +} + export const streamedMarkdown = (node: Node, markdown: Markdown, options: NodeOptions) => { let prefix = '' let count = 0 + let builds: Build[] = [] + + const shown = (build: Build) => build.adopted.some(adopted => node.contains(adopted)) + + const place = (nodes: Node[], scope: Disposer[], offset: number) => { + builds.push({ adopted: morph(node, nodes, offset), scope }) + const hidden = new Set(builds.filter(build => !shown(build))) + builds = builds.filter(build => !hidden.has(build)) + disposeAll([...hidden].flatMap(build => build.scope)) + } const whole = (source: string) => { prefix = '' count = 0 - morph(node, markdown.nodes(source, options)) + const { value, scope } = collectScope(() => markdown.nodes(source, options)) + place(value, scope, 0) } + scoped(() => disposeAll(builds.flatMap(build => build.scope))) + return (source: string, streaming: boolean) => { if (!streaming || !source.startsWith(prefix)) return whole(source) - const next = markdown.settle(source.slice(prefix.length), options) - if (!next) return whole(source) - morph(node, [...next.settled, ...next.open], count) + const { value: next, scope } = collectScope(() => markdown.settle(source.slice(prefix.length), options)) + if (!next) { + disposeAll(scope) + return whole(source) + } + place([...next.settled, ...next.open], scope, count) count += next.settled.length prefix = source.slice(0, prefix.length + next.length) } diff --git a/plugins/ui/shell/shell/src/rows.ts b/plugins/ui/shell/shell/src/rows.ts index 4b66c15a1..e86e9ed50 100644 --- a/plugins/ui/shell/shell/src/rows.ts +++ b/plugins/ui/shell/shell/src/rows.ts @@ -184,9 +184,11 @@ const offscreenRow = { contentVisibility: 'auto', containIntrinsicBlockSize: 'au const rowView = (model: Model, menu: ContextMenu, row: () => ShellRow, look: RowLook) => { const { workRow, rowBody } = model.kit const current = () => model.isCurrent(row().to) - return workRow({ current, large: look.phone, style: offscreenRow, ...rowMenu(menu, row, () => model.open(row().to)) }, rowBody(row, { large: look.phone })) + return workRow({ current, large: look.phone, ...rowMenu(menu, row, () => model.open(row().to)) }, rowBody(row, { large: look.phone })) } +const listedRow = (model: Model, menu: ContextMenu, row: () => ShellRow, look: RowLook) => div({ style: offscreenRow }, rowView(model, menu, row, look)) + export const singleRow = (model: Model, row: () => ShellRow) => { const menu = model.kit.contextMenu() return div({ class: 'contents' }, dynamicChild(model.phone, phone => rowView(model, menu, row, { phone })), menu.view()) @@ -230,7 +232,7 @@ const groupView = (model: Model, menu: ContextMenu, listed: Sig, lo list( derive(() => (shown() ? listed.get().group.rows : [])), row => row.id, - row => rowView(model, menu, () => row.get(), look), + row => listedRow(model, menu, () => row.get(), look), div({ class: 'flex flex-col gap-px' }), ), show( diff --git a/plugins/ui/threads/home/src/index.ts b/plugins/ui/threads/home/src/index.ts index 346022524..3c507a53d 100644 --- a/plugins/ui/threads/home/src/index.ts +++ b/plugins/ui/threads/home/src/index.ts @@ -20,7 +20,6 @@ import { threadEntries, threadRow } from './items/items' import { RowLooks } from './items/looks' import { chooseDraftPlace, newThread } from './launch/launch' import { threadLinks } from './links' -import { openThread } from './open' import { sessionSource } from './palette/source' import { wakeTimer } from './snooze/wake' @@ -74,7 +73,7 @@ export default definePlugin({ ) ctx.watch(settings, found => found?.section({ page: 'projects', id: 'settle', order: 5, items: [settleItem], render: () => settleRow(ctx, days) })) ctx.effect(() => ctx.shell.section({ id: 'threads', order: 20, groups: () => groups.get() })) - ctx.watch(markdownLinks, found => found?.scheme(threadLinks({ kit: ctx.kit, shell: ctx.shell, row, open: thread => openThread(ctx, ctx.shell, thread) }))) + ctx.watch(markdownLinks, found => found?.scheme(threadLinks({ shell: ctx.shell, row }))) ctx.watch(palette, found => found?.source(sessionSource({ ...parts, rowOf }, ctx.kit))) wakeTimer(ctx, ctx.threads, events.bump) }, diff --git a/plugins/ui/threads/home/src/links.ts b/plugins/ui/threads/home/src/links.ts index 5440d4cc9..085c9cf96 100644 --- a/plugins/ui/threads/home/src/links.ts +++ b/plugins/ui/threads/home/src/links.ts @@ -1,40 +1,22 @@ import { threadRoute } from '@sand/chat/contract' import { threadScheme } from '@sand/chats/contract' import type { LinkScheme } from '@sand/markdown/contract' -import type { Kit } from '@sand/ui-kit/contract' import type { Shell, ShellRow } from '@sand/ui-shell/contract' -import { div, dynamicChild, span } from '@vaakx-dev/vrui' +import { div } from '@vaakx-dev/vrui' export interface LinkParts { - kit: Kit shell: Shell row(thread: string): ShellRow | undefined - open(thread: string): void } const textOf = (label: (Node | string)[]) => label.map(part => (typeof part === 'string' ? part : part.textContent)).join('') const unknownRow = (thread: string, label: string): ShellRow => ({ id: thread, label, to: { kind: threadRoute, id: thread } }) -const block = ({ shell, row }: LinkParts, thread: string, label: string) => div({ class: '-mx-2' }, shell.row(() => row(thread) ?? unknownRow(thread, label))) - -const stateMark = ({ kit, row }: LinkParts, thread: string) => - dynamicChild( - () => row(thread)?.status, - status => (status ? kit.statusIcon(status) : kit.stateIcon('idle')), - ) - -const inline = (parts: LinkParts, thread: string, label: string) => - parts.kit.plainButton( - { class: 'inline-flex max-w-full items-center gap-1 underline hover:text-neutral-400', onClick: () => parts.open(thread) }, - stateMark(parts, thread), - span({ class: 'min-w-0 truncate' }, label), - ) - -export const threadLinks = (parts: LinkParts): LinkScheme => ({ +export const threadLinks = ({ shell, row }: LinkParts): LinkScheme => ({ scheme: threadScheme, - render(thread, label, place) { + render(thread, label) { const text = textOf(label) - return place === 'block' ? block(parts, thread, text) : inline(parts, thread, text) + return div({ class: '-mx-2' }, shell.row(() => row(thread) ?? unknownRow(thread, text))) }, })