forked from vhaudiquet/rhema-claw
feat: chips travel as span records, not mark embeds
The claw's wire carried chips only as U+FFFC-payload-U+FFFC marks written into the text — the very encoding 0.4.0's fold migrated at the provider seam. Now the record rhema-core defined is the wire's own: a message's pasted payloads ride the POST body's `pastes` array beside the plain draft, the fold composes the plain form and measures each chip's PasteSpan, and the `user_message` echo carries text plus `pastes` — the session annotation's own shape — while the turn's question carries the span note into the checkpoint, shifted by the exact bytes any framing prefix adds. The web client mints and renders the new record: the composer sends draft and payloads separately, the optimistic row composes the same plain text and spans the fold will record (so the echo dedupes), and the render slices the text at the record's byte offsets. Rows recorded before spans arrived still parse the mark form — as does every arrival that still mints it, including every surface the shim or an older client feeds. The phone is one of those: it parses chips by scanning marks, and kotlinx ignores the new field, so it reads spans-less rows exactly as before; adopting span records for its own rows is a follow-up.
This commit is contained in:
1 parent
22c502a9eb
commit
dd91501e10
12 files changed
+484
-108
No files matched your search
+12
-7
@@ -21,7 +21,7 @@ import type {
|
||||
SandboxState,
|
||||
StreamStatus,
|
||||
} from '~/composables/useClaw'
|
||||
import { useTranscript } from '~/composables/useTranscript'
|
||||
import { composeChips, useTranscript } from '~/composables/useTranscript'
|
||||
import type { StagedImage } from '~/composables/useTranscript'
|
||||
|
||||
const TOKEN_STORE_KEY = 'claw.token'
|
||||
@@ -533,21 +533,26 @@ async function saveSandbox(choice: SandboxSelection): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
|
||||
// The optimistic row renders the staged previews; the stream's
|
||||
// user_message echo carries the stored ids and dedupes against it.
|
||||
async function send(message: { text: string; pastes: string[]; images: StagedImage[] }): Promise<void> {
|
||||
// The optimistic row renders the staged previews and the composed
|
||||
// chip record — the same plain text and spans the fold records on
|
||||
// the other side — so the stream's user_message echo, which
|
||||
// carries the stored ids beside that record, dedupes against it.
|
||||
const composed = composeChips(message.text, message.pastes)
|
||||
const rowId = transcript.addSent(
|
||||
message.text,
|
||||
composed.text,
|
||||
message.images.map(({ media_type, url, name }) => ({ id: null, media_type, url, name })),
|
||||
composed.pastes,
|
||||
)
|
||||
busy.value = true
|
||||
try {
|
||||
// Fire-and-forget by design: the claw answers 202 and the reply
|
||||
// arrives on the event stream. The body carries the images only
|
||||
// when there are some.
|
||||
// arrives on the event stream. The chips and the images ride the
|
||||
// body only when there are some.
|
||||
await claw.sendMessage(
|
||||
activeKey.value,
|
||||
message.text,
|
||||
message.pastes,
|
||||
message.images.map(({ media_type, data }) => ({ media_type, data })),
|
||||
)
|
||||
apiError.value = null
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
import {
|
||||
PASTE_INLINE_LINES,
|
||||
chipLabel,
|
||||
embedPastes,
|
||||
byteToIndex,
|
||||
chipLinesLabel,
|
||||
lineCount,
|
||||
normalizePaste,
|
||||
pasteParts,
|
||||
} from '~/composables/useTranscript'
|
||||
import type { ClawSession, ConsentAnswer, StreamStatus } from '~/composables/useClaw'
|
||||
import type { PasteSpan } from '~/composables/useClaw'
|
||||
import type { PastePart, SentImage, StagedImage, TranscriptItem, TurnBlock } from '~/composables/useTranscript'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -45,6 +47,9 @@ const agentName = computed(() => props.identity?.name?.trim() || 'rhema')
|
||||
* the staged images, previews included for the optimistic row. */
|
||||
interface SendPayload {
|
||||
text: string
|
||||
/** The chip payloads, in staging order — the wire carries them
|
||||
* beside the plain draft; the fold composes the record. */
|
||||
pastes: string[]
|
||||
images: StagedImage[]
|
||||
}
|
||||
|
||||
@@ -157,7 +162,7 @@ function submit(): void {
|
||||
// answers 202 at once) — a running turn never blocks the composer,
|
||||
// because a send into one steers it.
|
||||
if (!text || !props.canSend || props.busy) return
|
||||
emit('send', { text: embedPastes(text, pastes.value), images: stagedImages.value })
|
||||
emit('send', { text, pastes: pastes.value, images: stagedImages.value })
|
||||
stageGeneration++
|
||||
draft.value = ''
|
||||
pastes.value = []
|
||||
@@ -359,17 +364,36 @@ function storedImageName(image: SentImage): string {
|
||||
type MessageSegment = PastePart | { kind: 'chip'; label: string }
|
||||
|
||||
/** The message's render pieces: literal text and resolved chips, the
|
||||
* chips' one-based ids counted across the message. */
|
||||
function messageSegments(text: string): MessageSegment[] {
|
||||
* chips' one-based ids counted across the message. The chips come
|
||||
* from the row's span record — the plain text sliced at the spans'
|
||||
* byte boundaries — and a row from before spans rode the wire
|
||||
* carries none; that one still scans the mark form in its text. */
|
||||
function messageSegments(text: string, pastes: PasteSpan[] = []): MessageSegment[] {
|
||||
if (pastes.length === 0) {
|
||||
const segments: MessageSegment[] = []
|
||||
let chip = 0
|
||||
for (const part of pasteParts(text)) {
|
||||
if (part.kind === 'text') {
|
||||
if (part.text !== '') segments.push(part)
|
||||
} else {
|
||||
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) })
|
||||
}
|
||||
}
|
||||
return segments
|
||||
}
|
||||
const indexOf = byteToIndex(text)
|
||||
const segments: MessageSegment[] = []
|
||||
let chip = 0
|
||||
for (const part of pasteParts(text)) {
|
||||
if (part.kind === 'text') {
|
||||
if (part.text !== '') segments.push(part)
|
||||
} else {
|
||||
segments.push({ kind: 'chip', label: chipLabel(part.text, chip++) })
|
||||
}
|
||||
let cut = 0
|
||||
for (const span of [...pastes].sort((a, b) => a.start - b.start)) {
|
||||
const start = indexOf(span.start)
|
||||
const end = indexOf(span.end)
|
||||
if (start === -1 || end === -1 || start < cut || end < start) continue
|
||||
if (start > cut) segments.push({ kind: 'text', text: text.slice(cut, start) })
|
||||
segments.push({ kind: 'chip', label: chipLinesLabel(span.lines, chip++) })
|
||||
cut = end
|
||||
}
|
||||
if (cut < text.length) segments.push({ kind: 'text', text: text.slice(cut) })
|
||||
return segments
|
||||
}
|
||||
|
||||
@@ -445,7 +469,7 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
|
||||
</button>
|
||||
</div>
|
||||
<div class="reply plain">
|
||||
<template v-for="(segment, index) in messageSegments(item.text)" :key="index">
|
||||
<template v-for="(segment, index) in messageSegments(item.text, item.pastes)" :key="index">
|
||||
<span v-if="segment.kind === 'chip'" class="badge paste-chip">{{ segment.label }}</span>
|
||||
<template v-else>{{ segment.text }}</template>
|
||||
</template>
|
||||
|
||||
@@ -56,9 +56,20 @@ export interface UserImage {
|
||||
media_type: string
|
||||
}
|
||||
|
||||
/** One paste chip a `user_message` carries: the record the session's
|
||||
* `rhema-code` annotation holds — the byte range in the plain text the
|
||||
* chip stands for (UTF-8 offsets; see useTranscript's
|
||||
* `byteToIndex`), plus the payload's line count for the chip's label
|
||||
* (rhema-core `PasteSpan`). */
|
||||
export interface PasteSpan {
|
||||
start: number
|
||||
end: number
|
||||
lines: number
|
||||
}
|
||||
|
||||
/** One turn event, exactly `hub.rs`'s `TurnEvent` (serde type tag, snake case). */
|
||||
export type TurnEvent =
|
||||
| { type: 'user_message'; text: string; images: UserImage[] }
|
||||
| { type: 'user_message'; text: string; images: UserImage[]; pastes: PasteSpan[] }
|
||||
| { type: 'thinking_delta'; text: string }
|
||||
| { type: 'text_delta'; text: string }
|
||||
| { type: 'tool_start'; name: string }
|
||||
@@ -398,8 +409,8 @@ export interface ClawApi {
|
||||
* a plain src will not do). Cached per id: attachments are immutable,
|
||||
* so a replayed event never refetches. */
|
||||
attachmentUrl(id: string): Promise<string>
|
||||
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
|
||||
sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void>
|
||||
/** `POST /v1/sessions/{key}/messages` — fire-and-forget: the claw answers 202 and the reply arrives on the event stream. Images and chip payloads ride the body only when there are some; without them the body is the old `{"text"}` shape byte-for-byte. The route 422s an empty text even with images aboard. */
|
||||
sendMessage(key: string, text: string, pastes?: string[], images?: OutboundImage[]): Promise<void>
|
||||
/** `GET /v1/providers` — the constructible backends and the active pair. */
|
||||
providers(): Promise<ProvidersState>
|
||||
/** `PUT /v1/providers/active` — switch the backend, persisted claw-side. Answers the new active pair only. */
|
||||
@@ -533,11 +544,19 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
})
|
||||
}
|
||||
|
||||
async function sendMessage(key: string, text: string, images?: OutboundImage[]): Promise<void> {
|
||||
async function sendMessage(
|
||||
key: string,
|
||||
text: string,
|
||||
pastes?: string[],
|
||||
images?: OutboundImage[],
|
||||
): Promise<void> {
|
||||
const body: { text: string; pastes?: string[]; images?: OutboundImage[] } = { text }
|
||||
if (pastes?.length) body.pastes = pastes
|
||||
if (images?.length) body.images = images
|
||||
await send(`/v1/sessions/${encodeURIComponent(key)}/messages`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
|
||||
body: JSON.stringify(images?.length ? { text, images } : { text }),
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -919,6 +938,24 @@ function parseUserImages(raw: unknown): UserImage[] {
|
||||
return images
|
||||
}
|
||||
|
||||
/** The paste chips a `user_message` carries: rows recorded before
|
||||
* chips rode as spans carry the mark form in the text instead and no
|
||||
* field at all — empty, the render falls back to scanning — and a
|
||||
* span without whole-number bounds or a line count is not one. */
|
||||
function parseUserPastes(raw: unknown): PasteSpan[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const pastes: PasteSpan[] = []
|
||||
for (const entry of raw) {
|
||||
const span = entry as Record<string, unknown>
|
||||
if (typeof span.start !== 'number' || typeof span.end !== 'number') continue
|
||||
if (typeof span.lines !== 'number') continue
|
||||
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || !Number.isInteger(span.lines)) continue
|
||||
if (span.start < 0 || span.end < span.start || span.lines < 0) continue
|
||||
pastes.push({ start: span.start, end: span.end, lines: span.lines })
|
||||
}
|
||||
return pastes
|
||||
}
|
||||
|
||||
/** Parses one `data:` payload into a `TurnEvent`; unknown shapes are dropped, not guessed. */
|
||||
function parseTurnEvent(data: string): TurnEvent | null {
|
||||
try {
|
||||
@@ -929,6 +966,7 @@ function parseTurnEvent(data: string): TurnEvent | null {
|
||||
type: 'user_message',
|
||||
text: String(raw.text ?? ''),
|
||||
images: parseUserImages(raw.images),
|
||||
pastes: parseUserPastes(raw.pastes),
|
||||
}
|
||||
case 'thinking_delta':
|
||||
case 'text_delta':
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// mirror when the stream reopens and folds what arrives, never the other
|
||||
// way around.
|
||||
import { ref } from 'vue'
|
||||
import type { AttachmentMedia, ConsentKind, OutboundImage, TurnEvent } from './useClaw'
|
||||
import type { AttachmentMedia, ConsentKind, OutboundImage, PasteSpan, TurnEvent } from './useClaw'
|
||||
|
||||
/** One tool call inside a turn: started, then completed by its result. */
|
||||
export interface ToolRow {
|
||||
@@ -89,7 +89,7 @@ export interface StagedImage extends OutboundImage {
|
||||
|
||||
/** A transcript line: a message the local user sent, or one streamed turn. */
|
||||
export type TranscriptItem =
|
||||
| { kind: 'sent'; id: number; text: string; images: SentImage[] }
|
||||
| { kind: 'sent'; id: number; text: string; images: SentImage[]; pastes: PasteSpan[] }
|
||||
| { kind: 'turn'; id: number; turn: TurnBlock }
|
||||
| { kind: 'consent'; id: number; consent: ConsentCard }
|
||||
| { kind: 'attachment'; id: number; attachment: AttachmentCard }
|
||||
@@ -123,20 +123,53 @@ export function lineCount(text: string): number {
|
||||
return lines.length
|
||||
}
|
||||
|
||||
/** A chip's label: `▣1 5L` — the anchor's one-based id and the
|
||||
* payload's line count (the TUI's chip_label). */
|
||||
export function chipLabel(paste: string, index: number): string {
|
||||
return `▣${index + 1} ${lineCount(paste)}L`
|
||||
/** A chip's label from its line count: `▣1 5L` — the chip's
|
||||
* one-based id and the payload's line count (the TUI's chip_label). */
|
||||
export function chipLinesLabel(lines: number, index: number): string {
|
||||
return `▣${index + 1} ${lines}L`
|
||||
}
|
||||
|
||||
/** Appends each paste as one MARK-payload-MARK embed, in order — the
|
||||
* session's record of the prompt (paste::embed; a web draft holds no
|
||||
* anchors, so every payload lands at the end). */
|
||||
export function embedPastes(draft: string, pastes: string[]): string {
|
||||
return (
|
||||
draft +
|
||||
pastes.map((paste) => `${PASTE_MARK}${normalizePaste(paste)}${PASTE_MARK}`).join('')
|
||||
)
|
||||
/** A chip's label from its payload (the TUI's chip_label). */
|
||||
export function chipLabel(paste: string, index: number): string {
|
||||
return chipLinesLabel(lineCount(paste), index)
|
||||
}
|
||||
|
||||
/** The modern record the wire carries: each paste a byte span in the
|
||||
* plain text (the `rhema-code` annotation's own shape), one walk over
|
||||
* the composed text mapping every code-point boundary — a span that
|
||||
* splits a code point maps to none, the render skips it. */
|
||||
export function byteToIndex(text: string): (byte: number) => number {
|
||||
const at = new Map<number, number>([[0, 0]])
|
||||
const bytesOf = new TextEncoder()
|
||||
let bytes = 0
|
||||
let units = 0
|
||||
for (const cp of text) {
|
||||
bytes += bytesOf.encode(cp).length
|
||||
units += cp.length
|
||||
at.set(bytes, units)
|
||||
}
|
||||
return (byte) => at.get(byte) ?? -1
|
||||
}
|
||||
|
||||
/** Composes a send the way the fold composes its record: each paste's
|
||||
* normalized payload appends to the draft, its chip's span measured
|
||||
* over the composed plain text. The same form the `user_message`
|
||||
* echo carries, so the optimistic row and the replay render rows of
|
||||
* one shape and the echo dedupes against what this surface sent. */
|
||||
export function composeChips(
|
||||
draft: string,
|
||||
pastes: string[],
|
||||
): { text: string; pastes: PasteSpan[] } {
|
||||
const bytesOf = new TextEncoder()
|
||||
let text = draft
|
||||
const spans: PasteSpan[] = []
|
||||
for (const paste of pastes) {
|
||||
const payload = normalizePaste(paste)
|
||||
const start = bytesOf.encode(text).length
|
||||
text += payload
|
||||
spans.push({ start, end: bytesOf.encode(text).length, lines: lineCount(payload) })
|
||||
}
|
||||
return { text, pastes: spans }
|
||||
}
|
||||
|
||||
/** One scanned piece of embedded-form text. */
|
||||
@@ -244,6 +277,7 @@ export function useTranscript() {
|
||||
id: nextId++,
|
||||
text: event.text,
|
||||
images: event.images.map((image) => ({ ...image, url: null, name: null })),
|
||||
pastes: event.pastes,
|
||||
})
|
||||
break
|
||||
}
|
||||
@@ -356,10 +390,10 @@ export function useTranscript() {
|
||||
* Its images render from the staged previews — the claw stores them
|
||||
* and the stream's echo dedupes against this row. Returns the row's
|
||||
* id, so a failed POST can retract it. */
|
||||
function addSent(text: string, images: SentImage[] = []): number {
|
||||
function addSent(text: string, images: SentImage[] = [], pastes: PasteSpan[] = []): number {
|
||||
const id = nextId++
|
||||
pendingSent.push({ text, images: images.length, itemId: id })
|
||||
items.value.push({ kind: 'sent', id, text, images })
|
||||
items.value.push({ kind: 'sent', id, text, images, pastes })
|
||||
return id
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user