Files
CatoandClaude e690b2254a Messenger: people talking to people, and to the agents among them (0.29.0) (#82)
* Messenger: people talking to people, and to the agents among them (0.26.0)

OrangeCat's direct messages were built in the app, so what was wrong with
them could not be fixed for the next product: an agent's answer in a
conversation between two people looked like the other person's, nothing
said an agent was taking part, top bar and a two-row box took half a
phone, and nothing could be attached. This is the messenger as a package.

@bitbaum/chatkit/messenger: Messenger (the whole screen) and its parts
useMessenger, ConversationList, MessageThread, MessageAttachments. The app
implements MessengerTransport; the package has no database, websocket or
storage. styles/messenger.css is the embedded sheet plus the Messenger's
section, without ChatApp.

- An agent is told from a person by the shape of its face, an Agent mark
  with whom it answered for, and an outlined bubble; the top bar says it
  is in the conversation; naming it shows that it is thinking, and says
  so if it never answers.
- Files: Camera, Photos, Videos, Files, checked against the attachment
  policy before an upload starts, photos shrunk in the browser, progress
  and Try again per file, a full-screen viewer, a film drawn as its still.
- The thread: runs, day lines, a New line, ticks from readState, a failed
  message kept with Try again, earlier messages loaded above with the
  reader's place kept, one bubble per message however often it arrives.
- Composer: layout="inline", attachmentsAlone, attach.take, attach.accept,
  a "videos" source, files dropped onto the box. Defaults unchanged.

The state is one pure function (messengerReducer), tested in Node.
test/browser-messenger.mjs drives demo/messenger.html at 390px, 320px
dark and 1280px. It found two defects before any product did: a read mark
that cleared the badge without telling the server, and a page of history
that pulled the reader to the end of the thread.

threadkit 0.1.2 (attachment policy, mention matcher, readState) is merged
and tagged but not on npm, so those rules are carried word for word in
src/thread-rules.ts with threadkit's own tests; the file says when it goes.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmsmMXvM981mcszxEA6

* test(messenger): wait for the opened conversation before reading its thread

Side by side, the conversation that was open can still be on screen with a
"New" line of its own, so the check read the old thread on a slow runner.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmsmMXvM981mcszxEA6

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 16:26:03 +01:00

157 lines
6.7 KiB
JavaScript

/**
* What a composer can attach, and the wire shape an app's API receives.
*
* From loki `lib/loki/attachments.ts`. The limits are defaults, not law — an
* app passes its own to `useAttachments` when its model or API differs.
*/
/** Whether pictures can be attached under these options' `sources`. */
export function acceptsImages(sources) {
return !sources || sources.includes("camera") || sources.includes("photos");
}
export const DEFAULT_ATTACHMENT_LIMITS = {
maxFiles: 5,
maxTextChars: 100_000,
maxImageBytes: 2_800_000,
maxImageEdge: 0,
};
export const DEFAULT_ATTACHMENT_NOTES = {
wrongType: (name) => `${name}: attach an image (PNG, JPEG, GIF, WebP) or a text file.`,
imageTooLarge: (name, maxMb) => `${name} is too large (max ${maxMb} MB).`,
textTooLarge: (name, k) => `${name} is too large (max ${k}k characters).`,
unreadable: (name) => `Could not read ${name}.`,
tooMany: (max) => `Up to ${max} files.`,
};
/**
* The size an image is drawn at to fit `maxEdge` on its longest side. Never
* enlarges; 0 (or less) means "leave it". Pure, so it is tested without a DOM.
*/
export function fitWithin(width, height, maxEdge) {
const longest = Math.max(width, height);
if (maxEdge <= 0 || longest <= maxEdge)
return { width, height, scaled: false };
const scale = maxEdge / longest;
return {
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale)),
scaled: true,
};
}
/** Bytes a base64 data URL decodes to — close enough to compare to a limit. */
export function dataUrlBytes(dataUrl) {
return Math.floor(stripDataUrlBase64(dataUrl).length * 0.75);
}
const IMAGE_MIME = /^image\/(jpeg|jpg|png|gif|webp)$/i;
export function isImageMime(mime) {
return IMAGE_MIME.test(mime);
}
/** Extensions a picker may hand over with no type, or as
* application/octet-stream, that are still plain text a model can read. */
const TEXT_EXTENSIONS = /\.(txt|md|markdown|json|jsonl|csv|tsv|log|ya?ml|toml|ini|xml|html?|css|scss|js|jsx|mjs|cjs|ts|tsx|py|rb|go|rs|java|kt|swift|c|h|cpp|hpp|cs|php|sh|bash|zsh|sql|env|diff|patch|srt|vtt)$/i;
const TEXT_MIME = /^(text\/|application\/(json|xml|x-yaml|yaml|javascript|x-sh|sql))/i;
/**
* Whether a file is text the model can read inline. The Files picker asks for
* documents (FILES_ACCEPT) but a picker may still hand over anything, so the
* decision about what can actually be sent stays here, after the pick, where
* a PDF gets a sentence instead of being read as binary noise and pasted into
* a prompt.
*/
export function isTextFile(name, mime) {
if (TEXT_MIME.test(mime))
return true;
if (mime && mime !== "application/octet-stream")
return false;
return TEXT_EXTENSIONS.test(name);
}
/**
* What the Files source asks the phone for: PDFs and text, one "document"
* family. MIME types first (what Android and iOS map to their pickers), then
* the extensions a desktop file dialog filters by. Only types every platform
* knows: an extension a phone cannot map can widen the request back to
* "anything" — the capture chooser this exists to avoid.
*/
export const FILES_ACCEPT = "application/pdf,text/*,application/json,.pdf,.txt,.md,.markdown,.csv,.tsv,.json";
/**
* What a messenger's Files source asks for: documents a person sends another
* person — PDF, text, office files, an archive. Still one "document" family,
* so a phone still answers with its file browser and not a capture chooser.
*/
export const MESSAGE_FILES_ACCEPT = "application/pdf,text/plain,text/csv,text/markdown,application/json,application/zip,application/rtf,application/msword,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/epub+zip,.pdf,.txt,.md,.csv,.json,.zip,.rtf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.odt,.ods,.epub";
export const ATTACH_SOURCE_INPUT = {
camera: { accept: "image/*", capture: "environment" },
photos: { accept: "image/*" },
videos: { accept: "video/*" },
files: { accept: FILES_ACCEPT },
};
const FAMILY_BY_EXTENSION = {};
for (const ext of [
"png",
"jpg",
"jpeg",
"gif",
"webp",
"heic",
"heif",
"avif",
"bmp",
"svg",
"tif",
"tiff",
])
FAMILY_BY_EXTENSION[ext] = "image";
for (const ext of ["mp3", "m4a", "wav", "ogg", "oga", "opus", "aac", "flac", "amr", "wma"])
FAMILY_BY_EXTENSION[ext] = "audio";
for (const ext of ["mp4", "mov", "m4v", "mkv", "avi", "wmv"])
FAMILY_BY_EXTENSION[ext] = "video";
// Containers that hold either sound or picture (.webm, .3gp) say nothing about
// the picker on their own, so they are not counted for either family.
const AMBIGUOUS_EXTENSIONS = new Set(["webm", "3gp", "3g2", "mpeg", "mpg"]);
/**
* The families an `accept` value spans. More than one is the bug
* `ATTACH_SOURCE_INPUT` exists to prevent: a phone answers a mixed accept with
* a chooser of capture apps instead of the picker the person needed. Pure, so
* the fleet's file-input check (`chatkit-check-file-inputs`) and the tests
* share one definition.
*/
export function acceptFamilies(accept) {
const found = new Set();
for (const raw of accept.split(",")) {
const token = raw.trim().toLowerCase();
if (!token)
continue;
if (token.startsWith(".")) {
const ext = token.slice(1);
if (AMBIGUOUS_EXTENSIONS.has(ext))
continue;
found.add(FAMILY_BY_EXTENSION[ext] ?? "document");
continue;
}
const major = token.split("/")[0];
if (major === "image" || major === "audio" || major === "video")
found.add(major);
else
found.add("document");
}
return [...found];
}
/** `data:image/png;base64,AAAA` → `AAAA`: FileReader hands back a data URL,
* the wire carries raw base64. */
export function stripDataUrlBase64(dataUrl) {
const i = dataUrl.indexOf(",");
return i >= 0 ? dataUrl.slice(i + 1) : dataUrl;
}
/** Identity for dedupe and removal: the same name and bytes are the same
* attachment however they arrived (picker, paste, drop). */
export function attachmentKey(a) {
return a.kind === "image"
? `image:${a.name}:${a.dataBase64.length}`
: `text:${a.name}:${a.content.length}`;
}
/** Strip client-only fields: what the API validates. */
export function toWire(staged) {
return staged.map((a) => {
const { previewUrl: _preview, ...rest } = a;
void _preview;
return rest;
});
}
//# sourceMappingURL=attachments.js.map