ZZZ Digital Lab

Back to HushBrief

src/main.ts

import './style.css';
import { createBrief, detectNano, redact, privateNotice, exportMarkdown, sourceNames, type NanoState, type Result } from './core.ts';
import { demoPorts } from './demo.ts';
import { firebaseConfigured, firebaseMissing, firebasePorts, prepareDevice } from './firebase.ts';
// Rehearsal's fake cloud exists only on a local dev server, never on the hosted app.
const localHost = ['localhost', '127.0.0.1'].includes(location.hostname);

const sample = [
  'Studio North / Friday handoff',
  'TODO: Review the prototype with Maya by Monday.',
  'Action: Send the accessibility checklist to the design team.',
  'Contact: maya@example.test / +65 8123 4567',
  '[[private: Internal budget ceiling is $18,000. Keep this within the studio.]]',
  'TODO: Confirm the next user interview slot.',
  'Decision: Keep the first release focused on keyboard navigation.'
].join('\n');
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
let nano: NanoState = 'unsupported';
let last: Result | undefined;
let busy = false;
let generation = 0;

$('app').innerHTML = `
<a class="skip-link" href="#notes">Skip to working notes</a>
<header class="topbar"><a class="brand" href="./" aria-label="HushBrief home"><span class="brandmark" aria-hidden="true">h.</span>hushbrief<span class="edition">CHROME EDITION</span></a><span class="session"><i aria-hidden="true"></i> Notes stay in this tab</span></header>
<main id="main">
<section class="hero"><div><div class="eyebrow">PRIVATE NOTES. CLEAR HANDOFFS.</div><h1>Keep the context.<br><em>Lose the exposure.</em></h1><p class="intro">A clearer next shift for freelancers and small studios. <br>Review the notes. Choose the boundary. Share the next steps.</p></div><aside class="promise"><span class="promise-icon" aria-hidden="true">↗</span><strong>Your notes. Your boundary.</strong><p>No saved notes. No silent cloud switch.<br>Cloud starts off. You approve the redacted preview.</p></aside></section>
<section class="start-guide" aria-label="Quick start"><strong>Try a private handoff in 30 seconds</strong><ol><li>Use the fictional example or paste notes.</li><li>Review what could leave this device.</li><li>Create a handoff, check its source, export.</li></ol></section>
<div id="mode-notice" class="notice">Rehearsal workspace · cloud requests use a local fake backend. No Gemini cloud model runs.</div>
<div id="network-state" class="network-state" role="status"></div>
<section class="controlbar" aria-label="Inference settings"><div class="mode-control"><label for="mode">Workspace mode</label><select id="mode"><option value="demo" ${localHost || !firebaseConfigured ? '' : 'disabled'}>Rehearsal · ${localHost ? 'local fake cloud' : 'local only'}</option><option value="live" ${firebaseConfigured ? 'selected' : 'disabled'}>Firebase AI Logic · live</option></select></div><div class="device-control"><span id="nano-status" role="status">Checking Chrome Nano…</span><button id="detect" class="subtle">Check device</button><button id="prepare" class="subtle">Prepare Nano</button></div></section>
<details class="setup"><summary>Firebase readiness <span id="setup-summary"></span></summary><p id="setup-details"></p><p>Console checks remain separate: enable AI Logic and the Gemini API; register reCAPTCHA Enterprise with App Check; allow the hosted domain and enforce AI Logic. Local development also needs a privately registered debug token.</p></details>
<details class="rehearsal" id="rehearsal" ${firebaseConfigured ? 'hidden' : ''}><summary>Rehearsal controls <span>Clearly labeled simulations for the demo</span></summary><div class="sim-controls"><label for="sim-nano">Nano scenario <select id="sim-nano"><option value="actual">Actual device detection</option><option value="available">Simulate ready</option><option value="unavailable">Simulate unavailable</option></select></label><label><input id="offline" type="checkbox"> Simulate offline</label><label><input id="cloud-fail" type="checkbox"> Simulate cloud failure</label></div></details>
<div class="workspace">
<section class="panel notes-panel"><div class="panel-heading"><div><span class="step">01</span><h2>Working notes</h2></div><button class="subtle" id="sample">Load example</button></div><label class="sr-only" for="notes">Private working notes</label><textarea id="notes" maxlength="12000" spellcheck="false" aria-describedby="notes-help input-error count" placeholder="Start with TODO: Review the prototype. Mark private passages as [[private: text]]."></textarea><p id="input-error" class="input-error" role="alert" hidden></p><div class="note-meta"><span><span id="count">0</span> / 12,000 characters</span><button class="subtle" id="clear">Clear workspace</button></div><p class="hint" id="notes-help">Mark names, identifiers or any sensitive passage with <code>[[private: …]]</code>. These spans never reach any model and never appear in the handoff or export; unclosed spans are withheld to the end. Automatic email/phone masking applies to the cloud packet. Emails and phones remain visible in device-only and local results. The example is fictional.</p></section>
<section class="panel boundary-panel"><div class="panel-heading"><div><span class="step">02</span><h2>The cloud boundary</h2></div><span id="masked" class="tag">0 masked</span></div><p class="panel-copy" id="packet-help">This is the exact notes payload a cloud-capable run can use. Review it for anything the masking missed. A fixed handoff instruction and service metadata also accompany the request.</p><pre id="packet" tabindex="0" role="region" aria-label="Cloud payload preview" aria-describedby="packet-help"></pre><label class="consent"><input type="checkbox" id="consent" aria-describedby="privacy-state"><span>Allow cloud fallback for this preview<strong>Only the previewed notes. Editing notes resets permission.</strong></span></label><div class="privacy-line"><span aria-hidden="true">◇</span><span id="privacy-state">Cloud off · original notes stay on this device</span></div></section>
</div>
<div class="runbar"><div><strong>Ready when you are.</strong><span id="run-hint">Local extraction works even without Nano.</span></div><button class="primary" id="run">Create handoff <span aria-hidden="true">↗</span></button></div>
<section class="panel result-panel" aria-labelledby="result-title" aria-busy="false"><div class="panel-heading"><div><span class="step">03</span><h2 id="result-title" tabindex="-1">The next shift starts here</h2></div><button id="export" class="subtle" disabled>Export Markdown ↓</button></div><div class="execution"><span class="execution-label">RESULT SOURCE</span><div id="route" class="route" role="status">Not run yet · no model request attempted</div><p id="attempt"></p></div><p id="status" role="status" aria-live="polite">Your handoff will appear here. Owners and dates are never assumed in local extraction.</p><p id="private-notice" class="hint" role="status" hidden></p><p id="recovery" class="recovery" role="alert" hidden></p><div id="cards"><div class="empty-state"><strong>A handoff you can trace back.</strong><p>Create a handoff to see action cards with source quotes. Review before sharing.</p></div></div></section>
<footer><span>HushBrief / #BuildHybridAI 2026</span><span>Notes in tab memory · Static app code cached for offline use</span></footer>
</main>`;
const notes = $('notes') as HTMLTextAreaElement;
notes.value = sample;

function isDemo() { return ($('mode') as HTMLSelectElement).value === 'demo'; }
function effectiveNano(): NanoState {
  const scenario = ($('sim-nano') as HTMLSelectElement).value;
  return isDemo() && scenario !== 'actual' ? scenario as NanoState : nano;
}
function refreshPreview() {
  const safe = redact(notes.value);
  $('packet').textContent = safe.text || 'Your redacted preview will appear here.';
  $('masked').textContent = safe.count + ' masked';
  $('private-notice').textContent = privateNotice(safe.privateSpans.length);
  $('private-notice').hidden = safe.privateSpans.length === 0;
  $('count').textContent = String(notes.value.length);
  $('privacy-state').textContent = ($('consent') as HTMLInputElement).checked ? 'Cloud allowed for this preview · original notes are excluded' : 'Cloud off · original notes stay on this device';
  ($('consent') as HTMLInputElement).disabled = !notes.value.trim();
  $('run-hint').textContent = notes.value.trim() ? 'Cloud is optional. Local rules work without a model.' : 'Add a TODO: line or load the fictional example to begin.';
}
function invalidate() {
  generation++;
  ($('consent') as HTMLInputElement).checked = false;
  ($('export') as HTMLButtonElement).disabled = true;
  last = undefined;
  $('result-title').textContent = 'The next shift starts here';
  $('route').textContent = 'Not run for these notes · no new model request attempted';
  $('attempt').textContent = '';
  $('recovery').hidden = true;
  $('input-error').hidden = true;
  notes.removeAttribute('aria-invalid');
  $('cards').replaceChildren();
  $('status').textContent = 'Notes or settings changed. Create a fresh handoff.';
  refreshPreview();
}
notes.addEventListener('input', invalidate);
$('consent').addEventListener('change', () => { generation++; refreshPreview(); });
for (const id of ['mode','sim-nano','offline','cloud-fail']) $(id).addEventListener('change', () => {
  invalidate();
  ($('rehearsal') as HTMLDetailsElement).hidden = !isDemo();
  refreshEnvironment();
});
$('sample').addEventListener('click', () => { notes.value = sample; invalidate(); });
$('clear').addEventListener('click', () => { notes.value = ''; invalidate(); notes.focus(); });
async function checkDevice() {
  nano = await detectNano();
  $('nano-status').textContent = 'Chrome Nano: ' + nano;
  ($('prepare') as HTMLButtonElement).disabled = isDemo() || !['downloadable','downloading','available'].includes(nano);
}
function refreshEnvironment() {
  const offline = !navigator.onLine || (isDemo() && ($('offline') as HTMLInputElement).checked);
  $('network-state').textContent = offline ? (navigator.onLine ? 'Offline simulation · no cloud route will be attempted' : 'You are offline · local rules remain available; a ready device model can also be attempted') : 'Network available · cloud still requires your permission';
  $('network-state').classList.toggle('offline', offline);
  $('mode-notice').textContent = isDemo() ? 'Rehearsal workspace · cloud requests use a local fake backend. No Gemini cloud model runs.' : 'Firebase workspace · source is reported after a valid SDK response. Configuration alone is not a successful inference.';
  ($('prepare') as HTMLButtonElement).disabled = isDemo() || !['downloadable','downloading','available'].includes(nano);
}
window.addEventListener('online', refreshEnvironment);
window.addEventListener('offline', refreshEnvironment);
$('setup-summary').textContent = firebaseConfigured ? ' · Firebase AI Logic with App Check' : ' · owner setup required';
$('setup-details').textContent = firebaseConfigured ? 'Connected to Firebase AI Logic. Requests are protected by Firebase App Check (reCAPTCHA Enterprise).' : 'Missing client fields: ' + firebaseMissing.join(', ') + '. Rehearsal remains available. The owner can run npm run configure and npm run preflight locally.';
$('detect').addEventListener('click', checkDevice);
$('prepare').addEventListener('click', () => {
  if (isDemo()) { $('status').textContent = 'Rehearsal does not download a model. Select configured Firebase mode to prepare Nano.'; return; }
  // Keep initialization in the original click activation.
  const p = prepareDevice(v => { $('nano-status').textContent = 'Nano download: ' + Math.round(v * 100) + '%'; });
  $('status').textContent = 'Preparing the on-device model. Initial download can take several minutes.';
  p.then(checkDevice).catch(() => { $('status').textContent = 'Nano preparation is unavailable. Cloud with permission or local rules remain available.'; });
});

function showResult(result: Result) {
  $('result-title').textContent = result.brief.title;
  $('route').replaceChildren();
  const badge = document.createElement('span');
  badge.className = 'source-badge';
  badge.textContent = sourceNames[result.source];
  $('route').append(badge);
  const attempts = { none: 'No model request attempted. Deterministic rules ran in this tab.', device: 'Device-only route attempted. Cloud was excluded.', hybrid: isDemo() ? 'Simulated device route attempted locally; no real model ran.' : 'Firebase prefer-on-device route attempted with the redacted preview; cloud was permitted.', cloud: isDemo() ? 'Fake-cloud HTTP route attempted on loopback; no Gemini request.' : 'Firebase cloud route attempted with the redacted preview.' };
  $('attempt').textContent = attempts[result.attempted];
  $('recovery').hidden = !result.warning;
  $('recovery').textContent = result.warning ? result.warning + ' Review this local result, or fix the issue and create a new handoff.' : '';
  $('status').textContent = result.reason + ' ' + result.brief.summary;
  $('private-notice').textContent = privateNotice(result.privateNotesWithheld);
  $('private-notice').hidden = result.privateNotesWithheld === 0;
  const cards = $('cards'); cards.replaceChildren();
  if (!result.brief.actions.length) {
    const p = document.createElement('p'); p.className = 'empty-state'; p.textContent = 'No action lines found. Add a line such as TODO: Review the prototype, then create a new handoff. Local rules extract explicit actions; they do not interpret general prose.'; cards.append(p);
  }
  result.brief.actions.forEach((card, i) => {
    const article = document.createElement('article'); article.className = 'action-card';
    const number = document.createElement('span'); number.className = 'action-number'; number.textContent = String(i+1).padStart(2,'0');
    const body = document.createElement('div');
    const h = document.createElement('h3'); h.textContent = card.action;
    const meta = document.createElement('p'); meta.className = 'action-meta'; meta.textContent = card.owner + ' / ' + card.due;
    const evidence = document.createElement('blockquote'); evidence.textContent = card.evidence;
    body.append(h,meta,evidence); article.append(number,body); cards.append(article);
  });
  ($('export') as HTMLButtonElement).disabled = !result.brief.actions.length;
  $('result-title').focus({ preventScroll: true });
}
$('run').addEventListener('click', async () => {
  if (busy) return;
  if (!notes.value.trim() || notes.value.length > 12000) {
    $('input-error').textContent = !notes.value.trim() ? 'Add a few notes first, or choose Load example.' : 'Keep notes under 12,000 characters.';
    $('input-error').hidden = false; notes.setAttribute('aria-invalid','true'); notes.focus(); return;
  }
  busy = true;
  const runVersion = generation;
  const button = $('run') as HTMLButtonElement; button.disabled = true; button.textContent = 'Creating handoff…';
  last = undefined; ($('export') as HTMLButtonElement).disabled = true;
  $('cards').replaceChildren(); $('recovery').hidden = true;
  document.querySelector('.result-panel')?.setAttribute('aria-busy','true');
  $('route').textContent = 'Processing · source not confirmed'; $('attempt').textContent = '';
  $('status').textContent = 'Building the handoff…';
  try {
    const result = await createBrief({ raw: notes.value, allowCloud: ($('consent') as HTMLInputElement).checked, online: navigator.onLine && !(isDemo() && ($('offline') as HTMLInputElement).checked), nano: effectiveNano() }, isDemo() ? demoPorts(($('cloud-fail') as HTMLInputElement).checked) : firebasePorts);
    if (runVersion !== generation) { $('route').textContent = 'Result discarded · no current handoff'; $('status').textContent = 'Input changed during processing. Result discarded; review the current preview and run again.'; return; }
    last = result; showResult(result);
  } catch { $('route').textContent = 'No valid handoff'; $('status').textContent = 'Unable to create a handoff. Review the notes and try again.'; }
  finally { busy = false; button.disabled = false; button.textContent = 'Create handoff ↗'; document.querySelector('.result-panel')?.setAttribute('aria-busy','false'); }
});
$('export').addEventListener('click', () => {
  if (!last) return;
  const text = exportMarkdown(last);
  const url = URL.createObjectURL(new Blob([text], {type:'text/markdown;charset=utf-8'}));
  const a = document.createElement('a'); a.href=url; a.download='hushbrief-handoff.md'; a.click(); setTimeout(()=>URL.revokeObjectURL(url),1000);
});
refreshPreview(); refreshEnvironment(); void checkDevice();
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
  void navigator.serviceWorker.register('/sw.js').catch(()=> { $('run-hint').textContent = 'Offline reload cache unavailable; local extraction still works in this tab.'; });
}