diff --git a/CHANGELOG.md b/CHANGELOG.md index 2512dfd..fabfec0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.1.2 — Files on a message, read receipts with an assistant in the room + +Additive: nothing that compiled against 0.1.1 changes. + +- **Attachments.** `Message.attachments` (an `Attachment`: kind, name, type, bytes, and pixels or duration where it has them) and the policy that decides what may be attached: `checkAttachment` answers with the kind or with the reason and its number (`type`, `size`, `count`, `quota`, `empty`). The policy is an allowlist; a type it does not name is refused, and `image/svg+xml` and `text/html` are left out of the default because both can carry script. `attachmentExpiresAt`, `isAttachmentExpired` and `isAbandonedUpload` are the lifetime rules, `storedBytes` is what a quota counts. The package still stores and signs nothing. +- **`readState(thread, message)`**: `none`, `some` or `all`, over the humans the message was for. Found in OrangeCat, 2026-11-12: once its assistant had answered in a conversation it stayed as a participant, never "read" anything, and every later message was stuck at delivered, because the receipt waited for a reader that does not read. +- **`mentionsAny` / `mentionMatcher`**: the whole-word matcher `whenMentioned` already used, exported so an interface and a server share one definition. It now treats letters outside ASCII as letters (`aiü` no longer matches the alias `ai`). +- **Your own message type comes back.** `mergeMessages`, `visibleMessages` and `unreadMessages` are generic over the message, so rows that carry more than this package knows (a sender's name, an edited-at) no longer have to be looked up again by id after a merge. + ## Renamed — `threadkit` is now `@bitbaum/threadkit` Same code, same version, same repository; the package now lives under the diff --git a/README.md b/README.md index a4152ef..608d649 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,43 @@ Defaults that keep it usable: Every reply carries `generatedBy`, so a record can say honestly which model wrote what. +## Files on a message + +A message can carry files: `attachments` is a list of what was sent, never of where it is kept. + +```ts +{ id: 'a1', kind: 'image', name: 'cat.jpg', mimeType: 'image/jpeg', bytes: 184_000, width: 1600, height: 1200 } +``` + +There is deliberately no URL on it. A link to a private file is a grant with an expiry, decided per reader at the moment of reading; whoever may see the message may see what was sent with it, and that question is `canSeeMessage`. + +Files are also where a messenger's costs live, so what may be attached is a policy, checked in the same words in the browser (before an upload starts) and on the server (because the browser can be anyone): + +```ts +import { checkAttachment, DEFAULT_ATTACHMENT_POLICY } from '@bitbaum/threadkit' + +const check = checkAttachment( + { mimeType: file.type, bytes: file.size }, + { onMessage: staged.length, usedBytes: storedByThisPerson }, +) +if (!check.ok) return say(check) // 'type' | 'size' | 'count' | 'quota' | 'empty', each with its number +``` + +- **An allowlist, not a blocklist.** A type the policy does not name is refused. `image/svg+xml` and `text/html` are absent from the default on purpose: both can carry script, and a file opened from your storage origin runs there. +- **A ceiling per kind.** A photo and a video are not the same risk. +- **A quota per person**, counted over what is still stored, so deleting something frees room. +- **A lifetime.** `isAbandonedUpload` finds the upload that never became a message; `attachmentExpiresAt` / `isAttachmentExpired` say when a sent file stops being kept, if your policy sets `retentionDays`. + +The package still stores nothing and signs nothing. It answers the questions; your storage does the work. + +## Read receipts that survive a third participant + +`readState(thread, message)` answers `'none' | 'some' | 'all'`, with the readers and the size of the audience. The audience is the people the message was for — humans who can see it and have not left. A model is left out: it has no reading to report, and counting it means a message in a room with an assistant can never be read by everyone. + +## Was it addressed? + +`mentionsAny(text, ['@cat'])` matches whole words only — `@catalogue` is somebody else, and an alias like `ai` does not fire inside "again". `whenMentioned` uses the same matcher, so a server deciding whether the assistant answers and an interface showing that it is about to cannot disagree. + ## Bring your own storage There is no database adapter and no ORM. Load a thread and its messages however you already do, call the functions, write the result back. That is the whole integration surface — which is also why it works the same on Drizzle, Prisma, Supabase, or a JSON file. @@ -111,6 +148,12 @@ There is no database adapter and no ORM. Load a thread and its messages however | `unreadThreadCount(entries, actorId)` | threads with anything unread | | `mergeMessages(existing, incoming)` | dedupe, reconcile optimistic, order | | `compareMessages` / `isPending` | ordering and pending-state helpers | +| `readState(thread, message)` | read by nobody else, some, or everyone it was for | +| `checkAttachment(file, usage?, policy?)` | may this file be attached, and if not, why | +| `attachmentKind(mimeType, policy?)` | image, video, audio, file — or `null` when refused | +| `attachmentExpiresAt` / `isAttachmentExpired` / `isAbandonedUpload` | the lifetime rules | +| `storedBytes(attachments)` | what a quota is compared against | +| `mentionsAny(text, aliases)` / `mentionMatcher(aliases)` | whole-word mentions | | `runAiTurn(thread, messages, config)` | decide whether the AI speaks, and what it says | | `afterEveryMessage` / `whenMentioned` / `defaultRespondPolicy` | response policies | diff --git a/package.json b/package.json index 41d5b45..8cb1af6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitbaum/threadkit", - "version": "0.1.1", + "version": "0.1.2", "description": "Headless multi-participant message threads. Permission is participation, unread is per-person, and an AI can be a participant subject to the same visibility rules as everyone else.", "license": "MIT", "author": "Mao Nakamoto", @@ -17,6 +17,7 @@ "chat", "threads", "group-chat", + "attachments", "ai", "authorization", "headless" diff --git a/src/ai.ts b/src/ai.ts index d75a277..734c4b4 100644 --- a/src/ai.ts +++ b/src/ai.ts @@ -1,5 +1,6 @@ import type { AiProvenance, CompleteFn, Message, Participant, Thread } from './types.js'; import { canWrite, findParticipant, visibleMessages } from './participants.js'; +import { mentionMatcher } from './mentions.js'; /** * An AI that participates in a thread rather than owning one. @@ -62,16 +63,13 @@ export const afterEveryMessage: RespondPolicy = ({ visible, self }) => { * turn is noise and, between a doctor and a patient, an interruption. */ export function whenMentioned(aliases: readonly string[]): RespondPolicy { - // Whole words only. A substring test looks fine until an alias like "ai" - // matches "again" or "wait" and the assistant starts answering turns nobody - // addressed to it. - const patterns = aliases - .filter(Boolean) - .map((a) => new RegExp(`(^|\\W)${a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\W|$)`, 'i')); + // Whole words only — see `mentionMatcher`, which an interface can share so + // "will the assistant answer this?" has one definition on both sides. + const mentioned = mentionMatcher(aliases); return ({ visible, self }) => { const last = visible[visible.length - 1]; if (!last || last.authorId === self.actorId) return false; - return patterns.some((re) => re.test(last.body)); + return mentioned(last.body); }; } diff --git a/src/attachments.ts b/src/attachments.ts new file mode 100644 index 0000000..5ae8da2 --- /dev/null +++ b/src/attachments.ts @@ -0,0 +1,253 @@ +import type { AttachmentKind } from './types.js'; + +/** + * What may be attached, how big, how much, and for how long. + * + * Files are where a messenger's costs live. Text is bytes; one phone video is + * megabytes, kept until somebody decides otherwise — and usually nobody does. + * So the decisions are a policy, stated once and enforced in the same words on + * the client (to refuse before an upload starts) and on the server (because + * the client can be anyone): + * + * - **An allowlist, not a blocklist.** A type that is not named is refused. A + * blocklist is correct until the first type nobody thought of, and the type + * nobody thought of is the one that runs script when a reader opens it. + * - **A ceiling per kind**, because a photo and a video are not the same risk. + * - **A quota per person**, counted over what is still stored, so deleting + * something frees room for something else. + * - **A lifetime.** An upload that never became a message is swept after a few + * hours; a sent file may expire after a stated number of days, or be kept + * as long as its message. Either way the rule is written down, not implied. + * + * Pure functions over numbers you already have. This file stores nothing, + * signs nothing and never sees a byte. + */ +export interface AttachmentPolicy { + /** Files on one message. */ + readonly maxPerMessage: number; + /** Largest file of each kind, in bytes. 0 refuses the kind outright. */ + readonly maxBytes: Readonly>; + /** + * MIME types accepted for each kind: exact (`image/png`) or a whole family + * (`audio/*`). Anything not listed is refused, whatever its extension says. + */ + readonly accept: Readonly>; + /** + * Bytes one person may keep stored at a time, across every thread. + * `null` means no ceiling — say so on purpose. + */ + readonly quotaBytes: number | null; + /** + * Days a sent attachment is kept. `null` keeps it as long as its message. + * The message outlives its files: words stay, the file is gone, and a + * reader is told so rather than shown a broken picture. + */ + readonly retentionDays: number | null; + /** Hours an uploaded file may wait to be sent before it is swept as abandoned. */ + readonly orphanHours: number; +} + +const MB = 1024 * 1024; + +/** + * Defaults sized for a messenger whose pictures are shrunk in the browser + * before they are sent: a photo arrives well under the image ceiling, and the + * ceiling is there for the animated GIF and the picture nothing could shrink. + * + * `image/svg+xml` and `text/html` are deliberately absent. Both can carry + * script, and a file a reader opens from your storage origin runs there. + */ +export const DEFAULT_ATTACHMENT_POLICY: AttachmentPolicy = { + maxPerMessage: 10, + maxBytes: { + image: 10 * MB, + video: 50 * MB, + audio: 20 * MB, + file: 25 * MB, + }, + accept: { + image: ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif'], + video: ['video/mp4', 'video/webm', 'video/quicktime'], + audio: [ + 'audio/mpeg', + 'audio/mp4', + 'audio/aac', + 'audio/ogg', + 'audio/webm', + 'audio/wav', + 'audio/x-wav', + 'audio/x-m4a', + ], + file: [ + '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', + ], + }, + quotaBytes: 1024 * MB, + retentionDays: null, + orphanHours: 24, +}; + +/** The parameters of a MIME type (`; charset=utf-8`) say nothing about what it is. */ +function bareMime(mimeType: string): string { + return mimeType.split(';')[0].trim().toLowerCase(); +} + +function matches(mime: string, pattern: string): boolean { + const p = pattern.toLowerCase(); + if (p.endsWith('/*')) return mime.startsWith(p.slice(0, -1)); + return mime === p; +} + +const KINDS: readonly AttachmentKind[] = ['image', 'video', 'audio', 'file']; + +/** + * Which kind a MIME type is under this policy, or `null` when the policy does + * not accept it at all. + * + * The policy decides, not the type's first word: `image/svg+xml` is an image + * by name and a document that can run script by nature, so unless a policy + * lists it under `image` it is never shown in place. + */ +export function attachmentKind( + mimeType: string, + policy: AttachmentPolicy = DEFAULT_ATTACHMENT_POLICY, +): AttachmentKind | null { + const mime = bareMime(mimeType); + if (!mime) return null; + for (const kind of KINDS) { + if (policy.accept[kind].some((pattern) => matches(mime, pattern))) return kind; + } + return null; +} + +/** Why a file was refused. Every reason carries the number a person needs to hear. */ +export type AttachmentRefusal = + | { readonly ok: false; readonly reason: 'empty' } + | { readonly ok: false; readonly reason: 'type' } + | { + readonly ok: false; + readonly reason: 'size'; + readonly kind: AttachmentKind; + readonly maxBytes: number; + } + | { readonly ok: false; readonly reason: 'count'; readonly maxPerMessage: number } + | { + readonly ok: false; + readonly reason: 'quota'; + readonly quotaBytes: number; + readonly usedBytes: number; + }; + +export type AttachmentCheck = + { readonly ok: true; readonly kind: AttachmentKind } | AttachmentRefusal; + +/** What is already there when a new file asks to join. */ +export interface AttachmentUsage { + /** Files already on the message being written. */ + readonly onMessage?: number; + /** Bytes this person already has stored. Only consulted when the policy has a quota. */ + readonly usedBytes?: number; +} + +/** + * May this file be attached? + * + * Returns rather than throws, and says why — a refusal is the normal outcome + * of somebody picking a two-gigabyte video, and the caller's job is to say the + * limit back to them. Checks run cheapest-first, so the answer for a wrong + * type never depends on a quota lookup. + * + * Run it twice: in the browser before the upload starts (to save the person + * the wait), and on the server before a storage URL is issued (because the + * first check proves nothing about a request you did not write). + */ +export function checkAttachment( + file: { readonly mimeType: string; readonly bytes: number }, + usage: AttachmentUsage = {}, + policy: AttachmentPolicy = DEFAULT_ATTACHMENT_POLICY, +): AttachmentCheck { + if (!Number.isFinite(file.bytes) || file.bytes <= 0) return { ok: false, reason: 'empty' }; + + const kind = attachmentKind(file.mimeType, policy); + if (!kind) return { ok: false, reason: 'type' }; + + const maxBytes = policy.maxBytes[kind]; + // A ceiling of 0 turns the kind off: it is a type this thread does not take. + if (maxBytes <= 0) return { ok: false, reason: 'type' }; + if (file.bytes > maxBytes) return { ok: false, reason: 'size', kind, maxBytes }; + + if ((usage.onMessage ?? 0) >= policy.maxPerMessage) { + return { ok: false, reason: 'count', maxPerMessage: policy.maxPerMessage }; + } + + if (policy.quotaBytes !== null) { + const usedBytes = usage.usedBytes ?? 0; + if (usedBytes + file.bytes > policy.quotaBytes) { + return { ok: false, reason: 'quota', quotaBytes: policy.quotaBytes, usedBytes }; + } + } + + return { ok: true, kind }; +} + +/** Bytes a set of attachments occupies — what a quota is compared against. */ +export function storedBytes(attachments: readonly { readonly bytes: number }[]): number { + let total = 0; + for (const a of attachments) total += Math.max(0, a.bytes); + return total; +} + +const HOUR_MS = 60 * 60 * 1000; +const DAY_MS = 24 * HOUR_MS; + +/** + * When a sent attachment stops being kept, or `null` when the policy keeps it + * as long as its message. + */ +export function attachmentExpiresAt( + sentAt: Date, + policy: AttachmentPolicy = DEFAULT_ATTACHMENT_POLICY, +): Date | null { + if (policy.retentionDays === null) return null; + return new Date(sentAt.getTime() + policy.retentionDays * DAY_MS); +} + +/** Has a sent attachment outlived the policy's retention? Never true without one. */ +export function isAttachmentExpired( + sentAt: Date, + now: Date = new Date(), + policy: AttachmentPolicy = DEFAULT_ATTACHMENT_POLICY, +): boolean { + const expiresAt = attachmentExpiresAt(sentAt, policy); + return expiresAt !== null && expiresAt.getTime() <= now.getTime(); +} + +/** + * Is an uploaded file that was never sent old enough to sweep? + * + * Uploading and sending are two steps, and the second does not always happen: + * a tab closes, a person changes their mind. Without this rule every abandoned + * upload is stored — and counted against its owner's quota — forever. + */ +export function isAbandonedUpload( + uploadedAt: Date, + now: Date = new Date(), + policy: AttachmentPolicy = DEFAULT_ATTACHMENT_POLICY, +): boolean { + return now.getTime() - uploadedAt.getTime() >= policy.orphanHours * HOUR_MS; +} diff --git a/src/index.ts b/src/index.ts index 951f77d..37772ac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,8 @@ export type { ActorKind, AiProvenance, + Attachment, + AttachmentKind, CompleteFn, Message, Participant, @@ -14,6 +16,7 @@ export { canWrite, findParticipant, readersOf, + readState, visibilityWindow, visibleMessages, } from './participants.js'; @@ -24,3 +27,21 @@ export { compareMessages, isPending, mergeMessages } from './merge.js'; export { afterEveryMessage, defaultRespondPolicy, runAiTurn, whenMentioned } from './ai.js'; export type { AiParticipantConfig, AiTurnContext, AiTurnResult, RespondPolicy } from './ai.js'; + +export { + DEFAULT_ATTACHMENT_POLICY, + attachmentExpiresAt, + attachmentKind, + checkAttachment, + isAbandonedUpload, + isAttachmentExpired, + storedBytes, +} from './attachments.js'; +export type { + AttachmentCheck, + AttachmentPolicy, + AttachmentRefusal, + AttachmentUsage, +} from './attachments.js'; + +export { mentionMatcher, mentionsAny } from './mentions.js'; diff --git a/src/mentions.ts b/src/mentions.ts new file mode 100644 index 0000000..15c9753 --- /dev/null +++ b/src/mentions.ts @@ -0,0 +1,36 @@ +/** + * Was somebody addressed by name? + * + * Whole words only. A substring test looks fine until an alias like "ai" + * matches "again" or "wait" and an assistant starts answering turns nobody + * addressed to it — or a "@cat" tag fires on "@catalogue". The same matcher + * decides it on the server (does the agent answer?) and in the interface + * (is the agent about to answer?), so the two cannot disagree. + */ + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * A matcher for a fixed set of aliases, compiled once. + * + * A word character on either side of the alias means it is part of a longer + * word and is not a mention; anything else — a space, punctuation, the start + * or the end of the text — is a boundary. Case is ignored. Empty aliases are + * dropped, so a blank handle can never match everything. + */ +export function mentionMatcher(aliases: readonly string[]): (text: string) => boolean { + const patterns = aliases + .map((alias) => alias.trim()) + .filter(Boolean) + .map( + (alias) => new RegExp(`(^|[^\\p{L}\\p{N}_])${escapeRegExp(alias)}(?![\\p{L}\\p{N}_])`, 'iu'), + ); + return (text) => patterns.some((re) => re.test(text)); +} + +/** Does `text` mention any of `aliases` as a whole word? */ +export function mentionsAny(text: string, aliases: readonly string[]): boolean { + return mentionMatcher(aliases)(text); +} diff --git a/src/merge.ts b/src/merge.ts index 494ac15..4521fd8 100644 --- a/src/merge.ts +++ b/src/merge.ts @@ -23,15 +23,18 @@ export function compareMessages(a: Message, b: Message): number { * Identity is `id` first, then `clientId`. The `clientId` pass is what retires * an optimistic bubble: the stored row carries the same `clientId`, so it * replaces the placeholder in place instead of arriving as a second message. + * + * Generic over your own message type: rows that carry more than this package + * knows about (a sender's name, an edited-at) come back as what they were. */ -export function mergeMessages( - existing: readonly Message[], - incoming: readonly Message[], -): Message[] { - const byId = new Map(); +export function mergeMessages( + existing: readonly M[], + incoming: readonly M[], +): M[] { + const byId = new Map(); const idByClientId = new Map(); - const put = (m: Message) => { + const put = (m: M) => { // A confirmed row supersedes the optimistic one that shares its clientId. if (m.clientId) { const placeholderId = idByClientId.get(m.clientId); diff --git a/src/participants.ts b/src/participants.ts index 89aecb7..ba703b1 100644 --- a/src/participants.ts +++ b/src/participants.ts @@ -57,11 +57,11 @@ export function canSeeMessage(p: Participant, message: Message): boolean { * that forgets to check `canRead` first still leaks nothing. Failing closed is * the entire point. */ -export function visibleMessages( +export function visibleMessages( thread: Thread, actorId: string, - messages: readonly Message[], -): Message[] { + messages: readonly M[], +): M[] { const p = findParticipant(thread, actorId); if (!p) return []; return messages.filter((m) => m.threadId === thread.id && canSeeMessage(p, m)); @@ -82,3 +82,41 @@ export function readersOf(thread: Thread, message: Message): Participant[] { return p.lastReadAt.getTime() >= message.createdAt.getTime(); }); } + +/** + * How far a message has been read: by nobody else, by some, or by everyone + * who could have. + * + * `audience` is the people the message was *for*: every human participant + * other than its author who can see it and has not left. A model is left out + * on purpose — it has no reading to report, and counting it would mean a + * message in a room with an assistant could never be "read by all". + * + * This is what a tick is drawn from. One grey tick, two, or two coloured is a + * presentation choice; which of the three states a message is in is a rule, + * and it has to be the same rule for two participants and for ten. + */ +export function readState( + thread: Thread, + message: Message, +): { + readonly state: 'none' | 'some' | 'all'; + readonly readers: readonly Participant[]; + readonly audience: number; +} { + const audience = thread.participants.filter( + (p) => + p.kind === 'human' && + p.actorId !== message.authorId && + !p.leftAt && + canSeeMessage(p, message), + ); + const readers = readersOf(thread, message).filter((p) => p.kind === 'human' && !p.leftAt); + const state = + audience.length === 0 || readers.length === 0 + ? 'none' + : readers.length >= audience.length + ? 'all' + : 'some'; + return { state, readers, audience: audience.length }; +} diff --git a/src/types.ts b/src/types.ts index 050ae95..f71880c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -61,6 +61,37 @@ export interface Participant { readonly lastReadAt?: Date | null; } +/** + * What a file on a message is, as a reader meets it. + * + * `image`, `video` and `audio` are shown in place; `file` is something to + * open or download. The split is by how it is used, not by where it is kept. + */ +export type AttachmentKind = 'image' | 'video' | 'audio' | 'file'; + +/** + * A file that travels with a message. + * + * The thread knows what it is and how big it is; the bytes live in your object + * storage, under whatever key you gave them. Deliberately no URL here: a URL + * to a private file is a grant with an expiry, and that is decided per reader + * at the moment of reading, never stored on the message. + */ +export interface Attachment { + readonly id: string; + readonly kind: AttachmentKind; + /** The name the sender's device gave it. Shown to readers; never used as a path. */ + readonly name: string; + readonly mimeType: string; + /** Size as stored, in bytes. What a quota counts. */ + readonly bytes: number; + /** Pixels, for an image or a video — lets a reader lay it out before it loads. */ + readonly width?: number; + readonly height?: number; + /** Length of a video or a recording, in milliseconds. */ + readonly durationMs?: number; +} + /** Where an AI message came from, so a clinical record can say so honestly. */ export interface AiProvenance { readonly model: string; @@ -81,6 +112,12 @@ export interface Message { readonly clientId?: string; /** Present iff a model wrote this. Absent means a human or your system did. */ readonly generatedBy?: AiProvenance; + /** + * Files sent with these words. A message may be only files: `body` is then + * the empty string. Visibility is the message's — whoever may see the + * message may see what was sent with it, and nobody else. + */ + readonly attachments?: readonly Attachment[]; } export interface Thread { diff --git a/src/unread.ts b/src/unread.ts index 9673885..fc1a794 100644 --- a/src/unread.ts +++ b/src/unread.ts @@ -12,11 +12,11 @@ import { findParticipant, canSeeMessage } from './participants.js'; */ /** Messages this actor can see, did not write, and has not caught up to. */ -export function unreadMessages( +export function unreadMessages( thread: Thread, actorId: string, - messages: readonly Message[], -): Message[] { + messages: readonly M[], +): M[] { const p = findParticipant(thread, actorId); if (!p) return []; const since = p.lastReadAt?.getTime() ?? null; diff --git a/test/attachments.test.js b/test/attachments.test.js new file mode 100644 index 0000000..4b95dc0 --- /dev/null +++ b/test/attachments.test.js @@ -0,0 +1,152 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { + DEFAULT_ATTACHMENT_POLICY, + attachmentExpiresAt, + attachmentKind, + checkAttachment, + isAbandonedUpload, + isAttachmentExpired, + storedBytes, +} from '../dist/index.js'; + +const MB = 1024 * 1024; + +test('a type the policy does not name is refused, whatever it is called', () => { + // The two that matter: both can carry script, and a reader opens them from + // the storage origin. + assert.equal(attachmentKind('image/svg+xml'), null); + assert.equal(attachmentKind('text/html'), null); + assert.equal(attachmentKind('application/x-msdownload'), null); + assert.deepEqual(checkAttachment({ mimeType: 'image/svg+xml', bytes: 10 }), { + ok: false, + reason: 'type', + }); +}); + +test('a missing type is refused rather than guessed from the name', () => { + assert.equal(attachmentKind(''), null); + assert.equal(checkAttachment({ mimeType: '', bytes: 10 }).ok, false); +}); + +test('each accepted type lands in the kind a reader will meet it as', () => { + assert.equal(attachmentKind('image/jpeg'), 'image'); + assert.equal(attachmentKind('IMAGE/PNG'), 'image'); + assert.equal(attachmentKind('video/mp4'), 'video'); + assert.equal(attachmentKind('audio/webm'), 'audio'); + assert.equal(attachmentKind('application/pdf'), 'file'); + // Parameters say nothing about what the file is. + assert.equal(attachmentKind('text/plain; charset=utf-8'), 'file'); +}); + +test('a family pattern accepts the whole family and nothing beside it', () => { + const policy = { + ...DEFAULT_ATTACHMENT_POLICY, + accept: { ...DEFAULT_ATTACHMENT_POLICY.accept, audio: ['audio/*'] }, + }; + assert.equal(attachmentKind('audio/flac', policy), 'audio'); + assert.equal(attachmentKind('audiobook/flac', policy), null); +}); + +test('a file over its kind’s ceiling is refused with the ceiling', () => { + const check = checkAttachment({ mimeType: 'video/mp4', bytes: 51 * MB }); + assert.deepEqual(check, { ok: false, reason: 'size', kind: 'video', maxBytes: 50 * MB }); + assert.deepEqual(checkAttachment({ mimeType: 'video/mp4', bytes: 50 * MB }), { + ok: true, + kind: 'video', + }); +}); + +test('a photo and a video do not share a ceiling', () => { + assert.equal(checkAttachment({ mimeType: 'image/jpeg', bytes: 11 * MB }).ok, false); + assert.equal(checkAttachment({ mimeType: 'video/mp4', bytes: 11 * MB }).ok, true); +}); + +test('a ceiling of zero turns a kind off', () => { + const policy = { + ...DEFAULT_ATTACHMENT_POLICY, + maxBytes: { ...DEFAULT_ATTACHMENT_POLICY.maxBytes, video: 0 }, + }; + assert.deepEqual(checkAttachment({ mimeType: 'video/mp4', bytes: 1 }, {}, policy), { + ok: false, + reason: 'type', + }); +}); + +test('an empty file is refused before anything else is asked', () => { + assert.deepEqual(checkAttachment({ mimeType: 'image/png', bytes: 0 }), { + ok: false, + reason: 'empty', + }); + assert.deepEqual(checkAttachment({ mimeType: 'image/png', bytes: Number.NaN }), { + ok: false, + reason: 'empty', + }); +}); + +test('a message takes only so many files', () => { + const full = checkAttachment({ mimeType: 'image/png', bytes: 10 }, { onMessage: 10 }); + assert.deepEqual(full, { ok: false, reason: 'count', maxPerMessage: 10 }); + assert.equal(checkAttachment({ mimeType: 'image/png', bytes: 10 }, { onMessage: 9 }).ok, true); +}); + +test('the quota counts what is already stored, and says how much that is', () => { + const quota = DEFAULT_ATTACHMENT_POLICY.quotaBytes; + const over = checkAttachment({ mimeType: 'image/png', bytes: 2 * MB }, { usedBytes: quota - MB }); + assert.deepEqual(over, { + ok: false, + reason: 'quota', + quotaBytes: quota, + usedBytes: quota - MB, + }); + // Exactly filling the quota is allowed; one byte more is not. + assert.equal( + checkAttachment({ mimeType: 'image/png', bytes: MB }, { usedBytes: quota - MB }).ok, + true, + ); +}); + +test('a policy with no quota never refuses for room', () => { + const policy = { ...DEFAULT_ATTACHMENT_POLICY, quotaBytes: null }; + const check = checkAttachment( + { mimeType: 'image/png', bytes: MB }, + { usedBytes: Number.MAX_SAFE_INTEGER - 2 * MB }, + policy, + ); + assert.equal(check.ok, true); +}); + +test('the wrong type is the answer even when the quota is also full', () => { + // Cheapest-first: a person is told the thing they can actually change. + const check = checkAttachment( + { mimeType: 'text/html', bytes: MB }, + { usedBytes: DEFAULT_ATTACHMENT_POLICY.quotaBytes }, + ); + assert.equal(check.reason, 'type'); +}); + +test('stored bytes add up, and a negative size counts for nothing', () => { + assert.equal(storedBytes([]), 0); + assert.equal(storedBytes([{ bytes: 10 }, { bytes: 5 }, { bytes: -3 }]), 15); +}); + +test('with no retention a sent file is kept as long as its message', () => { + const sentAt = new Date('2026-01-01T00:00:00Z'); + assert.equal(attachmentExpiresAt(sentAt), null); + assert.equal(isAttachmentExpired(sentAt, new Date('2036-01-01T00:00:00Z')), false); +}); + +test('with a retention a sent file expires on the day the policy names', () => { + const policy = { ...DEFAULT_ATTACHMENT_POLICY, retentionDays: 90 }; + const sentAt = new Date('2026-01-01T00:00:00Z'); + assert.equal(attachmentExpiresAt(sentAt, policy).toISOString(), '2026-04-01T00:00:00.000Z'); + assert.equal(isAttachmentExpired(sentAt, new Date('2026-03-31T23:59:59Z'), policy), false); + assert.equal(isAttachmentExpired(sentAt, new Date('2026-04-01T00:00:00Z'), policy), true); +}); + +test('an upload that was never sent is abandoned after the policy’s hours, not before', () => { + const uploadedAt = new Date('2026-01-01T00:00:00Z'); + assert.equal(isAbandonedUpload(uploadedAt, new Date('2026-01-01T23:59:59Z')), false); + assert.equal(isAbandonedUpload(uploadedAt, new Date('2026-01-02T00:00:00Z')), true); +}); diff --git a/test/mentions.test.js b/test/mentions.test.js new file mode 100644 index 0000000..97f7933 --- /dev/null +++ b/test/mentions.test.js @@ -0,0 +1,49 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { mentionMatcher, mentionsAny } from '../dist/index.js'; + +test('a handle is matched as a whole word', () => { + assert.equal(mentionsAny('@cat who is right?', ['@cat']), true); + assert.equal(mentionsAny('who is right, @cat?', ['@cat']), true); + assert.equal(mentionsAny('ask @cat', ['@cat']), true); + assert.equal(mentionsAny('@Cat', ['@cat']), true, 'case is ignored'); +}); + +test('a longer handle that starts the same way is somebody else', () => { + assert.equal(mentionsAny('see the @catalogue', ['@cat']), false); + assert.equal(mentionsAny('@cats are great', ['@cat']), false); + assert.equal(mentionsAny('@cat_2', ['@cat']), false); +}); + +test('an address is not a mention', () => { + assert.equal(mentionsAny('write to me@cat.example', ['@cat']), false); +}); + +test('a short alias does not fire inside ordinary words', () => { + assert.equal(mentionsAny('I had to wait again', ['ai']), false); + assert.equal(mentionsAny('ask the AI.', ['ai']), true); +}); + +test('letters outside ASCII are still letters', () => { + // \W would call "ü" a boundary and match "ai" inside "aiü". + assert.equal(mentionsAny('aiü', ['ai']), false); + assert.equal(mentionsAny('über @käthe!', ['@käthe']), true); +}); + +test('punctuation in an alias is literal', () => { + assert.equal(mentionsAny('ping a.b now', ['a.b']), true); + assert.equal(mentionsAny('ping axb now', ['a.b']), false); +}); + +test('an empty alias matches nothing', () => { + assert.equal(mentionsAny('anything at all', ['', ' ']), false); + assert.equal(mentionsAny('anything at all', []), false); +}); + +test('a matcher is reusable', () => { + const mentioned = mentionMatcher(['@cat', 'assistant']); + assert.equal(mentioned('hello assistant'), true); + assert.equal(mentioned('hello @cat'), true); + assert.equal(mentioned('hello'), false); +}); diff --git a/test/package.test.js b/test/package.test.js index 65a990b..273df1c 100644 --- a/test/package.test.js +++ b/test/package.test.js @@ -20,17 +20,27 @@ import { join } from 'node:path'; */ const PUBLIC_API = [ + 'DEFAULT_ATTACHMENT_POLICY', 'afterEveryMessage', + 'attachmentExpiresAt', + 'attachmentKind', 'canRead', 'canSeeMessage', 'canWrite', + 'checkAttachment', 'compareMessages', 'defaultRespondPolicy', 'findParticipant', + 'isAbandonedUpload', + 'isAttachmentExpired', 'isPending', + 'mentionMatcher', + 'mentionsAny', 'mergeMessages', + 'readState', 'readersOf', 'runAiTurn', + 'storedBytes', 'unreadCount', 'unreadMessages', 'unreadThreadCount', diff --git a/test/read-state.test.js b/test/read-state.test.js new file mode 100644 index 0000000..a1969bb --- /dev/null +++ b/test/read-state.test.js @@ -0,0 +1,110 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { mergeMessages, readState, unreadMessages, visibleMessages } from '../dist/index.js'; + +const T0 = new Date('2026-01-01T09:00:00Z'); +const T1 = new Date('2026-01-01T10:00:00Z'); +const T2 = new Date('2026-01-01T11:00:00Z'); + +const person = (actorId, extra = {}) => ({ + actorId, + kind: 'human', + joinedAt: T0, + visibleFrom: 'thread-start', + ...extra, +}); + +const message = { id: 'm1', threadId: 't1', authorId: 'ada', body: 'hello', createdAt: T1 }; + +test('nobody else has read it yet', () => { + const thread = { id: 't1', createdAt: T0, participants: [person('ada'), person('ben')] }; + const state = readState(thread, message); + assert.equal(state.state, 'none'); + assert.equal(state.audience, 1); +}); + +test('read by the only other person is read by all', () => { + const thread = { + id: 't1', + createdAt: T0, + participants: [person('ada'), person('ben', { lastReadAt: T2 })], + }; + assert.equal(readState(thread, message).state, 'all'); +}); + +test('in a group, one reader of two is some, not all', () => { + const thread = { + id: 't1', + createdAt: T0, + participants: [person('ada'), person('ben', { lastReadAt: T2 }), person('cy')], + }; + const state = readState(thread, message); + assert.equal(state.state, 'some'); + assert.deepEqual( + state.readers.map((p) => p.actorId), + ['ben'], + ); + assert.equal(state.audience, 2); +}); + +test('an assistant in the room does not hold a message at unread', () => { + const thread = { + id: 't1', + createdAt: T0, + participants: [ + person('ada'), + person('ben', { lastReadAt: T2 }), + { actorId: 'cat', kind: 'ai', joinedAt: T0, visibleFrom: 'thread-start' }, + ], + }; + const state = readState(thread, message); + assert.equal(state.state, 'all'); + assert.equal(state.audience, 1); +}); + +test('somebody who left is not waited for', () => { + const thread = { + id: 't1', + createdAt: T0, + participants: [person('ada'), person('ben', { lastReadAt: T2 }), person('cy', { leftAt: T2 })], + }; + assert.equal(readState(thread, message).state, 'all'); +}); + +test('a message nobody else can see has no audience and no readers', () => { + const thread = { + id: 't1', + createdAt: T0, + participants: [person('ada'), person('ben', { visibleFrom: T2, lastReadAt: T2 })], + }; + const state = readState(thread, message); + assert.equal(state.state, 'none'); + assert.equal(state.audience, 0); +}); + +test('rows that carry more than the package knows come back as they were', () => { + // The generic signatures: a consumer's own fields survive every function. + const thread = { id: 't1', createdAt: T0, participants: [person('ada'), person('ben')] }; + const rich = { ...message, senderName: 'Ada', attachments: [] }; + const [merged] = mergeMessages([], [rich]); + assert.equal(merged.senderName, 'Ada'); + assert.equal(visibleMessages(thread, 'ben', [rich])[0].senderName, 'Ada'); + assert.equal(unreadMessages(thread, 'ben', [rich])[0].senderName, 'Ada'); +}); + +test('a message of only files is a message', () => { + const thread = { id: 't1', createdAt: T0, participants: [person('ada'), person('ben')] }; + const photo = { + id: 'm2', + threadId: 't1', + authorId: 'ada', + body: '', + createdAt: T1, + attachments: [ + { id: 'a1', kind: 'image', name: 'cat.jpg', mimeType: 'image/jpeg', bytes: 1200 }, + ], + }; + assert.equal(unreadMessages(thread, 'ben', [photo]).length, 1); + assert.equal(visibleMessages(thread, 'ben', [photo])[0].attachments[0].name, 'cat.jpg'); +});