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
3 changes: 1 addition & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
1 change: 0 additions & 1 deletion plugins/ui/chat/chat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
3 changes: 0 additions & 3 deletions plugins/ui/chat/chat/src/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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'
Expand Down Expand Up @@ -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 }) => {
Expand Down
10 changes: 0 additions & 10 deletions plugins/ui/chat/chat/src/links.ts

This file was deleted.

11 changes: 9 additions & 2 deletions plugins/ui/chat/chat/test/web/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-'))
Expand Down
63 changes: 63 additions & 0 deletions plugins/ui/chat/chat/test/web/thread-link.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof startSandbox>>
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)
})
2 changes: 1 addition & 1 deletion plugins/ui/chat/markdown/src/blocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions plugins/ui/chat/markdown/src/blocks/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))])
}

Expand Down
5 changes: 1 addition & 4 deletions plugins/ui/chat/markdown/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,9 @@ export interface Markdown {

export const markdown = service<Markdown>('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 {
Expand Down
15 changes: 10 additions & 5 deletions plugins/ui/chat/markdown/src/inline/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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

Expand Down Expand Up @@ -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)

Expand All @@ -61,15 +61,15 @@ 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
}
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; ) {
Expand All @@ -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]
}
81 changes: 48 additions & 33 deletions plugins/ui/chat/markdown/src/inline/links.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -21,50 +35,54 @@ 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(/[?!.,:;*_~'"]+$/, '')
while (trimmed.endsWith(')') && trimmed.split('(').length < trimmed.split(')').length) trimmed = trimmed.slice(0, -1)
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)
Expand All @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions plugins/ui/chat/markdown/src/nodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
9 changes: 1 addition & 8 deletions plugins/ui/chat/markdown/src/schemes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
}
6 changes: 4 additions & 2 deletions plugins/ui/chat/markdown/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
}
Loading
Loading