From 9393f43c701bd3b6f4e48977edeaa5bf202fe00e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 15:37:06 +0000 Subject: [PATCH 1/4] Core: letter format, recorder, replay, summary and pulse seal, with tests Co-Authored-By: Claude Opus 5.5 --- .gitignore | 6 + package.json | 17 +++ src/shared/letter-format.js | 201 ++++++++++++++++++++++++++++ src/shared/playback.js | 145 ++++++++++++++++++++ src/shared/recorder.js | 156 ++++++++++++++++++++++ src/shared/seal.js | 114 ++++++++++++++++ src/shared/sim-source.js | 83 ++++++++++++ src/shared/summary.js | 98 ++++++++++++++ src/shared/vitals.js | 146 +++++++++++++++++++++ test/core.test.js | 254 ++++++++++++++++++++++++++++++++++++ 10 files changed, 1220 insertions(+) create mode 100644 .gitignore create mode 100644 package.json create mode 100644 src/shared/letter-format.js create mode 100644 src/shared/playback.js create mode 100644 src/shared/recorder.js create mode 100644 src/shared/seal.js create mode 100644 src/shared/sim-source.js create mode 100644 src/shared/summary.js create mode 100644 src/shared/vitals.js create mode 100644 test/core.test.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..93eea39 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +release/ +.smartspectra-key +*.log +.DS_Store diff --git a/package.json b/package.json new file mode 100644 index 0000000..d8ca7fd --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "heartwritten", + "version": "0.1.0", + "private": true, + "description": "Letters that carry the heartbeat you wrote them with. Built on the Presage SmartSpectra SDK.", + "type": "module", + "main": "app/main.cjs", + "scripts": { + "test": "node --test test/*.test.js", + "build": "node scripts/build.mjs", + "start": "npm run build && electron .", + "start:sim": "npm run build && HEARTWRITTEN_SIMULATE=1 electron .", + "smoke": "node scripts/sdk-smoke.mjs", + "sample": "node scripts/make-sample.mjs" + }, + "engines": { "node": ">=20" } +} diff --git a/src/shared/letter-format.js b/src/shared/letter-format.js new file mode 100644 index 0000000..efdb2c8 --- /dev/null +++ b/src/shared/letter-format.js @@ -0,0 +1,201 @@ +// letter-format.js +// The wire format of a Heartwritten letter, and how it is packed into a link. +// +// A letter is plain data. It never goes to a server: the writer app packs it +// into the #fragment of a link (browsers never send the fragment over the +// network) or into a self-contained .html file. +// +// Decoded shape (version 1): +// { +// v: 1, +// from: "Subomi", // optional, as typed by the writer +// to: "Deola", // optional +// day: "2026-11-12", // the day it was sealed, no time of day +// sim: 0 | 1, // 1 when the signals were simulated (sample letters) +// share: { edits: bool, smiles: bool }, +// ops: [[t, pos, del, ins], ...] // replayable edits, t = ms since start +// vit: { hz, bpm: [...], br: [...], sm: [...] } // signals sampled over time +// wave: { hz, v: [...] } // a few seconds of the pulse wave, for the seal +// } +// +// On the wire the ops and samples are delta- and integer-coded, then the JSON +// is deflated and base64url-encoded. + +export const FORMAT_VERSION = 1; +export const LINK_PREFIX = 'v1.'; +// Times are stored in 10 ms ticks to keep the numbers small. +const TICK_MS = 10; + +const MAX_TEXT = 20000; +const MAX_OPS = 40000; +const MAX_SAMPLES = 20000; + +/** Turn a decoded letter into the compact JSON-able form. */ +export function pack(letter) { + validate(letter); + let prevT = 0; + const ops = letter.ops.map(([t, pos, del, ins]) => { + const tick = Math.round(t / TICK_MS); + const dt = tick - prevT; + prevT = tick; + return ins ? [dt, pos, del, ins] : [dt, pos, del]; + }); + return { + v: FORMAT_VERSION, + f: letter.from || undefined, + to: letter.to || undefined, + d: letter.day || undefined, + s: letter.sim ? 1 : undefined, + sh: (letter.share.edits ? 1 : 0) | (letter.share.smiles ? 2 : 0), + o: ops, + vh: letter.vit.hz, + b: deltaCode(letter.vit.bpm), + r: deltaCode(letter.vit.br), + m: letter.share.smiles ? letter.vit.sm : undefined, + wh: letter.wave.hz, + w: deltaCode(letter.wave.v), + }; +} + +/** Inverse of pack(). Throws on anything malformed. */ +export function unpack(p) { + if (!p || p.v !== FORMAT_VERSION) throw new Error('Unsupported letter version'); + let t = 0; + const ops = (p.o || []).map((op) => { + t += op[0]; + return [t * TICK_MS, op[1], op[2], op[3] || '']; + }); + const share = { edits: !!(p.sh & 1), smiles: !!(p.sh & 2) }; + const bpm = deltaDecode(p.b || []); + const letter = { + v: FORMAT_VERSION, + from: p.f || '', + to: p.to || '', + day: p.d || '', + sim: p.s ? 1 : 0, + share, + ops, + vit: { + hz: p.vh || 1, + bpm, + br: deltaDecode(p.r || []), + sm: share.smiles && Array.isArray(p.m) ? p.m : new Array(bpm.length).fill(0), + }, + wave: { hz: p.wh || 25, v: deltaDecode(p.w || []) }, + }; + validate(letter); + return letter; +} + +/** Checks the shape and bounds of a decoded letter. */ +export function validate(letter) { + const fail = (why) => { throw new Error(`Invalid letter: ${why}`); }; + if (!letter || typeof letter !== 'object') fail('not an object'); + if (!Array.isArray(letter.ops) || letter.ops.length > MAX_OPS) fail('ops'); + let len = 0; + let lastT = -1; + for (const op of letter.ops) { + if (!Array.isArray(op) || op.length < 3) fail('op shape'); + const [t, pos, del, ins = ''] = op; + if (!isInt(t) || t < lastT) fail('op time'); + if (!isInt(pos) || pos < 0 || pos > len) fail('op position'); + if (!isInt(del) || del < 0 || pos + del > len) fail('op delete'); + if (typeof ins !== 'string') fail('op insert'); + len = len - del + ins.length; + if (len > MAX_TEXT) fail('text too long'); + lastT = t; + } + const vit = letter.vit; + if (!vit || !(vit.hz > 0) || vit.hz > 50) fail('vit.hz'); + for (const k of ['bpm', 'br', 'sm']) { + if (!Array.isArray(vit[k]) || vit[k].length > MAX_SAMPLES) fail(`vit.${k}`); + if (!vit[k].every(isInt)) fail(`vit.${k} values`); + } + if (!letter.wave || !Array.isArray(letter.wave.v) || letter.wave.v.length > 2000) fail('wave'); + if (!(letter.wave.hz > 0) || letter.wave.hz > 120) fail('wave.hz'); + for (const k of ['from', 'to']) { + if (letter[k] != null && (typeof letter[k] !== 'string' || letter[k].length > 80)) fail(k); + } + if (!letter.share || typeof letter.share !== 'object') fail('share'); + return true; +} + +/** Replays the ops and returns the final text. */ +export function finalText(letter) { + let s = ''; + for (const [, pos, del, ins = ''] of letter.ops) s = s.slice(0, pos) + ins + s.slice(pos + del); + return s; +} + +// --------------------------------------------------------------------------- +// Link encoding + +/** Letter -> "v1." */ +export async function encodeLetter(letter) { + const json = JSON.stringify(pack(letter)); + const bytes = await deflate(new TextEncoder().encode(json)); + return LINK_PREFIX + toBase64Url(bytes); +} + +/** "v1.<...>" (or a whole URL / fragment containing it) -> letter */ +export async function decodeLetter(token) { + const raw = extractToken(token); + if (!raw) throw new Error('No letter in this link'); + const bytes = fromBase64Url(raw.slice(LINK_PREFIX.length)); + if (bytes.length > 2_000_000) throw new Error('Letter too large'); + const json = new TextDecoder().decode(await inflate(bytes)); + return unpack(JSON.parse(json)); +} + +/** Pulls the letter token out of a URL, a hash or a bare token. */ +export function extractToken(input) { + if (typeof input !== 'string') return null; + const at = input.indexOf(LINK_PREFIX); + if (at === -1) return null; + const tok = input.slice(at).split(/[&\s]/)[0]; + return /^v1\.[A-Za-z0-9_-]+$/.test(tok) ? tok : null; +} + +export function buildLink(base, token) { + const clean = String(base || '').split('#')[0]; + return `${clean}#${token}`; +} + +// --------------------------------------------------------------------------- +// helpers + +function isInt(n) { return Number.isInteger(n); } + +function deltaCode(arr) { + let prev = 0; + return arr.map((x) => { const d = x - prev; prev = x; return d; }); +} + +function deltaDecode(arr) { + let acc = 0; + return arr.map((d) => (acc += d)); +} + +async function pipeThrough(bytes, stream) { + const out = new Blob([bytes]).stream().pipeThrough(stream); + return new Uint8Array(await new Response(out).arrayBuffer()); +} + +async function deflate(bytes) { return pipeThrough(bytes, new CompressionStream('deflate-raw')); } +async function inflate(bytes) { return pipeThrough(bytes, new DecompressionStream('deflate-raw')); } + +export function toBase64Url(bytes) { + let bin = ''; + for (let i = 0; i < bytes.length; i += 0x8000) { + bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)); + } + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +export function fromBase64Url(s) { + const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4); + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} diff --git a/src/shared/playback.js b/src/shared/playback.js new file mode 100644 index 0000000..d5fd830 --- /dev/null +++ b/src/shared/playback.js @@ -0,0 +1,145 @@ +// playback.js +// Replays a letter: the words reappear at the pace they were written, long +// pauses are shortened (but remembered), and every character keeps the +// heart rate its writer had when it was typed. Pure logic; the reader page +// draws what this returns. + +import { finalText } from './letter-format.js'; + +export const DEFAULTS = { + maxGapMs: 1400, // no silence in the replay lasts longer than this + longPauseMs: 8000, // pauses longer than this get a quiet note in the margin + speed: 1, // 1 = the writer's real typing pace (after gap capping) +}; + +/** + * Build the replay timeline. Returns + * { ops: [{at, t, pos, del, ins}], pauses: [{at, t, ms, pos}], duration, writtenMs } + * where `t` is the writer's real time and `at` the replay time. + */ +export function buildTimeline(letter, opts = {}) { + const o = { ...DEFAULTS, ...opts }; + const ops = []; + const pauses = []; + let at = 0; + let prevT = null; + let len = 0; + for (const [t, pos, del, ins = ''] of letter.ops) { + if (prevT != null) { + const gap = t - prevT; + at += Math.min(gap, o.maxGapMs) / o.speed; + if (gap >= o.longPauseMs) pauses.push({ at, t: prevT, ms: gap, pos }); + } else { + at = 600 / o.speed; // a beat of stillness before the first word + } + // Long pastes would appear all at once; spread them like typing. + if (ins.length > 12 && del === 0) { + const chunk = 3; + for (let k = 0; k < ins.length; k += chunk) { + ops.push({ at: at + (k / chunk) * (24 / o.speed), t, pos: pos + k, del: 0, ins: ins.slice(k, k + chunk) }); + } + at += Math.ceil(ins.length / chunk) * (24 / o.speed); + } else { + ops.push({ at, t, pos, del, ins }); + } + len = len - del + ins.length; + prevT = t; + } + const writtenMs = letter.ops.length ? letter.ops[letter.ops.length - 1][0] - letter.ops[0][0] : 0; + return { ops, pauses, duration: at, writtenMs, length: len }; +} + +/** Value of a sampled series at writer-time t (ms). */ +export function sampleAt(series, hz, tMs) { + if (!series || !series.length) return 0; + const i = Math.min(series.length - 1, Math.max(0, Math.floor((tMs / 1000) * hz))); + return series[i]; +} + +/** Heart rate at writer-time t, looking a little either side when unknown. */ +export function bpmAt(letter, tMs) { + const { bpm, hz } = letter.vit; + if (!bpm.length) return 0; + const i = Math.min(bpm.length - 1, Math.max(0, Math.floor((tMs / 1000) * hz))); + for (let d = 0; d < hz * 4; d++) { + if (bpm[i - d] > 0) return bpm[i - d]; + if (bpm[i + d] > 0) return bpm[i + d]; + } + return 0; +} + +/** + * Incremental player. Call advance(atMs) every frame; it applies every op + * due by then and reports what changed. + */ +export class Player { + constructor(letter, opts) { + this.letter = letter; + this.timeline = buildTimeline(letter, opts); + this.reset(); + } + + reset() { + this.i = 0; + this.chars = []; // [{ch, t}] the visible text, each char with its typing time + this.at = 0; + this.tookBack = 0; + } + + get done() { return this.i >= this.timeline.ops.length; } + + /** Writer-time currently being replayed. */ + get writerTime() { + const ops = this.timeline.ops; + if (!ops.length) return 0; + const k = Math.min(this.i, ops.length) - 1; + return k < 0 ? ops[0].t : ops[k].t; + } + + advance(atMs) { + this.at = atMs; + const ops = this.timeline.ops; + let changed = false; + while (this.i < ops.length && ops[this.i].at <= atMs) { + const { t, pos, del, ins } = ops[this.i++]; + this.chars.splice(pos, del, ...splitUnits(ins, t)); + this.tookBack += del; + changed = true; + } + return changed; + } + + text() { return this.chars.map((c) => c.ch).join(''); } +} + +function splitUnits(s, t) { + // One entry per UTF-16 unit, to stay aligned with editor positions. The two + // halves of an emoji share a time, so the reader draws them in one run. + const out = []; + for (let k = 0; k < s.length; k++) out.push({ ch: s[k], t }); + return out; +} + +/** + * Ink colour for a heartbeat relative to the writer's own resting level. + * Calm is deep ink blue, a quickened heart turns the ink warm red. + */ +export function inkFor(bpm, baseline) { + if (!(bpm > 0) || !(baseline > 0)) return 'rgb(31, 41, 66)'; + const d = Math.max(-1, Math.min(1, (bpm - baseline) / 18)); + const calm = [31, 41, 66]; + const warm = [168, 38, 44]; + const cool = [24, 54, 92]; + const [a, b, f] = d >= 0 ? [calm, warm, d] : [calm, cool, -d]; + const mix = a.map((x, k) => Math.round(x + (b[k] - x) * f)); + return `rgb(${mix[0]}, ${mix[1]}, ${mix[2]})`; +} + +/** Final characters of the letter, each with the time it was typed. */ +export function finalChars(letter) { + const p = new Player(letter, { maxGapMs: Infinity }); + p.advance(Infinity); + return p.chars; +} + +export { finalText }; diff --git a/src/shared/recorder.js b/src/shared/recorder.js new file mode 100644 index 0000000..0d71836 --- /dev/null +++ b/src/shared/recorder.js @@ -0,0 +1,156 @@ +// recorder.js +// Records a letter while it is being written: every edit with its time, and +// the writer's signals sampled on a fixed clock. Pure logic, no DOM, so it is +// tested in Node. + +import { FORMAT_VERSION } from './letter-format.js'; + +export const VITALS_HZ = 4; // signals are sampled four times a second +export const WAVE_HZ = 30; // the pulse wave kept for the seal +export const WAVE_SECONDS = 6; + +/** + * Smallest single edit that turns `prev` into `next`: + * returns { pos, del, ins } or null when nothing changed. + * Works for typing, backspace, paste, cut, autocorrect and IME commits. + * With repeated characters ("aa" -> "aaa") the reported position may be one + * of several equivalent ones; the resulting text is the same either way. + */ +export function diffText(prev, next) { + if (prev === next) return null; + let start = 0; + const max = Math.min(prev.length, next.length); + while (start < max && prev[start] === next[start]) start++; + let endPrev = prev.length; + let endNext = next.length; + while (endPrev > start && endNext > start && prev[endPrev - 1] === next[endNext - 1]) { + endPrev--; endNext--; + } + return { pos: start, del: endPrev - start, ins: next.slice(start, endNext) }; +} + +export class LetterRecorder { + constructor({ now = () => Date.now() } = {}) { + this._now = now; + this.reset(); + } + + reset() { + this.t0 = null; + this.text = ''; + this.charTimes = []; // insertion time of each character of `text` + this.ops = []; + this.samples = { bpm: [], br: [], sm: [] }; + this.wave = []; // rolling pulse wave, values -127..127 + this.tookBack = 0; // characters deleted along the way + } + + /** ms since the first keystroke (or since start() was called). */ + elapsed() { + if (this.t0 == null) return 0; + return Math.max(0, this._now() - this.t0); + } + + start() { if (this.t0 == null) this.t0 = this._now(); } + + /** Feed the full editor value after every input event. */ + edit(nextText) { + this.start(); + const d = diffText(this.text, nextText); + if (!d) return null; + const t = this.elapsed(); + const last = this.ops[this.ops.length - 1]; + const tRounded = Math.max(Math.round(t), last ? last[0] : 0); + this.ops.push([tRounded, d.pos, d.del, d.ins]); + this.charTimes.splice(d.pos, d.del, ...new Array(d.ins.length).fill(tRounded)); + this.tookBack += d.del; + this.text = nextText; + return d; + } + + /** + * Called on the sampling clock with the latest live signals. + * bpm: number|null, breath: -1..1|null, smile: 0..1|null + */ + sample({ bpm, breath, smile }) { + if (this.t0 == null) return; + const due = Math.floor((this.elapsed() / 1000) * VITALS_HZ) + 1; + while (this.samples.bpm.length < due) { + this.samples.bpm.push(bpm > 0 ? Math.round(bpm) : 0); + this.samples.br.push(breath == null ? 0 : clampInt(breath * 100, -100, 100)); + this.samples.sm.push(smile == null ? 0 : clampInt(smile * 9, 0, 9)); + } + } + + /** Append pulse-wave samples (already resampled to WAVE_HZ, any scale). */ + pushWave(values) { + for (const v of values) this.wave.push(v); + const keep = WAVE_HZ * 20; + if (this.wave.length > keep) this.wave.splice(0, this.wave.length - keep); + } + + /** + * Seal the letter. With share.edits off, the deletions are dropped and + * the letter is rebuilt as if each final character had been typed once, + * at the time it was typed. + */ + finish({ from = '', to = '', day = '', sim = false, share = { edits: false, smiles: true } } = {}) { + const ops = share.edits ? this.ops.map((o) => o.slice()) : opsFromCharTimes(this.text, this.charTimes); + const sm = share.smiles ? this.samples.sm.slice() : this.samples.sm.map(() => 0); + return { + v: FORMAT_VERSION, + from: from.slice(0, 80), + to: to.slice(0, 80), + day, + sim: sim ? 1 : 0, + share: { edits: !!share.edits, smiles: !!share.smiles }, + ops, + vit: { hz: VITALS_HZ, bpm: this.samples.bpm.slice(), br: this.samples.br.slice(), sm }, + wave: { hz: WAVE_HZ, v: normalizeWave(this.wave.slice(-WAVE_HZ * WAVE_SECONDS)) }, + }; + } +} + +/** + * Rebuild a forward-only edit list from the final text and the time each + * character was typed: characters appear in the order they were typed, each + * at its place in the final text. Runs typed at the same moment are merged. + */ +export function opsFromCharTimes(text, times) { + // Work in UTF-16 indices to stay aligned with the editor's value. + const idx = Array.from({ length: text.length }, (_, i) => i); + idx.sort((a, b) => times[a] - times[b] || a - b); + const ops = []; + // Fenwick tree for "how many revealed characters sit before index i". + const tree = new Int32Array(text.length + 1); + const add = (i) => { for (i++; i <= text.length; i += i & -i) tree[i]++; }; + const before = (i) => { let s = 0; for (; i > 0; i -= i & -i) s += tree[i]; return s; }; + for (const i of idx) { + const pos = before(i); + const t = times[i]; + const last = ops[ops.length - 1]; + if (last && last[0] === t && last[1] + last[3].length === pos) { + last[3] += text[i]; + } else { + ops.push([t, pos, 0, text[i]]); + } + add(i); + } + return ops; +} + +/** Scale a wave to integers in -100..100 around its median. */ +export function normalizeWave(values) { + const vals = values.filter((v) => Number.isFinite(v)); + if (vals.length < 2) return []; + const sorted = [...vals].sort((a, b) => a - b); + const med = sorted[Math.floor(sorted.length / 2)]; + let span = 0; + for (const v of vals) span = Math.max(span, Math.abs(v - med)); + if (span === 0) return vals.map(() => 0); + return vals.map((v) => clampInt(((v - med) / span) * 100, -100, 100)); +} + +function clampInt(x, lo, hi) { + return Math.max(lo, Math.min(hi, Math.round(x))); +} diff --git a/src/shared/seal.js b/src/shared/seal.js new file mode 100644 index 0000000..036cedb --- /dev/null +++ b/src/shared/seal.js @@ -0,0 +1,114 @@ +// seal.js +// A wax seal drawn from the writer's own pulse. The wave recorded in the last +// seconds before sealing is wrapped once around the seal, so no two seals +// look alike. Returns an SVG string; deterministic for the same input. + +const SIZE = 200; +const C = SIZE / 2; + +function hash(values) { + let h = 2166136261; + for (const v of values) { h ^= (v + 1000) & 0xffff; h = Math.imul(h, 16777619); } + return h >>> 0; +} + +function rng(seed) { + let s = seed || 1; + return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return ((s >>> 0) % 10000) / 10000; }; +} + +function polar(r, a) { return [C + r * Math.cos(a), C + r * Math.sin(a)]; } + +function pathFrom(points) { + return `${points.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join(' ')} Z`; +} + +function smooth(values, k) { + if (!values.length) return values; + return values.map((_, i) => { + let s = 0; let n = 0; + for (let d = -k; d <= k; d++) { + const j = (i + d + values.length) % values.length; + s += values[j]; n++; + } + return s / n; + }); +} + +function escapeXml(s) { + return String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); +} + +/** + * @param {number[]} wave pulse wave, -100..100 (may be empty) + * @param {object} opts { initial, bpm, id } + */ +export function sealSvg(wave, { initial = '', bpm = 0, id = 'seal' } = {}) { + const w = wave && wave.length >= 16 ? wave : flatline(120); + const rand = rng(hash(w)); + const uid = `${id}-${hash(w).toString(36)}`; + + // Melted wax edge: an irregular blob, a little different every time. + const edge = []; + const blobs = 7 + Math.floor(rand() * 4); + const phase = rand() * Math.PI * 2; + for (let i = 0; i < 160; i++) { + const a = (i / 160) * Math.PI * 2; + const r = 88 + 4.5 * Math.sin(a * blobs + phase) + 2.2 * Math.sin(a * (blobs + 5) + phase * 2) + (rand() - 0.5) * 1.6; + edge.push(polar(r, a)); + } + + // Pressed rim. + const rim = []; + for (let i = 0; i < 120; i++) rim.push(polar(70, (i / 120) * Math.PI * 2)); + + // The pulse ring: the wave wrapped once around the seal. + const sm = smooth(w, 1); + const ring = []; + const N = sm.length; + for (let i = 0; i < N; i++) { + const a = (i / N) * Math.PI * 2 - Math.PI / 2; + ring.push(polar(56 + (sm[i] / 100) * 9, a)); + } + + const letter = escapeXml((initial || '♥').slice(0, 2).toUpperCase()); + const bpmText = bpm > 0 ? `${Math.round(bpm)} BPM` : ''; + + return ` + + + + + + + + + + + + + + + + + + + + + + ${letter} + ${bpmText ? `${bpmText}` : ''} + + +`; +} + +function flatline(n) { + // A gentle placeholder beat when no wave was captured. + const out = []; + for (let i = 0; i < n; i++) { + const p = (i % 30) / 30; + out.push(Math.round(p < 0.12 ? Math.sin(p / 0.12 * Math.PI) * 80 : p < 0.3 ? -Math.sin((p - 0.12) / 0.18 * Math.PI) * 20 : 0)); + } + return out; +} diff --git a/src/shared/sim-source.js b/src/shared/sim-source.js new file mode 100644 index 0000000..e02647b --- /dev/null +++ b/src/shared/sim-source.js @@ -0,0 +1,83 @@ +// sim-source.js +// A stand-in for the camera, for development and tests only. It emits +// packets shaped like SmartSpectra's decoded Metrics so the rest of the app +// runs the same code path. The app labels every simulated session and every +// letter written with it, so a simulated letter can't pass for a real one. + +export class SimulatedSource { + constructor({ seed = 7, restingBpm = 66, now = () => performance.now() } = {}) { + this.rest = restingBpm; + this.now = now; + this.seed = seed; + this.handlers = {}; + this.timer = null; + this.excite = 0; // 0..1, nudged by bump() + } + + on(event, fn) { this.handlers[event] = fn; return this; } + + emit(event, ...args) { const h = this.handlers[event]; if (h) h(...args); } + + /** Pretend something stirred the writer's heart. */ + bump(amount = 0.6) { this.excite = Math.min(1, this.excite + amount); } + + start() { + this.t0 = this.now(); + this.lastUs = 0; + this.phase = 0; + this.breathPhase = 0; + this.smileUntil = 0; + this.emit('processingStatus', 3); + this.emit('validationStatus', 0, 0, ''); + this.timer = setInterval(() => this.tick(), 200); + } + + stop() { + clearInterval(this.timer); + this.timer = null; + this.emit('processingStatus', 1); + } + + bpmNow(tS) { + const drift = 3 * Math.sin(tS / 23) + 1.5 * Math.sin(tS / 7.3 + this.seed); + return this.rest + drift + this.excite * 22; + } + + /** Build one packet covering the time since the previous one. */ + tick() { + const nowUs = Math.round((this.now() - this.t0) * 1000); + const fromUs = this.lastUs; + this.lastUs = nowUs; + this.excite *= 0.985; + const bpm = this.bpmNow(nowUs / 1e6); + const trace = []; + const breath = []; + for (let t = fromUs; t < nowUs; t += 33333) { + this.phase += (bpm / 60) * 0.033333; + this.breathPhase += (14 / 60) * 0.033333; + trace.push({ value: ppg(this.phase % 1), timestamp: t, stable: true, confidence: 80 }); + breath.push({ value: Math.sin(this.breathPhase * Math.PI * 2), timestamp: t, stable: true }); + } + const tS = nowUs / 1e6; + if (tS > this.smileUntil + 25 && Math.sin(tS * 1.7 + this.seed) > 0.995) this.smileUntil = tS + 2.5; + const happy = tS < this.smileUntil ? 82 : 4; + this.emit('metrics', { + cardio: { + pulseRate: [{ value: bpm, confidence: 78, stable: true, timestamp: nowUs }], + arterialPressureTrace: trace, + }, + breathing: { + rate: [{ value: 14, confidence: 70, stable: true, timestamp: nowUs }], + upperTrace: breath, + }, + face: { expression: [{ stable: true, timestamp: nowUs, scores: [{ type: 5, confidence: happy }, { type: 6, confidence: 100 - happy }] }] }, + }, nowUs); + } +} + +// A rough pulse-wave shape: quick rise, slow fall, a small notch. +function ppg(p) { + if (p < 0.15) return Math.sin((p / 0.15) * (Math.PI / 2)); + const d = (p - 0.15) / 0.85; + return Math.exp(-3.2 * d) + 0.12 * Math.exp(-((d - 0.28) ** 2) / 0.004) - 0.05; +} diff --git a/src/shared/summary.js b/src/shared/summary.js new file mode 100644 index 0000000..142f576 --- /dev/null +++ b/src/shared/summary.js @@ -0,0 +1,98 @@ +// summary.js +// The closing card a reader sees: how long the letter took, where the +// writer's heart was quickest and steadiest, and how often they smiled. +// Wellness wording only: these are camera estimates for feeling, not medicine. + +import { bpmAt, finalChars } from './playback.js'; + +export function median(xs) { + const v = xs.filter((x) => x > 0).sort((a, b) => a - b); + if (!v.length) return 0; + const m = Math.floor(v.length / 2); + return v.length % 2 ? v[m] : Math.round((v[m - 1] + v[m]) / 2); +} + +function percentile(xs, p) { + const v = xs.filter((x) => x > 0).sort((a, b) => a - b); + if (!v.length) return 0; + return v[Math.min(v.length - 1, Math.max(0, Math.round((p / 100) * (v.length - 1))))]; +} + +/** Split text into sentences with their start/end indices. */ +export function sentences(text) { + const out = []; + const re = /[^.!?\n]+[.!?]*["”’)]*|\n+/g; + let m; + while ((m = re.exec(text))) { + const raw = m[0]; + const lead = raw.length - raw.trimStart().length; + const s = raw.trim(); + if (!s) continue; + out.push({ text: s, start: m.index + lead, end: m.index + lead + s.length }); + } + return out; +} + +export function summarize(letter) { + const chars = finalChars(letter); + const text = chars.map((c) => c.ch).join(''); + const baseline = median(letter.vit.bpm); + const scored = []; + for (const s of sentences(text)) { + if (s.text.replace(/\W/g, '').length < 12) continue; // too short to mean much + const bs = []; + for (let i = s.start; i < s.end; i++) { + const b = bpmAt(letter, chars[i].t); + if (b > 0) bs.push(b); + } + if (bs.length < 6) continue; + scored.push({ text: s.text, bpm: Math.round(bs.reduce((a, b) => a + b, 0) / bs.length) }); + } + let quickest = null; + let steadiest = null; + for (const s of scored) { + if (!quickest || s.bpm > quickest.bpm) quickest = s; + if (!steadiest || s.bpm < steadiest.bpm) steadiest = s; + } + // Only call out a difference that is actually there. + if (quickest && steadiest && quickest.bpm - steadiest.bpm < 4) { quickest = null; steadiest = null; } + if (quickest && quickest === steadiest) steadiest = null; + + let smiles = 0; + const sm = letter.vit.sm; + for (let i = 0; i < sm.length; i++) { + if (sm[i] >= 6 && (i === 0 || sm[i - 1] < 6)) smiles++; + } + + const ops = letter.ops; + const writtenMs = ops.length ? ops[ops.length - 1][0] : 0; + return { + words: (text.match(/\S+/g) || []).length, + writtenMs, + baseline, + low: percentile(letter.vit.bpm, 5), + high: percentile(letter.vit.bpm, 95), + quickest, + steadiest, + smiles: letter.share.smiles ? smiles : null, + tookBack: letter.share.edits ? ops.reduce((n, op) => n + op[2], 0) : null, + }; +} + +export function formatDuration(ms) { + const s = Math.round(ms / 1000); + if (s < 60) return `${s} second${s === 1 ? '' : 's'}`; + const m = Math.floor(s / 60); + const r = s % 60; + if (m < 60) return r ? `${m} min ${r} s` : `${m} min`; + const h = Math.floor(m / 60); + return `${h} h ${m % 60} min`; +} + +/** Short excerpt for quoting a sentence on the closing card. */ +export function excerpt(s, max = 64) { + if (s.length <= max) return s; + const cut = s.slice(0, max); + const sp = cut.lastIndexOf(' '); + return `${cut.slice(0, sp > max * 0.6 ? sp : max).trimEnd()}…`; +} diff --git a/src/shared/vitals.js b/src/shared/vitals.js new file mode 100644 index 0000000..85d645a --- /dev/null +++ b/src/shared/vitals.js @@ -0,0 +1,146 @@ +// vitals.js +// Turns SmartSpectra `metrics` packets into the few live signals Heartwritten +// uses. Each packet from the SDK is a windowed slice (only what is new since +// the last packet), so this keeps its own small rolling state. +// +// Signals used: +// cardio.pulseRate[] -> heart rate, only when `stable` +// cardio.arterialPressureTrace[] -> the pulse wave (the seal, the live ink line) +// breathing.upperTrace[] -> the breathing wave (the page breathes with it) +// breathing.rate[] -> breaths per minute (shown live) +// face.expression[] -> HAPPY confidence (a smile in the margin) + +export const HAPPY = 5; // presage.smartspectra.ExpressionType.HAPPY +const PULSE_STALE_MS = 6000; // forget a heart rate this old +const BREATH_WINDOW_S = 20; + +export function tsToUs(ts) { + if (ts == null) return 0; + if (typeof ts === 'number') return ts; + if (typeof ts === 'bigint') return Number(ts); + if (typeof ts.toNumber === 'function') return ts.toNumber(); + return Number(ts); +} + +export class VitalsTracker { + constructor() { this.reset(); } + + reset() { + this.bpm = null; // latest stable heart rate + this.bpmAtUs = 0; + this.breathRate = null; + this.breathTrace = []; // [{t, v}] last BREATH_WINDOW_S seconds + this.pulseTrace = []; // [{t, v}] last 10 seconds + this.smile = 0; // 0..1 + this.lastUs = 0; + this.packets = 0; + } + + /** Feed one decoded Metrics message. Returns the list of new pulse-wave values. */ + ingest(m) { + this.packets++; + const newWave = []; + const cardio = m && m.cardio; + const breathing = m && m.breathing; + const face = m && m.face; + + for (const s of (cardio && cardio.pulseRate) || []) { + const t = tsToUs(s.timestamp); + this.lastUs = Math.max(this.lastUs, t); + if (s.stable && Number.isFinite(s.value) && s.value > 25 && s.value < 230) { + this.bpm = s.value; + this.bpmAtUs = t; + } + } + for (const s of (cardio && cardio.arterialPressureTrace) || []) { + if (!Number.isFinite(s.value)) continue; + const t = tsToUs(s.timestamp); + this.lastUs = Math.max(this.lastUs, t); + this.pulseTrace.push({ t, v: s.value }); + newWave.push(s); + } + for (const s of (breathing && breathing.upperTrace) || []) { + if (!Number.isFinite(s.value)) continue; + const t = tsToUs(s.timestamp); + this.lastUs = Math.max(this.lastUs, t); + this.breathTrace.push({ t, v: s.value }); + } + for (const s of (breathing && breathing.rate) || []) { + if (s.stable && Number.isFinite(s.value)) this.breathRate = s.value; + } + const expr = face && face.expression; + if (expr && expr.length) { + const latest = expr[expr.length - 1]; + const happy = (latest.scores || []).find((x) => x.type === HAPPY); + this.smile = happy ? clamp01((happy.confidence || 0) / 100) : 0; + } + + trimOlderThan(this.pulseTrace, this.lastUs - 10e6); + trimOlderThan(this.breathTrace, this.lastUs - BREATH_WINDOW_S * 1e6); + if (this.bpm != null && this.lastUs - this.bpmAtUs > PULSE_STALE_MS * 1000) this.bpm = null; + return resample(newWave, 30); + } + + /** Where the latest breath sits within the recent range, -1 (out) .. 1 (in). */ + breathPhase() { + const tr = this.breathTrace; + if (tr.length < 8) return null; + let lo = Infinity; let hi = -Infinity; + for (const { v } of tr) { if (v < lo) lo = v; if (v > hi) hi = v; } + if (hi - lo < 1e-9) return 0; + return ((tr[tr.length - 1].v - lo) / (hi - lo)) * 2 - 1; + } + + /** The live signals the recorder samples. */ + snapshot() { + return { bpm: this.bpm, breath: this.breathPhase(), smile: this.smile }; + } +} + +/** Resample timestamped samples ({timestamp, value}) to `hz`, linear. */ +export function resample(samples, hz) { + if (samples.length < 2) return samples.map((s) => s.value); + const pts = samples.map((s) => ({ t: tsToUs(s.timestamp), v: s.value })).sort((a, b) => a.t - b.t); + const step = 1e6 / hz; + const out = []; + let j = 0; + for (let t = pts[0].t; t <= pts[pts.length - 1].t; t += step) { + while (j < pts.length - 2 && pts[j + 1].t < t) j++; + const a = pts[j]; const b = pts[j + 1]; + const f = b.t === a.t ? 0 : (t - a.t) / (b.t - a.t); + out.push(a.v + (b.v - a.v) * Math.max(0, Math.min(1, f))); + } + return out; +} + +/** Plain-language hints for the SDK's validation codes. */ +export const HINTS = { + 0: 'Reading you clearly', + 1: 'I can’t see your face yet', + 2: 'Just one face, please', + 3: 'Slide a little to the centre', + 4: 'Move a little closer or further', + 5: 'A little more light, please', + 6: 'Too bright, ease the light', + 7: 'Sit back so your shoulders show', + 10: 'Tuning the camera…', + 11: 'The camera is running slowly', + 12: 'Keep your head still while you think', + 13: 'Lean back a little', + 14: 'Lean in a little', + 15: 'Lower the camera, or sit taller', + 16: 'Raise the camera a little', + 17: 'Look toward the screen', +}; + +export function hintFor(code, fallback) { + return HINTS[code] || fallback || 'Settling in…'; +} + +function clamp01(x) { return Math.max(0, Math.min(1, x)); } + +function trimOlderThan(arr, tMin) { + let k = 0; + while (k < arr.length && arr[k].t < tMin) k++; + if (k) arr.splice(0, k); +} diff --git a/test/core.test.js b/test/core.test.js new file mode 100644 index 0000000..a34bf3a --- /dev/null +++ b/test/core.test.js @@ -0,0 +1,254 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { + encodeLetter, decodeLetter, pack, unpack, validate, finalText, extractToken, buildLink, +} from '../src/shared/letter-format.js'; +import { diffText, LetterRecorder, opsFromCharTimes, normalizeWave, VITALS_HZ } from '../src/shared/recorder.js'; +import { VitalsTracker, resample, hintFor } from '../src/shared/vitals.js'; +import { Player, buildTimeline, bpmAt, inkFor, finalChars } from '../src/shared/playback.js'; +import { summarize, sentences, median, formatDuration, excerpt } from '../src/shared/summary.js'; +import { sealSvg } from '../src/shared/seal.js'; +import { SimulatedSource } from '../src/shared/sim-source.js'; + +// A fake clock the recorder can read. +function clock() { + let t = 1_000_000; + const now = () => t; + now.tick = (ms) => { t += ms; }; + return now; +} + +// Types `s` into the recorder one char at a time, `gap` ms apart. +function type(rec, now, s, gap = 120) { + for (const ch of s) { now.tick(gap); rec.edit(rec.text + ch); } +} + +function backspace(rec, now, n, gap = 90) { + for (let i = 0; i < n; i++) { now.tick(gap); rec.edit(rec.text.slice(0, -1)); } +} + +function sampleLetter({ edits = true, smiles = true } = {}) { + const now = clock(); + const rec = new LetterRecorder({ now }); + let bpm = 64; + const feed = () => rec.sample({ bpm, breath: Math.sin(now() / 700), smile: bpm > 80 ? 0.9 : 0.1 }); + for (const ch of 'Dear Deola, I have news. ') { now.tick(150); rec.edit(rec.text + ch); feed(); } + bpm = 88; + for (const ch of 'I got the job I told you about!') { now.tick(130); rec.edit(rec.text + ch); feed(); } + backspace(rec, now, 1); feed(); + rec.edit(`${rec.text}.`); feed(); + now.tick(12000); feed(); // a long pause + bpm = 62; + for (const ch of ' Thank you for believing in me when I did not.') { now.tick(160); rec.edit(rec.text + ch); feed(); } + rec.pushWave(Array.from({ length: 300 }, (_, i) => Math.sin(i / 4))); + return rec.finish({ from: 'Subomi', to: 'Deola', day: '2026-11-12', share: { edits, smiles } }); +} + +test('diffText finds the smallest edit', () => { + assert.deepEqual(diffText('', 'a'), { pos: 0, del: 0, ins: 'a' }); + assert.deepEqual(diffText('abc', 'abXc'), { pos: 2, del: 0, ins: 'X' }); + assert.deepEqual(diffText('hello world', 'hello'), { pos: 5, del: 6, ins: '' }); + assert.deepEqual(diffText('I love it', 'I adore it'), { pos: 2, del: 3, ins: 'ador' }); + assert.equal(diffText('same', 'same'), null); +}); + +test('recorder replays to the exact final text, with and without edits', () => { + for (const edits of [true, false]) { + const letter = sampleLetter({ edits }); + const expected = 'Dear Deola, I have news. I got the job I told you about. Thank you for believing in me when I did not.'; + assert.equal(finalText(letter), expected); + assert.equal(finalChars(letter).map((c) => c.ch).join(''), expected); + validate(letter); + } +}); + +test('with edits off, nothing deleted survives in the letter', () => { + const now = clock(); + const rec = new LetterRecorder({ now }); + type(rec, now, 'I miss you'); + backspace(rec, now, 8); + type(rec, now, 'am fine'); + const hidden = rec.finish({ share: { edits: false, smiles: true } }); + const json = JSON.stringify(pack(hidden)); + assert.ok(!json.includes('miss'), 'deleted words must not be in the payload'); + assert.ok(hidden.ops.every((op) => op[2] === 0), 'no deletions'); + assert.equal(finalText(hidden), 'I am fine'); + const shown = rec.finish({ share: { edits: true, smiles: true } }); + const p = new Player(shown); + let sawIt = false; + for (let at = 0; !p.done; at += 40) { p.advance(at); if (p.text().includes('I miss you')) sawIt = true; } + assert.ok(sawIt, 'with edits on, the reader sees the words that were taken back'); +}); + +test('opsFromCharTimes keeps typing order for edits made mid-text', () => { + // "ac" typed first, then "b" inserted between them later. + const ops = opsFromCharTimes('abc', [0, 500, 10]); + const letter = { ops, vit: { hz: 1, bpm: [], br: [], sm: [] }, wave: { hz: 25, v: [] }, share: {} }; + assert.equal(finalText(letter), 'abc'); + assert.deepEqual(ops.map((o) => o[0]), [0, 10, 500]); +}); + +test('smiles off means no smile samples are kept', () => { + const letter = sampleLetter({ smiles: false }); + assert.ok(letter.vit.sm.every((x) => x === 0)); + const packed = pack(letter); + assert.equal(packed.m, undefined); +}); + +test('pack/unpack and link encoding round-trip', async () => { + const letter = sampleLetter(); + assert.deepEqual(unpack(pack(letter)), letter); + const token = await encodeLetter(letter); + assert.match(token, /^v1\.[A-Za-z0-9_-]+$/); + const link = buildLink('https://example.test/read/', token); + const back = await decodeLetter(link); + assert.deepEqual(back, letter); + assert.equal(extractToken(`https://x.test/#${token}`), token); + assert.equal(extractToken('https://x.test/#nothing'), null); +}); + +test('a long letter still fits in a reasonable link', async () => { + const now = clock(); + const rec = new LetterRecorder({ now }); + const para = 'It has been a strange and lovely year, and I keep wanting to tell you about the small things. '; + for (let i = 0; i < 16; i++) { // ~1,500 characters over ~4 minutes + for (const ch of para) { now.tick(160); rec.edit(rec.text + ch); rec.sample({ bpm: 70 + (i % 5), breath: 0.2, smile: 0 }); } + } + rec.pushWave(Array.from({ length: 300 }, (_, i) => Math.sin(i / 4))); + const token = await encodeLetter(rec.finish({ share: { edits: true, smiles: true } })); + assert.ok(token.length < 12000, `token is ${token.length} chars`); +}); + +test('decoder rejects tampered or hostile letters', async () => { + const bad = [ + { ...pack(sampleLetter()), v: 9 }, + { ...pack(sampleLetter()), o: [[0, 5, 0, 'x']] }, // insert past the end + { ...pack(sampleLetter()), o: [[0, 0, 3, '']] }, // delete what isn't there + { ...pack(sampleLetter()), vh: 999 }, + ]; + for (const p of bad) assert.throws(() => unpack(p)); + await assert.rejects(decodeLetter('v1.!!!')); + await assert.rejects(decodeLetter('no letter here')); +}); + +test('vitals tracker reads SDK-shaped packets', () => { + const v = new VitalsTracker(); + v.ingest({ cardio: { pulseRate: [{ value: 72, stable: false, timestamp: 1e6 }] } }); + assert.equal(v.bpm, null, 'unstable readings are ignored'); + const wave = v.ingest({ + cardio: { + pulseRate: [{ value: 71.6, stable: true, confidence: 60, timestamp: { toNumber: () => 2e6 } }], + arterialPressureTrace: Array.from({ length: 30 }, (_, i) => ({ value: Math.sin(i), timestamp: 2e6 + i * 33333 })), + }, + breathing: { rate: [{ value: 13, stable: true }], upperTrace: Array.from({ length: 20 }, (_, i) => ({ value: i, timestamp: 2e6 + i * 50000 })) }, + face: { expression: [{ scores: [{ type: 5, confidence: 90 }, { type: 6, confidence: 10 }] }] }, + }); + assert.equal(v.bpm, 71.6); + assert.equal(v.breathRate, 13); + assert.ok(wave.length >= 28 && wave.length <= 31); + const snap = v.snapshot(); + assert.equal(snap.smile, 0.9); + assert.equal(snap.breath, 1, 'latest breath sample is the top of the range'); + // Heart rate goes stale when no fresh stable value arrives. + v.ingest({ cardio: { arterialPressureTrace: [{ value: 0, timestamp: 9e6 }] } }); + assert.equal(v.bpm, null); +}); + +test('resample produces evenly spaced values', () => { + const s = [{ value: 0, timestamp: 0 }, { value: 10, timestamp: 1e6 }]; + const r = resample(s, 10); + assert.equal(r.length, 11); + assert.equal(r[5], 5); +}); + +test('hints read like a person talking', () => { + assert.equal(hintFor(5), 'A little more light, please'); + assert.equal(hintFor(999, 'SDK hint'), 'SDK hint'); +}); + +test('timeline shortens long pauses and remembers them', () => { + const letter = sampleLetter(); + const tl = buildTimeline(letter); + assert.ok(tl.pauses.length >= 1, 'the 12 s pause is noted'); + assert.ok(tl.pauses[0].ms >= 12000); + assert.ok(tl.duration < tl.writtenMs, 'replay is shorter than the writing'); + for (let i = 1; i < tl.ops.length; i++) assert.ok(tl.ops[i].at >= tl.ops[i - 1].at); +}); + +test('player shows the writer taking a word back', () => { + const letter = sampleLetter({ edits: true }); + const p = new Player(letter); + let sawBang = false; + for (let at = 0; !p.done; at += 50) { + p.advance(at); + if (p.text().endsWith('about!')) sawBang = true; + } + assert.ok(sawBang, 'the exclamation mark appears before it is replaced'); + assert.equal(p.tookBack, 1); + assert.equal(p.text(), finalText(letter)); +}); + +test('ink warms with a quicker heart and stays calm otherwise', () => { + assert.equal(inkFor(66, 66), 'rgb(31, 41, 66)'); + assert.equal(inkFor(0, 66), 'rgb(31, 41, 66)'); + const warm = inkFor(90, 66).match(/\d+/g).map(Number); + assert.ok(warm[0] > 150 && warm[2] < 50); +}); + +test('summary finds the quickest and steadiest sentences', () => { + const s = summarize(sampleLetter()); + assert.match(s.quickest.text, /got the job/); + assert.match(s.steadiest.text, /believing in me/); + assert.ok(s.quickest.bpm > s.steadiest.bpm); + assert.equal(s.tookBack, 1); + assert.ok(s.smiles >= 1); + assert.ok(s.words > 15); + assert.equal(median([0, 60, 70, 80]), 70); + assert.equal(formatDuration(75_000), '1 min 15 s'); + assert.equal(excerpt('a '.repeat(80)).endsWith('…'), true); +}); + +test('summary says nothing about the heart when it barely moved', () => { + const now = clock(); + const rec = new LetterRecorder({ now }); + for (const ch of 'One calm sentence here. And another calm sentence.') { now.tick(150); rec.edit(rec.text + ch); rec.sample({ bpm: 70, breath: 0, smile: 0 }); } + const s = summarize(rec.finish({})); + assert.equal(s.quickest, null); + assert.equal(s.steadiest, null); +}); + +test('sentences splits on punctuation and new lines', () => { + assert.deepEqual(sentences('Hi there. How are you?\nGood!').map((s) => s.text), ['Hi there.', 'How are you?', 'Good!']); +}); + +test('bpmAt looks past gaps in the signal', () => { + const letter = { vit: { hz: VITALS_HZ, bpm: [0, 0, 70, 0, 0], br: [], sm: [] } }; + assert.equal(bpmAt(letter, 0), 70); + assert.equal(bpmAt(letter, 1000), 70); +}); + +test('seal is deterministic, unique per pulse and safe to inline', () => { + const a = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 5))), { initial: 'S', bpm: 68 }); + const b = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 5))), { initial: 'S', bpm: 68 }); + const c = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 3))), { initial: 'S', bpm: 68 }); + assert.equal(a, b); + assert.notEqual(a, c); + assert.match(a, /^$/); + assert.match(a, /68 BPM/); + const evil = sealSvg([], { initial: '`)); +await writeFile(new URL('../dist/sample-token.txt', import.meta.url), token); +console.log(`sample letter: ${rec.text.length} chars, written over ${(t / 60000).toFixed(1)} min, token ${token.length} chars`); diff --git a/scripts/sdk-smoke.mjs b/scripts/sdk-smoke.mjs new file mode 100644 index 0000000..7e05114 --- /dev/null +++ b/scripts/sdk-smoke.mjs @@ -0,0 +1,49 @@ +// sdk-smoke.mjs +// Headless check that the SmartSpectra SDK loads and that Heartwritten reads +// its packets. With a key and a short face video it runs a real measurement: +// +// SMARTSPECTRA_API_KEY=... npm run smoke -- path/to/face-clip.mp4 +// +// Without a key it only checks that the native runtime loads. + +import { createRequire } from 'node:module'; +import { VitalsTracker } from '../src/shared/vitals.js'; + +const require = createRequire(import.meta.url); +const ss = require('@smartspectra/node-sdk'); +const { decodeMetrics } = require('@smartspectra/node-sdk/messages'); + +console.log(`SmartSpectra SDK ${ss.SmartSpectraSDK.version} loaded on ${process.platform}-${process.arch}`); +try { + const cams = ss.SmartSpectraSDK.availableCameras(); + console.log(`Cameras found: ${cams.length}`); +} catch (e) { + console.log(`Camera discovery unavailable here (${e.message})`); +} + +const key = process.env.SMARTSPECTRA_API_KEY; +const clip = process.argv[2]; +if (!key || !clip) { + console.log('No key or clip given: load check passed. Pass both to run a real measurement.'); + process.exit(0); +} + +const metrics = [...ss.breathingMetrics, ...ss.cardioMetrics, ss.MetricType.EXPRESSIONS]; +const sdk = new ss.SmartSpectraSDK({ apiKey: key, requestedMetrics: metrics, enableTelemetry: false }); +const vitals = new VitalsTracker(); +let packets = 0; +sdk.on('metrics', (buf) => { packets++; vitals.ingest(decodeMetrics(buf)); }); +sdk.on('validationStatus', (code, _ts, hint) => { if (code !== 0) console.log(`validation ${code} ${hint || ''}`); }); +sdk.on('error', (code, msg) => console.error(`SDK error ${code}: ${msg}`)); +sdk.useFile(clip, { interframeDelayMs: 33 }); +sdk.start(); +sdk.waitUntilComplete(180000); +await sdk.destroy(); + +const snap = vitals.snapshot(); +console.log(`packets=${packets} bpm=${snap.bpm?.toFixed(1) ?? '—'} breathsPerMin=${vitals.breathRate ?? '—'} pulseSamples=${vitals.pulseTrace.length} smile=${snap.smile}`); +if (!packets || !vitals.pulseTrace.length) { + console.error('FAIL: no pulse data came back'); + process.exit(1); +} +console.log('PASS'); diff --git a/src/reader/index.html b/src/reader/index.html new file mode 100644 index 0000000..1f1f68f --- /dev/null +++ b/src/reader/index.html @@ -0,0 +1,72 @@ + + + + + + + +Heartwritten + + + + +
+
+

Heartwritten

+

Letters that carry the heartbeat they were written with. Open one from the link you were sent.

+
+ +
+
+

+

+

+ +

Tap the seal to open it.

+ +
+

This letter lives only in its link. Opening it sends nothing anywhere.

+
+ +
+
+ +
+

+

+
+

+ +
+
+ + +
+
+ + + + diff --git a/src/reader/reader.css b/src/reader/reader.css new file mode 100644 index 0000000..f2a4d9a --- /dev/null +++ b/src/reader/reader.css @@ -0,0 +1,152 @@ +:root { + --paper: #fbf6ec; + --paper-edge: #efe5d2; + --desk: #e9dfcc; + --ink: #1f2942; + --muted: #6d6556; + --wax: #a3232a; + --glow: rgba(232, 176, 60, 0.32); + --serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif; + --hand: "Snell Roundhand", "Segoe Script", "Bradley Hand", "Apple Chancery", cursive; + color-scheme: light dark; +} +@media (prefers-color-scheme: dark) { + :root { --desk: #1c1a17; --muted: #a49a88; } +} +* { box-sizing: border-box; } +html, body { margin: 0; min-height: 100%; } +body { + background: radial-gradient(120% 90% at 50% 0%, color-mix(in srgb, var(--desk) 70%, #fff 30%), var(--desk)); + color: var(--ink); + font: 18px/1.65 var(--serif); + -webkit-font-smoothing: antialiased; + min-height: 100vh; +} +main { max-width: 860px; margin: 0 auto; padding: 48px 16px 64px; } +button { font: inherit; cursor: pointer; } + +.view { display: none; } +body[data-view="empty"] .view-empty, +body[data-view="envelope"] .view-envelope, +body[data-view="breaking"] .view-envelope, +body[data-view="letter"] .view-letter { display: block; } + +.wordmark { font-style: italic; font-weight: 400; font-size: 44px; margin: 18vh 0 8px; text-align: center; } +.view-empty p { text-align: center; color: var(--muted); max-width: 34em; margin: 0 auto; } + +/* Envelope */ +.envelope { + margin: 8vh auto 0; max-width: 520px; padding: 48px 32px 40px; text-align: center; + background: linear-gradient(160deg, var(--paper), var(--paper-edge)); + border-radius: 6px; box-shadow: 0 1px 0 #fff inset, 0 30px 60px -30px rgba(40, 25, 5, 0.45), 0 2px 6px rgba(40, 25, 5, 0.12); + position: relative; color: #1f2942; +} +.envelope::before { /* the flap */ + content: ""; position: absolute; inset: 0 0 auto 0; height: 46%; + background: linear-gradient(to bottom right, transparent 49.5%, rgba(120, 90, 40, 0.10) 50%, transparent 50.5%), + linear-gradient(to bottom left, transparent 49.5%, rgba(120, 90, 40, 0.10) 50%, transparent 50.5%); + pointer-events: none; +} +.eyebrow { font-size: 13px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin: 0 0 8px; } +.envelope .eyebrow { color: #7d7262; } +.to { font-weight: 400; font-style: italic; font-size: 38px; margin: 0; } +.from { margin: 4px 0 26px; color: #6d6556; } +.seal-button { background: none; border: 0; padding: 0; border-radius: 50%; display: inline-block; } +.seal-button:focus-visible { outline: 3px solid #c99a3b; outline-offset: 6px; } +.seal { display: block; width: 168px; height: 168px; animation: heartbeat var(--beat, 0.9s) ease-in-out infinite; transform-origin: 50% 52%; } +.seal svg { width: 100%; height: 100%; } +.hint { color: #7d7262; font-size: 15px; margin: 14px 0 0; } +.fine { color: var(--muted); font-size: 13px; text-align: center; margin-top: 28px; } +.badge { display: inline-block; margin: 16px auto 0; font-size: 12px; letter-spacing: 0.04em; padding: 4px 10px; border-radius: 99px; background: #f1e0b6; color: #5b4310; } +@keyframes heartbeat { + 0%, 100% { transform: scale(1); } + 12% { transform: scale(1.045); } + 24% { transform: scale(0.995); } + 36% { transform: scale(1.025); } + 50% { transform: scale(1); } +} +body[data-view="breaking"] .seal { animation: crack 0.9s cubic-bezier(.5,0,.2,1) forwards; } +body[data-view="breaking"] .envelope { animation: lift 0.9s ease forwards; } +@keyframes crack { + 0% { transform: scale(1) rotate(0); filter: none; } + 30% { transform: scale(1.08) rotate(-4deg); } + 100% { transform: scale(0.6) rotate(18deg) translateY(40px); opacity: 0; filter: blur(2px); } +} +@keyframes lift { to { transform: translateY(-12px); opacity: 0; } } + +/* Letter */ +.desk { display: grid; grid-template-columns: 92px 1fr; gap: 20px; align-items: start; } +.margin { position: sticky; top: 32px; text-align: center; color: var(--muted); font-size: 14px; } +.heart { color: var(--ink); display: inline-block; transition: color 1.2s ease; transform-origin: 50% 60%; } +.heart.beat { animation: thump 0.42s ease-out; } +@keyframes thump { 0% { transform: scale(1); } 18% { transform: scale(1.28); } 38% { transform: scale(0.96); } 60% { transform: scale(1.1); } 100% { transform: scale(1); } } +.bpm { margin: 2px 0 18px; font-variant-numeric: tabular-nums; } +.bpm span { font-size: 22px; color: var(--ink); display: block; line-height: 1.1; } +@media (prefers-color-scheme: dark) { .bpm span { color: #eadfca; } } +.bpm small { letter-spacing: 0.12em; text-transform: uppercase; font-size: 11px; } +.pauses { list-style: none; padding: 0; margin: 0; font-style: italic; font-size: 13px; line-height: 1.4; } +.pauses li { margin-bottom: 8px; animation: fadein 1.2s ease; } +.took-back { font-style: italic; font-size: 13px; line-height: 1.4; } +@keyframes fadein { from { opacity: 0; transform: translateY(4px); } } + +.paper { + --breath: 0; + background: linear-gradient(170deg, var(--paper), var(--paper-edge)); + color: #1f2942; + padding: 44px 48px 40px; border-radius: 4px; min-height: 60vh; + box-shadow: 0 1px 0 #fff inset, 0 calc(26px + var(--breath) * 6px) calc(56px + var(--breath) * 10px) -30px rgba(40, 25, 5, 0.42), 0 2px 6px rgba(40, 25, 5, 0.1); + transform: translateY(calc(var(--breath) * -2px)) scale(calc(1 + var(--breath) * 0.004)); + transition: transform 0.25s linear, box-shadow 0.25s linear; + animation: unfold 0.9s cubic-bezier(.2,.7,.2,1); +} +@keyframes unfold { from { transform: translateY(24px) scaleY(0.92); opacity: 0; } } +.salutation { font-style: italic; font-size: 22px; margin: 0 0 14px; } +.body-text { font-size: 20px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; min-height: 3em; } +.body-text span { transition: color 0.6s ease; } +.body-text .smiled { background: linear-gradient(transparent 62%, var(--glow) 62%, var(--glow) 92%, transparent 92%); border-radius: 2px; } +.caret { display: inline-block; width: 2px; height: 1.1em; background: #1f2942; vertical-align: -0.18em; margin-left: 1px; animation: blink 1.1s steps(1) infinite; } +.finished .caret { display: none; } +@keyframes blink { 50% { opacity: 0; } } +.signature { font-family: var(--hand); font-size: 30px; margin: 24px 0 0; text-align: right; min-height: 1.2em; } + +.controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin: 22px 0 0 112px; } +.controls button, .summary-actions button { + background: transparent; border: 1px solid color-mix(in srgb, var(--muted) 45%, transparent); color: var(--muted); + border-radius: 99px; padding: 6px 14px; font-size: 14px; +} +.controls button[aria-pressed="true"] { background: var(--ink); color: var(--paper); border-color: var(--ink); } +@media (prefers-color-scheme: dark) { .controls button[aria-pressed="true"] { background: #eadfca; color: #1c1a17; border-color: #eadfca; } } +.controls button:focus-visible, .summary-actions button:focus-visible { outline: 2px solid #c99a3b; outline-offset: 2px; } +.finished .controls { display: none; } + +.summary { margin: 28px 0 0 112px; padding: 28px 32px; border-radius: 6px; background: color-mix(in srgb, var(--paper) 70%, transparent); color: #1f2942; animation: fadein 1s ease; } +.summary h2 { font-weight: 400; font-style: italic; font-size: 24px; margin: 0 0 10px; } +.summary p { margin: 8px 0; } +.summary .sum-lead { color: #6d6556; } +.summary .q span { color: #7d7262; font-size: 14px; white-space: nowrap; margin-left: 6px; } +.summary q { font-style: italic; } +.legend { font-size: 13px; color: #7d7262; display: flex; gap: 14px; flex-wrap: wrap; } +.ink::before { content: ""; display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 6px; vertical-align: -1px; } +.ink.calm::before { background: rgb(31, 41, 66); } +.ink.warm::before { background: rgb(168, 38, 44); } +.ink.glow::before { background: rgba(232, 176, 60, 0.6); } +.summary-actions { display: flex; gap: 8px; margin-top: 16px; } +.summary-actions button { color: #6d6556; } +.summary .fine { text-align: left; margin-top: 18px; color: #7d7262; } + +@media (max-width: 640px) { + main { padding: 24px 16px 48px; } + .desk { grid-template-columns: 1fr; } + .margin { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 10px; justify-content: flex-start; padding: 8px 0; background: var(--desk); } + .bpm { margin: 0; display: flex; gap: 4px; align-items: baseline; } + .bpm span { display: inline; } + .pauses, .took-back { display: none; } + .paper { padding: 28px 22px; } + .body-text { font-size: 18px; } + .controls, .summary { margin-left: 0; } + .to { font-size: 30px; } +} +@media (prefers-reduced-motion: reduce) { + .seal, .heart.beat, .paper { animation: none !important; } + .paper { transform: none; transition: none; } +} diff --git a/src/reader/reader.js b/src/reader/reader.js new file mode 100644 index 0000000..d5c4906 --- /dev/null +++ b/src/reader/reader.js @@ -0,0 +1,218 @@ +// reader.js +// The page a letter opens in. It reads the letter from the link's #fragment +// (or from the file it was saved into), never from a server, and replays it. + +import { decodeLetter, extractToken, finalText } from '../shared/letter-format.js'; +import { Player, bpmAt, inkFor, sampleAt } from '../shared/playback.js'; +import { summarize, median, formatDuration, excerpt } from '../shared/summary.js'; +import { sealSvg } from '../shared/seal.js'; + +const $ = (id) => document.getElementById(id); + +function embeddedToken() { + const el = document.getElementById('letter-data'); + return el ? extractToken(el.textContent.trim()) : null; +} + +function esc(s) { + return String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); +} + +function dayLabel(day) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(day || '')) return ''; + const d = new Date(`${day}T12:00:00`); + return d.toLocaleDateString(undefined, { day: 'numeric', month: 'long', year: 'numeric' }); +} + +export async function boot() { + const token = extractToken(location.hash) || embeddedToken(); + if (!token) return showEmpty(); + let letter; + try { + letter = await decodeLetter(token); + } catch (e) { + return showEmpty('This link doesn’t hold a whole letter. It may have been cut short when it was shared.'); + } + showEnvelope(letter); +} + +function showEmpty(message) { + document.body.dataset.view = 'empty'; + if (message) $('empty-text').textContent = message; +} + +// --------------------------------------------------------------------------- +// The envelope + +function showEnvelope(letter) { + document.body.dataset.view = 'envelope'; + const base = median(letter.vit.bpm); + const initial = (letter.from || '').trim().charAt(0); + $('seal').innerHTML = sealSvg(letter.wave.v, { initial, bpm: base }); + const to = letter.to ? `For ${esc(letter.to)}` : 'A letter for you'; + const from = letter.from ? `sealed with ${esc(letter.from)}’s heartbeat` : 'sealed with a heartbeat'; + $('envelope-to').innerHTML = to; + $('envelope-from').innerHTML = from; + $('envelope-day').textContent = dayLabel(letter.day); + $('sim-badge').hidden = !letter.sim; + if (base > 0) $('seal').style.setProperty('--beat', `${(60 / base).toFixed(3)}s`); + const open = () => openLetter(letter); + $('seal-button').addEventListener('click', open, { once: true }); +} + +// --------------------------------------------------------------------------- +// Replay + +const state = { speed: 1, sound: false, audio: null, raf: 0, player: null, startedAt: 0, at: 0, paused: false }; + +function openLetter(letter) { + document.body.dataset.view = 'breaking'; + setTimeout(() => startReplay(letter), 900); +} + +function startReplay(letter) { + document.body.dataset.view = 'letter'; + const player = new Player(letter); + state.player = player; + state.letter = letter; + state.baseline = median(letter.vit.bpm); + state.pauses = player.timeline.pauses; + state.at = 0; + state.last = performance.now(); + state.nextBeat = 0; + $('salutation').textContent = letter.to ? `To ${letter.to},` : ''; + $('signature').textContent = ''; + $('letter-day').textContent = dayLabel(letter.day); + $('replay-sim').hidden = !letter.sim; + render(true); + cancelAnimationFrame(state.raf); + state.raf = requestAnimationFrame(frame); +} + +function frame(now) { + const dt = Math.min(100, now - state.last); + state.last = now; + if (!state.paused) state.at += dt * state.speed; + const p = state.player; + const changed = p.advance(state.at); + if (changed) render(); + pulse(now); + if (p.done) return finish(); + state.raf = requestAnimationFrame(frame); +} + +// The heart in the margin beats at the writer's rate at this point in the +// letter; the page rises and falls with their breathing. +function pulse(now) { + const { letter } = state; + const t = state.player.writerTime + Math.max(0, state.at - lastOpAt()); + const bpm = bpmAt(letter, t); + const heart = $('heart'); + $('heart-bpm').textContent = bpm > 0 ? String(bpm) : '·'; + heart.style.color = inkFor(bpm, state.baseline); + if (bpm > 0 && now >= state.nextBeat) { + state.nextBeat = now + (60000 / bpm) / Math.max(1, state.speed * 0.6 + 0.4); + heart.classList.remove('beat'); + void heart.offsetWidth; + heart.classList.add('beat'); + if (state.sound) thump(); + } + const br = sampleAt(letter.vit.br, letter.vit.hz, t) / 100; + $('paper').style.setProperty('--breath', br.toFixed(3)); +} + +function lastOpAt() { + const { ops } = state.player.timeline; + const k = state.player.i - 1; + return k >= 0 ? ops[k].at : 0; +} + +function render() { + const { player, letter, baseline } = state; + const chars = player.chars; + let html = ''; + let i = 0; + const smileAt = (t) => letter.share.smiles && sampleAt(letter.vit.sm, letter.vit.hz, t) >= 6; + while (i < chars.length) { + const t = chars[i].t; + let j = i; + let run = ''; + while (j < chars.length && chars[j].t === t) { run += chars[j].ch; j++; } + const bpm = bpmAt(letter, t); + const cls = smileAt(t) ? ' class="smiled"' : ''; + run = esc(run).replace(/\n/g, '
'); + html += `${run}`; + i = j; + } + $('body-text').innerHTML = html + ''; + // Long pauses are noted in the margin, in order. + const notes = state.pauses.filter((pz) => pz.at <= state.at); + $('pauses').innerHTML = notes.map((pz) => `
  • paused ${formatDuration(pz.ms)}
  • `).join(''); + $('took-back').textContent = letter.share.edits && player.tookBack + ? `${player.tookBack} character${player.tookBack === 1 ? '' : 's'} taken back` + : ''; +} + +function finish() { + const { letter } = state; + render(); + $('signature').textContent = letter.from ? `— ${letter.from}` : ''; + document.body.classList.add('finished'); + const s = summarize(letter); + const rows = []; + rows.push(`

    Written in ${formatDuration(s.writtenMs)}, ${s.words} words.

    `); + if (s.low > 0 && s.high > 0) rows.push(`

    ${esc(letter.from || 'Their')}${letter.from ? '’s' : ''} heart ran between ${s.low} and ${s.high} beats a minute while writing.

    `); + if (s.quickest) rows.push(`

    Quickest at ${esc(excerpt(s.quickest.text))} ${s.quickest.bpm} bpm

    `); + if (s.steadiest) rows.push(`

    Steadiest at ${esc(excerpt(s.steadiest.text))} ${s.steadiest.bpm} bpm

    `); + if (s.smiles) rows.push(`

    ${letter.from ? esc(letter.from) : 'They'} smiled ${s.smiles === 1 ? 'once' : `${s.smiles} times`}; the words glow where.

    `); + if (s.tookBack) rows.push(`

    ${s.tookBack} characters were written and taken back.

    `); + $('summary-body').innerHTML = rows.join(''); + $('summary').hidden = false; + $('copy-text').onclick = async () => { + try { await navigator.clipboard.writeText(finalText(letter)); $('copy-text').textContent = 'Copied'; } catch { /* clipboard blocked */ } + }; +} + +// --------------------------------------------------------------------------- +// Controls + +function thump() { + if (!state.audio) state.audio = new AudioContext(); + const ctx = state.audio; + const o = ctx.createOscillator(); + const g = ctx.createGain(); + o.frequency.setValueAtTime(64, ctx.currentTime); + o.frequency.exponentialRampToValueAtTime(38, ctx.currentTime + 0.16); + g.gain.setValueAtTime(0.0001, ctx.currentTime); + g.gain.exponentialRampToValueAtTime(0.5, ctx.currentTime + 0.012); + g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.22); + o.connect(g).connect(ctx.destination); + o.start(); + o.stop(ctx.currentTime + 0.25); +} + +function wireControls() { + for (const b of document.querySelectorAll('[data-speed]')) { + b.addEventListener('click', () => { + state.speed = Number(b.dataset.speed); + for (const o of document.querySelectorAll('[data-speed]')) o.setAttribute('aria-pressed', String(o === b)); + }); + } + $('skip').addEventListener('click', () => { if (state.player) state.at = Infinity; }); + $('sound').addEventListener('click', () => { + state.sound = !state.sound; + $('sound').setAttribute('aria-pressed', String(state.sound)); + $('sound').textContent = state.sound ? 'Heartbeat sound on' : 'Hear the heartbeat'; + }); + $('replay').addEventListener('click', () => { + document.body.classList.remove('finished'); + $('summary').hidden = true; + startReplay(state.letter); + }); + window.addEventListener('hashchange', () => location.reload()); +} + +if (typeof document !== 'undefined' && !globalThis.__HW_NO_AUTOBOOT__) { + wireControls(); + boot(); +} diff --git a/src/writer/index.html b/src/writer/index.html new file mode 100644 index 0000000..0cf62b5 --- /dev/null +++ b/src/writer/index.html @@ -0,0 +1,93 @@ + + + + + +Heartwritten + + + +
    + + + + + +
    +
    +
    +
    + +
    + — bpm + — breaths/min + ◡ +
    +
    +
    +

    Settling in…

    + + +
    +
    + +
    + + + +
    + +
    + Nothing is recorded until you type. + + +
    +
    + + +
    +
    +
    +

    Sealed.

    +

    + + +
    + + + +
    +

    The camera is off. This letter isn’t saved anywhere on this computer; it exists in that link and any file you save. Closing this window forgets it.

    +
    +
    + +
    + + + diff --git a/src/writer/preload.cjs b/src/writer/preload.cjs new file mode 100644 index 0000000..4001726 --- /dev/null +++ b/src/writer/preload.cjs @@ -0,0 +1,14 @@ +// preload.cjs +// Bundled into dist/preload.cjs. It installs SmartSpectra's own bridge +// (window.__smartspectraBridge) and a tiny Heartwritten bridge. Nothing +// else from Node or Electron reaches the page. +'use strict'; + +require('@smartspectra/node-sdk/preload'); +const { contextBridge, ipcRenderer } = require('electron'); + +contextBridge.exposeInMainWorld('heartwritten', { + getConfig: () => ipcRenderer.invoke('hw:config'), + getApiKey: () => ipcRenderer.invoke('hw:api-key'), + openPreview: (token) => ipcRenderer.invoke('hw:preview', String(token)), +}); diff --git a/src/writer/sdk-source.js b/src/writer/sdk-source.js new file mode 100644 index 0000000..0cc9ac4 --- /dev/null +++ b/src/writer/sdk-source.js @@ -0,0 +1,77 @@ +// sdk-source.js +// The live camera source: SmartSpectra's Electron renderer SDK. It emits the +// same events as SimulatedSource, with each metrics packet already decoded. + +import { + SmartSpectraSDK, breathingMetrics, cardioMetrics, MetricType, SmartSpectraErrorCode, +} from '@smartspectra/node-sdk/renderer'; +import { decodeMetrics } from '@smartspectra/node-sdk/messages'; + +export class SmartSpectraSource { + constructor({ apiKey, telemetry = false, smiles = true }) { + this.apiKey = apiKey; + this.telemetry = telemetry; + this.smiles = smiles; + this.handlers = {}; + this.sdk = null; + this.simulated = false; + } + + on(event, fn) { this.handlers[event] = fn; return this; } + + emit(event, ...args) { const h = this.handlers[event]; if (h) h(...args); } + + metrics() { + // Breathing and cardio for the heart and the breath; EXPRESSIONS alone + // (not the whole face bundle) for smiles, since landmarks aren't needed. + const m = [...breathingMetrics, ...cardioMetrics]; + if (this.smiles) m.push(MetricType.EXPRESSIONS); + return m; + } + + build() { + this.sdk = new SmartSpectraSDK({ + apiKey: this.apiKey, + requestedMetrics: this.metrics(), + enableTelemetry: this.telemetry, + enableAccumulatedOutput: false, + }); + this.sdk.on('streamAvailable', (stream) => this.emit('stream', stream)); + this.sdk.on('processingStatus', (s) => this.emit('processingStatus', s)); + this.sdk.on('validationStatus', (code, ts, hint) => this.emit('validationStatus', code, ts, hint)); + this.sdk.on('metrics', (buf, ts) => { + try { this.emit('metrics', decodeMetrics(buf), ts); } catch (e) { console.error('decode failed', e); } + }); + this.sdk.on('error', (code, message, retryable) => this.onError(code, message, retryable)); + } + + async start() { + if (!this.sdk) this.build(); + try { + await this.sdk.start(); + } catch (err) { + this.onError(err.code, err.message, err.retryable); + } + } + + async onError(code, message, retryable) { + // A key that isn't allowed expressions still gets the heart and breath. + if (code === SmartSpectraErrorCode.kMetricNotAuthorized && this.smiles) { + this.smiles = false; + this.emit('notice', 'Smiles aren’t available with this key, so they’re left out.'); + await this.stop(); + return this.start(); + } + this.emit('error', code, message, retryable); + } + + async stop() { + if (!this.sdk) return; + const sdk = this.sdk; + this.sdk = null; + try { await sdk.stop(); } catch { /* already stopped */ } + try { sdk.destroy(); } catch { /* already destroyed */ } + } +} + +export { SmartSpectraErrorCode }; diff --git a/src/writer/writer.css b/src/writer/writer.css new file mode 100644 index 0000000..cf5db27 --- /dev/null +++ b/src/writer/writer.css @@ -0,0 +1,78 @@ +:root { + --paper: #fbf6ec; + --paper-edge: #efe5d2; + --desk: #e7dcc7; + --ink: #1f2942; + --muted: #6d6556; + --line: rgba(31, 41, 66, 0.12); + --wax: #a3232a; + --serif: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif; + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; +} +* { box-sizing: border-box; } +html, body { margin: 0; height: 100%; } +body { background: var(--desk); color: var(--ink); font: 16px/1.55 var(--serif); -webkit-font-smoothing: antialiased; } +main { max-width: 900px; margin: 0 auto; padding: 28px 24px; min-height: 100%; } +button { font: 15px var(--sans); cursor: pointer; border-radius: 99px; padding: 9px 18px; border: 1px solid rgba(31, 41, 66, 0.25); background: transparent; color: var(--ink); } +button:disabled { opacity: 0.45; cursor: default; } +button.primary { background: var(--ink); color: var(--paper); border-color: var(--ink); } +button.quiet { border-color: transparent; color: var(--muted); } +button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid #c99a3b; outline-offset: 2px; } + +.step { display: none; } +body[data-step="consent"] .step-consent, +body[data-step="write"] .step-write, +body[data-step="sealed"] .step-sealed { display: block; } + +.card { background: linear-gradient(165deg, var(--paper), var(--paper-edge)); border-radius: 6px; padding: 36px 40px; box-shadow: 0 24px 50px -28px rgba(40, 25, 5, 0.45), 0 1px 4px rgba(40, 25, 5, 0.1); } +.card.center { text-align: center; } +.wordmark { font-style: italic; font-weight: 400; font-size: 42px; margin: 0 0 6px; } +.lede { font-size: 19px; margin: 0 0 18px; } +.facts { padding-left: 18px; margin: 0 0 18px; } +.facts li { margin-bottom: 8px; } +.choices { border: 1px solid var(--line); border-radius: 6px; padding: 12px 16px; margin: 0 0 14px; font: 15px/1.5 var(--sans); } +.choices legend { padding: 0 6px; color: var(--muted); } +.choices label, .agree { display: block; margin: 6px 0; font: 15px/1.5 var(--sans); } +.agree { font-weight: 600; margin: 12px 0 16px; } +.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } +.row.center { justify-content: center; margin-top: 18px; } +.note { color: var(--muted); font: 13px/1.4 var(--sans); } +.fine { color: var(--muted); font: 12px/1.5 var(--sans); margin-top: 18px; } + +/* Live strip */ +.live { display: grid; grid-template-columns: 88px 1fr 200px; gap: 16px; align-items: center; margin-bottom: 16px; } +.cam { position: relative; width: 88px; height: 88px; border-radius: 50%; overflow: hidden; background: #2b2a28; box-shadow: 0 0 0 3px var(--paper); } +.cam video { width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); } +.rec { position: absolute; right: 10px; top: 10px; width: 9px; height: 9px; border-radius: 50%; background: #d23c3c; box-shadow: 0 0 0 2px var(--paper); } +.camera-off .rec { background: #888; } +.live-heart canvas { width: 100%; height: 64px; display: block; } +.live-stats { display: flex; gap: 18px; font: 13px var(--sans); color: var(--muted); align-items: center; } +.live-stats b { font: 600 20px var(--sans); color: var(--ink); font-variant-numeric: tabular-nums; } +.smile-dot { font-size: 20px; opacity: 0.25; transition: opacity 0.4s, color 0.4s; } +.smile-dot.on { opacity: 1; color: #c48a1a; } +.live-side { text-align: right; } +.hint { margin: 0 0 6px; font: 14px var(--sans); color: #8a4b18; } +.hint[data-ok="true"] { color: #2f6b45; } +.sim { display: inline-block; margin: 0 0 6px; font: 12px var(--sans); background: #f1e0b6; color: #5b4310; border-radius: 99px; padding: 2px 10px; } + +.paper { background: linear-gradient(170deg, var(--paper), var(--paper-edge)); border-radius: 4px; padding: 28px 40px 22px; box-shadow: 0 24px 50px -30px rgba(40, 25, 5, 0.45), 0 1px 4px rgba(40, 25, 5, 0.1); } +.paper label { display: flex; gap: 10px; align-items: baseline; font-style: italic; color: var(--muted); } +.paper input { border: 0; border-bottom: 1px solid var(--line); background: transparent; font: italic 20px var(--serif); color: var(--ink); padding: 2px 4px; flex: 0 1 260px; } +.field-from { justify-content: flex-end; margin-top: 8px; } +textarea { width: 100%; min-height: 46vh; border: 0; resize: vertical; background: repeating-linear-gradient(transparent 0 33px, var(--line) 33px 34px); background-attachment: local; font: 20px/34px var(--serif); color: var(--ink); padding: 8px 2px; margin: 10px 0; } +textarea:focus { outline: none; } +.write-foot { display: flex; gap: 16px; align-items: center; justify-content: space-between; margin-top: 14px; } + +/* Sealed */ +.seal { width: 190px; height: 190px; margin: 0 auto 6px; animation: press 0.7s cubic-bezier(.2,.9,.3,1.3); } +.seal svg { width: 100%; height: 100%; } +@keyframes press { from { transform: scale(1.6) rotate(-10deg); opacity: 0; } } +.step-sealed h2 { font-style: italic; font-weight: 400; font-size: 34px; margin: 0; } +.link-row { display: flex; gap: 8px; max-width: 620px; margin: 10px auto 4px; } +.link-row input { flex: 1; font: 13px ui-monospace, Menlo, monospace; padding: 9px 12px; border-radius: 99px; border: 1px solid var(--line); background: #fff8; color: var(--ink); min-width: 0; } + +@media (prefers-color-scheme: dark) { + body { background: #1d1b18; } + .note, .fine, .live-stats { color: #a89f8e; } + .live-stats b { color: #f0e6d2; } +} diff --git a/src/writer/writer.js b/src/writer/writer.js new file mode 100644 index 0000000..e17e491 --- /dev/null +++ b/src/writer/writer.js @@ -0,0 +1,234 @@ +// writer.js +// The writing desk. Consent first, then the camera, then the letter. + +import { LetterRecorder } from '../shared/recorder.js'; +import { VitalsTracker, hintFor } from '../shared/vitals.js'; +import { encodeLetter, buildLink, finalText } from '../shared/letter-format.js'; +import { inkFor } from '../shared/playback.js'; +import { median, formatDuration } from '../shared/summary.js'; +import { sealSvg } from '../shared/seal.js'; +import { SimulatedSource } from '../shared/sim-source.js'; +import readerHtml from '../../dist/reader/index.html'; + +const $ = (id) => document.getElementById(id); +const bridge = window.heartwritten || null; + +const app = { + cfg: { hasKey: false, simulate: true, readerUrl: '' }, + source: null, + simulated: true, + tracker: new VitalsTracker(), + recorder: new LetterRecorder(), + sampler: 0, + drawer: 0, + bpmHistory: [], + token: '', + letter: null, +}; + +function setStep(step) { document.body.dataset.step = step; } + +async function init() { + if (bridge) app.cfg = await bridge.getConfig(); + app.simulated = app.cfg.simulate || !app.cfg.hasKey; + $('mode-note').textContent = app.simulated + ? 'No SmartSpectra key found, so the signals will be simulated and the letter marked as a sample. See the README to add your key.' + : ''; + $('agree').addEventListener('change', () => { $('begin').disabled = !$('agree').checked; }); + $('begin').addEventListener('click', begin); + $('body').addEventListener('input', onType); + $('seal-it').addEventListener('click', seal); + $('stop-camera').addEventListener('click', stopCamera); + $('copy').addEventListener('click', copyLink); + $('preview-letter').addEventListener('click', previewLetter); + $('save-file').addEventListener('click', saveFile); + $('again').addEventListener('click', () => location.reload()); +} + +// --------------------------------------------------------------------------- +// Camera + +async function begin() { + $('begin').disabled = true; + const share = choices(); + if (app.simulated) { + app.source = new SimulatedSource(); + $('sim-flag').hidden = false; + } else { + const { SmartSpectraSource } = await import('./sdk-source.js'); + const apiKey = await bridge.getApiKey(); + app.source = new SmartSpectraSource({ apiKey, telemetry: share.telemetry, smiles: share.smiles }); + } + const src = app.source; + src.on('stream', (stream) => { $('preview').srcObject = stream; $('preview').play().catch(() => {}); }); + src.on('validationStatus', (code, _ts, hint) => { + $('hint').textContent = hintFor(code, hint); + $('hint').dataset.ok = String(code === 0); + }); + src.on('metrics', (m) => onMetrics(m)); + src.on('notice', (msg) => { $('notice').textContent = msg; }); + src.on('error', (code, message) => { + $('hint').textContent = code === 2 ? 'Your SmartSpectra key wasn’t accepted.' : `The camera stopped: ${message}`; + $('hint').dataset.ok = 'false'; + }); + setStep('write'); + await src.start(); + app.sampler = setInterval(() => app.recorder.sample(app.tracker.snapshot()), 250); + app.drawer = requestAnimationFrame(drawWave); + $('body').focus(); +} + +async function stopCamera() { + const src = app.source; + app.source = null; + if (src) await src.stop(); + app.tracker.reset(); + $('preview').srcObject = null; + $('hint').textContent = 'Camera off. The rest of the letter keeps no heartbeat.'; + $('hint').dataset.ok = 'false'; + $('stop-camera').disabled = true; + document.body.classList.add('camera-off'); +} + +function onMetrics(m) { + const wave = app.tracker.ingest(m); + if (wave.length) app.recorder.pushWave(wave); + const t = app.tracker; + if (t.bpm) { + app.bpmHistory.push(t.bpm); + if (app.bpmHistory.length > 400) app.bpmHistory.shift(); + } + $('live-bpm').textContent = t.bpm ? Math.round(t.bpm) : '—'; + $('live-br').textContent = t.breathRate ? Math.round(t.breathRate) : '—'; + $('live-smile').classList.toggle('on', choices().smiles && t.smile >= 0.6); +} + +function drawWave() { + const c = $('wave'); + const ctx = c.getContext && c.getContext('2d'); + if (!ctx) return; + const W = c.width; const H = c.height; + ctx.clearRect(0, 0, W, H); + const tr = app.tracker.pulseTrace; + if (tr.length > 4) { + const tEnd = tr[tr.length - 1].t; + const span = 6e6; + let lo = Infinity; let hi = -Infinity; + for (const { t, v } of tr) if (t >= tEnd - span) { lo = Math.min(lo, v); hi = Math.max(hi, v); } + const range = hi - lo || 1; + ctx.lineWidth = 2.2; + ctx.lineJoin = 'round'; + ctx.strokeStyle = inkFor(app.tracker.bpm, median(app.bpmHistory)); + ctx.beginPath(); + let first = true; + for (const { t, v } of tr) { + if (t < tEnd - span) continue; + const x = ((t - (tEnd - span)) / span) * W; + const y = H - 6 - ((v - lo) / range) * (H - 12); + if (first) { ctx.moveTo(x, y); first = false; } else ctx.lineTo(x, y); + } + ctx.stroke(); + } + app.drawer = requestAnimationFrame(drawWave); +} + +// --------------------------------------------------------------------------- +// Writing + +function onType(e) { + app.recorder.edit(e.target.value); + if (app.simulated && app.source && e.data === '!') app.source.bump(0.5); + $('seal-it').disabled = !e.target.value.trim(); + updateClock(); +} + +function updateClock() { + const words = (app.recorder.text.match(/\S+/g) || []).length; + $('clock').textContent = `Writing for ${formatDuration(app.recorder.elapsed())} · ${words} word${words === 1 ? '' : 's'} · nothing saved yet`; +} +setInterval(() => { if (app.recorder.t0 != null && document.body.dataset.step === 'write') updateClock(); }, 1000); + +function choices() { + return { + smiles: $('opt-smiles').checked, + edits: $('opt-edits').checked, + telemetry: $('opt-telemetry').checked, + }; +} + +function today() { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +// --------------------------------------------------------------------------- +// Sealing + +async function seal() { + $('seal-it').disabled = true; + clearInterval(app.sampler); + cancelAnimationFrame(app.drawer); + const src = app.source; + app.source = null; + if (src) await src.stop(); + $('preview').srcObject = null; + + const { smiles, edits } = choices(); + const letter = app.recorder.finish({ + from: $('from').value.trim(), + to: $('to').value.trim(), + day: today(), + sim: app.simulated, + share: { smiles, edits }, + }); + app.letter = letter; + app.token = await encodeLetter(letter); + const base = median(letter.vit.bpm); + $('seal').innerHTML = sealSvg(letter.wave.v, { initial: letter.from.charAt(0), bpm: base }); + const bits = []; + if (letter.to) bits.push(`For ${letter.to}`); + bits.push(`written in ${formatDuration(app.recorder.elapsed())}`); + if (base) bits.push(`your heart around ${base} bpm`); + $('sealed-sub').textContent = `${bits.join(' · ')}.`; + const link = app.cfg.readerUrl ? buildLink(app.cfg.readerUrl, app.token) : ''; + $('link').value = link || 'Set a reader address to share by link, or save it as a file.'; + $('copy').disabled = !link; + $('link-note').textContent = link.length > 6000 + ? 'This is a long letter, so the link is long. Some chat apps cut long links; if it won’t open for them, send the file instead.' + : (app.simulated ? 'Marked as a sample letter, because the signals were simulated.' : ''); + setStep('sealed'); +} + +async function copyLink() { + try { + await navigator.clipboard.writeText($('link').value); + $('copy').textContent = 'Copied'; + setTimeout(() => { $('copy').textContent = 'Copy link'; }, 1600); + } catch { + $('link').select(); + } +} + +function previewLetter() { + if (bridge) return bridge.openPreview(app.token); + return window.open(`../reader/index.html#${app.token}`, '_blank', 'noopener'); +} + +export function letterFileHtml(token) { + return readerHtml.replace('', + ``); +} + +function saveFile() { + const html = letterFileHtml(app.token); + const name = (app.letter.to || 'you').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'you'; + const a = document.createElement('a'); + a.href = URL.createObjectURL(new Blob([html], { type: 'text/html' })); + a.download = `a-letter-for-${name}.html`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 4000); +} + +export { finalText }; + +if (!globalThis.__HW_NO_AUTOBOOT__) init(); diff --git a/test/dom.test.js b/test/dom.test.js new file mode 100644 index 0000000..81483e0 --- /dev/null +++ b/test/dom.test.js @@ -0,0 +1,138 @@ +// End-to-end checks of the built pages in jsdom: the reader opens a letter +// from a link and from a saved file, and the writer (in simulated mode) +// goes consent -> write -> seal. +import { test, before } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { execFileSync } from 'node:child_process'; +import { JSDOM, VirtualConsole } from 'jsdom'; + +const root = new URL('../', import.meta.url); +let readerHtml; +let token; + +before(() => { + execFileSync('node', ['scripts/build.mjs'], { cwd: root }); + execFileSync('node', ['scripts/make-sample.mjs'], { cwd: root }); +}); + +function webGlobals(win) { + // jsdom lacks these; borrow Node's (same web-standard implementations). + for (const k of ['CompressionStream', 'DecompressionStream', 'Blob', 'Response', 'TextEncoder', 'TextDecoder', 'ReadableStream']) { + win[k] = globalThis[k]; + } + win.HTMLMediaElement.prototype.play = () => Promise.resolve(); +} + +function load(html, url) { + const errors = []; + const vc = new VirtualConsole(); + vc.on('jsdomError', (e) => { if (!/Not implemented/.test(e.message)) errors.push(e); }); + vc.on('error', (e) => errors.push(e)); + const dom = new JSDOM(html, { url, runScripts: 'dangerously', pretendToBeVisual: true, virtualConsole: vc, beforeParse: webGlobals }); + return { dom, win: dom.window, doc: dom.window.document, errors }; +} + +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +async function until(fn, ms = 4000) { + const end = Date.now() + ms; + while (Date.now() < end) { if (fn()) return true; await wait(25); } + return false; +} + +test('reader opens a letter from its link and replays it to the end', async () => { + readerHtml = await readFile(new URL('dist/reader/index.html', root), 'utf8'); + token = (await readFile(new URL('dist/sample-token.txt', root), 'utf8')).trim(); + const { win, doc, errors } = load(readerHtml, `https://reader.test/#${token}`); + assert.ok(await until(() => doc.body.dataset.view === 'envelope'), 'envelope shows'); + assert.match(doc.getElementById('envelope-to').textContent, /For Maya/); + assert.match(doc.getElementById('envelope-from').textContent, /Sam’s heartbeat/); + assert.ok(doc.querySelector('#seal svg'), 'wax seal drawn'); + assert.equal(doc.getElementById('sim-badge').hidden, false, 'sample letters say so'); + + doc.getElementById('seal-button').click(); + assert.ok(await until(() => doc.body.dataset.view === 'letter', 3000), 'letter opens after the seal breaks'); + assert.ok(await until(() => doc.getElementById('body-text').textContent.length > 3, 3000), 'words start appearing'); + doc.getElementById('skip').click(); + assert.ok(await until(() => doc.body.classList.contains('finished'), 3000), 'replay finishes'); + + const text = doc.getElementById('body-text').textContent; + assert.match(text, /I actually got it!/); + assert.match(text, /not good enough/); + assert.doesNotMatch(text, /terrible/, 'the taken-back word is gone at the end'); + const summary = doc.getElementById('summary-body').textContent; + assert.match(summary, /Quickest at/); + assert.match(summary, /got it/); + assert.match(summary, /Steadiest at/); + assert.match(summary, /smiled/); + assert.match(summary, /taken back|written and taken back/); + assert.ok(doc.querySelector('#body-text .smiled'), 'smiled words are marked'); + const colours = new Set([...doc.querySelectorAll('#body-text span[style]')].map((s) => s.style.color)); + assert.ok(colours.size > 3, 'ink changes colour with the heart'); + assert.match(doc.getElementById('pauses').textContent, /paused/); + assert.equal(doc.getElementById('signature').textContent, '— Sam'); + assert.deepEqual(errors, []); + win.close(); +}); + +test('a saved letter file opens with no link at all', async () => { + const html = await readFile(new URL('dist/sample-letter.html', root), 'utf8'); + const { win, doc, errors } = load(html, 'file:///Users/someone/Downloads/a-letter-for-maya.html'); + assert.ok(await until(() => doc.body.dataset.view === 'envelope')); + assert.deepEqual(errors, []); + win.close(); +}); + +test('a cut-off link explains itself instead of breaking', async () => { + const { win, doc } = load(readerHtml, `https://reader.test/#${token.slice(0, 200)}`); + assert.ok(await until(() => doc.body.dataset.view === 'empty')); + assert.match(doc.getElementById('empty-text').textContent, /cut short/); + win.close(); +}); + +test('the reader page makes no network requests', () => { + // CSP forbids it, and the page has no URLs to fetch. + assert.match(readerHtml, /connect-src 'none'/); + assert.match(readerHtml, /default-src 'none'/); + assert.doesNotMatch(readerHtml, /<(link|img|iframe)[^>]+(href|src)="https?:/i); + assert.doesNotMatch(readerHtml, /fetch\(/); +}); + +test('writer in simulated mode: consent, write, seal, save', async () => { + const html = (await readFile(new URL('dist/writer/index.html', root), 'utf8')) + .replace('', ''); + const { win, doc, errors } = load(html, 'file:///app/dist/writer/index.html'); + const js = await readFile(new URL('dist/writer/writer.js', root), 'utf8'); + win.eval(js); + + assert.equal(doc.body.dataset.step, 'consent', 'nothing starts before consent'); + assert.ok(doc.getElementById('begin').disabled, 'camera button waits for agreement'); + assert.match(doc.getElementById('mode-note').textContent, /simulated/); + doc.getElementById('opt-edits').checked = true; + const agree = doc.getElementById('agree'); + agree.checked = true; + agree.dispatchEvent(new win.Event('change')); + assert.equal(doc.getElementById('begin').disabled, false); + doc.getElementById('begin').click(); + assert.ok(await until(() => doc.body.dataset.step === 'write')); + assert.equal(doc.getElementById('sim-flag').hidden, false, 'simulated signals are labelled'); + assert.ok(await until(() => doc.getElementById('live-bpm').textContent !== '—', 3000), 'live heart rate shows'); + + doc.getElementById('to').value = 'Maya'; + doc.getElementById('from').value = 'Sam'; + const body = doc.getElementById('body'); + for (const ch of 'Hello Maya. I got it!') { + body.value += ch; + body.dispatchEvent(new win.InputEvent('input', { data: ch })); + await wait(15); + } + await wait(600); + assert.equal(doc.getElementById('seal-it').disabled, false); + doc.getElementById('seal-it').click(); + assert.ok(await until(() => doc.body.dataset.step === 'sealed'), 'sealed'); + assert.ok(doc.querySelector('#seal svg')); + assert.match(doc.getElementById('sealed-sub').textContent, /For Maya/); + assert.match(doc.getElementById('link-note').textContent, /sample/); + assert.deepEqual(errors, []); + win.close(); +}); From dd5f93c0d5ae5f16e9cd37280f7b19c2cb4e0250 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 15:46:08 +0000 Subject: [PATCH 3/4] README, privacy notes, Vercel config for the reader, DEV post draft and demo script Co-Authored-By: Claude Opus 5.5 --- LICENSE | 21 ++++++++ PRIVACY.md | 65 +++++++++++++++++++++++ README.md | 119 +++++++++++++++++++++++++++++++++++++++++- docs/demo-script.md | 25 +++++++++ docs/dev-post.md | 80 ++++++++++++++++++++++++++++ src/writer/index.html | 2 +- vercel.json | 12 +++++ 7 files changed, 322 insertions(+), 2 deletions(-) create mode 100644 LICENSE create mode 100644 PRIVACY.md create mode 100644 docs/demo-script.md create mode 100644 docs/dev-post.md create mode 100644 vercel.json diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8823ab8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Subomi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 0000000..378d162 --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,65 @@ +# Consent and data handling + +Heartwritten reads your face through your camera to estimate your heart rate, +pulse wave, breathing and smiles while you write a letter. This page says what +happens to that data. + +## Before anything starts + +The app opens on a consent screen. The camera stays off until you tick +"I'm the only person on camera, and I agree to this" and press +**Turn on the camera**. A red dot shows while the camera is on, and +**Stop camera** turns it off at any point; the rest of the letter then +carries no heartbeat. + +You choose, before you start: + +- whether the reader sees where you smiled (on by default) +- whether the reader sees words you typed and took back (off by default) +- whether the SmartSpectra SDK sends telemetry to Presage (off by default) + +## What is kept + +- **Kept:** the letter's text, when each character was typed, and numbers + sampled four times a second: heart rate, a breathing value and (if you + allow it) a smile score. Six seconds of the pulse wave for the seal. +- **Never kept:** video, photos, frames or anything that shows your face. + Words you delete are dropped unless you chose to share them. + +## Where it goes + +- **While you write**, nothing is saved to disk. The letter exists only in + the app's memory. +- **The SmartSpectra SDK** measures on your computer. Presage's documentation + says all metric computation runs on-device and the SDK calls Presage's + service only to check the API key, so it needs a network connection while + measuring. Presage says its telemetry does not include frames or vitals. Telemetry + is off in Heartwritten unless you turn it on; if you do, Presage receives + session summaries and device details linked to your API key. +- **When you seal it**, the letter is packed into a token that lives in the link + (after the `#`, which browsers don't send to servers) or in an HTML file you + save. Heartwritten has no server and no account. Nobody has the letter until + you send the link or file to them. +- **The reader page** can't send anything: its Content Security Policy blocks + every network request, and it loads nothing from anywhere else. + +## How long it lasts, and deleting it + +- Closing the writer forgets the letter unless you copied the link or saved the + file. +- A sealed letter lasts as long as the link or file does. Delete the file, or + the message you sent the link in, to delete the letter. Anyone you've sent it + to keeps their copy, as with any letter. +- Heartwritten stores nothing else. Your API key stays in the file or + environment variable you put it in. + +## AI + +Heartwritten uses no AI model of its own. The physiological estimates come from +the SmartSpectra SDK. + +## Not medical + +Heart rate and breathing are camera estimates for feeling, not medicine. +Heartwritten makes no diagnosis, gives no health advice and isn't for +monitoring anyone. Only write with your own face on camera. diff --git a/README.md b/README.md index d2c8f88..97b3b6f 100644 --- a/README.md +++ b/README.md @@ -1 +1,118 @@ -# heartwritten \ No newline at end of file +# Heartwritten + +**Letters that carry the heartbeat you wrote them with.** + +You write a letter at your desk. While you type, your laptop camera reads your +heart rate, pulse wave, breathing and smiles with the +[Presage SmartSpectra SDK](https://physiology.presagetech.com). When you're +done, you seal it with a wax seal pressed from your own pulse wave. + +The person you send it to opens the envelope and watches the letter being +written again at your pace: the pauses where you thought, the sentence you +rushed, the ink warming where your heart sped up, the page rising and falling +with your breath, a soft glow where you smiled. At the end they see where your +heart was quickest and where it was steadiest. + +Nothing goes to a server. A sealed letter lives inside its link (in the part +after `#`, which browsers never send) or inside a single HTML file. + +## Try it + +You need Node 20 or newer and a webcam. + +``` +npm install +npm run start:sim +``` + +`start:sim` runs the whole app with simulated signals, so you can try it with +no key. Letters written this way are marked as samples, everywhere. + +To read the real thing: + +1. Get an API key from [physiology.presagetech.com](https://physiology.presagetech.com). +2. Put it in a file called `.smartspectra-key` in this folder (it's git-ignored), + or set `SMARTSPECTRA_API_KEY` in your shell. +3. Check the SDK and key work: `npm run smoke` +4. Write a letter: `npm start` + +The SDK ships native libraries for macOS on Apple silicon, Linux (x64 and arm64) +and Windows x64. Measurement runs on your computer; the SDK needs a network connection +only so Presage can check the key. + +To see a finished letter without the app, run `npm run sample` and open +`dist/sample-letter.html` in a browser. + +## Sharing by link + +The writer can save any letter as a file. To share by link instead, host the +reader page somewhere static and tell the writer its address: + +``` +npm run build # makes dist/reader/index.html, one self-contained file +``` + +Deploy `dist/reader` anywhere static (a `vercel.json` is included), then put +the address in `heartwritten.config.json`: + +```json +{ "readerUrl": "https://your-reader.example" } +``` + +or set `HEARTWRITTEN_READER_URL`. The reader has a Content Security Policy of +`default-src 'none'; connect-src 'none'`, so it can't send anything anywhere, +and the letter in the `#` part of the link never reaches the host's logs. + +## How it responds to human signals + +| Signal (SmartSpectra) | While writing | In the letter | +| --- | --- | --- | +| Pulse rate (`cardio.pulseRate`, stable values only) | Live number and a trace drawn in the ink colour | Ink colour per character: calm navy near the writer's own median, warming toward red as the heart quickens, cooling as it settles. A beating heart in the margin keeps time. The closing card finds the quickest and steadiest sentences. | +| Pulse wave (`cardio.arterialPressureTrace`) | Live trace | The wax seal: six seconds of the wave, wrapped into a ring and pressed into wax. Every seal is different. | +| Breathing (`breathing.upperTrace`, `breathing.rate`) | Breaths a minute | The paper rises and falls with the writer's breathing as it replays. | +| Smiles (`face.expression`, happy) | A small mark lights up | Words written while smiling glow softly. Optional. | +| Validation status | Plain-language hints: "move a little closer or further", "a little more light, please" | | + +Typing is recorded as timed edits, so the replay keeps the real rhythm. Long +pauses (over eight seconds) are shortened in the replay but noted in the margin. +Words you delete are dropped from the letter unless you choose to share them. + +## Privacy and consent + +The consent screen comes before the camera turns on, and says plainly what is +read, what is kept and where it goes. See [PRIVACY.md](PRIVACY.md) for the full +data handling, including the SDK's telemetry, which is off unless you turn it on. + +Heartwritten is for feeling, not medicine. Heart rate and breathing are camera +estimates. It makes no diagnosis and gives no health advice. + +## How it's built + +``` +app/main.cjs Electron main: window, camera permission, SDK IPC, key lookup +src/writer/ The writing desk (consent → write → seal) + sdk-source.js SmartSpectra renderer SDK, events decoded into metrics +src/reader/ The reader, built into one self-contained HTML file +src/shared/ + vitals.js Turns SDK metrics packets into steady pulse, breath and smile values + recorder.js Records timed edits and 4 Hz vitals while you write + letter-format.js Packs a letter into a compact, deflated, URL-safe token + playback.js Replays the edits and maps the heart to ink + summary.js Quickest and steadiest sentences, smiles, words taken back + seal.js Draws the wax seal from the pulse wave + sim-source.js Simulated SDK output for development and tests +test/ node --test: the core, plus the built pages in jsdom +``` + +`npm test` builds everything and runs 25 tests, including the reader replaying +a full letter and the writer going from consent to a sealed letter in +simulated mode. + +The Electron wiring follows Presage's `electron-quickstart` sample: the main +process binds the SDK's IPC, the preload exposes it, and the renderer runs +`SmartSpectraSDK` with the camera. + +## License + +MIT for this code (see [LICENSE](LICENSE)). The SmartSpectra SDK has its own +license from Presage Technologies. diff --git a/docs/demo-script.md b/docs/demo-script.md new file mode 100644 index 0000000..ae4efbb --- /dev/null +++ b/docs/demo-script.md @@ -0,0 +1,25 @@ +# Demo video script (about 90 seconds) + +Record on your Mac with a real key, good light on your face and the room quiet. +Screen-record the app, with a small picture-in-picture of your face only for +shot 2. Write a short, real letter to someone (about 4 sentences) with one +moment that actually moves you, and one line that makes you smile. + +| # | Time | On screen | Voice-over | +| --- | --- | --- | --- | +| 1 | 0:00–0:08 | A typed message on a phone, then a scanned handwritten letter with a crossed-out word | "Handwritten letters told you how they felt to write. Typed ones don't." | +| 2 | 0:08–0:18 | Heartwritten consent screen; tick agree; camera on; live heart trace and bpm settle | "Heartwritten reads your heartbeat, breathing and smiles through the webcam, with Presage SmartSpectra. Nothing is saved, and nothing goes to a server." | +| 3 | 0:18–0:40 | Write the letter. Let the bpm visibly change at the emotional line. Smile once. Pause for a few seconds before the last line. | (Quiet. Let the typing and the live heart carry it.) | +| 4 | 0:40–0:48 | Press **Seal it with my heartbeat**; the wax seal presses in | "You seal it with your own pulse wave. No two seals are the same." | +| 5 | 0:48–1:15 | Open the link in a browser as the recipient. Tap the seal, it cracks. The letter writes itself: ink warming at the emotional line, the margin heart beating, a glow on the smiling words, "paused 9 seconds" in the margin | "They watch it written again, at your pace. The ink warms where your heart sped up. The page breathes with you." | +| 6 | 1:15–1:25 | The closing card: quickest and steadiest sentences | "And at the end, where your heart was quickest, and where it was steadiest." | +| 7 | 1:25–1:30 | The seal again, with the line "lives only in its link" | "Heartwritten. Letters that carry your heartbeat." | + +Tips: + +- Keep the camera picture out of shot 5: the letter is the point, and it shows + the recipient never sees your face. +- If the heart barely moves while writing, read the letter aloud once first, or + write about something you care about. Don't fake it with exercise; judges + will see the ink jump. +- Use the 1× replay speed for the emotional part, then skip to the end. diff --git a/docs/dev-post.md b/docs/dev-post.md new file mode 100644 index 0000000..70343dd --- /dev/null +++ b/docs/dev-post.md @@ -0,0 +1,80 @@ +--- +title: "Heartwritten: letters that carry the heartbeat you wrote them with" +tags: presagechallenge, devchallenge, electron, javascript +--- + +*This is a submission for the [Presage SmartSpectra SDK Challenge](https://dev.to/challenges/presage-2026-11-04).* + +## What I Built + +A handwritten letter used to tell you things the words didn't: where the pen pressed harder, where the writer stopped, the line they crossed out. Typed messages lost all of that. + +**Heartwritten** brings it back with the one signal that never lies about how a sentence felt to write: your heartbeat. + +You write a letter on your laptop. While you type, SmartSpectra reads your pulse, breathing and smiles through the webcam. When you're done you seal it with a wax seal pressed from six seconds of your own pulse wave, so no two seals are alike. + +The person you send it to taps the seal, it cracks, and they watch your letter being written again at your real pace: + +- the **ink warms** toward red where your heart sped up, and settles back to navy as you calmed down +- a small **heart in the margin beats** at your rate, sentence by sentence +- the **paper rises and falls** with your breathing +- words you wrote **while smiling glow** +- **pauses** stay in, and the long ones are noted in the margin ("paused 14 seconds") +- if you allow it, they see the words you **typed and took back** + +At the end, a card shows where your heart was quickest and where it was steadiest, with the sentences. + +There's no server and no account. A sealed letter lives entirely inside its link (in the part after `#`, which browsers never send anywhere) or in a single HTML file you can attach to an email. + +## Demo + + + + + +## Code + + + +Setup is in the README: `npm install`, add your SmartSpectra key, `npm start`. `npm run start:sim` runs the whole thing with simulated signals if you want to try it without a key. + +## How It Responds to Human Signals + +Every signal changes something you can see or hold in the finished letter. None of them is a number on a dashboard. + +| SmartSpectra signal | What it becomes | +| --- | --- | +| `cardio.pulseRate` (stable readings only) | The colour of each character's ink, measured against *your own* median for that letter, so a calm writer and an anxious one both get a full range. It also sets the beat of the margin heart, and finds the quickest and steadiest sentences. | +| `cardio.arterialPressureTrace` | The wax seal. Six seconds of the pulse wave, wrapped into a ring around your initial. | +| `breathing.upperTrace`, `breathing.rate` | The page breathing during replay. | +| `face.expression` (happy) | The glow on words you wrote smiling. Optional, and it's the only face metric I request. | +| Validation status | Gentle hints while you write: "move a little closer or further", "a little more light, please". | + +A few things I cared about: + +- **The signal follows the writing, not the clock.** Typing is recorded as timed edits and vitals at 4 Hz, and the replay lines them up, so the ink colour of a word is your heart rate *when you typed that word*. +- **Only trustworthy readings count.** Pulse values that SmartSpectra doesn't mark stable are ignored, and old readings go stale after six seconds rather than painting the rest of the letter. +- **Relative, not clinical.** The ink compares you to yourself in that letter. It never says a number is good or bad. +- **Graceful degradation.** If a key isn't allowed expressions, the app drops smiles and keeps going. If you stop the camera halfway, the rest of the letter simply carries no heartbeat. + +Under the hood it's an Electron app following Presage's quickstart pattern (main process binds the SDK IPC, the renderer runs `SmartSpectraSDK` with the camera), plus a reader page built into one self-contained HTML file. The letter is packed into a compact, deflated, URL-safe token, so a full page of writing with its heartbeat fits in a link of a few thousand characters. The repo has 25 tests, including the reader replaying a whole letter and the writer going from consent to a sealed letter. + +## Prize Categories + +Most Creative or Delightful Use. + +## Consent and Data Handling + +- **Consent first.** The app opens on a consent screen. The camera stays off until you confirm you're the only person on camera and agree. A red dot shows while it's on, and you can stop it at any time. +- **What's read:** heart rate, pulse wave, breathing and smiles, estimated by SmartSpectra from your face. Measurement runs on your computer; per Presage's docs, the SDK contacts Presage's service only to check the API key. +- **What's kept:** the text, when each character was typed, and numbers sampled four times a second. Never video, photos or frames. Words you delete are dropped unless you choose to share them. +- **Storage:** nothing is saved while you write. A sealed letter exists only in the link or file you choose to send. Heartwritten has no server, no database and no account. +- **Sharing:** only with whoever you send the link or file to. The reader page has a Content Security Policy that blocks every network request, so opening a letter sends nothing anywhere, and the `#` part of a link never reaches the host. +- **Retention and deletion:** a letter lasts as long as its link or file. Delete those and it's gone. Closing the writer forgets an unsent letter. +- **SDK telemetry:** off by default (`enableTelemetry: false`). You can turn it on in the consent screen; Presage says its telemetry contains session summaries and device details linked to the key, never frames or vitals. +- **AI:** none. All the physiology comes from SmartSpectra. +- **Not medical:** camera estimates for feeling, not medicine. No diagnosis, no health advice, and not for monitoring anyone. + +The full write-up is in [PRIVACY.md](https://github.com/ubmids/heartwritten/blob/main/PRIVACY.md). + + diff --git a/src/writer/index.html b/src/writer/index.html index 0cf62b5..d7d49e9 100644 --- a/src/writer/index.html +++ b/src/writer/index.html @@ -18,7 +18,7 @@

    Heartwritten

  • What the camera reads: heart rate, the pulse wave, breathing and smiles, estimated by the Presage SmartSpectra SDK from your face.
  • What the letter keeps: numbers only, a few a second. Never video, photos or your face.
  • Where it goes: nowhere until you seal it. A sealed letter lives inside its link or file, not on a server. You decide who gets it.
  • -
  • What leaves this computer while you write: the SDK talks to Presage’s service to check your key and take the measurement. Presage says frames and vitals are not in its telemetry, which is off below unless you turn it on.
  • +
  • What leaves this computer while you write: the measurement runs on this computer. The SDK contacts Presage’s service only to check the key. Presage says frames and vitals are never in its telemetry, which stays off unless you turn it on below.
  • Your choices diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..e00e093 --- /dev/null +++ b/vercel.json @@ -0,0 +1,12 @@ +{ + "installCommand": "ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm ci", + "buildCommand": "node scripts/build.mjs", + "outputDirectory": "dist/reader", + "headers": [ + { "source": "/(.*)", "headers": [ + { "key": "Referrer-Policy", "value": "no-referrer" }, + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "Cache-Control", "value": "public, max-age=300" } + ] } + ] +} From e72cb451c17ddce1bddce9c68d3c22e14de57076 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 15:51:29 +0000 Subject: [PATCH 4/4] Run the tests and the SDK load check on every push Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..af896d8 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,19 @@ +name: test +on: + push: + branches: [main] + pull_request: +jobs: + test: + runs-on: ubuntu-latest + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm test + - run: npm run smoke