Files
learnharness/components/chat-transport.ts
T
amosblomqvist 2f8cf71f52 Wave 2: 409 merge-retry transport, dead pendingJob code, evidence-based timing, prompt-size guard
- components/chat-transport.ts (NEW): createChatTransport(chatId) — the
  chat.tsx seam is now a one-line swap. Its fetch turns a 409 on POST
  /api/chat (a learner send racing the wake pipeline's ~1s adoption window)
  into: wait out the in-flight turn (poll turnInFlight, 30s cap), refetch
  the record, MERGE the outgoing messages onto the fresh server list, re-POST.
  A bare retry would clobber the steer + wake messages via the write-ahead
  persist (steerDelivered makes that loss permanent) — merging is the whole
  point. Unit-tested: pass-through, wait+merge+reorder, dedupe by id,
  repeated-409 loop, bounded give-up.
- src/core/pending.ts: findPendingJobCall deleted (dead since wave 1 —
  job tools resolve server-side with an ack, nothing pends client-side).
  JOB_TOOLS kept (runner.ts still uses it). Header doc rewritten.
- src/server/jobs.ts: GRACE_MS 1500 → 750, with the evidence in the
  comment: the race window is only the learner's answer→POST flight
  (sendAutomaticallyWhen dispatches synchronously; ~10ms localhost,
  <300ms realistic RTT — 750 is 2.5× worst case) and misses self-heal
  via the pump's gate recheck, the 409 backoff ramp, and the new
  transport merge-retry. POLL_MS=400 kept (sampling granularity only).
- tests/jobs.test.ts: prompt-size guard — every fragment ≤8k chars,
  composed prompt ≤60k — the README-leak class (815 bytes ≈ 200 tokens
  per teacher turn before wave 1's fix) can't silently recur.

Gates: typecheck, 279/279 tests, lint, build — all green.
2026-09-05 21:33:13 +03:00

117 lines
4.6 KiB
TypeScript

/**
* Chat transport with 409 merge-retry — the learner's send can race the
* server's wake pipeline (contracts/jobs.ts "THE ASYNC PROTOCOL"): the wake
* turn starts server-side and the client only notices via the /api/jobs poll
* up to a second later. A send in that window gets 409'd ("a turn is already
* running") and, before this file, surfaced as an error banner.
*
* Why NOT a bare retry: every 409 means the server record is AHEAD of the
* client — the wake turn persisted the steer message (and, once it finishes,
* its response) that the client hasn't seen. The chat handler's write-ahead
* persist makes the request body the canonical transcript, so re-POSTing the
* stale client list would clobber the steer + wake messages out of the
* record (and the job already flipped done — steerDelivered makes
* re-delivery impossible: permanent loss). The retry must therefore MERGE:
* wait for the in-flight turn to finish, refetch the record, append the
* client's unsent messages (by id) to the server's list, and re-POST the
* merged transcript.
*
* Client-side gap after a merged retry: useChat's local list still lacks the
* steer/wake messages until the next syncFromServer (job settle, remount, or
* a future "server-ahead" heal in the poller). Rare path; self-heals.
*/
import { DefaultChatTransport } from "ai";
import type { TeacherUIMessage } from "@/src/core/ui-message";
/** How often to poll turnInFlight while the racing turn runs. */
const TURN_POLL_MS = 500;
/** Give up waiting (a wake turn can run long) and surface the 409 as before. */
const TURN_WAIT_MAX_MS = 30_000;
/** Injectable timing (tests). */
export interface RetryFetchOptions {
pollMs?: number;
waitMaxMs?: number;
}
function delay(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
const t = setTimeout(resolve, ms);
signal?.addEventListener("abort", () => {
clearTimeout(t);
reject(new DOMException("Aborted", "AbortError"));
}, { once: true });
});
}
async function turnInFlight(chatId: string): Promise<boolean | null> {
try {
const res = await fetch(`/api/jobs?chatId=${encodeURIComponent(chatId)}`);
if (!res.ok) return null;
return ((await res.json()) as { turnInFlight?: boolean }).turnInFlight === true;
} catch {
return null; // network hiccup: keep waiting, the deadline bounds us
}
}
async function serverMessages(chatId: string): Promise<TeacherUIMessage[] | null> {
try {
const res = await fetch(`/api/chats/${encodeURIComponent(chatId)}`);
if (!res.ok) return null;
const record = (await res.json()) as { messages?: TeacherUIMessage[] };
return Array.isArray(record.messages) ? record.messages : null;
} catch {
return null;
}
}
/**
* A fetch that turns a 409 on POST /api/chat into: wait for the running turn,
* merge the outgoing messages onto the fresh server record, re-POST. Non-409
* responses pass through untouched.
*/
/** Exported for tests. */
export function retryingFetch(chatId: string, opts: RetryFetchOptions = {}): typeof globalThis.fetch {
const pollMs = opts.pollMs ?? TURN_POLL_MS;
const waitMaxMs = opts.waitMaxMs ?? TURN_WAIT_MAX_MS;
return async (input, init) => {
let response = await fetch(input, init);
let waited = 0;
while (response.status === 409) {
// Free the 409 body's socket before waiting on the racing turn.
await response.body?.cancel().catch(() => {});
if (init?.signal?.aborted || waited >= waitMaxMs) return response;
await delay(pollMs, init?.signal ?? undefined);
waited += pollMs;
if (init?.signal?.aborted) return response;
if ((await turnInFlight(chatId)) !== false) continue;
// Turn finished: merge onto the fresh record, then re-POST.
const record = await serverMessages(chatId);
if (!record || typeof init?.body !== "string") return response;
const serverIds = new Set(record.map((m) => m.id));
const body = JSON.parse(init.body) as { messages?: TeacherUIMessage[] };
if (!Array.isArray(body.messages)) return response;
const outgoing = body.messages.filter((m) => m.id && !serverIds.has(m.id));
const merged = JSON.stringify({ ...body, messages: [...record, ...outgoing] });
response = await fetch(input, { ...init, body: merged }); // may 409 again → loop
}
return response;
};
}
/**
* The chat.tsx one-liner: `transport: createChatTransport(chatId)` replaces
* `new DefaultChatTransport({ api: "/api/chat", body: { chatId } })`.
*/
export function createChatTransport(chatId: string): DefaultChatTransport<TeacherUIMessage> {
return new DefaultChatTransport<TeacherUIMessage>({
api: "/api/chat",
body: { chatId },
fetch: retryingFetch(chatId),
});
}