Cotton code
76 lines · 2.5 KB · TypeScriptRaw
/** * Echo suppression — crates/cotton-tools/src/session_echo.rs. A reply the * phone sent, typed into the terminal by the Mac, comes back in the transcript * as the owner's own turn; the message row is already on the session page, so * that turn is not written a second time. A message absorbs at most one turn. */import { rfc3339 } from "./common.ts";export const TYPED_KINDS = ["instruction", "answer"];const TURN_TEXT_CAP = 8000;export interface DeliveredMessage {  id: string;  body: string;  created_at: string;}/** What the Mac typed for a body: CRLF and CR as LF, other control characters dropped, the tail trimmed. */export function typedText(body: string): string {  let out = "";  for (const ch of body.replace(/\r\n/g, "\n")) {    if (ch === "\r") out += "\n";    else if (ch === "\n" || ch === "\t") out += ch;    else if (/\p{Cc}/u.test(ch)) continue;    else out += ch;  }  return out.trimEnd();}function comparable(value: string): string {  return value.split(/\s+/).filter(Boolean).join(" ");}function sameWords(turn: string, body: string): boolean {  const said = comparable(turn);  if (!said) return false;  const clippedTurn = [...turn].length >= TURN_TEXT_CAP;  const sent = comparable(typedText(body));  return sent === said || (clippedTurn && sent.startsWith(said));}type Key = [number, string];function keyOf(message: DeliveredMessage): Key | null {  const at = rfc3339(message.created_at);  return at ? [at.ms, message.id] : null;}function after(a: Key, b: Key): boolean {  return a[0] > b[0] || (a[0] === b[0] && a[1] > b[1]);}/** The earliest message sent strictly after `afterTs` (and after `past`, the one this window already absorbed) saying the turn's words. */export function absorbing(turn: string, afterTs: string | null, past: DeliveredMessage | null, messages: DeliveredMessage[]): DeliveredMessage | null {  let afterMs: number | null = null;  if (afterTs !== null) {    const at = rfc3339(afterTs);    if (!at) return null;    afterMs = at.ms;  }  let pastKey: Key | null = null;  if (past) {    pastKey = keyOf(past);    if (!pastKey) return null;  }  let best: { key: Key; message: DeliveredMessage } | null = null;  for (const message of messages) {    const key = keyOf(message);    if (!key) continue;    if (afterMs !== null && !(key[0] > afterMs)) continue;    if (pastKey && !after(key, pastKey)) continue;    if (!sameWords(turn, message.body)) continue;    if (!best || after(best.key, key)) best = { key, message };  }  return best ? best.message : null;}