iterate.com / ui

git clone https://git.iterate.com/repos/ui

ui / src / agent-kind-view / chat-history.tsmain at d68d7e1

// chat-history.ts — THE OLDER PAGES OF AN AGENT'S LOG, READ FOR THE CHAT WITHOUT THE RAW PROMPTS.
//
// Jonas, 28 Nov 2026, in the Dash: "proactively load more events in the past in agent and context
// views on dash - atm too many loading breaks when scrolling up". A page of an agent's log is
// mostly a few facts that the chat draws nothing of (a request's instructions, the provider's
// body): megabytes for each screen of rows, and a page a second. A mind may offer a read that
// cuts those texts short, `itx.config.chatHistory({ path, after, limit })`, which answers what
// the context's `readEvents` answers (the config repo's chat-history.ts).
//
// `withChatHistory(stub, read)` is the context's stub with that read in the place of `readEvents`
// for the pages BELOW the first one. The first page (the newest events) and every read at or over
// it come from the context itself, whole, and so do the live events: what the agent does now is
// never cut. A mind with no such read answers an error once, and the stub reads plainly from then.
//
// A BLOCK AHEAD OF THE READER. The mind answers one large read far faster than many small ones
// (measured 28 Nov 2026 on a large chat: about 100 ms a call, then 45 ms for each 1,000 offsets,
// and calls at once are answered one after the other). The log's own reader asks for small
// windows, 1,000 offsets and then 2,000, so on a chat whose rows are few for its offsets a reader
// on a steady way up stood at the list's top for 15 s of 25. So an older page is answered from a
// block that this stub holds: `BLOCK` offsets read in one call (`through`), and the next block
// below is read as soon as the reader is half through the one held. One block ahead, never more:
// nothing is read for a reader who asked for no older page.

type Page = {
  events: unknown[];
  atHead: boolean;
  scannedThroughOffset: number;
  version?: number;
  versionStartedAtOffset?: number;
};
type Reads = { readEvents(after?: number, limit?: number): Promise<Page> };
/** The mind's read: a page after `after`, or with `through` every event in (after, through]. */
export type ChatHistoryRead = (after: number, limit: number, through?: number) => Promise<Page>;

/** How many offsets one block holds. */
const BLOCK = 8_000;
/** The events above the reader that the stub keeps: a read never asks for them again. */
const KEPT_ABOVE = 24_000;

const offsetOf = (event: unknown) => (event as { offset: number }).offset;

export function withChatHistory<Stub extends object>(stub: Stub, read: ChatHistoryRead): Stub {
  // where the first page began: a read from below it is an older page
  let firstPage: number | undefined;
  let refused = false;
  // the mind answered once: a later error is the connection's, and only that read is plain
  let answered = false;
  // the block held: every event that the chat reads in (lo, hi], ascending
  let block: { lo: number; hi: number; events: unknown[]; of: Page } | undefined;
  let ahead: Promise<void> | undefined;
  const plain = (after?: number, limit?: number) =>
    (stub as unknown as Reads).readEvents(after, limit);

  /** Every event in (lo, hi], or nothing when the mind's answer is not the whole span. */
  const span = async (lo: number, hi: number) => {
    const page = await read(lo, 1, hi);
    if (page.scannedThroughOffset < hi) return undefined;
    return { lo, hi, events: page.events.filter((event) => offsetOf(event) <= hi), of: page };
  };
  /** The block below the one held, joined to it. */
  const below = async () => {
    const held = block;
    if (!held || held.lo <= 0) return;
    const more = await span(Math.max(0, held.lo - BLOCK), held.lo);
    if (!more || block !== held) return;
    block = { lo: more.lo, hi: held.hi, events: [...more.events, ...held.events], of: held.of };
  };
  const older = async (after: number, limit: number): Promise<Page> => {
    await ahead?.catch(() => undefined);
    // over the block: a window's rest, which the log's reader asks for after a full answer
    if (block && after >= block.hi) return read(after, limit);
    if (!block || after + limit < block.lo) {
      // the first older page, or a jump far below: a block that ends where this window ends and
      // begins on a multiple of BLOCK, so that every block below it is a whole one that the mind
      // keeps (it answers a kept block from a file, with no scan of the log)
      const top = after + limit;
      const aligned = Math.floor((top - 1) / BLOCK) * BLOCK;
      const fresh = await span(Math.max(0, aligned > after ? aligned - BLOCK : aligned), top);
      if (!fresh || after < fresh.lo) return read(after, limit);
      block = fresh;
    } else if (after < block.lo) {
      await below();
      if (after < block.lo) return read(after, limit);
    }
    const held = block;
    const from = held.events.findIndex((event) => offsetOf(event) > after);
    const events = from < 0 ? [] : held.events.slice(from, from + limit);
    const all = from < 0 || from + limit >= held.events.length;
    // the reader is half through the block: read the next one now, for the ask that comes
    if (after - held.lo < BLOCK / 2 && held.lo > 0 && !ahead)
      ahead = below().finally(() => {
        ahead = undefined;
      });
    // what stands far over the reader is never asked for again
    if (held.hi - after > KEPT_ABOVE) {
      const hi = after + KEPT_ABOVE;
      block = { ...held, hi, events: held.events.filter((event) => offsetOf(event) <= hi) };
    }
    return {
      ...held.of,
      events,
      atHead: false,
      scannedThroughOffset: all ? held.hi : offsetOf(events.at(-1)),
    };
  };
  const readEvents = (after?: number, limit?: number): Promise<Page> => {
    // a probe of one row (the head, a gap) is no page
    if (refused || after === undefined || limit === undefined || limit <= 1)
      return plain(after, limit);
    if (firstPage === undefined || after >= firstPage) {
      firstPage ??= after;
      return plain(after, limit);
    }
    return older(after, limit).then(
      (page) => {
        answered = true;
        return page;
      },
      () => {
        if (!answered) refused = true;
        block = undefined;
        return plain(after, limit);
      },
    );
  };
  return new Proxy(stub, {
    get: (target, key) => (key === "readEvents" ? readEvents : Reflect.get(target, key)),
  });
}