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
9 changes: 9 additions & 0 deletions docs/architecture/session-projection.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ canonical text or thinking, remove a round or tool result, or turn a settled
record back into an executing one. Externally projected sessions such as ACP
remain owned by their external projection.

The generation journal also owns the relative order of its model rounds.
Checkpoints may contain only a suffix or scattered rounds; filling gaps by tail
append would place earlier tool calls after the final response. Merge metadata
by stable round ID, then restore journal order and chronological round indexes.
Keep prior generations ahead of the current generation and retain other rounds
absent from the journal beside their preceding shared round. Repeating the merge
must preserve order and all retained records. Completion timestamps and the
checkpoint's partial indexes are not evidence of execution order.

Native Turn completion also reconciles cumulative token usage from the executing
host's durable request ledger before publishing the settled record. The query
uses native request-attempt identities scoped to the Session and Turn, including
Expand Down
7 changes: 7 additions & 0 deletions src/apps/mobile/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ UiState or an Intent declared there, and no module above it is visible to them.
same `commonTest` sources onto ART; they are not in CI, so run them by hand
when touching either module.

## Chat Markdown verification

For chat Markdown ranges, double-tilde strikethrough, escapes and streaming
prefixes, run from `shared/` with the Android guide's Java runtime:
`./gradlew :core-feature:jvmTest --tests '*MarkdownParserTest*'`.
Android and iOS share this parser; their native inline renderers own styles.

## Remote capability ownership

For next-input suggestion replay, stale-turn retirement, host restart and session
Expand Down
9 changes: 9 additions & 0 deletions src/apps/mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ and platform adapters. Product logic and stable contracts should remain in the
platform-agnostic Rust layers and be exposed to these apps through explicit
interfaces.

## Chat Markdown

Android, iOS and HarmonyOS keep single tildes literal in chat, matching the
desktop and mobile-web renderers: `24~30°C`, `1~2mm` and `~5 min` remain plain
text. Use `~~removed~~` for strikethrough. Escaped tildes (`\~`) and inline code
keep their literal text; unfinished double pairs remain literal while streaming.
This rendering policy applies to existing transcripts without changing the
host's saved Markdown or requiring a protocol upgrade.

## Image messages

All three apps can send images with or without text. Camera photos are decoded
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@ private fun annotatedInlines(

"emphasis" -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { append(inline.text) }

"delete" -> withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) { append(inline.text) }

"code" -> withStyle(SpanStyle(fontFamily = FontFamily.Monospace)) { append(inline.text) }

// A link in an agent turn is nearly always a file it just touched,
Expand Down
8 changes: 8 additions & 0 deletions src/apps/mobile/harmonyos/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,14 @@ insertion, 30 identical publications, text correction, deletion and completion;
block counts must be 2, 3, 3, 3, 2, 2, with one visible answer. Verify compact,
wide and live fold transitions, then return to normal `EntryAbility`.

For chat Markdown tildes, escapes, streaming prefixes and plain/rich copy, run
`node --test tools/tests/markdown-html-serializer.test.cjs tools/tests/streaming-markdown.test.cjs`.
These host tests execute the production parser and serializer; they do not
replace native rendering checks.
For a parser-only ArkTS compile without packaging/signing, source
`scripts/ohos-env.sh`, then run
`"$HVIGORW" --mode module -p product=default -p module=entry@default 'default@CompileArkTS' --no-daemon`.

For host shutdown/restart handling, run
`node --test tools/tests/connection-health.test.cjs tools/tests/session-record.test.cjs tools/tests/host-stream.test.cjs`.
In `durable-timeline`, **Host offline** must retain content and disable Stop;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,13 @@ export class MarkdownParser {
}

static formatInlineText(value: string): string {
let text = value;
text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)');
text = text.replace(/<(https?:\/\/|computer:\/\/|file:\/\/)([^\s<>]+)>/g, '$1$2');
text = text.replace(/`([^`]+)`/g, '$1');
text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
text = text.replace(/__([^_]+)__/g, '$1');
text = text.replace(/~~([^~]+)~~/g, '$1');
text = text.replace(/\*([^*]+)\*/g, '$1');
text = text.replace(/_([^_]+)_/g, '$1');
return text;
return MarkdownParser.plainInlineText(MarkdownParser.parseInlineText(value));
}

private static plainInlineText(inlines: ParsedMarkdownInline[]): string {
return inlines.map((inline: ParsedMarkdownInline) => {
return inline.type === 'link' && inline.text !== inline.url ? `${inline.text} (${inline.url})` : inline.text;
}).join('');
}

private static readCodeBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number {
Expand Down Expand Up @@ -198,11 +195,12 @@ export class MarkdownParser {
text += ' ' + continuationTrimmed;
nextIndex += 1;
}
const inlines = MarkdownParser.parseInlineText(text, `li-${start}-${items.length}`);
const item: ParsedMarkdownListItem = {
id: `li-${start}-${items.length}`,
marker,
text: MarkdownParser.formatInlineText(text),
inlines: MarkdownParser.parseInlineText(text, `li-${start}-${items.length}`),
text: MarkdownParser.plainInlineText(inlines),
inlines,
depth: MarkdownParser.listDepth(raw),
checked: taskMatch ? (taskMatch[1].toLowerCase() === 'x' ? 1 : 0) : -1
};
Expand Down Expand Up @@ -268,8 +266,8 @@ export class MarkdownParser {
tableRows: ParsedMarkdownTableRow[] = []
): void {
const id = `md-${blocks.length}-${type}`;
const normalizedText = MarkdownParser.shouldParseInline(type) ? MarkdownParser.formatInlineText(text) : text;
const inlines = MarkdownParser.shouldParseInline(type) ? MarkdownParser.parseInlineText(text, id) : [];
const normalizedText = MarkdownParser.shouldParseInline(type) ? MarkdownParser.plainInlineText(inlines) : text;
const block: ParsedMarkdownBlock = {
id,
renderKey: '',
Expand Down Expand Up @@ -389,10 +387,13 @@ export class MarkdownParser {
return end + 2;
}
}
if (value.slice(start, start + 2) === '~~') {
const end = value.indexOf('~~', start + 2);
if (MarkdownParser.isStrikeDelimiter(value, start, false)) {
let end = value.indexOf('~~', start + 2);
while (end >= 0 && !MarkdownParser.isStrikeDelimiter(value, end, true)) {
end = value.indexOf('~~', end + 2);
}
if (end > start + 2) {
MarkdownParser.pushInline(inlines, prefix, 'delete', value.slice(start + 2, end), '');
MarkdownParser.pushInline(inlines, prefix, 'delete', MarkdownParser.unescapeText(value.slice(start + 2, end)), '');
return end + 2;
}
}
Expand Down Expand Up @@ -448,6 +449,22 @@ export class MarkdownParser {
return next;
}

private static isStrikeDelimiter(value: string, index: number, closing: boolean): boolean {
// Single tildes are chat ranges; runs longer than two are literal inlines.
if (value.slice(index, index + 2) !== '~~' || value.charAt(index - 1) === '~' ||
value.charAt(index + 2) === '~' || MarkdownParser.isEscaped(value, index)) {
return false;
}
const before = value.charAt(index - 1);
const after = value.charAt(index + 2);
const beforeSpace = before.length === 0 || /\s/.test(before);
const afterSpace = after.length === 0 || /\s/.test(after);
const beforePunctuation = /[\p{P}\p{S}]/u.test(before);
const afterPunctuation = /[\p{P}\p{S}]/u.test(after);
return closing ? !beforeSpace && (!beforePunctuation || afterSpace || afterPunctuation) :
!afterSpace && (!afterPunctuation || beforeSpace || beforePunctuation);
}

private static pushInline(
inlines: ParsedMarkdownInline[],
prefix: string,
Expand Down Expand Up @@ -755,10 +772,11 @@ export class MarkdownParser {
for (let column = 0; column < columnCount; column += 1) {
const text = column < values.length ? values[column] : '';
const id = `table-${start}-${rowIndex}-${column}`;
const inlines = MarkdownParser.parseInlineText(text, id);
cells.push({
id,
text: MarkdownParser.formatInlineText(text),
inlines: MarkdownParser.parseInlineText(text, id),
text: MarkdownParser.plainInlineText(inlines),
inlines,
alignment: column < alignments.length ? alignments[column] : 'left'
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,37 @@ const { MarkdownParser } = parserModule;
const { MarkdownHtmlSerializer } = serializerModule;
const html = (text) => MarkdownHtmlSerializer.toHtml(text);

test('chat tildes preserve ranges, escapes and code while only double pairs strike', () => {
const cases = [
['24~30°C, rain 1~2mm; ~5 min; ~plain~', '24~30°C, rain 1~2mm; ~5 min; ~plain~', []],
['~~removed~~', 'removed', ['removed']],
[String.raw`\~escaped\~; \~~literal\~~`, '~escaped~; ~~literal~~', []],
['`~~code~~`', '~~code~~', []],
['before ~~~literal~~~ after', 'before ~~~literal~~~ after', []],
['~~ a~~; ~~b ~~; ~~unfinished', '~~ a~~; ~~b ~~; ~~unfinished', []],
[String.raw`~~a\~~b~~`, 'a~~b', ['a~~b']],
];
for (const [source, text, deleted] of cases) {
const inlines = MarkdownParser.parseInlineText(source);
assert.equal(inlines.map(inline => inline.text).join(''), text, source);
assert.deepEqual(inlines.filter(inline => inline.type === 'delete').map(inline => inline.text), deleted, source);
assert.equal(MarkdownParser.formatInlineText(source), text, source);
}
assert.equal(html('24~30°C, rain 1~2mm; ~~removed~~'), '<p>24~30°C, rain 1~2mm; <del>removed</del></p>');
});

test('streaming tildes stay literal until the double pair closes', () => {
const cache = new parserModule.MarkdownParseCache();
const prefix = '24~30°C, rain 1~2mm; ';
for (const suffix of ['~', '~~', '~~removed', '~~removed~']) {
const block = cache.blocksFor(prefix + suffix)[0];
assert.equal(block.inlines.map(inline => inline.text).join(''), prefix + suffix);
assert.deepEqual(block.inlines.filter(inline => inline.type === 'delete'), []);
}
assert.equal(MarkdownHtmlSerializer.blocksToHtml(cache.blocksFor(prefix + '~~removed~~')),
`<p>${prefix}<del>removed</del></p>`);
});

test('empty and whitespace-only input produce no payload', () => {
assert.equal(html(''), '');
assert.equal(html(' '), '');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,7 @@ private func markdownInlineString(
switch inline.type {
case "strong": part.inlinePresentationIntent = .stronglyEmphasized
case "emphasis": part.inlinePresentationIntent = .emphasized
case "delete": part.inlinePresentationIntent = .strikethrough
case "code":
part.inlinePresentationIntent = .code
part.backgroundColor = OpenBitFunTheme.soft
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,11 @@ public object MarkdownParser {
return blocks
}

public fun formatInlineText(value: String): String = value
.replace(Regex("\\[([^]]+)]\\(([^)]+)\\)"), "$1 ($2)")
.replace(Regex("`([^`]+)`"), "$1")
.replace(Regex("\\*\\*([^*]+)\\*\\*"), "$1")
.replace(Regex("__([^_]+)__"), "$1")
.replace(Regex("\\*([^*]+)\\*"), "$1")
.replace(Regex("_([^_]+)_"), "$1")
public fun formatInlineText(value: String): String = plainInlineText(parseInlineText(value))

private fun plainInlineText(inlines: List<MarkdownInline>): String = inlines.joinToString("") {
if (it.type == "link" && it.text != it.url) "${it.text} (${it.url})" else it.text
}

public fun parseInlineText(value: String): List<MarkdownInline> = parseInlineText(value, "inline")

Expand All @@ -83,10 +81,10 @@ public object MarkdownParser {
while (index < value.length) {
val next = nextInlineMarker(value, index)
if (next < 0) {
pushInline(inlines, prefix, "text", value.substring(index), "")
pushInline(inlines, prefix, "text", unescapeText(value.substring(index)), "")
break
}
if (next > index) pushInline(inlines, prefix, "text", value.substring(index, next), "")
if (next > index) pushInline(inlines, prefix, "text", unescapeText(value.substring(index, next)), "")
val consumed = readInlineAt(value, next, prefix, inlines)
if (consumed <= next) {
pushInline(inlines, prefix, "text", value[next].toString(), "")
Expand Down Expand Up @@ -144,7 +142,8 @@ public object MarkdownParser {
val raw = lines[index].trim()
val text = listText(raw)
val id = "li-" + start + "-" + items.size
items += MarkdownListItem(id, listMarker(raw), formatInlineText(text), parseInlineText(text, id))
val inlines = parseInlineText(text, id)
items += MarkdownListItem(id, listMarker(raw), plainInlineText(inlines), inlines)
index += 1
}
pushBlock(blocks, "list", 0, "", "", items)
Expand Down Expand Up @@ -197,14 +196,15 @@ public object MarkdownParser {
) {
val id = "md-" + blocks.size + "-" + type
val parseInline = shouldParseInline(type)
val inlines = if (parseInline) parseInlineText(text, id) else emptyList()
blocks += MarkdownBlock(
id = id,
type = type,
level = level,
language = language,
text = if (parseInline) formatInlineText(text) else text,
text = if (parseInline) plainInlineText(inlines) else text,
items = items,
inlines = if (parseInline) parseInlineText(text, id) else emptyList(),
inlines = inlines,
)
}

Expand All @@ -224,6 +224,17 @@ public object MarkdownParser {
if (end > start + 2) return pushAndReturn(inlines, prefix, "strong", value.substring(start + 2, end), "", end + 2)
}
}
// Chat ranges use a single tilde. Only an unescaped double pair may
// strike text; longer runs and unfinished streaming markers stay literal.
if (isStrikeDelimiter(value, start, closing = false)) {
var end = value.indexOf("~~", start + 2)
while (end >= 0 && !isStrikeDelimiter(value, end, closing = true)) {
end = value.indexOf("~~", end + 2)
}
if (end > start + 2) {
return pushAndReturn(inlines, prefix, "delete", unescapeText(value.substring(start + 2, end)), "", end + 2)
}
}
if (value[start] == '[') {
val labelEnd = value.indexOf(']', start + 1)
if (labelEnd > start + 1 && labelEnd + 1 < value.length && value[labelEnd + 1] == '(') {
Expand Down Expand Up @@ -262,11 +273,47 @@ public object MarkdownParser {
}

private fun nextInlineMarker(value: String, start: Int): Int =
listOf("`", "**", "__", "[", "*", "_")
.map { value.indexOf(it, start) }
listOf("`", "**", "__", "~~", "[", "*", "_")
.map { marker ->
var index = value.indexOf(marker, start)
while (index >= 0 && isEscaped(value, index)) index = value.indexOf(marker, index + marker.length)
index
}
.filter { it >= 0 }
.minOrNull() ?: -1

private fun isStrikeDelimiter(value: String, index: Int, closing: Boolean): Boolean {
if (!value.startsWith("~~", index) || value.getOrNull(index - 1) == '~' ||
value.getOrNull(index + 2) == '~' || isEscaped(value, index)
) return false
val before = value.getOrNull(index - 1)
val after = value.getOrNull(index + 2)
val beforeSpace = before == null || before.isWhitespace()
val afterSpace = after == null || after.isWhitespace()
val beforePunctuation = before != null && PUNCTUATION.matches(before.toString())
val afterPunctuation = after != null && PUNCTUATION.matches(after.toString())
return if (closing) !beforeSpace && (!beforePunctuation || afterSpace || afterPunctuation)
else !afterSpace && (!afterPunctuation || beforeSpace || beforePunctuation)
}

private fun isEscaped(value: String, index: Int): Boolean {
var cursor = index - 1
while (cursor >= 0 && value[cursor] == '\\') cursor -= 1
return (index - cursor - 1) % 2 == 1
}

private fun unescapeText(value: String): String = buildString {
var index = 0
while (index < value.length) {
if (value[index] == '\\' && index + 1 < value.length && value[index + 1] in ESCAPABLE) index += 1
append(value[index])
index += 1
}
}

private const val ESCAPABLE = "\\`*{}[]()#+-.!_>~|"
private val PUNCTUATION = Regex("[\\p{P}\\p{S}]")

private fun pushInline(
inlines: MutableList<MarkdownInline>,
prefix: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,39 @@ import kotlin.test.Test
import kotlin.test.assertEquals

class MarkdownParserTest {
@Test
fun chatTildesPreserveRangesEscapesAndCode() {
val cases = listOf(
Triple("24~30°C, rain 1~2mm; ~5 min; ~plain~", "24~30°C, rain 1~2mm; ~5 min; ~plain~", emptyList()),
Triple("~~removed~~", "removed", listOf("removed")),
Triple("\\~escaped\\~; \\~~literal\\~~", "~escaped~; ~~literal~~", emptyList()),
Triple("`~~code~~`", "~~code~~", emptyList()),
Triple("before ~~~literal~~~ after", "before ~~~literal~~~ after", emptyList()),
Triple("~~ a~~; ~~b ~~; ~~unfinished", "~~ a~~; ~~b ~~; ~~unfinished", emptyList()),
Triple("~~a\\~~b~~", "a~~b", listOf("a~~b")),
)
cases.forEach { (source, text, deleted) ->
val inlines = MarkdownParser.parseInlineText(source)
assertEquals(text, inlines.joinToString("") { it.text }, source)
assertEquals(deleted, inlines.filter { it.type == "delete" }.map { it.text }, source)
assertEquals(text, MarkdownParser.formatInlineText(source), source)
}
}

@Test
fun streamingTildesRemainLiteralUntilTheDoublePairCloses() {
val cache = MarkdownParseCache()
val prefix = "24~30°C, rain 1~2mm; "
listOf("~", "~~", "~~removed", "~~removed~").forEach { suffix ->
val block = cache.blocksFor(prefix + suffix).single()
assertEquals(prefix + suffix, block.inlines.joinToString("") { it.text })
assertEquals(emptyList(), block.inlines.filter { it.type == "delete" })
}
val complete = cache.blocksFor(prefix + "~~removed~~").single()
assertEquals(prefix + "removed", complete.inlines.joinToString("") { it.text })
assertEquals(listOf("removed"), complete.inlines.filter { it.type == "delete" }.map { it.text })
}

@Test
fun parsesCommonMarkdownBlocksIntoStableBlockTypes() {
val blocks = MarkdownParser.parse(
Expand Down
Loading
Loading