iterate.com / ui

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

ui / src / agent-kind-view / writers.tsmain at d68d7e1

// writers.ts — WHO WROTE THE MESSAGES OF A CONVERSATION, as a member's page may show them: the
// name and the picture that a person's own context says of them, in the place of initials.
//
// A person's context is `/users/<their platform id>`; its `itx/described` gives the catalog row
// a `metadata.title` (the name) and a `metadata.image.file` (a file of the mind). The PAGE reads
// that row and signs the file's address, as the person who looks at the page: a view in its frame
// names no path of the mind and gets a signed address only for its own agent's files (`fileUrl`
// in dash-agents.tsx). So the page hands the view this record, by the platform's id on a message
// and never by a name in a text. A page whose viewer may not list `/users` (a guest) gets a
// refusal and hands nothing: the view then draws initials, as before.
import { useEffect, useMemo, useState } from "react";

/** One writer, as the view draws them. */
export type Writer = { name?: string; picture?: string };
/** The writers of the held messages that have a name or a picture, by platform id. */
export type Writers = Readonly<Record<string, Writer>>;

type CatalogRow = { path?: unknown; metadata?: unknown };
/** The slice of the member's itx that this reads: the catalog, and a file's signed address. */
export type WritersItx = {
  contexts: {
    list(input: { under: string; search: string; limit: number }): Promise<readonly CatalogRow[]>;
  };
  files: {
    get(path: string): { url(): Promise<{ url: string }>; [Symbol.dispose](): void };
  };
};

const ID = /^user_[0-9a-f]{8,64}$/;
const NONE: Writers = Object.freeze({});

/** The platform ids of the people who wrote the messages among `events`, each once. */
export function writerIdsOf(events: readonly unknown[]): string[] {
  const ids = new Set<string>();
  for (const raw of events) {
    const event = raw as {
      type?: unknown;
      source?: {
        principal?: { actor?: unknown };
        onBehalfOf?: { principal?: { actor?: unknown } };
      };
    } | null;
    if (typeof event?.type !== "string" || !event.type.endsWith("/message-received")) continue;
    const actor = (event.source?.principal || event.source?.onBehalfOf?.principal)?.actor;
    if (typeof actor === "string" && ID.test(actor)) ids.add(actor);
  }
  return [...ids];
}

/** What the catalog row of `/users/<id>` says of the person: a name, and a picture's file when it
 *  is an image under `/users/`. A row that names any other file gives no picture: a context's
 *  metadata is written by agents, and this signs an address as the viewer. */
export function writerOf(
  id: string,
  rows: readonly CatalogRow[],
): { name?: string; file?: string } | null {
  const row = rows.find((each) => each.path === `/users/${id}`);
  const metadata = row?.metadata as
    | { title?: unknown; image?: { file?: unknown; contentType?: unknown } }
    | undefined;
  if (!metadata || typeof metadata !== "object") return null;
  const name =
    typeof metadata.title === "string" && metadata.title.trim()
      ? metadata.title.trim().slice(0, 80)
      : undefined;
  const image = metadata.image;
  const file =
    image &&
    typeof image.file === "string" &&
    /^\/users\/[^?#]+$/.test(image.file) &&
    !image.file.includes("..") &&
    typeof image.contentType === "string" &&
    /^image\/(png|jpeg|webp|gif)$/.test(image.contentType)
      ? image.file
      : undefined;
  return name || file ? { name, file } : null;
}

/** One person's record, read and signed as the viewer. Null: nothing to show, or refused. */
async function readWriter(itx: WritersItx, id: string): Promise<Writer | null> {
  const rows = await itx.contexts.list({ under: "/users", search: id, limit: 5 });
  const said = writerOf(id, rows);
  if (!said) return null;
  if (!said.file) return { name: said.name };
  const file = itx.files.get(said.file);
  try {
    return { name: said.name, picture: (await file.url()).url };
  } catch {
    // the picture is not there, or not the viewer's to read: the name alone
    return said.name ? { name: said.name } : null;
  } finally {
    file[Symbol.dispose]();
  }
}

/** THE WRITERS OF `events`, read once for each person while the page lives. `itx` undefined (no
 *  member's session): none. The same object while nothing changed, so the frame is told once. */
export function useWriters(itx: WritersItx | undefined, events: readonly unknown[]): Writers {
  const ids = useMemo(() => writerIdsOf(events).join(","), [events]);
  const [known, setKnown] = useState<{ itx: unknown; writers: Record<string, Writer | null> }>({
    itx,
    writers: {},
  });
  // another session: what was read as another viewer is not this one's
  if (known.itx !== itx) setKnown({ itx, writers: {} });
  useEffect(() => {
    if (!itx || !ids) return;
    let current = true;
    for (const id of ids.split(",")) {
      if (id in known.writers) continue;
      readWriter(itx, id)
        .catch(() => null)
        .then((writer) => {
          if (current)
            setKnown((held) =>
              held.itx !== itx || id in held.writers
                ? held
                : { itx, writers: { ...held.writers, [id]: writer } },
            );
        });
    }
    return () => {
      current = false;
    };
  }, [itx, ids, known.writers]);
  return useMemo(() => {
    const shown = Object.entries(known.writers).filter(
      (entry): entry is [string, Writer] => entry[1] !== null,
    );
    return shown.length ? Object.fromEntries(shown) : NONE;
  }, [known.writers]);
}