import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { Particles } from './particles.js'; import { BlocksView, BLOCK_COLORS } from './blocks3d.js'; import { SentinelsView, ROLE_COLORS } from './sentinels3d.js'; import qrcode from './vendor/qrcode.mjs'; // Telefono o tablet: 3D alleggerito (un neurone ogni LITE_STRIDE) per restare fluido. const LITE = matchMedia('(max-width: 900px)').matches || /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent); const LITE_STRIDE = 8; const $ = (id) => document.getElementById(id); const fmt = (n) => n.toLocaleString('it-IT'); const REGION_COLORS = ['#5ce1e6', '#7b8cff', '#c77dff', '#ff6fb5', '#ffb347', '#9be15d', '#4dabf7', '#ff8c69', '#63e6be', '#e599f7', '#ffd43b', '#b2f2bb']; const GLOW_CAP = 40000; // neuroni accesi contemporaneamente al massimo const MARK_CAP = 20000; // neuroni modificati evidenziati const S = { nLayer: 0, nFF: 0, atlas: null, regionOfLayer: [], basePos: null, ws: null, generating: false, aiMsg: null, factors: new Map(), // chiave L*nFF+idx -> fattore eeg: new Float32Array(0), eegMax: new Float32Array(0), selected: null, // {L, idx} focusRegion: -1, tokCount: 0, tokStart: 0, blocks: [], // blocchi dal motore blockProgress: new Map(), // id -> messaggio di elaborazione in corso editing: new Set(), // blocchi di cui si sta cambiando la funzione focusBlock: -1, regions: [], // macroaree con le modifiche dell'utente regionBusy: new Map(), // id area -> id blocco in elaborazione (0 = in coda) ui: null, doctor: null, // stato dell'autodiagnosi e diario memory: null, // memoria a gruppi di neuroni memFocus: -1, // ricordo evidenziato nel 3D // modifica aperta: {kind: 'region'|'block', id, mode: 'rename'|'use'|'delete'|'function'} synapses: null, // ultime sinapsi calcolate per il neurone selezionato msgCount: 0, }; // ---------------------------------------------------------------- scena const canvas = $('scene'); const renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); renderer.setPixelRatio(LITE ? 1 : Math.min(devicePixelRatio, 2)); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200); camera.position.set(0, 5, 16); const controls = new OrbitControls(camera, canvas); controls.enableDamping = true; controls.autoRotate = true; controls.autoRotateSpeed = 0.35; let idleTimer; controls.addEventListener('start', () => { controls.autoRotate = false; clearTimeout(idleTimer); }); controls.addEventListener('end', () => { idleTimer = setTimeout(() => (controls.autoRotate = true), 20000); }); function glowSprite() { const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'); const grad = g.createRadialGradient(32, 32, 0, 32, 32, 32); grad.addColorStop(0, 'rgba(255,255,255,1)'); grad.addColorStop(0.25, 'rgba(255,255,255,0.55)'); grad.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = grad; g.fillRect(0, 0, 64, 64); return new THREE.CanvasTexture(c); } const sprite = glowSprite(); function pointsLayer(cap, material) { const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage)); geo.setAttribute('color', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage)); geo.setDrawRange(0, 0); const pts = new THREE.Points(geo, material); pts.frustumCulled = false; scene.add(pts); return pts; } let base = null; // tutti i neuroni const glow = pointsLayer(GLOW_CAP, new THREE.PointsMaterial({ size: 0.11, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false })); const marks = pointsLayer(MARK_CAP, new THREE.PointsMaterial({ size: 0.14, map: sprite, vertexColors: true, transparent: true, depthWrite: false, depthTest: false })); marks.renderOrder = 2; // sempre visibili, sopra l'attività const pick = pointsLayer(1, new THREE.PointsMaterial({ size: 0.45, map: sprite, color: 0xffffff, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending })); const posOf = (l, j) => { const k = (l * S.nFF + j) * 3; return [S.basePos[k], S.basePos[k + 1], S.basePos[k + 2]]; }; const particles = new Particles(scene, sprite); const blocksView = new BlocksView(scene, sprite, posOf); const sentinelsView = new SentinelsView(scene, sprite, posOf); let sentinelsKey = ''; function syncSentinels(force) { const d = S.doctor; const key = d ? JSON.stringify([d.network_on, d.groups.map((g) => [g.index, g.region, g.first, g.last, g.enabled])]) : ''; if (!force && key === sentinelsKey) return; sentinelsKey = key; sentinelsView.sync(d?.groups, S.nLayer, S.nFF, !!(d && d.network_on && S.basePos)); } const EXCITE = new THREE.Color('#bff6ff'), INHIBIT = new THREE.Color('#ff5c7a'); let synLines = null; // fili delle sinapsi del neurone selezionato // Esercitazione di infezione: neuroni infetti in verde tossico. const INFECT_GREEN = new THREE.Color('#7cff4f'), CURED_WHITE = new THREE.Color('#e8fbff'); const infGlow = pointsLayer(4000, new THREE.PointsMaterial({ size: 0.12, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false })); infGlow.renderOrder = 3; const BKEY = 16777216; // chiavi dei neuroni dei blocchi: BKEY + id * 1024 + indice function onInfection(ev) { if (!S.basePos) return; const nff = ev.neurons_per_layer; const at = (key) => { if (key < BKEY) return posOf(Math.floor(key / nff), key % nff); const v = blocksView.views.get(Math.floor((key - BKEY) / 1024)), k = (key - BKEY) % 1024; return v && k < v.block.neurons ? [v.pos[k * 3], v.pos[k * 3 + 1], v.pos[k * 3 + 2]] : null; }; const p = infGlow.geometry.attributes.position.array, c = infGlow.geometry.attributes.color.array; let n = 0; for (const key of ev.list) { const a = at(key); if (!a || n >= 4000) continue; p[n * 3] = a[0]; p[n * 3 + 1] = a[1]; p[n * 3 + 2] = a[2]; c[n * 3] = INFECT_GREEN.r; c[n * 3 + 1] = INFECT_GREEN.g; c[n * 3 + 2] = INFECT_GREEN.b; n++; } infGlow.geometry.attributes.position.needsUpdate = true; infGlow.geometry.attributes.color.needsUpdate = true; infGlow.geometry.setDrawRange(0, n); for (const [from, to] of ev.new) { const a = at(from), b = at(to); if (a && b) particles.spawn(a, b, INFECT_GREEN, 1, 0.7); } // contagio lungo la sinapsi for (const key of ev.cured) { const a = at(key); if (a) particles.spawn(a, [a[0], a[1] + 0.5, a[2]], CURED_WHITE, 1, 0.9); } // guarito const bar = $('infection-bar'); bar.hidden = !ev.on && !ev.healed; bar.classList.toggle('cured', !ev.on); $('inf-cure').hidden = !ev.on; $('inf-text').textContent = ev.on ? `Infezione: ${fmt(ev.infected)} neuroni infetti · ${fmt(ev.healed)} guariti · ${Math.round(ev.seconds)} s${ev.detected ? '' : ' · incubazione, i presidi non se ne sono ancora accorti'}` : `Infezione debellata: ${fmt(ev.healed)} neuroni guariti (massimo ${fmt(ev.peak)} infetti insieme)`; if (!ev.on) setTimeout(() => { if (!S.infOn) bar.hidden = true; }, 15000); S.infOn = ev.on; } $('inf-cure').onclick = () => send({ cmd: 'infect_cure' }); $('btn-infect').onclick = () => { if (S.selected) send({ cmd: 'infect', layer: S.selected.L, idx: S.selected.idx }); }; const MEM_GOLD = new THREE.Color('#ffd166'); const memGlow = pointsLayer(128 * 64, new THREE.PointsMaterial({ size: 0.07, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false })); memGlow.renderOrder = 3; let memGlowUntil = 0, memGlowPersist = false; // Accende tutti i neuroni dei gruppi indicati (128 per gruppo). function showMemoryGroups(groups, persist) { if (!S.basePos || !S.memory) return; const per = S.memory.per_layer, gs = S.memory.group_neurons; const p = memGlow.geometry.attributes.position.array, c = memGlow.geometry.attributes.color.array; let n = 0; for (const g of groups.slice(0, 64)) { const l = Math.floor(g / per), q = g % per; for (let j = q * gs; j < (q + 1) * gs && j < S.nFF; j++) { const k = (l * S.nFF + j) * 3; p[n * 3] = S.basePos[k]; p[n * 3 + 1] = S.basePos[k + 1]; p[n * 3 + 2] = S.basePos[k + 2]; c[n * 3] = MEM_GOLD.r; c[n * 3 + 1] = MEM_GOLD.g; c[n * 3 + 2] = MEM_GOLD.b; n++; } } memGlow.geometry.attributes.position.needsUpdate = true; memGlow.geometry.attributes.color.needsUpdate = true; memGlow.geometry.setDrawRange(0, n); memGlow.material.opacity = 1; memGlowPersist = persist; memGlowUntil = performance.now() + 4000; } const regionColor = (r) => new THREE.Color(REGION_COLORS[((r % REGION_COLORS.length) + REGION_COLORS.length) % REGION_COLORS.length]); // Disposizione: gli strati scorrono lungo x (dall'ingresso all'uscita), ogni strato è una sezione // ellittica del "cervello"; le macroaree sono separate da un piccolo solco, gli emisferi da una fessura. function buildBrain() { const { nLayer: L, nFF: F } = S; const total = L * F; const pos = new Float32Array(total * 3); const col = new Float32Array(total * 3); const span = 12, gap = 0.32; const nReg = S.atlas ? S.atlas.regions.length : 1; const golden = Math.PI * (3 - Math.sqrt(5)); const gray = new THREE.Color(0.24, 0.26, 0.29); const tmp = new THREE.Color(); let seed = 12345; const rand = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff); for (let l = 0; l < L; l++) { const r = S.regionOfLayer[l] ?? 0; const x = -span / 2 + (l / (L - 1)) * span + (r - (nReg - 1) / 2) * gap; const t = (l + 0.5) / L; const radius = 0.55 + 2.4 * Math.pow(Math.sin(Math.PI * (0.06 + 0.88 * t)), 0.55); const state = S.regions[r]?.state; tmp.copy(gray).lerp(regionColor(r), r === S.focusRegion ? 0.55 : state === 'modificata' ? 0.45 : 0.2); if (S.focusRegion >= 0 && r !== S.focusRegion) tmp.multiplyScalar(0.45); if (state === 'eliminata') tmp.multiplyScalar(0.35); // specializzazione spenta if (state === 'eliminata_tutta') tmp.setRGB(0.07, 0.07, 0.08); // area spenta del tutto for (let j = 0; j < F; j++) { const i = l * F + j; const rr = radius * Math.sqrt((j + 0.5) / F); const th = j * golden; let z = rr * Math.cos(th); z += Math.sign(z) * 0.18; // fessura tra gli emisferi pos[i * 3] = x + (rand() - 0.5) * (span / (L - 1)); pos[i * 3 + 1] = rr * Math.sin(th) * 0.8; pos[i * 3 + 2] = z; const shade = 0.75 + rand() * 0.5; col[i * 3] = tmp.r * shade; col[i * 3 + 1] = tmp.g * shade; col[i * 3 + 2] = tmp.b * shade; } } S.basePos = pos; if (base) { scene.remove(base); base.geometry.dispose(); } // sul telefono si disegna un neurone ogni LITE_STRIDE; le posizioni di tutti restano per attività e selezione let dpos = pos, dcol = col; S.displayKey = null; if (LITE) { const n = Math.ceil(total / LITE_STRIDE); dpos = new Float32Array(n * 3); dcol = new Float32Array(n * 3); S.displayKey = new Int32Array(n); for (let k = 0, i = 0; i < total; i += LITE_STRIDE, k++) { S.displayKey[k] = i; dpos.set(pos.subarray(i * 3, i * 3 + 3), k * 3); dcol.set(col.subarray(i * 3, i * 3 + 3), k * 3); } } const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(dpos, 3)); geo.setAttribute('color', new THREE.BufferAttribute(dcol, 3)); geo.computeBoundingSphere(); base = new THREE.Points(geo, new THREE.PointsMaterial({ size: LITE ? 0.022 : 0.011, vertexColors: true, transparent: true, opacity: 0.6, depthWrite: false })); scene.add(base); glowReset(); renderMarks(); renderPick(); particles.clear(); blocksView.sync(S.blocks, true); syncSentinels(true); drawSynapses(); $('st-neurons').textContent = fmt(total); } // ---------------------------------------------------------------- neuroni accesi const glowSlot = new Map(); // chiave -> slot const glowKey = new Int32Array(GLOW_CAP); const glowInt = new Float32Array(GLOW_CAP); let glowN = 0; function glowReset() { glowSlot.clear(); glowN = 0; glow.geometry.setDrawRange(0, 0); } function light(l, j, v) { const key = l * S.nFF + j; let s = glowSlot.get(key); if (s === undefined) { if (glowN >= GLOW_CAP) return; s = glowN++; glowSlot.set(key, s); glowKey[s] = key; glowInt[s] = 0; const p = glow.geometry.attributes.position.array; p[s * 3] = S.basePos[key * 3]; p[s * 3 + 1] = S.basePos[key * 3 + 1]; p[s * 3 + 2] = S.basePos[key * 3 + 2]; glow.geometry.attributes.position.needsUpdate = true; } glowInt[s] = Math.max(glowInt[s], v); } function glowUpdate(dt) { const decay = Math.pow(0.015, dt); // ~0.25 s di persistenza: si vede il flusso, non una nebbia const p = glow.geometry.attributes.position.array; const c = glow.geometry.attributes.color.array; let moved = false; for (let s = 0; s < glowN; s++) { glowInt[s] *= decay; if (glowInt[s] < 0.04) { // spento: sposta l'ultimo al suo posto glowSlot.delete(glowKey[s]); const last = --glowN; if (s !== last) { glowKey[s] = glowKey[last]; glowInt[s] = glowInt[last]; glowSlot.set(glowKey[s], s); p[s * 3] = p[last * 3]; p[s * 3 + 1] = p[last * 3 + 1]; p[s * 3 + 2] = p[last * 3 + 2]; moved = true; } s--; continue; } const v = glowInt[s]; const rc = regionColor(S.regionOfLayer[Math.floor(glowKey[s] / S.nFF)] ?? 0); const w = v * v * v * 0.7; // i più intensi virano al bianco c[s * 3] = rc.r * v + w; c[s * 3 + 1] = rc.g * v + w; c[s * 3 + 2] = rc.b * v + w; } if (moved) glow.geometry.attributes.position.needsUpdate = true; glow.geometry.attributes.color.needsUpdate = true; glow.geometry.setDrawRange(0, glowN); $('st-active').textContent = fmt(glowN); } // ---------------------------------------------------------------- neuroni modificati e selezione const markColor = (f) => (f === 0 ? new THREE.Color('#ff5c7a') : f > 1 ? new THREE.Color('#5ce1e6') : new THREE.Color('#ffb347')); function renderMarks() { if (!S.basePos) return; const p = marks.geometry.attributes.position.array; const c = marks.geometry.attributes.color.array; let n = 0; for (const [key, f] of S.factors) { if (n >= MARK_CAP) break; const col = markColor(f); p[n * 3] = S.basePos[key * 3]; p[n * 3 + 1] = S.basePos[key * 3 + 1]; p[n * 3 + 2] = S.basePos[key * 3 + 2]; c[n * 3] = col.r; c[n * 3 + 1] = col.g; c[n * 3 + 2] = col.b; n++; } marks.geometry.attributes.position.needsUpdate = true; marks.geometry.attributes.color.needsUpdate = true; marks.geometry.setDrawRange(0, n); } function renderPick() { const sel = S.selected; if (!sel || !S.basePos) { pick.geometry.setDrawRange(0, 0); return; } const key = sel.L * S.nFF + sel.idx; const p = pick.geometry.attributes.position.array; p[0] = S.basePos[key * 3]; p[1] = S.basePos[key * 3 + 1]; p[2] = S.basePos[key * 3 + 2]; pick.geometry.attributes.position.needsUpdate = true; pick.geometry.setDrawRange(0, 1); } const raycaster = new THREE.Raycaster(); raycaster.params.Points.threshold = 0.05; let downAt = null; canvas.addEventListener('pointerdown', (e) => (downAt = [e.clientX, e.clientY])); canvas.addEventListener('pointerup', (e) => { if (!downAt || !base || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 4) return; const r = canvas.getBoundingClientRect(); raycaster.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera); const shit = raycaster.intersectObjects(sentinelsView.pickables)[0]; if (shit) { showTab('blocks'); document.getElementById('diagnosis')?.scrollIntoView({ behavior: 'smooth' }); return; } const bhit = raycaster.intersectObjects(blocksView.pickables)[0]; const hit = raycaster.intersectObject(base)[0]; if (bhit && (!hit || bhit.distance <= hit.distance)) { S.blockNeuron = { id: bhit.object.userData.blockId, k: bhit.index }; openBlock(bhit.object.userData.blockId); return; } if (!hit) return; const key = S.displayKey ? S.displayKey[hit.index] : hit.index; select(Math.floor(key / S.nFF), key % S.nFF); }); function regionName(l) { const r = S.regionOfLayer[l]; return S.atlas && r !== undefined ? S.atlas.regions[r].name : '—'; } function describeFactor(f) { if (f === undefined || f === 1) return 'normale'; if (f === 0) return 'spento'; if (f < 0) return `invertito (×${f})`; return f > 1 ? `amplificato ×${f}` : `ridotto ×${f}`; } function select(l, j) { S.selected = { L: l, idx: j }; S.synapses = null; $('syn-list').replaceChildren(); $('btn-syn').textContent = 'Mostra le sinapsi'; drawSynapses(); $('inspector').hidden = false; $('insp-title').textContent = `Neurone ${fmt(j)}`; $('insp-sub').textContent = `strato ${l} · ${regionName(l)}`; refreshInspector(); renderPick(); } function refreshInspector() { const sel = S.selected; if (!sel) return; const key = sel.L * S.nFF + sel.idx; $('insp-state').textContent = describeFactor(S.factors.get(key)); const s = glowSlot.get(key); $('insp-act').textContent = s === undefined ? 'a riposo' : `${Math.round(glowInt[s] * 100)}% del massimo dello strato`; // ogni neurone ha un indirizzo e sa dove si trova il suo pezzo di memoria sul disco $('insp-addr').textContent = `n. ${fmt(key)}`; if (S.memory) { const per = S.memory.per_layer, gs = S.memory.group_neurons, q = Math.floor(sel.idx / gs), g = sel.L * per + q; const owner = S.memory.memories.find((m) => m.groups.includes(g)); $('insp-group').textContent = `n. ${fmt(g)} (${gs} neuroni, ${S.memory.slot_bits} bit)${owner ? ` · custodisce «${owner.title}»` : ' · libero'}`; $('insp-disk').textContent = `memoria/strato_${String(sel.L).padStart(2, '0')}.bin, byte ${q * (S.memory.slot_bits / 8)}–${(q + 1) * (S.memory.slot_bits / 8) - 1}`; } } $('insp-close').onclick = () => { S.selected = null; S.synapses = null; $('inspector').hidden = true; renderPick(); drawSynapses(); }; // ---------------------------------------------------------------- sinapsi del neurone selezionato $('btn-syn').onclick = () => { if (!S.selected) return; $('btn-syn').textContent = 'Calcolo dai pesi del modello…'; send({ cmd: 'synapses', layer: S.selected.L, idx: S.selected.idx }); }; function onSynapses(ev) { if (!S.selected || ev.layer !== S.selected.L || ev.idx !== S.selected.idx) return; S.synapses = ev; $('btn-syn').textContent = `Ricalcola (${ev.seconds.toFixed(2)} s)`; const list = $('syn-list'); list.replaceChildren(); const section = (title, items, dirIn) => { const box = document.createElement('div'); box.innerHTML = `

${title}

`; for (const [l, j, w] of items.slice(0, 6)) { const b = document.createElement('button'); b.innerHTML = `strato ${l} · neurone ${fmt(j)}${w >= 0 ? '+' : ''}${w.toFixed(3)}`; b.title = (w >= 0 ? 'eccitatoria' : 'inibitoria') + ' — clicca per andare a quel neurone'; b.onclick = () => select(l, j); box.append(b); } list.append(box); }; section('Riceve da (strato precedente)', ev.in, true); section('Invia a (strato successivo)', ev.out, false); drawSynapses(); // un'ondata di messaggi lungo le sinapsi appena scoperte const me = posOf(ev.layer, ev.idx); const maxw = Math.max(1e-9, ...ev.in.map((x) => Math.abs(x[2])), ...ev.out.map((x) => Math.abs(x[2]))); for (const [l, j, w] of ev.in) particles.spawn(posOf(l, j), me, w >= 0 ? EXCITE : INHIBIT, Math.abs(w) / maxw, 1.1); for (const [l, j, w] of ev.out) particles.spawn(me, posOf(l, j), w >= 0 ? EXCITE : INHIBIT, Math.abs(w) / maxw, 1.1); } function drawSynapses() { if (synLines) { scene.remove(synLines); synLines.geometry.dispose(); synLines.material.dispose(); synLines = null; } const ev = S.synapses; if (!ev || !S.basePos) return; const me = posOf(ev.layer, ev.idx); const pos = [], col = []; const maxw = Math.max(1e-9, ...ev.in.map((x) => Math.abs(x[2])), ...ev.out.map((x) => Math.abs(x[2]))); const add = (a, b, w) => { const c = (w >= 0 ? EXCITE : INHIBIT).clone().multiplyScalar(0.25 + 0.75 * Math.abs(w) / maxw); pos.push(...a, ...b); col.push(c.r, c.g, c.b, c.r, c.g, c.b); }; for (const [l, j, w] of ev.in) add(posOf(l, j), me, w); for (const [l, j, w] of ev.out) add(me, posOf(l, j), w); const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(col, 3)); synLines = new THREE.LineSegments(g, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.85, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false })); synLines.renderOrder = 2; scene.add(synLines); } document.querySelectorAll('#inspector [data-factor]').forEach((b) => (b.onclick = () => { if (!S.selected) return; send({ cmd: 'neurons', layer: S.selected.L, idx: [S.selected.idx], factor: Number(b.dataset.factor) }); })); document.querySelectorAll('#inspector [data-top]').forEach((b) => (b.onclick = () => { if (!S.selected) return; send({ cmd: 'neurons', layer: S.selected.L, top: Number(b.dataset.top), factor: Number(b.dataset.topfactor) }); })); $('btn-undo').onclick = () => send({ cmd: 'undo' }); $('btn-reset').onclick = () => { if (confirm('Riportare tutti i neuroni allo stato originale? Non si può annullare.')) send({ cmd: 'reset' }); }; $('btn-remap').onclick = () => { showBoot('Rimappatura del cervello in corso…'); send({ cmd: 'remap' }); }; // ---------------------------------------------------------------- attività per strato (EEG) const eeg = $('eeg'); function drawEEG() { const dpr = Math.min(devicePixelRatio, 2); const w = eeg.clientWidth, h = eeg.clientHeight; if (eeg.width !== w * dpr) { eeg.width = w * dpr; eeg.height = h * dpr; } const g = eeg.getContext('2d'); g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, w, h); const L = S.nLayer; if (!L) return; const bw = w / L; for (let l = 0; l < L; l++) { const v = S.eegMax[l] > 0 ? S.eeg[l] / S.eegMax[l] : 0; const bh = Math.max(1, v * (h - 12)); g.fillStyle = REGION_COLORS[(S.regionOfLayer[l] ?? 0) % REGION_COLORS.length]; g.globalAlpha = 0.25 + 0.75 * v; g.fillRect(l * bw + 1, h - 12 - bh, Math.max(1, bw - 2), bh); } g.globalAlpha = 1; g.fillStyle = '#7d8a9c'; g.font = '10px Consolas, monospace'; g.fillText('strato 0', 0, h - 1); g.textAlign = 'right'; g.fillText(`strato ${L - 1}`, w, h - 1); } // ---------------------------------------------------------------- frame di attività // header: u8 'A', u8 versione, u16 strati, u16 k, u16 0, u32 seq; per strato: f32 media, u16 idx[k], f32 val[k] function onFrame(buf) { const dv = new DataView(buf); if (dv.getUint8(0) === 80) return playVoice(buf); // 'P': la voce di Neuronal nella chiamata if (!S.basePos || dv.getUint8(1) !== 1) return; const kind = dv.getUint8(0); if (kind === 83) return onMessages(dv); // 'S' if (kind === 67) return onBlockFrame(dv); // 'C' if (kind === 68) return sentinelsView.onFrame(dv); // 'D' if (kind !== 65) return; // 'A' const L = dv.getUint16(2, true), k = dv.getUint16(4, true); const per = 4 + 6 * k; for (let l = 0; l < L; l++) { const o = 12 + l * per; const mean = dv.getFloat32(o, true); S.eeg[l] = S.eeg[l] * 0.5 + mean * 0.5; S.eegMax[l] = Math.max(S.eegMax[l] * 0.999, S.eeg[l]); const top = Math.abs(dv.getFloat32(o + 4 + 2 * k, true)) || 1; for (let t = 0; t < k; t++) { const idx = dv.getUint16(o + 4 + 2 * t, true); const v = Math.abs(dv.getFloat32(o + 4 + 2 * k + 4 * t, true)) / top; if (v > 0.3) light(l, idx, v); // solo i neuroni davvero dominanti nello strato } } } // Messaggi tra neuroni lungo sinapsi reali: u16 n, u32 seq; per messaggio u16 strato, u16 da, u16 a, i16 forza function onMessages(dv) { const n = dv.getUint16(2, true); for (let k = 0; k < n; k++) { const o = 8 + k * 8; const l = dv.getUint16(o, true), i = dv.getUint16(o + 2, true), j = dv.getUint16(o + 4, true); const f = dv.getInt16(o + 6, true) / 32767; if (l + 1 >= S.nLayer) continue; particles.spawn(posOf(l, i), posOf(l + 1, j), f >= 0 ? EXCITE : INHIBIT, Math.abs(f), 0.55); S.msgCount++; } } // Attivazione dei neuroni dei blocchi: u16 blocchi, u32 seq; per blocco u16 id, u16 n, f32 att[n] function onBlockFrame(dv) { const nb = dv.getUint16(2, true); let o = 8; for (let b = 0; b < nb; b++) { const id = dv.getUint16(o, true), n = dv.getUint16(o + 2, true); o += 4; const vals = new Float32Array(n); for (let k = 0; k < n; k++) vals[k] = dv.getFloat32(o + 4 * k, true); o += 4 * n; blocksView.setActivations(id, vals); } } // ---------------------------------------------------------------- blocchi $('new-block').onsubmit = (e) => { e.preventDefault(); const n = Number($('nb-n').value); if (!(n >= 1 && n <= 512)) return; send({ cmd: 'block_create', neurons: n, name: $('nb-name').value.trim() }); $('nb-name').value = ''; }; function openBlock(id) { S.focusBlock = id; showTab('blocks'); renderBlocks(); const c = blocksView.focus(id); if (c) controls.target.set(c[0], c[1] * 0.5, 0); document.querySelector(`.block[data-id="${id}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } const STATE_LABEL = { normale: 'originale', modificata: 'nuovo utilizzo', eliminata: 'eliminata · specializzazione spenta', eliminata_tutta: 'eliminata completamente', }; const isUi = (kind, id, mode) => S.ui && S.ui.kind === kind && S.ui.id === id && (!mode || S.ui.mode === mode); const openUi = (kind, id, mode) => { S.ui = isUi(kind, id, mode) ? null : { kind, id, mode }; renderBlocks(); }; // Controlli comuni di un blocco applicato: acceso, intensità, prova di Neuronal, esempi. function blockControls(b) { return `
Si attiva nel ${Math.round(b.pos_rate * 100)}% degli esempi della funzione e nel ${Math.round(b.neg_rate * 100)}% dei testi neutri · ${fmt(b.neurons)} neuroni negli strati ${b.first}–${b.last}
Come lo usa Neuronal

${esc(b.effect)}

Esempi elaborati da Neuronal (${b.examples.length})
`; } function renameForm(name) { return `
`; } function examplesField() { return `
Aggiungi esempi tuoi (facoltativo, uno per riga)
`; } const readExamples = (li) => (li.querySelector('[data-act="examples"]')?.value || '').split('\n').map((x) => x.trim()).filter(Boolean); function wireBlockControls(li, b) { li.querySelector('[data-act="enabled"]')?.addEventListener('change', (e) => send({ cmd: 'block_set', id: b.id, enabled: e.target.checked })); const g = li.querySelector('[data-act="gain"]'); if (g) { g.oninput = () => (g.nextElementSibling.textContent = '×' + Number(g.value).toFixed(1)); g.onchange = () => send({ cmd: 'block_set', id: b.id, gain: Number(g.value) }); } li.querySelector('[data-act="infect"]')?.addEventListener('click', () => { const k = S.blockNeuron?.id === b.id ? S.blockNeuron.k : Math.floor(Math.random() * b.neurons); send({ cmd: 'infect', block: b.id, k }); }); } const HEALTH = { ok: ['live', 'in salute'], controllo: ['busy', 'si sta controllando…'], riparato: ['live', 'riparato da solo'], problema: ['danger', 'problema non risolto'], riavvio: ['busy', 'si sta riavviando'], spento: ['', 'autodiagnosi spenta'], }; // "Sospeso da Neuronal" con la possibilità di riattivare comunque. function autoNote(reason, kind, id) { return `
Neuronal: ${esc(reason)}
`; } function wireForce(el) { el.querySelectorAll('[data-force]').forEach((b) => (b.onclick = () => { if (confirm('Riattivare comunque? Neuronal aveva rilevato che gli impediva di funzionare bene. Rispetterà la tua scelta fino al prossimo riavvio.')) send({ cmd: 'doctor_force', kind: b.dataset.force, id: Number(b.dataset.id) }); })); } const ROLE_LABELS = [['analisi', 'analisi'], ['controllo', 'controllo'], ['sicurezza', 'sicurezza'], ['riparazione', 'riparazione'], ['coordinamento', 'nucleo']]; const when = (t) => (t ? new Date(t * 1000).toLocaleString('it-IT', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit' }) : 'mai'); function renderDiagnosisCard() { const li = document.createElement('li'); li.className = 'block diag'; const d = S.doctor; if (!d) { li.textContent = 'Rete della Diagnosi: in attesa del motore…'; return li; } const [cls, label] = HEALTH[d.status] || ['', d.status]; const legend = ROLE_LABELS.map(([r, l]) => `${l}`).join(''); let html = `
Rete della Diagnosi ${Math.max(0, d.groups.length - 1)} presidi + nucleo
${label}
Presidi di neuroni sentinella distribuiti dentro ogni macroarea e coordinati da un nucleo centrale. Ogni presidio analizza l'attività dei suoi strati, controlla che la sua area funzioni, verifica la sicurezza dei suoi pesi e ripara o ricostruisce quando serve.
${legend}
${d.last_check ? `ultimo controllo ${when(d.last_check)}` : ''}
`; if (d.network_on) { html += ''; html += `
Sicurezza dei pesi: ${esc(d.security || 'non ancora controllata')} ${d.security_t ? `(${when(d.security_t)})` : ''} ${d.security_running ? ' · controllo in corso…' : ''}
Punto di ripristino sano: ${when(d.snapshot)}
`; } // tutto quello che la rete ha sospeso o attenuato const notes = []; if (d.interventions_suspended) notes.push(autoNote('ha sospeso i tuoi interventi manuali sui neuroni (non cancellati).', 'interventions', 0)); for (const r of S.regions) if (r.auto_off || r.auto_state !== 'normale' || r.auto_keep_old) notes.push(autoNote(r.auto_reason, 'region', r.id)); for (const b of S.blocks) if (b.auto_off || b.auto_gain > 0) notes.push(autoNote(b.auto_reason, 'block', b.id)); if (notes.length) html += `
${notes.join('')}
`; const journal = (d.journal || []).slice().reverse(); if (journal.length) { const line = (e) => `
  • ${esc(e.text)}
  • `; html += ``; if (journal.length > 5) html += `
    Diario completo (${journal.length})
    `; } if (d.network_on) html += `
    `; li.innerHTML = html; li.querySelector('[data-act="network"]').onchange = (e) => { if (!e.target.checked && !confirm('Spegnere la Rete della Diagnosi? Neuronal smetterà di controllarsi, proteggersi e ripararsi da solo.')) { e.target.checked = true; return; } send({ cmd: e.target.checked ? 'network_on' : 'network_off' }); }; li.querySelectorAll('[data-group]').forEach((el) => (el.onchange = () => send({ cmd: 'sentinel_set', index: Number(el.dataset.group), enabled: el.checked }))); li.querySelector('[data-act="check"]')?.addEventListener('click', () => send({ cmd: 'doctor' })); li.querySelector('[data-act="security"]')?.addEventListener('click', () => send({ cmd: 'security_check' })); li.querySelector('[data-act="rebuild"]')?.addEventListener('click', () => { if (confirm(`Ricostruire tutto com'era all'ultimo punto sano (${when(d.snapshot)})? Blocchi e macroaree torneranno a quello stato e il motore si riavvierà.`)) send({ cmd: 'reconstruct' }); }); wireForce(li); return li; } function renderRegionCard(r, i) { const li = document.createElement('li'); li.className = 'block' + (i === S.focusRegion ? ' focus' : ''); const blk = r.block ? S.blocks.find((b) => b.id === r.block) : null; const busyBlock = S.regionBusy.get(r.id); const busy = busyBlock !== undefined ? (S.blockProgress.get(busyBlock) || 'In coda: Neuronal inizierà appena libero…') : null; const renamed = r.name !== r.original_name; let html = `
    ${esc(r.name)}strati ${r.first}–${r.last}
    ${STATE_LABEL[r.state] || ''}${renamed ? `
    nome originale: ${esc(r.original_name)}
    ` : ''}
    ${esc(r.function)}
    `; if (r.auto_off || r.auto_state !== 'normale' || r.auto_keep_old) html += autoNote(r.auto_reason, 'region', r.id); if (r.state === 'modificata') { html += `
    ${r.replace ? 'Sostituisce' : 'Si aggiunge a'} la funzione originale: «${esc(r.original_function)}»
    `; if (blk && blk.applied) html += blockControls(blk); } else { html += `
    ${fmt(r.selective)} neuroni specializzati
    `; } if (busy) html += `
    ${esc(busy)}
    `; else if (isUi('region', r.id, 'rename')) html += renameForm(r.name); else if (isUi('region', r.id, 'use')) { html += `
    Se sostituisce, i ${fmt(r.selective)} neuroni specializzati dell'area vengono attenuati al 30%; altrimenti la nuova funzione si aggiunge.
    ${examplesField()}
    `; } else if (isUi('region', r.id, 'delete')) { html += `
    Eliminare «${esc(r.name)}»?

    Solo la specializzazione: si spengono i suoi ${fmt(r.selective)} neuroni specializzati. Neuronal continua a funzionare ma perde questa capacità.

    Completamente: si spengono tutti i ${fmt((r.last - r.first + 1) * S.nFF)} neuroni dell'area. Nelle prove Neuronal ha cominciato a sbagliare o è rimasto muto. Puoi sempre ripristinarla.

    `; } else { html += '
    '; html += ''; html += ''; if (!r.state.startsWith('eliminata')) html += ''; if (r.state !== 'normale' || renamed) html += ''; html += '
    '; } li.innerHTML = html; if (blk) wireBlockControls(li, blk); wireForce(li); const on = (act, fn) => li.querySelector(`[data-act="${act}"]`)?.addEventListener('click', fn); on('rename', () => openUi('region', r.id, 'rename')); on('use', () => openUi('region', r.id, 'use')); on('delete', () => openUi('region', r.id, 'delete')); on('cancel', () => { S.ui = null; renderBlocks(); }); on('show', () => { showTab('atlas'); focusRegion(i); }); on('save-name', () => { const name = li.querySelector('[data-act="name"]').value.trim(); if (name) send({ cmd: 'region_rename', id: r.id, name }); S.ui = null; }); on('apply', () => { const fn = li.querySelector('[data-act="function"]').value.trim(); if (fn.length < 3) { li.querySelector('[data-act="function"]').focus(); return; } send({ cmd: 'region_apply', id: r.id, function: fn, examples: readExamples(li), neurons: Number(li.querySelector('[data-act="neurons"]').value) || 64, replace: li.querySelector('[data-act="replace"]').checked }); S.ui = null; S.regionBusy.set(r.id, 0); renderBlocks(); }); on('del-spec', () => { send({ cmd: 'region_delete', id: r.id, total: false }); S.ui = null; }); on('del-all', () => { send({ cmd: 'region_delete', id: r.id, total: true }); S.ui = null; }); on('restore', () => { if (!confirm(`Riportare «${r.name}» allo stato originale misurato?`)) return; send({ cmd: 'region_restore', id: r.id }); if (renamed) send({ cmd: 'region_rename', id: r.id, name: r.original_name }); }); return li; } function renderBlockCard(b, order) { const li = document.createElement('li'); li.className = 'block' + (b.id === S.focusBlock ? ' focus' : ''); li.dataset.id = b.id; const busy = S.blockProgress.get(b.id); const editing = !b.applied || isUi('block', b.id, 'function'); const status = busy ? 'in elaborazione' : !b.applied ? 'in attesa di una funzione' : b.enabled ? `attivo · strati ${b.first}–${b.last}` : 'spento'; let html = `
    ${esc(b.name)}${fmt(b.neurons)} neuroni
    ${status}`; if (b.applied) html += `
    ${esc(b.function)}
    ` + blockControls(b); if (b.auto_off || b.auto_gain > 0) html += autoNote(b.auto_reason, 'block', b.id); if (busy) html += `
    ${esc(busy)}
    `; else if (isUi('block', b.id, 'rename')) html += renameForm(b.name); else if (editing) { html += `
    ${examplesField()}
    ${b.applied ? '' : ''}
    `; } else { html += `
    `; } li.innerHTML = html; if (b.applied) wireBlockControls(li, b); wireForce(li); const on = (act, fn) => li.querySelector(`[data-act="${act}"]`)?.addEventListener('click', fn); on('edit', () => openUi('block', b.id, 'function')); on('rename', () => openUi('block', b.id, 'rename')); on('cancel', () => { S.ui = null; renderBlocks(); }); on('show', () => openBlock(b.id)); on('save-name', () => { const name = li.querySelector('[data-act="name"]').value.trim(); if (name) send({ cmd: 'block_rename', id: b.id, name }); S.ui = null; }); on('apply', () => { const fnEl = li.querySelector('[data-act="function"]'); const fn = fnEl.value.trim(); if (fn.length < 3) { fnEl.focus(); return; } S.ui = null; S.blockProgress.set(b.id, 'Invio a Neuronal…'); send({ cmd: 'block_apply', id: b.id, function: fn, examples: readExamples(li), neurons: Number(li.querySelector('[data-act="neurons"]').value) || b.neurons }); renderBlocks(); }); on('delete', () => { if (confirm(`Eliminare il blocco «${b.name}» e i suoi ${b.neurons} neuroni?`)) send({ cmd: 'block_delete', id: b.id }); }); return li; } function renderBlocks() { const panel = $('panel-blocks'); const active = document.activeElement; if (panel.contains(active) && (active.tagName === 'TEXTAREA' || (active.tagName === 'INPUT' && active.type === 'text'))) return; // non interrompere chi scrive const regionsList = $('regions-edit'), list = $('blocks'); $('diagnosis').replaceChildren(renderDiagnosisCard()); regionsList.replaceChildren(...S.regions.map((r, i) => renderRegionCard(r, i))); const created = S.blocks.map((b, order) => [b, order]).filter(([b]) => !b.region); if (!created.length) { const li = document.createElement('li'); li.className = 'hint'; li.textContent = 'Nessun blocco creato. Scegli quanti neuroni vuoi e premi «Crea blocco».'; list.replaceChildren(li); } else { list.replaceChildren(...created.map(([b, order]) => renderBlockCard(b, order))); } } // ---------------------------------------------------------------- mappa function applyAtlas(atlas) { S.atlas = atlas; S.regionOfLayer = []; if (atlas) atlas.regions.forEach((r, i) => { for (let l = r.first; l <= r.last; l++) S.regionOfLayer[l] = i; }); if (S.nLayer) buildBrain(); renderAtlasPanel(); } function renderAtlasPanel() { const a = S.atlas; const list = $('regions'), nets = $('networks'); list.replaceChildren(); nets.replaceChildren(); if (!a) { $('atlas-intro').textContent = 'Mappa non ancora disponibile.'; return; } const selective = a.regions.reduce((s, r) => s + r.selective, 0); $('atlas-intro').textContent = `Misurata all'avvio: ${a.regions.length} macroaree su ${a.layers} strati. ` + `${fmt(selective)} neuroni su ${fmt(a.layers * a.neurons_per_layer)} sono specializzati. ` + `Nomi e funzioni li ha scelti il modello stesso guardando i dati.`; a.regions.forEach((r, i) => { const li = document.createElement('li'); li.className = 'region' + (i === S.focusRegion ? ' focus' : ''); li.tabIndex = 0; const chips = r.specialization.map((s) => `${esc(s.category)} ×${s.enrichment.toFixed(1)}`).join('') || 'nessuna specializzazione netta'; const cur = S.regions[i]; const shownName = cur ? cur.name : r.name, shownFn = cur ? cur.function : r.function; const chip = cur && cur.state !== 'normale' ? STATE_LABEL[cur.state] : ''; li.innerHTML = `
    ${esc(shownName)}strati ${r.first}–${r.last}
    ${chip}
    ${esc(shownFn)}
    ${chips}
    `; const go = () => focusRegion(i === S.focusRegion ? -1 : i); li.onclick = go; li.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }; list.append(li); }); for (const n of a.networks) { const max = Math.max(1, ...n.per_layer); const li = document.createElement('li'); li.className = 'net-row'; li.title = `picco allo strato ${n.peak_layer}, estensione ${n.span[0]}–${n.span[1]}`; li.innerHTML = `${esc(n.category)}${n.per_layer.map((v) => ``).join('')}${fmt(n.selective)}`; nets.append(li); } } function focusRegion(i) { S.focusRegion = i; buildBrain(); renderAtlasPanel(); if (i >= 0) { const r = S.atlas.regions[i]; const mid = Math.floor((r.first + r.last) / 2) * S.nFF * 3; controls.target.set(S.basePos[mid], 0, 0); } else { controls.target.set(0, 0, 0); } } // ---------------------------------------------------------------- schede const tabs = [...document.querySelectorAll('.tab')]; function showTab(name) { for (const t of tabs) { const on = t.dataset.tab === name; t.classList.toggle('active', on); t.setAttribute('aria-selected', on); $('panel-' + t.dataset.tab).hidden = !on; } if (name === 'procs') { renderLog(true); send({ cmd: 'logs' }); } } tabs.forEach((t) => (t.onclick = () => showTab(t.dataset.tab))); if (location.hash === '#mappa') showTab('atlas'); if (location.hash === '#blocchi') showTab('blocks'); if (location.hash === '#permessi') showTab('perms'); if (location.hash === '#memoria') showTab('memory'); // ---------------------------------------------------------------- memoria $('mem-form').onsubmit = (e) => { e.preventDefault(); const text = $('mem-text').value.trim(); if (!text) return; send({ cmd: 'memory_add', title: $('mem-title').value.trim(), text }); $('mem-text').value = ''; $('mem-title').value = ''; }; $('mem-test-form').onsubmit = (e) => { e.preventDefault(); const text = $('mem-test').value.trim(); if (text) { $('mem-test-out').textContent = 'Il navigatore cerca…'; send({ cmd: 'memory_test', text }); } }; function renderMemory() { const m = S.memory; if (!m) return; const usedBytes = m.used * (m.slot_bits / 8); $('mem-intro').innerHTML = `Ogni neurone ha un indirizzo. I neuroni sono divisi in ${fmt(m.groups)} gruppi da ${m.group_neurons}, ognuno con ${m.slot_bits} bit sul disco (un file per strato): in tutto ${fmt(m.capacity_bytes)} byte. Occupati ${fmt(m.used)} gruppi (${fmt(usedBytes)} byte). Quando fai una domanda, il navigatore trova i gruppi che custodiscono il ricordo giusto e lo ricompone.`; const list = $('memories'); list.replaceChildren(); if (!m.memories.length) { const li = document.createElement('li'); li.className = 'hint'; li.textContent = 'Nessun ricordo ancora.'; list.append(li); return; } for (const mem of m.memories.slice().sort((a, b) => b.t - a.t)) { const per = m.per_layer; const files = [...new Set(mem.groups.map((g) => `strato_${String(Math.floor(g / per)).padStart(2, '0')}.bin`))]; const li = document.createElement('li'); li.className = 'block' + (mem.id === S.memFocus ? ' focus' : ''); li.innerHTML = `
    ${esc(mem.title)} ${mem.bytes} byte · ${mem.groups.length} gruppi
    ${mem.intact ? '' : 'bit danneggiati'}
    ${esc(mem.text)}
    gruppi ${mem.groups.map((g) => fmt(g)).join(', ')} · file ${files.join(', ')}
    `; li.querySelector('[data-act="show"]').onclick = () => { if (S.memFocus === mem.id) { S.memFocus = -1; memGlowPersist = false; memGlowUntil = performance.now(); } else { S.memFocus = mem.id; showMemoryGroups(mem.groups, true); } renderMemory(); }; li.querySelector('[data-act="delete"]').onclick = () => { if (confirm(`Far dimenticare a Neuronal «${mem.title}»? I suoi ${mem.groups.length} gruppi tornano liberi.`)) send({ cmd: 'memory_delete', id: mem.id }); }; list.append(li); } } $('st-health').onclick = () => showTab('blocks'); const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); // ---------------------------------------------------------------- chat condivisa const input = $('input'), sendBtn = $('send'), messages = $('messages'); const aiMsgs = new Map(); // richiesta -> messaggio di Neuronal in costruzione const pending = new Set(); // richieste non ancora concluse (da qualsiasi dispositivo) function addMsg(cls, text) { $('empty')?.remove(); const d = document.createElement('div'); d.className = 'msg ' + cls; if (cls === 'doctor-msg') d.onclick = () => { showTab('blocks'); }; d.textContent = text; messages.append(d); messages.scrollTop = messages.scrollHeight; return d; } function userMsg(device, voice, text) { const d = addMsg('user', ''); d.innerHTML = `
    ${esc(device || '')}${voice ? ' · 🎙 a voce' : ''}
    `; d.append(document.createTextNode(text)); messages.scrollTop = messages.scrollHeight; } function startAiMsg(voice) { $('empty')?.remove(); const d = document.createElement('div'); d.className = 'msg ai'; d.innerHTML = `
    NEURONAL${voice ? ' · 🔊' : ''}
    `; messages.append(d); return { el: d, body: d.querySelector('.body'), thought: d.querySelector('.thought'), thoughtText: d.querySelector('.thought div'), words: 0, tok: 0, t0: performance.now() }; } const aiFor = (ev) => { let m = aiMsgs.get(ev.req); if (!m) { m = startAiMsg(ev.voice); aiMsgs.set(ev.req, m); } return m; }; function setGenerating(on) { S.generating = on; sendBtn.textContent = on ? 'Ferma' : 'Invia'; sendBtn.classList.toggle('primary', !on); } $('composer').onsubmit = (e) => { e.preventDefault(); if (S.generating && !input.value.trim()) { send({ cmd: 'stop' }); return; } const waiting = S.files.some((f) => f.state === 'lettura'); if (waiting) { addMsg('error', 'Aspetta: sto ancora leggendo gli allegati.'); return; } const ready = S.files.filter((f) => f.state === 'pronto'); const text = input.value.trim() || (ready.length ? 'Guarda gli allegati.' : ''); if (!text || !S.ws || S.ws.readyState !== 1) return; input.value = ''; autoGrow(); const image = !!S.attach; if (image) { sendImage(S.attach, 0); S.sentThumb = S.attach.thumb; clearAttach(); } S.files = S.files.filter((f) => f.state === 'lettura'); renderFiles(); send({ cmd: 'chat', text, thinking: $('think-on').checked, think_budget: Number($('think-budget').value), tools: $('tools-on').checked, web: $('web-on').checked, mode: $('mode').value, image }); }; input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('composer').requestSubmit(); } }); const autoGrow = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 160) + 'px'; }; input.addEventListener('input', autoGrow); const syncBudget = () => { $('budget-out').textContent = $('think-budget').value; $('budget-wrap').classList.toggle('off', !$('think-on').checked); }; $('think-budget').oninput = syncBudget; $('think-on').onchange = syncBudget; syncBudget(); $('btn-clear').onclick = () => { if (confirm('Iniziare una nuova conversazione per tutti i dispositivi collegati?')) send({ cmd: 'clear' }); }; function onToken(ev) { const m = aiFor(ev); m.tok++; const stick = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 40; if (ev.thought) { m.thought.hidden = false; m.thoughtText.textContent += ev.text; m.words = m.thoughtText.textContent.split(/\s+/).length; m.thought.querySelector('summary').textContent = `Ragionamento (${m.words} parole)`; } else { appendText(m, ev.text); } const secs = (performance.now() - m.t0) / 1000; if (secs > 0.3) $('st-speed').textContent = (m.tok / secs).toFixed(1); if (stick) messages.scrollTop = messages.scrollHeight; } // Il testo va in coda al corpo del messaggio, dopo le eventuali schede degli strumenti. function appendText(m, text) { let t = m.body.lastChild; if (!t || t.nodeType !== Node.TEXT_NODE) { if (t && !text.trim()) return; // niente a capo vuoti subito dopo una scheda t = m.body.appendChild(document.createTextNode(t ? text.replace(/^\s+/, '') : text)); return; } t.data += text; } // ---------------------------------------------------------------- strumenti di programmazione const TOOL_LABEL = { list_files: ['📁', 'Guarda i file'], read_file: ['📄', 'Legge'], write_file: ['✎', 'Scrive'], edit_file: ['✎', 'Modifica'], search_files: ['🔍', 'Cerca'], run_command: ['▶', 'Esegue'] }; function onTool(ev) { const m = aiFor(ev); let args = {}; try { args = JSON.parse(ev.args); } catch { /* argomenti non leggibili: il motore ha già risposto con l'errore */ } const [icon, label] = TOOL_LABEL[ev.name] || ['⚙', ev.name]; const target = args.path ?? args.command ?? args.pattern ?? ''; let card = m.body.querySelector(`.tool[data-step="${ev.step}"][data-name="${ev.name}"]:not(.done)`); if (!card) { card = document.createElement('details'); card.className = 'tool running'; card.dataset.step = ev.step; card.dataset.name = ev.name; card.innerHTML = `…`; card.querySelector('.tool-icon').textContent = icon; card.querySelector('.tool-label').textContent = label; card.querySelector('code').textContent = target || (ev.name === 'list_files' ? 'lavori' : ''); if (ev.name === 'write_file' && args.content != null) addPre(card, args.content, 'tool-code'); if (ev.name === 'edit_file' && args.new_text != null) addPre(card, args.new_text, 'tool-code'); m.body.append(card); } if (ev.phase === 'end') { card.classList.remove('running'); card.classList.add('done', ev.ok ? 'ok' : 'fail'); card.querySelector('.tool-state').textContent = ev.ok ? '✓' : '✗'; addPre(card, ev.result || '', 'tool-out'); if (!ev.ok && ev.name === 'run_command') card.open = true; // gli errori si vedono subito } if (messages.scrollHeight - messages.scrollTop - messages.clientHeight < 160) messages.scrollTop = messages.scrollHeight; } function addPre(card, text, cls) { const pre = document.createElement('pre'); pre.className = cls; pre.textContent = text; card.append(pre); } function onDone(ev) { const m = aiFor(ev); m.body.classList.remove('caret'); if (!m.body.childNodes.length || !m.body.textContent.trim()) m.body.textContent = ev.answer || '(nessuna risposta)'; m.el.querySelector('.meta').textContent = `${ev.tokens} token · ${ev.seconds.toFixed(1)} s`; aiMsgs.delete(ev.req); pending.delete(ev.req); setGenerating(pending.size > 0); } function showHistory(ev) { messages.replaceChildren(); aiMsgs.clear(); for (const m of ev.messages) { if (m.role === 'user') userMsg(m.device, m.voice, m.text); else { const a = startAiMsg(m.voice); a.body.classList.remove('caret'); a.body.textContent = m.text; } } if (!ev.messages.length) { const e = document.createElement('div'); e.className = 'empty'; e.id = 'empty'; e.textContent = 'Parla con Neuronal da qui, da un altro dispositivo o con una chiamata: la conversazione è una sola.'; messages.append(e); } } // ---------------------------------------------------------------- chiamata vocale // Microfono -> 16 kHz mono, a pacchetti da 20 ms (320 campioni), con il livello per l'indicatore. const MIC_WORKLET = ` class Mic16k extends AudioWorkletProcessor { constructor() { super(); this.step = sampleRate / 16000; this.t = 0; this.prev = 0; this.out = new Int16Array(320); this.n = 0; this.e = 0; } process(inputs) { const ch = inputs[0] && inputs[0][0]; if (!ch) return true; let t = this.t; while (t < ch.length) { const i = Math.floor(t), f = t - i; const a = i === 0 ? this.prev : ch[i - 1], b = ch[i]; const v = Math.max(-1, Math.min(1, a + (b - a) * f)); this.out[this.n++] = v * 32767; this.e += v * v; if (this.n === 320) { this.port.postMessage({ pcm: this.out.buffer.slice(0), level: Math.sqrt(this.e / 320) }); this.n = 0; this.e = 0; } t += this.step; } this.t = t - ch.length; this.prev = ch[ch.length - 1]; return true; } } registerProcessor('mic-16k', Mic16k);`; const CALL_LABEL = { 'in ascolto': 'Ti ascolto…', 'ti ascolto': 'Stai parlando…', trascrivo: 'Ho sentito, trascrivo…', penso: 'Sto pensando…', parlo: 'Sto parlando' }; async function startCall() { if (S.call) return; if (!navigator.mediaDevices?.getUserMedia) { const url = S.tlsPort ? `https://${location.hostname}:${S.tlsPort}/` : ''; addMsg('error', location.protocol === 'https:' ? 'Questo browser non consente il microfono.' : `Il microfono funziona solo sulla pagina sicura. Apri ${url || "l'indirizzo https del PC"} (dal PC: pulsante «Telefono»).`); return; } try { // Tutto ciò che sblocca l'audio va fatto subito, dentro il tocco sul pulsante (prima di qualsiasi attesa). // La voce passa da un lettore