* feat(native-chat): add native chat view across mobile * fix(native-chat): address review findings and CodeRabbit threads Correctness: - Restore an independent initial readSession seed and surface initial-drain errors as snapshot frames so the chat view can never strand on 'loading' - Pair mobile tool results to calls by ordinal FIFO (parallel calls no longer misgraft results); clear a pending ask only when its own call resolves - Show a new streaming reply immediately (same-turn suppression, not length) - Delegate mobile noise filtering to the shared harness-injected classifier - Admit soft-leaving mobile clients in beginMobileInputFloor (parity with mobileTookFloor) so grace-window writes aren't dropped - Self-heal a stale 'working' status once this turn's reply lands - Catch RPC rejections in mobile file-open helpers; guard sanitizeToolInput key collisions; settle web/runtime transports on unrecognized first frames and forward snapshot errors Perf: - Throttle the mobile streaming bubble (50ms) so per-part status frames stop re-parsing the whole accumulated markdown - Short-circuit markdown path detection on dot-less or oversized runs (quadratic backtracking guard) UX/minor: - Wire hold-mode dictation through the native chat composer - Allow scoped-package (@) paths in file-path detection - Move caret after mid-text autocomplete insertion; index-prefixed ask option keys; single scroll-to-end effect; bounded wait + toast when image attach races a resubscribe; count-based pending reconciliation; cache-hit search cancels stale debounce; chat-tab toggle wins over in-flight preference load - Share shouldStepNativeChatAskAnswer between desktop and mobile; import block guards/source priority from shared instead of local copies - Defensive non-positive transcript limits; test strengthening (TTL expiry, post-unsubscribe stale frame, lease readiness, filtered console.error) * refactor(native-chat): share desktop/mobile chat logic in src/shared Extract the parity-mirrored native-chat modules into shared implementations both surfaces re-export: ask parsing (registry, parseAskFromStatus, extractPendingAsk, formatAskAnswer), answer stepping offsets/scheduler, diff detection/parsing, harness-noise filtering, tool fold/pair/split, and tool summaries. Removes the hand-synced copies and their stale Metro comments. Divergence reconciliations take the safer side of each: diffs truncate at 120 lines/32KB everywhere (desktop previously unbounded), tool-run summaries cap at 3 parts with bounded-depth previews, nameless tool calls are skipped, and basenames split on both separators. Also: settle and kill every sibling quick-open pass when one reaches maxResults (main rg/git and relay git; relay rg already did) so a capped search cannot leave a scan walking a huge tree; fold window-bounding into the shared merger's applyAppend; localize the web 'Pair a host' snapshot error. * fix(native-chat): address CodeRabbit follow-ups on shared modules - Attachment lease gate re-checks connection/target/tab after the bounded wait, so a tab/host switch or disconnect mid-wait can't send into a stale terminal; a moved-away target drops silently like the pre-wait guard and only an unrecovered lease surfaces the toast. Adds hook tests. - extractPendingAsk parses transcript tool-calls through the same registered-parser + canonical-shape fallback as live status, so a custom question tool that rendered live survives reconnect/replay. - Direct unit tests for the shared ask parser (FIFO ordering, fallback, malformed payloads) and tool-summary bounded preview (depth/collection caps, circular refs, basename/command branches). * fix(native-chat): treat initialLimit 0 as a valid empty window Both engine guards used truthiness, so an explicit zero limit skipped the bounded tail reader and fell back to an unbounded incremental read. Latent only (every caller clamps positive), hardened for consistency with the tail reader's non-positive-limit handling. * fix(mobile): native-chat composer lock UX + send-failure feedback - Distinguish input-lock reasons: transport 'disconnected' shows Reconnecting… instead of mislabeling a reconnect as locked-by-another-client - Guard the composer lock behind a 600ms hold so connState blips / lease hand-offs don't flicker the placeholder; unlock stays instant - Surface a rejected send inline above the composer (a bottom toast hides behind the keyboard); auto-dismisses after 4s - waiting-session hint invites the first message instead of implying the agent is still starting * test(mobile): sync answer-send pacing test to the 500ms advance buffer Missed in merge 8fe3c391c, which carried main's NATIVE_CHAT_ADVANCE_BUFFER_MS 300->500 (#8568) into the shared stepping module that mobile derives from. * fix(mobile): restore terminal stream after chat cold start * fix(native-chat): harden retries, optimistic sends, and file scans * fix(mobile): deliver AskUserQuestion answers by option number (STA-1860) Port #8840's fix to the mobile native chat: the Ask card now tracks per-question option INDICES (+ free text) and the answer-send hook drives Claude's arrow-navigate selector with buildAskAnswerKeys keystroke groups — option numbers, next-tab arrows, Enter — paced one selector step apart, instead of pasting label text that the selector ignores (which silently committed the default option). Non-Claude agents keep the pasted-label path via the selection-based formatAskAnswer. Backcompat: keystrokes are built client-side and written through the EXISTING terminal.send passthrough with enter:false — the same contract the permission card already uses — so an older desktop runtime (SSH/relay included) replays them verbatim; no RPC/contract change in either update order. Free text is newline-sanitized because terminal.send has no paste framing. Drops the now-unused formatCompleteAskAnswer from the shared module. * fix native chat send and runtime races * fix mobile native chat formatting * fix(native-chat): mobile empty state matches desktop copy Mobile showed a single generic line ('Send a message to get started') where desktop shows a titled two-line empty state naming the agent ('Start a chat with Claude' + 'Ask Claude to inspect code, explain output, or make a change.'). Align them from one source of truth so they can't drift again: - Extract the agent-type label map + formatAgentTypeLabel to src/shared/agent-type-label.ts (desktop re-exports; mobile imports). - Add src/shared/native-chat-empty-state.ts with the canonical English copy; desktop uses it as its i18n fallbacks (localization unchanged — en/es/ja/ko/zh keys still win), mobile substitutes the agent label and renders it directly (mobile ships English only). - Mobile: render title + subtitle for waiting-session AND ready-but-empty (both are 'start a chat'), error copy for errors; keep the loading spinner. Live-verified on the iOS sim against a pn-dev of this branch. typecheck node/web + mobile tsc clean; 30 mobile + 428 desktop/shared native-chat tests green. * style: oxfmt the empty-state parity test (line wrap) --------- Co-authored-by: Brennan Benson <brennanbenson@Brennans-MacBook-Pro.local> Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
86 lines
2.9 KiB
TypeScript
86 lines
2.9 KiB
TypeScript
export type NativeChatDiffLineKind = 'add' | 'del' | 'context' | 'meta'
|
|
|
|
export type NativeChatDiffLine = {
|
|
kind: NativeChatDiffLineKind
|
|
text: string
|
|
}
|
|
|
|
const EDIT_TOOL_NAMES = new Set(['Edit', 'MultiEdit', 'Write', 'str_replace', 'apply_patch'])
|
|
const MAX_DIFF_CHARS = 32_000
|
|
const DEFAULT_MAX_DIFF_LINES = 120
|
|
const DIFF_TRUNCATED_LINE: NativeChatDiffLine = {
|
|
kind: 'meta',
|
|
text: '… diff truncated …'
|
|
}
|
|
|
|
function toLines(value: unknown, maxLines: number): { lines: string[]; truncated: boolean } {
|
|
if (typeof value !== 'string') {
|
|
return { lines: [], truncated: false }
|
|
}
|
|
const clipped = value.slice(0, MAX_DIFF_CHARS)
|
|
const lines = clipped.split('\n', maxLines + 1)
|
|
const truncated = value.length > MAX_DIFF_CHARS || lines.length > maxLines
|
|
const bounded = lines.slice(0, maxLines)
|
|
if (!truncated && bounded.at(-1) === '') {
|
|
bounded.pop()
|
|
}
|
|
return { lines: bounded, truncated }
|
|
}
|
|
|
|
export function diffFromToolCall(
|
|
name: string,
|
|
input: unknown,
|
|
maxLines = DEFAULT_MAX_DIFF_LINES
|
|
): NativeChatDiffLine[] | null {
|
|
if (!EDIT_TOOL_NAMES.has(name) || typeof input !== 'object' || input === null) {
|
|
return null
|
|
}
|
|
const value = input as Record<string, unknown>
|
|
const oldLines = toLines(value.old_string ?? value.oldString ?? value.old, maxLines)
|
|
const newLines = toLines(
|
|
value.new_string ?? value.newString ?? value.new ?? value.content ?? value.file_text,
|
|
maxLines
|
|
)
|
|
const deleted = oldLines.lines.map((text): NativeChatDiffLine => ({ kind: 'del', text }))
|
|
const added = newLines.lines.map((text): NativeChatDiffLine => ({ kind: 'add', text }))
|
|
if (deleted.length === 0 && added.length === 0) {
|
|
return null
|
|
}
|
|
const path = value.file_path ?? value.path
|
|
const prefix: NativeChatDiffLine[] =
|
|
typeof path === 'string' ? [{ kind: 'meta', text: path }] : []
|
|
const combined = [...prefix, ...deleted, ...added]
|
|
const truncated = oldLines.truncated || newLines.truncated || combined.length > maxLines
|
|
return truncated ? [...combined.slice(0, maxLines - 1), DIFF_TRUNCATED_LINE] : combined
|
|
}
|
|
|
|
export function diffFromText(
|
|
text: string,
|
|
maxLines = DEFAULT_MAX_DIFF_LINES
|
|
): NativeChatDiffLine[] | null {
|
|
if (text.length === 0) {
|
|
return null
|
|
}
|
|
const bounded = toLines(text, maxLines)
|
|
let added = 0
|
|
let removed = 0
|
|
const lines = bounded.lines.map((line): NativeChatDiffLine => {
|
|
if (line.startsWith('@@') || line.startsWith('diff ') || line.startsWith('index ')) {
|
|
return { kind: 'meta', text: line }
|
|
}
|
|
if (line.startsWith('+') && !line.startsWith('+++')) {
|
|
added += 1
|
|
return { kind: 'add', text: line.slice(1) }
|
|
}
|
|
if (line.startsWith('-') && !line.startsWith('---')) {
|
|
removed += 1
|
|
return { kind: 'del', text: line.slice(1) }
|
|
}
|
|
return { kind: 'context', text: line }
|
|
})
|
|
if (added + removed < 2) {
|
|
return null
|
|
}
|
|
return bounded.truncated ? [...lines.slice(0, maxLines - 1), DIFF_TRUNCATED_LINE] : lines
|
|
}
|