Something went wrong. Try again.
small gleam coding and (not yet) persistent agent daemon with a detachable cli forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272import type { FileUpload, ImageUpload } from '../api';
// Images in the composer, as the terminal client keeps them// (cli/internal/tui/attachments.go): each attached image puts a numbered// marker in the text at the cursor, deleting the marker drops the image, and// sending numbers the images still marked 1..n in reading order.// Generic files are cards beside the prose and never put text in it, so any// `[File #n: name]` a person types stays their words.
export const MAX_IMAGES = 10;export const MAX_FILES = 10;export const MAX_BYTES = 20 * 1024 * 1024;const MARKER = /\[Image #(\d+)\]/g;const TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
export interface Attached extends ImageUpload { /** A data URL, for the thumbnail. */ preview: string; name?: string; size?: number;}
export interface AttachedFile extends FileUpload { size: number;}
export interface AttachmentSelection { imageCount: number; fileCount: number; bytes: number;}
export const REMOTE_FILES_NOTICE = 'files need a local workspace; images still work here';
/** What a send would carry: the images the text still marks, and every file card. */export function attachmentSelection( text: string, images: Map<number, Attached>, files: Map<number, AttachedFile>,): AttachmentSelection { const marked = referenced(text, images); return { imageCount: marked.length, fileCount: files.size, bytes: marked.reduce((sum, n) => sum + attachmentSize(images.get(n)!), 0) + [...files.values()].reduce((sum, file) => sum + file.size, 0), };}
/** Deleting an image tile frees its bytes; file cards own their bytes until removed. */export function collectAttachments( text: string, images: Map<number, Attached>, files: Map<number, AttachedFile>,): AttachmentSelection { const marked = new Set(referenced(text, images)); for (const n of images.keys()) if (!marked.has(n)) images.delete(n); return attachmentSelection(text, images, files);}
/** * Why a selection cannot be sent as one message, or null. A restored draft can * hold more than one message allows; its bytes stay until the person removes some. */export function attachmentProblem( selection: AttachmentSelection,): string | null { if (selection.imageCount > MAX_IMAGES) return `${selection.imageCount} images attached — remove some to send at most ${MAX_IMAGES}`; if (selection.fileCount > MAX_FILES) return `${selection.fileCount} files attached — remove some to send at most ${MAX_FILES}`; if (selection.bytes > MAX_BYTES) return `attachments total ${formatSize(selection.bytes)} — remove some to send at most 20 MiB`; return null;}
/** Admission uses browser metadata; reading the accepted file happens later. */export function chooseAttachment( file: Pick<File, 'name' | 'type' | 'size'>, selected: AttachmentSelection, remote = false,): { kind: 'image' | 'file' } | { problem: string } { const image = attachable(file); if (!image && remote) return { problem: REMOTE_FILES_NOTICE }; const count = image ? selected.imageCount : selected.fileCount; const limit = image ? MAX_IMAGES : MAX_FILES; if (count >= limit) return { problem: `this message is full — up to ${limit} ${image ? 'images' : 'files'} at a time`, }; if (selected.bytes + file.size > MAX_BYTES) return { problem: `${file.name} won't fit — keep attachments at 20 MiB or less`, }; if ( !image && (!file.name || file.name === '.' || file.name === '..' || new TextEncoder().encode(file.name).length > 255 || /[/\\\0\r\n]/.test(file.name)) ) { return { problem: `${file.name || 'this file'} needs a plain filename of at most 255 bytes, with no path separators or newlines`, }; } return { kind: image ? 'image' : 'file' };}
/** Keep a short extension visible while a long filename's stem ellipsizes. */export function filenameParts(name: string): { stem: string; extension: string;} { const dot = name.lastIndexOf('.'); return dot > 0 && name.length - dot <= 17 ? { stem: name.slice(0, dot), extension: name.slice(dot) } : { stem: name, extension: '' };}
/** Exact decoded bytes, also for an image restored without browser metadata. */export function attachmentSize(file: { data: string; size?: number }): number { return ( file.size ?? Math.floor((file.data.length * 3) / 4) - (file.data.endsWith('==') ? 2 : file.data.endsWith('=') ? 1 : 0) );}
export function formatSize(size: number): string { if (size < 1024) return `${size.toLocaleString()} B`; const scale = size < 1024 * 1024 ? 1024 : 1024 * 1024; return `${(size / scale).toLocaleString(undefined, { maximumFractionDigits: 1 })} ${scale === 1024 ? 'KiB' : 'MiB'}`;}
export function marker(n: number): string { return `[Image #${n}]`;}
/** Whether a file is an image the daemon accepts. */export function attachable(file: Pick<File, 'type'>): boolean { return TYPES.includes(file.type);}
function readDataURL(file: File): Promise<{ preview: string; data: string }> { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { const result = reader.result; // Accommodate an empty-file representation without treating a malformed // nonempty result as its own base64 payload. if (file.size === 0 && result === 'data:') { resolve({ preview: `data:${file.type || 'application/octet-stream'};base64,`, data: '', }); return; } if (typeof result !== 'string') { reject(new Error('file reader did not return a data URL')); return; } const separator = result.indexOf(','); if ( separator < 0 || !/^data:[^,]*;base64$/i.test(result.slice(0, separator)) ) { reject(new Error('file reader returned a malformed data URL')); return; } const data = result.slice(separator + 1); const padding = data.indexOf('='); if ( data.length % 4 || /[^A-Za-z0-9+/=]/.test(data) || (padding >= 0 && !/^={1,2}$/.test(data.slice(padding))) || attachmentSize({ data }) !== file.size ) { reject(new Error('file reader returned incomplete or invalid bytes')); return; } resolve({ preview: result, data }); }; reader.onerror = () => reject(reader.error); reader.onabort = () => reject(new Error('file read was cancelled')); reader.readAsDataURL(file); });}
export async function readImage(file: File): Promise<Attached> { const image = await readDataURL(file); return { mime_type: file.type as ImageUpload['mime_type'], ...image, name: file.name, size: file.size, };}
/** The numbers of the images the text still marks, in reading order, each once. */export function referenced( text: string, images: Map<number, Attached>,): number[] { const numbers: number[] = []; for (const match of text.matchAll(MARKER)) { const n = Number(match[1]); if (images.has(n) && !numbers.includes(n)) numbers.push(n); } return numbers;}
export async function readFile(file: File): Promise<AttachedFile> { const encoded = await readDataURL(file); return { name: file.name, data: encoded.data, size: file.size };}
/** Renumbers the marked images 1..n and returns the text to match with the images in order. */export function resolve( text: string, images: Map<number, Attached>,): { text: string; images: Attached[] } { const numbers = referenced(text, images); const renumbered = new Map(numbers.map((n, index) => [n, index + 1])); return { text: text.replace(MARKER, (found, n) => renumbered.has(Number(n)) ? marker(renumbered.get(Number(n))!) : found, ), images: numbers.map((n) => images.get(n)!), };}
/** The text with every image marker (and the space before it) taken out, for text kept without its images. */export function withoutMarkers(text: string): string { return text.replaceAll(new RegExp(` ?${MARKER.source}`, 'g'), '');}
/** A canvas note carries the prose; the images it marks stay in the composer. */export function splitForNote( text: string, images: Map<number, Attached>,): { note: string; text: string } { const retained = new Set<string>(); const note = text.replaceAll( new RegExp(` ?${MARKER.source}`, 'g'), (found, n) => { if (!images.has(Number(n))) return found; retained.add(marker(Number(n))); return ''; }, ); const markers = [...retained]; return { note, text: markers.join(' ') + (markers.length ? ' ' : '') };}
/** The text without one image's markers. */export function unmark(text: string, n: number): string { return text.replaceAll(` ${marker(n)}`, '').replaceAll(marker(n), '');}
/** The text with each image marker it backs renumbered; other text is left alone. */export function remapMarkers( text: string, images: Map<number, number>,): string { return text.replace(MARKER, (found, n) => images.has(Number(n)) ? marker(images.get(Number(n))!) : found, );}