refactor(tui): organize source by feature boundaries (#5975)

* refactor(tui): group source files by feature

* refactor(tui): split app and gateway responsibilities
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-29 16:57:36 +08:00
1 parent b7abbcd70b
commit f18423800e
73 files changed
+6401 -6006

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, test } from "bun:test"
import type { ClipboardReadResult, HostClipboardService } from "@opentui/core"
import { createClipboardImageReader } from "./clipboard-image"
function clipboard(result: ClipboardReadResult) {
let disposed = false
const service = {
maxWriteBytes: 1,
read: async () => result,
writeText: async () => ({ status: "unsupported" as const }),
clear: async () => ({ status: "unsupported" as const }),
dispose: async () => { disposed = true },
} satisfies HostClipboardService
return { service, disposed: () => disposed }
}
describe("clipboard image reader", () => {
test("encodes supported native clipboard bytes as a data URL", async () => {
const fake = clipboard({
status: "read",
representation: { mimeType: "image/png", bytes: Uint8Array.from([0, 1, 2, 255]) },
})
const reader = createClipboardImageReader(() => fake.service)
expect(await reader.read()).toEqual({
mimeType: "image/png",
dataUrl: "data:image/png;base64,AAEC/w==",
})
await reader.dispose()
expect(fake.disposed()).toBeTrue()
})
test.each([
["empty", "No image in clipboard"],
["limit-exceeded", "Clipboard image is larger than 6 MB"],
["timed-out", "Clipboard image read timed out"],
["unsupported", "Clipboard image paste is unavailable"],
] as const)("reports %s without exposing native details", async (status, message) => {
const fake = clipboard({ status })
const reader = createClipboardImageReader(() => fake.service)
await expect(reader.read()).rejects.toThrow(message)
await reader.dispose()
})
})
+64
View File
@@ -0,0 +1,64 @@
import {
createHostClipboard,
type HostClipboardService,
} from "@opentui/core"
const IMAGE_MIME_TYPES = [
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
] as const
const MAX_IMAGE_BYTES = 6 * 1024 * 1024
interface ClipboardImage {
dataUrl: string
mimeType: typeof IMAGE_MIME_TYPES[number]
}
export interface ClipboardImageReader {
read(): Promise<ClipboardImage>
dispose(): Promise<void>
}
type ClipboardFactory = () => HostClipboardService
function readFailure(status: string): Error {
if (status === "empty") return new Error("No image in clipboard")
if (status === "limit-exceeded") return new Error("Clipboard image is larger than 6 MB")
if (status === "timed-out") return new Error("Clipboard image read timed out")
return new Error("Clipboard image paste is unavailable")
}
/** Lazily owns OpenTUI's native host clipboard so ordinary TUI startup does no clipboard work. */
export function createClipboardImageReader(
createClipboard: ClipboardFactory = () => createHostClipboard({ maxReadBytes: MAX_IMAGE_BYTES }),
): ClipboardImageReader {
let clipboard: HostClipboardService | null = null
let disposed = false
return {
async read(): Promise<ClipboardImage> {
if (disposed) throw new Error("Clipboard image paste is unavailable")
clipboard ||= createClipboard()
const result = await clipboard.read({ preferredTypes: IMAGE_MIME_TYPES })
if (result.status !== "read") throw readFailure(result.status)
const normalizedMime = result.representation.mimeType.toLowerCase()
const mimeType = IMAGE_MIME_TYPES.find((candidate) => candidate === normalizedMime)
if (!mimeType) throw new Error("Clipboard does not contain a supported image")
const bytes = result.representation.bytes
if (!bytes.length) throw new Error("Clipboard image is empty")
if (bytes.length > MAX_IMAGE_BYTES) throw new Error("Clipboard image is larger than 6 MB")
return {
mimeType,
dataUrl: `data:${mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
}
},
async dispose(): Promise<void> {
if (disposed) return
disposed = true
await clipboard?.dispose()
clipboard = null
},
}
}
+151
View File
@@ -0,0 +1,151 @@
import { describe, expect, test } from "bun:test"
import { ComposerDraft, MAX_DRAFT_IMAGES } from "./composer-draft"
describe("ComposerDraft", () => {
test("keeps ordinary pastes editable as ordinary text", () => {
const draft = new ComposerDraft()
const insertion = draft.paste("first\r\nsecond")
expect(insertion).toEqual({ text: "first\nsecond", compacted: false, description: "" })
expect(draft.expand(`before ${insertion.text} after`)).toBe("before first\nsecond after")
})
test("compacts large pastes and expands only placeholders that remain", () => {
const draft = new ComposerDraft()
const content = Array.from({ length: 12 }, (_, index) => `line ${index}`).join("\n")
const first = draft.paste(content)
const second = draft.paste(content)
expect(first.text).toBe("[Pasted 12 lines] ")
expect(second.text).toBe("[Pasted 12 lines #2] ")
expect(draft.expand(`review ${first.text.trim()}`)).toBe(`review ${content}`)
draft.prune(second.text)
expect(draft.expand(first.text.trim())).toBe(first.text.trim())
expect(draft.expand(second.text.trim())).toBe(content)
})
test("keeps image bytes outside the editor and drops attachments with deleted placeholders", () => {
const draft = new ComposerDraft()
const first = draft.image({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })
const second = draft.image({ mimeType: "image/jpeg", dataUrl: "data:image/jpeg;base64,BBBB" })
expect(first?.text).toBe("[Image #1] ")
expect(second?.text).toBe("[Image #2] ")
const visible = `compare ${second?.text}${first?.text}`
expect(draft.expand(visible)).toBe("compare ")
expect(draft.display(visible)).toBe(visible)
expect(draft.media(visible)).toEqual([
{ data_url: "data:image/jpeg;base64,BBBB", name: "clipboard-image-2.jpg" },
{ data_url: "data:image/png;base64,AAAA", name: "clipboard-image-1.png" },
])
draft.prune(first?.text || "")
expect(draft.imageCount).toBe(1)
expect(draft.media(second?.text || "")).toEqual([])
})
test("removes a partially edited image placeholder as one atomic unit", () => {
const draft = new ComposerDraft()
const image = draft.image({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })
const previous = `before ${image?.text}after`
const value = previous.replace("[Image #1]", "Image #1]")
expect(draft.reconcileImageEdit(previous, value, 7)).toEqual({
value: "before after",
cursor: 7,
removedImages: ["Image #1"],
})
expect(draft.imageCount).toBe(0)
expect(draft.media(value)).toEqual([])
})
test("removes an edited duplicate occurrence without leaving a placeholder fragment", () => {
const draft = new ComposerDraft()
const image = draft.image({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })
const label = image?.text.trim() || ""
const previous = `${label} ${label}`
expect(draft.reconcileImageEdit(previous, previous.slice(1), 0)).toEqual({
value: ` ${label}`,
cursor: 0,
removedImages: [],
})
expect(draft.imageCount).toBe(1)
})
test("snaps cursor movement across complete image placeholders", () => {
const draft = new ComposerDraft()
const image = draft.image({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })
const visible = `a ${image?.text}b`
expect(draft.snapImageCursor(visible, 3, 2)).toBe(12)
expect(draft.snapImageCursor(visible, 11, 12)).toBe(2)
expect(draft.snapImageCursor(visible, 2, 0)).toBe(2)
expect(draft.snapImageCursor(visible, 12, 13)).toBe(12)
expect(draft.moveImageCursor(visible, 2, 1)).toBe(12)
expect(draft.moveImageCursor(visible, 12, -1)).toBe(2)
})
test("allocates image labels around literal composer text", () => {
const draft = new ComposerDraft()
const content = "Explain [Image #1]"
const insertion = draft.image(
{ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" },
content,
)
expect(insertion?.text).toBe("[Image #2] ")
expect(draft.expand(`${content} ${insertion?.text}`.trim())).toBe(`${content} `)
})
test("detects image labels duplicated after insertion without deleting text", () => {
const draft = new ComposerDraft()
const image = draft.image({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })
const visible = `${image?.text}Explain [Image #1]`
expect(draft.hasImageLabelConflict(visible)).toBeTrue()
expect(draft.expand(visible)).toBe(visible)
})
test("detects image labels inside compacted paste text added afterward", () => {
const draft = new ComposerDraft()
const image = draft.image({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })
const content = ["Explain [Image #1]", ...Array.from({ length: 11 }, () => "detail")].join("\n")
const paste = draft.paste(content)
const visible = `${image?.text}${paste.text}`
expect(draft.hasImageLabelConflict(visible)).toBeTrue()
expect(draft.expand(visible)).toContain("Explain [Image #1]")
})
test("allocates image labels around hidden compacted paste text", () => {
const draft = new ComposerDraft()
const content = ["Explain [Image #1]", ...Array.from({ length: 11 }, () => "detail")].join("\n")
const paste = draft.paste(content)
const image = draft.image(
{ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" },
paste.text,
)
expect(image?.text).toBe("[Image #2] ")
expect(draft.expand(`${paste.text}${image?.text}`)).toContain("Explain [Image #1]")
})
test("matches the gateway image count before accepting another placeholder", () => {
const draft = new ComposerDraft()
for (let index = 0; index < MAX_DRAFT_IMAGES; index += 1) {
expect(draft.image({
mimeType: "image/png",
dataUrl: `data:image/png;base64,${index}`,
})).not.toBeNull()
}
expect(draft.image({
mimeType: "image/png",
dataUrl: "data:image/png;base64,overflow",
})).toBeNull()
expect(draft.imageCount).toBe(MAX_DRAFT_IMAGES)
})
})
+199
View File
@@ -0,0 +1,199 @@
import type { OutboundMedia } from "../client"
const LARGE_PASTE_CHARS = 1_000
const LARGE_PASTE_LINES = 10
export const MAX_DRAFT_IMAGES = 4
export interface PasteInsertion {
text: string
compacted: boolean
description: string
}
export interface DraftEditReconciliation {
value: string
cursor: number
removedImages: string[]
}
const IMAGE_EXTENSIONS = {
"image/png": "png",
"image/jpeg": "jpg",
"image/webp": "webp",
"image/gif": "gif",
} as const
interface DraftImage {
dataUrl: string
mimeType: keyof typeof IMAGE_EXTENSIONS
}
/** Keeps large pasted text and image payloads out of the editable composer surface. */
export class ComposerDraft {
private readonly pastes = new Map<string, string>()
private readonly images = new Map<string, OutboundMedia>()
get imageCount(): number {
return this.images.size
}
paste(value: string): PasteInsertion {
const text = value.replace(/\r\n/gu, "\n").replace(/\r/gu, "\n")
const lines = text.split("\n").length
if (text.length < LARGE_PASTE_CHARS && lines < LARGE_PASTE_LINES) {
return { text, compacted: false, description: "" }
}
const description = lines > 1 ? `${lines} lines` : `${text.length} characters`
const base = `[Pasted ${description}]`
let label = base
for (let index = 2; this.pastes.has(label); index += 1) label = `${base.slice(0, -1)} #${index}]`
this.pastes.set(label, text)
return { text: `${label} `, compacted: true, description }
}
private imageLabelInUse(label: string, visible: string): boolean {
if (this.images.has(label) || visible.includes(label)) return true
for (const content of this.pastes.values()) {
if (content.includes(label)) return true
}
return false
}
private nextImageIndex(visible: string): number {
let index = 1
while (this.imageLabelInUse(`[Image #${index}]`, visible)) index += 1
return index
}
image(image: DraftImage, visible = ""): PasteInsertion | null {
if (this.images.size >= MAX_DRAFT_IMAGES) return null
const index = this.nextImageIndex(visible)
const label = `[Image #${index}]`
this.images.set(label, {
data_url: image.dataUrl,
name: `clipboard-image-${index}.${IMAGE_EXTENSIONS[image.mimeType]}`,
})
return { text: `${label} `, compacted: true, description: label.slice(1, -1) }
}
private expandPastes(visible: string): string {
let expanded = visible
for (const [label, content] of this.pastes) expanded = expanded.split(label).join(content)
return expanded
}
private labelOccurrences(content: string, label: string): number {
return content.split(label).length - 1
}
imagePlaceholderRanges(visible: string): Array<{ start: number; end: number }> {
const ranges: Array<{ start: number; end: number }> = []
for (const label of this.images.keys()) {
let start = visible.indexOf(label)
while (start >= 0) {
ranges.push({ start, end: start + label.length })
start = visible.indexOf(label, start + label.length)
}
}
return ranges.sort((left, right) => left.start - right.start)
}
snapImageCursor(visible: string, cursor: number, previousCursor: number): number {
const range = this.imagePlaceholderRanges(visible)
.find(({ start, end }) => cursor > start && cursor < end)
if (!range) return cursor
if (previousCursor <= range.start) return range.end
if (previousCursor >= range.end) return range.start
return cursor - range.start < range.end - cursor ? range.start : range.end
}
moveImageCursor(visible: string, cursor: number, direction: -1 | 1): number | null {
const range = this.imagePlaceholderRanges(visible).find(({ start, end }) => (
direction < 0
? cursor > start && cursor <= end
: cursor >= start && cursor < end
))
if (!range) return null
return direction < 0 ? range.start : range.end
}
reconcileImageEdit(
previous: string,
value: string,
cursor: number,
): DraftEditReconciliation {
let oldStart = 0
const sharedLength = Math.min(previous.length, value.length)
while (oldStart < sharedLength && previous[oldStart] === value[oldStart]) oldStart += 1
let oldEnd = previous.length
let newEnd = value.length
while (
oldEnd > oldStart
&& newEnd > oldStart
&& previous[oldEnd - 1] === value[newEnd - 1]
) {
oldEnd -= 1
newEnd -= 1
}
const ranges = this.imagePlaceholderRanges(previous).filter(({ start, end }) => (
oldStart === oldEnd
? oldStart > start && oldStart < end
: oldStart < end && oldEnd > start
))
if (!ranges.length) return { value, cursor, removedImages: [] }
const replaceStart = Math.min(oldStart, ...ranges.map((range) => range.start))
const replaceEnd = Math.max(oldEnd, ...ranges.map((range) => range.end))
const inserted = value.slice(oldStart, newEnd)
const reconciled = previous.slice(0, replaceStart) + inserted + previous.slice(replaceEnd)
const missing = [...this.images.keys()].filter((label) => !reconciled.includes(label))
for (const label of missing) this.images.delete(label)
return {
value: reconciled,
cursor: replaceStart + inserted.length,
removedImages: missing.map((label) => label.slice(1, -1)),
}
}
hasImageLabelConflict(visible: string): boolean {
const expanded = this.expandPastes(visible)
return [...this.images.keys()]
.some((label) => this.labelOccurrences(expanded, label) !== 1)
}
expand(visible: string): string {
let expanded = this.expandPastes(visible)
for (const label of this.images.keys()) {
if (this.labelOccurrences(expanded, label) === 1) expanded = expanded.replace(label, "")
}
return expanded
}
display(visible: string): string {
return this.expandPastes(visible)
}
media(visible: string): OutboundMedia[] {
return [...this.images]
.filter(([label]) => visible.includes(label))
.sort(([left], [right]) => visible.indexOf(left) - visible.indexOf(right))
.map(([, media]) => media)
}
prune(visible: string): void {
for (const label of this.pastes.keys()) {
if (!visible.includes(label)) this.pastes.delete(label)
}
for (const label of this.images.keys()) {
if (!visible.includes(label)) this.images.delete(label)
}
}
clear(): void {
this.pastes.clear()
this.images.clear()
}
}
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, test } from "bun:test"
import { PromptQueue } from "./prompt-queue"
const prompt = (content: string) => ({ content, options: {} })
describe("PromptQueue", () => {
test("returns the latest follow-up for editing", () => {
const queue = new PromptQueue()
queue.enqueue(prompt("next one"))
queue.enqueue(prompt("steer now"))
expect(queue.takeLast()?.content).toBe("steer now")
expect(queue.snapshot().map(({ content }) => content)).toEqual(["next one"])
expect(queue.takeFollowUp()?.content).toBe("next one")
})
test("keeps follow-ups FIFO and restores unsent drafts", () => {
const queue = new PromptQueue()
queue.enqueue(prompt("first"))
queue.enqueue(prompt("second"))
expect(queue.takeFollowUp()?.content).toBe("first")
expect(queue.restore().map(({ content }) => content)).toEqual(["second"])
expect(queue.length).toBe(0)
})
})
+42
View File
@@ -0,0 +1,42 @@
import type { MessageOptions } from "../client"
export interface QueuedPrompt {
content: string
displayContent?: string
options: MessageOptions
}
/** Owns prompts that should start after the active turn finishes. */
export class PromptQueue {
private prompts: QueuedPrompt[] = []
get length(): number {
return this.prompts.length
}
enqueue(prompt: QueuedPrompt): void {
this.prompts.push(prompt)
}
takeLast(): QueuedPrompt | null {
return this.prompts.pop() ?? null
}
takeFollowUp(): QueuedPrompt | null {
return this.prompts.shift() ?? null
}
snapshot(): readonly QueuedPrompt[] {
return this.prompts
}
restore(): QueuedPrompt[] {
const prompts = this.prompts
this.prompts = []
return prompts
}
clear(): void {
this.prompts = []
}
}
+37
View File
@@ -0,0 +1,37 @@
import { afterEach, describe, expect, test } from "bun:test"
import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
import { QueuePreview } from "./queue-preview"
describe("QueuePreview", () => {
let setup: TestRendererSetup | undefined
afterEach(() => {
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
setup = undefined
})
test("shows the latest follow-ups without becoming another card", async () => {
setup = await createTestRenderer({ width: 64, height: 12, screenMode: "alternate-screen" })
const preview = new QueuePreview(setup.renderer, {
accent: "#EF8E30",
muted: "#A1A1AA",
faint: "#71717A",
}, "darwin")
setup.renderer.root.add(preview.root)
preview.update(["first\nline", "second", "third", "fourth"])
await setup.renderOnce()
const frame = setup.captureCharFrame()
expect(frame).toContain("Queued next 4")
expect(frame).toContain("⌥↑ edit last")
expect(frame).not.toContain("first line")
expect(frame).toContain("↳ second")
expect(frame).toContain("↳ fourth")
preview.update([])
await setup.renderOnce()
expect(setup.captureCharFrame()).not.toContain("Queued next")
})
})
+101
View File
@@ -0,0 +1,101 @@
import {
BoxRenderable,
RGBA,
StyledText,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
} from "@opentui/core"
import { optionArrowUp } from "../platform/platform-keys"
export interface QueuePreviewTheme {
accent: ColorInput
muted: ColorInput
faint: ColorInput
}
const MAX_VISIBLE = 3
/** A compact, retained projection of follow-ups waiting behind the active turn. */
export class QueuePreview {
readonly root: BoxRenderable
private readonly header: TextRenderable
private readonly rows: TextRenderable[]
private readonly editKey: string
private theme: QueuePreviewTheme
private messages: readonly string[] = []
constructor(renderer: CliRenderer, theme: QueuePreviewTheme, platform: string = process.platform) {
this.theme = theme
this.editKey = optionArrowUp(platform)
this.root = new BoxRenderable(renderer, {
id: "nanobot-tui-queue-preview",
width: "100%",
height: 1,
flexShrink: 0,
flexDirection: "column",
paddingLeft: 1,
paddingRight: 1,
visible: false,
backgroundColor: RGBA.defaultBackground(),
})
this.header = new TextRenderable(renderer, {
id: "nanobot-tui-queue-header",
width: "100%",
height: 1,
flexShrink: 0,
truncate: true,
})
this.rows = Array.from({ length: MAX_VISIBLE }, (_, index) => new TextRenderable(renderer, {
id: `nanobot-tui-queue-row-${index}`,
width: "100%",
height: 1,
flexShrink: 0,
truncate: true,
visible: false,
}))
this.root.add(this.header)
for (const row of this.rows) this.root.add(row)
}
update(messages: readonly string[]): void {
this.messages = [...messages]
const visible = messages.slice(-MAX_VISIBLE)
this.root.visible = messages.length > 0
this.root.height = messages.length ? visible.length + 1 : 1
this.header.content = new StyledText([
chunk("Queued next", this.theme.accent, true),
chunk(` ${messages.length}`, this.theme.faint),
chunk(` · ${this.editKey} edit last`, this.theme.faint),
])
this.rows.forEach((row, index) => {
const message = visible[index]
row.visible = Boolean(message)
row.content = message ? ` ↳ ${oneLine(message)}` : ""
row.fg = this.theme.muted
})
}
setTheme(theme: QueuePreviewTheme): void {
this.theme = theme
this.update(this.messages)
}
}
function oneLine(value: string): string {
const preview = value.slice(0, 240).replace(/\s+/gu, " ").trim()
return value.length > 240 ? `${preview}…` : preview
}
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return {
__isChunk: true,
text,
fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0,
}
}