diff --git a/fedac/native/REPORTS.md b/fedac/native/REPORTS.md new file mode 100644 index 0000000000..f0ec20515f --- /dev/null +++ b/fedac/native/REPORTS.md @@ -0,0 +1,177 @@ +# AC Native — Stack Report + +*Last updated: 2026-03-11* + +## What Is This? + +AC Native is a bare-metal Linux system that boots from USB (or internal disk) directly into a creative computing runtime. No distro, no systemd, no desktop — just a custom kernel running a C binary as PID 1 that executes JavaScript "pieces" via QuickJS. + +## The Stack + +### Layer 0: Hardware +- **Target**: ThinkPad X1 Nano Gen 2 (primary), any x86_64 UEFI machine +- **Display**: DRM (Direct Rendering Manager) — writes pixels directly to framebuffer +- **Audio**: ALSA (Advanced Linux Sound Architecture) — PCM output + Flite TTS +- **Input**: evdev — keyboard, trackpad, touchscreen, joystick, NuPhy analog keys +- **WiFi**: Intel iwlwifi (9260, AX200, AX201) via wpa_supplicant + dhclient +- **Storage**: FAT32 EFI System Partition on USB or internal NVMe + +### Layer 1: Kernel +- **Linux 6.14.2** — custom minimal config (~200 options vs ~5000 in a typical distro) +- **No distro** — not Fedora, Ubuntu, or anything else. Raw kernel + initramfs +- **EFI stub boot** — kernel IS the bootloader (BOOTX64.EFI on FAT32 ESP) +- **Embedded initramfs** — root filesystem is LZ4-compressed CPIO archive baked into the kernel +- **Size**: ~40MB total (kernel + initramfs) + +### Layer 2: Initramfs (Root Filesystem) +Everything the system needs lives in a ~33MB compressed archive: + +| Component | Size | Purpose | +|-----------|------|---------| +| ac-native binary | 1.1 MB | PID 1 — the entire runtime | +| Shared libraries | ~40 MB (uncompressed) | libc, libdrm, libasound, libssl, etc. | +| WiFi firmware | 4.9 MB | Intel iwlwifi microcode | +| Flite TTS | 5.2 MB | Text-to-speech (2 voices) | +| ALSA config | 352 KB | Audio device configuration | +| WiFi tools | ~6 MB | wpa_supplicant, dhclient, iw, ip | +| Dropbear SSH | 228 KB | SSH daemon for remote access | +| CA certificates | ~200 KB | HTTPS trust chain | +| Pieces (.mjs) | ~120 KB | JavaScript programs | +| Shell + utils | ~3 MB | bash, grep, curl, etc. | + +### Layer 3: ac-native (The Runtime) +A single C binary (~1.1MB) that does everything: + +- **PID 1 init**: Mounts /proc, /sys, /dev, /tmp. Sets CPU governor. Finds boot device +- **Display**: DRM initialization, double-buffered framebuffer, 60fps vsync +- **Graphics**: Software rasterizer — wipe, ink, line, box, circle, plot, write (bitmap fonts) +- **Audio**: ALSA PCM output with synthesizer (sine, square, saw, triangle, noise) +- **Input**: Multi-device polling (keyboard, mouse, trackpad, touch, analog keys) +- **WiFi**: Scan, connect, DHCP — full network stack management +- **JavaScript**: QuickJS engine with custom AC API bindings +- **Networking**: curl (HTTP/S), WebSocket client (TLS), UDP client +- **OTA updates**: Download vmlinuz, flash to EFI partition, verify, reboot +- **Config**: JSON config on FAT32 partition (handle, colors, tokens) +- **SSH**: Dropbear daemon for remote access + +### Layer 4: Pieces (JavaScript) +Interactive programs executed by QuickJS with lifecycle functions: + +``` +boot() → [act() → sim() → paint()] × 60fps → leave() +``` + +**Current pieces:** +- `notepat.mjs` — Musical notation pad (default boot piece, ~96KB) +- `prompt.mjs` — Command line with KidLisp evaluation +- `lisp.mjs` — KidLisp visual evaluator +- `claude.mjs` — Claude API chat client (OAuth refresh tokens) +- `roz.mjs` — Character piece + +## Boot Sequence + +``` +UEFI firmware + → BOOTX64.EFI (Linux kernel with embedded initramfs) + → /init (symlink to /ac-native) + → mount /proc /sys /dev /tmp + → mount EFI partition to /mnt + → read /mnt/config.json (handle, colors, tokens) + → init display (DRM) + → render boot title ("hi @jeffrey" with custom colors) + → init audio → boot beep (E5→B5 two-tone) + → init input (keyboard, trackpad, etc.) + → init WiFi (auto-connect to saved network) + → load piece.mjs → call boot() + → main loop: input_poll → act → sim → paint → present +``` + +**Boot time target**: Sub-second to interactive piece. + +## Network Architecture + +All networking is **outbound only** (except SSH when enabled): + +- **HTTP/S**: curl via system() — used for OTA checks, clock sync, API calls +- **WebSocket**: Custom TLS client in background pthread — AC chat/multiplayer +- **UDP**: Raw datagrams for lightweight co-presence data +- **SSH**: Dropbear on port 22 (auto-starts on WiFi connect) + +## OTA Update Flow + +1. Check version: `GET https://aesthetic.computer/api/native/version` +2. Download kernel: `GET https://aesthetic.computer/api/native/vmlinuz` (binary fetch with progress) +3. Flash to EFI: Copy to /mnt/EFI/BOOT/BOOTX64.EFI with fsync + syncfs +4. Verify: Drop page caches, byte-for-byte comparison of source vs destination +5. Reboot: Show verified bytes count, then `reboot(RB_AUTOBOOT)` + +## Claude Integration (3 Approaches) + +### 1. Direct API Client (claude.mjs) +- Pure JavaScript piece running in QuickJS +- Uses `system.fetchPost()` for HTTP POST requests +- OAuth: Stores refresh token in config.json, exchanges for access token +- Calls `/v1/messages` API with Claude Sonnet +- No external dependencies + +### 2. SSH Remote Access (dropbear) +- Lightweight SSH daemon (~228KB) bundled in initramfs +- Auto-starts when WiFi connects +- SSH in from any machine on the local network +- Run Claude Code CLI remotely over the SSH session +- `ssh root@` + +### 3. Node.js + Claude Code CLI (planned) +- Bundle Node.js binary in initramfs +- `system.execNode(script)` runs JS via Node subprocess +- Could run actual `@anthropic-ai/claude-code` package +- Renders output through AC native display + +## Key Files + +``` +fedac/native/ + src/ + ac-native.c — PID 1, main loop, boot sequence + js-bindings.c/h — QuickJS ↔ C API (graphics, audio, network, system) + drm-display.c/h — DRM framebuffer display + audio.c/h — ALSA audio + synthesizer + input.c/h — evdev input handling + wifi.c/h — WiFi management + ws-client.c/h — WebSocket client + graph.c/h — Software rasterizer + font.c/h — Bitmap font renderer + pieces/ + notepat.mjs — Musical notation (default piece) + prompt.mjs — Command prompt + claude.mjs — Claude API client + lisp.mjs — KidLisp evaluator + scripts/ + build-and-flash.sh — Full build pipeline + upload-release.sh — OTA release to DO Spaces + kernel/ + config-minimal — Linux kernel config + build-kernel.sh — Kernel compilation script + Makefile — ac-native binary build +``` + +## Build Pipeline + +``` +make CC=gcc → build/ac-native (1.1MB) +scripts/build-and-flash.sh → build/vmlinuz (~40MB) + ├── compile ac-native + ├── create initramfs (copy binary + libs + firmware + tools + pieces) + ├── compress with LZ4 + ├── build Linux kernel with embedded initramfs + └── flash to USB via mtools (no root mount needed) +``` + +## What Makes This Different + +- **No OS layer**: No systemd, no package manager, no filesystem hierarchy. Just kernel + one binary +- **Sub-second boot**: UEFI → interactive in under 1 second +- **Single binary runtime**: Everything in one ~1.1MB C program +- **JavaScript pieces**: Creative programs with immediate-mode graphics, audio synthesis, network +- **OTA with verification**: Flash + fsync + drop caches + byte-compare before reboot +- **Fits on any USB**: ~40MB total, boots on any UEFI x86_64 machine diff --git a/fedac/native/ac-os b/fedac/native/ac-os index 3f91355943..2dc3b71aaf 100755 --- a/fedac/native/ac-os +++ b/fedac/native/ac-os @@ -17,6 +17,16 @@ CMD="${1:-build}" log() { echo -e "\033[0;36m[ac-os]\033[0m $*"; } err() { echo -e "\033[0;31m[ac-os]\033[0m $*" >&2; } +# Load env vars (MongoDB, etc.) if not already set +if [ -z "${MONGODB_CONNECTION_STRING:-}" ] && [ -f "/home/me/envs/devcontainer.env" ]; then + while IFS='=' read -r key value; do + [[ "$key" =~ ^[[:space:]]*# ]] && continue + [[ -z "$key" ]] && continue + key=$(echo "$key" | xargs) + [ -z "${!key:-}" ] && export "$key=$value" 2>/dev/null || true + done < /home/me/envs/devcontainer.env +fi + build_binary() { log "Building binary..." cd "${SCRIPT_DIR}" @@ -73,59 +83,129 @@ build_kernel() { log "Kernel: $(du -sh "${VMLINUZ}" | cut -f1)" } -flash_usb() { - # Find USB device - local USB_DEV="" +find_usb_dev() { + # Find removable USB block device via sysfs for dev in sda sdb sdc; do if [ -e "/sys/block/${dev}/removable" ]; then local rem=$(cat "/sys/block/${dev}/removable" 2>/dev/null) if [ "${rem}" = "1" ] && lsblk "/dev/${dev}" &>/dev/null 2>&1; then - USB_DEV="/dev/${dev}" - break + echo "/dev/${dev}" + return 0 fi fi done - - if [ -z "${USB_DEV}" ]; then - # Fallback: check lsblk for sda with removable flag - if lsblk /dev/sda &>/dev/null 2>&1; then - USB_DEV="/dev/sda" - else - err "No USB device found" - exit 1 - fi + # Fallback + if lsblk /dev/sda &>/dev/null 2>&1; then + echo "/dev/sda" + return 0 fi + return 1 +} + +flash_usb() { + local USB_DEV + USB_DEV="$(find_usb_dev)" || { err "No USB device found"; exit 1; } log "Flashing to ${USB_DEV}1..." - sudo docker run --rm --privileged \ - -v "$(realpath "${BUILD_DIR}"):/build:ro" \ - -v /dev:/dev \ - fedora:41 bash -c " - dnf install -y -q dosfstools 2>/dev/null - mkdir -p /mnt/usb - # Create partition if needed - if ! lsblk ${USB_DEV}1 &>/dev/null 2>&1; then - dnf install -y -q util-linux 2>/dev/null - sfdisk --force ${USB_DEV} </dev/null 2>&1; then + apk add --quiet util-linux + sfdisk --force ${USB_DEV} <&1 | grep -v "^Package\|^Installing\|^Transaction\|^[[:space:]]" +PARTEOF + sleep 2 + mkfs.vfat -F 32 -n ACBOOT ${USB_DEV}1 + fi + mount ${USB_DEV}1 /mnt/usb + mkdir -p /mnt/usb/EFI/BOOT + cp /tmp/vmlinuz /mnt/usb/EFI/BOOT/BOOTX64.EFI + sync && sleep 1 && sync + echo '=== Verify ===' + sha256sum /mnt/usb/EFI/BOOT/BOOTX64.EFI /tmp/vmlinuz + umount /mnt/usb + echo 'Flashed!' + ") + sudo docker cp "${VMLINUZ}" "${CONTAINER}:/tmp/vmlinuz" + sudo docker start -a "${CONTAINER}" 2>&1 +} + +load_vault_creds() { + # Decrypt DO Spaces credentials from vault GPG file + # Tries: 1) already in env, 2) plaintext cache, 3) GPG decrypt (agent or prompt) + if [ -n "${DO_SPACES_KEY:-}" ] && [ -n "${DO_SPACES_SECRET:-}" ]; then + return 0 + fi + + local CACHE="/tmp/.ac-upload-env" + if [ -f "${CACHE}" ]; then + set -a; source "${CACHE}"; set +a + if [ -n "${DO_SPACES_KEY:-}" ] && [ -n "${DO_SPACES_SECRET:-}" ]; then + log "Credentials loaded from session cache" + return 0 + fi + fi + + # Find the encrypted file + local GPG_FILE="" + for candidate in \ + "${SCRIPT_DIR}/upload.env.gpg" \ + "${SCRIPT_DIR}/../../aesthetic-computer-vault/fedac/native/upload.env.gpg" \ + "/home/me/aesthetic-computer-vault/fedac/native/upload.env.gpg"; do + if [ -f "${candidate}" ]; then + GPG_FILE="${candidate}" + break + fi + done + + if [ -z "${GPG_FILE}" ]; then + err "No upload.env.gpg found in vault or local paths" + err "Expected locations:" + err " ${SCRIPT_DIR}/upload.env.gpg" + err " aesthetic-computer-vault/fedac/native/upload.env.gpg" + return 1 + fi + + log "Decrypting credentials from $(basename "${GPG_FILE}")..." + + # Try GPG agent first (no tty needed if key is cached) + local DECRYPTED + DECRYPTED=$(gpg --batch --pinentry-mode loopback -d "${GPG_FILE}" 2>/dev/null | grep "=") || true + + # If agent didn't have it cached, prompt for passphrase + if [ -z "${DECRYPTED}" ]; then + if [ -t 0 ]; then + # Interactive terminal — let GPG prompt naturally + log "GPG agent needs passphrase..." + DECRYPTED=$(gpg --pinentry-mode loopback -d "${GPG_FILE}" 2>/dev/null | grep "=") || true + fi + fi + + if [ -z "${DECRYPTED}" ]; then + err "Failed to decrypt ${GPG_FILE}" + err "Import your key: gpg --import " + err "Then retry — GPG will prompt for your passphrase" + return 1 + fi + + # Cache decrypted creds for this session (readable only by us) + echo "${DECRYPTED}" > "${CACHE}" + chmod 600 "${CACHE}" + + set -a; eval "${DECRYPTED}"; set +a + log "Credentials decrypted and cached for session" } upload_ota() { log "Uploading OTA release..." + load_vault_creds || exit 1 + export DO_SPACES_KEY DO_SPACES_SECRET DO_SPACES_BUCKET DO_SPACES_REGION cd "${SCRIPT_DIR}" bash scripts/upload-release.sh "${VMLINUZ}" } diff --git a/fedac/native/ac-usb b/fedac/native/ac-usb new file mode 100755 index 0000000000..ca023e283b --- /dev/null +++ b/fedac/native/ac-usb @@ -0,0 +1,103 @@ +#!/bin/bash +# ac-usb — List and inspect USB devices through Docker (for devcontainer environments) +# Usage: +# ac-usb List all USB block devices +# ac-usb ls Same as above +# ac-usb read PATH Read a file from USB partition (e.g., ac-usb read EFI/BOOT/BOOTX64.EFI) +# ac-usb logs Pull /logs/ and /perf/ from USB /mnt partition +# ac-usb sha256 Show SHA256 of BOOTX64.EFI on USB +set -e + +CMD="${1:-ls}" + +find_usb_dev() { + for dev in sda sdb sdc; do + if [ -e "/sys/block/${dev}/removable" ]; then + local rem=$(cat "/sys/block/${dev}/removable" 2>/dev/null) + if [ "${rem}" = "1" ] && lsblk "/dev/${dev}" &>/dev/null 2>&1; then + echo "/dev/${dev}" + return 0 + fi + fi + done + if lsblk /dev/sda &>/dev/null 2>&1; then + echo "/dev/sda" + return 0 + fi + return 1 +} + +docker_usb() { + # Run a command inside a privileged container with USB access + sudo docker run --rm --privileged -v /dev:/dev alpine:latest sh -c "$1" 2>&1 +} + +case "${CMD}" in + ls|list) + echo "=== USB Block Devices ===" + lsblk 2>/dev/null | grep -E "^sd|─sd" || echo "(none found)" + echo "" + USB_DEV="$(find_usb_dev 2>/dev/null)" || { echo "No removable USB detected"; exit 0; } + echo "USB device: ${USB_DEV}" + echo "" + echo "=== Partition contents ===" + docker_usb " + apk add --quiet dosfstools + mkdir -p /mnt/usb + mount ${USB_DEV}1 /mnt/usb 2>/dev/null && { + echo '--- ${USB_DEV}1 ---' + find /mnt/usb -type f | head -50 + echo '' + du -sh /mnt/usb/EFI/BOOT/BOOTX64.EFI 2>/dev/null + umount /mnt/usb + } || echo 'Could not mount ${USB_DEV}1' + " + ;; + sha256|hash) + USB_DEV="$(find_usb_dev)" || { echo "No USB found"; exit 1; } + docker_usb " + apk add --quiet dosfstools + mkdir -p /mnt/usb + mount ${USB_DEV}1 /mnt/usb + sha256sum /mnt/usb/EFI/BOOT/BOOTX64.EFI 2>/dev/null || echo 'No EFI file found' + umount /mnt/usb + " + ;; + logs) + USB_DEV="$(find_usb_dev)" || { echo "No USB found"; exit 1; } + mkdir -p /tmp/usb-logs + CONTAINER=$(sudo docker create --privileged -v /dev:/dev alpine:latest sh -c " + apk add --quiet dosfstools + mkdir -p /mnt/usb /out + mount ${USB_DEV}1 /mnt/usb + # Copy logs and perf data + cp /mnt/usb/ac-native.log /out/ 2>/dev/null || true + cp -r /mnt/usb/perf /out/ 2>/dev/null || true + cp /mnt/usb/config.json /out/ 2>/dev/null || true + cp /mnt/usb/booted-version /out/ 2>/dev/null || true + ls -la /out/ + umount /mnt/usb + ") + sudo docker start -a "${CONTAINER}" + sudo docker cp "${CONTAINER}:/out/." /tmp/usb-logs/ 2>/dev/null + sudo docker rm "${CONTAINER}" 2>/dev/null + echo "" + echo "Logs copied to /tmp/usb-logs/" + ls -la /tmp/usb-logs/ + ;; + read) + FILE="${2:?Usage: ac-usb read }" + USB_DEV="$(find_usb_dev)" || { echo "No USB found"; exit 1; } + docker_usb " + apk add --quiet dosfstools + mkdir -p /mnt/usb + mount ${USB_DEV}1 /mnt/usb + cat '/mnt/usb/${FILE}' 2>/dev/null || echo 'File not found: ${FILE}' + umount /mnt/usb + " + ;; + *) + echo "Usage: ac-usb {ls|sha256|logs|read }" + exit 1 + ;; +esac diff --git a/fedac/native/pieces/lisp.mjs b/fedac/native/pieces/lisp.mjs index 2b69b65c5b..8aa5c2b818 100644 --- a/fedac/native/pieces/lisp.mjs +++ b/fedac/native/pieces/lisp.mjs @@ -169,14 +169,8 @@ function paint({ wipe, ink, line, box, circle, write, scroll, spin, zoom, write("eval: " + (e.message || e).slice(0, 60), { x: 2, y: 2, size: 1, font: "6x10" }); } - // Source label overlay (top-left) - if (sourceLabel) { - ink(255, 255, 255, 80); - write(sourceLabel, { x: 4, y: 4, size: 1, font: "6x10" }); - } - // esc hint (bottom-left) - ink(255, 255, 255, 50); - write("esc:back", { x: 4, y: screen.height - 14, size: 1, font: "6x10" }); + // No overlay text — avoids compositing source/crosshair into + // backbuffer effects (scroll/spin/zoom). User knows esc goes back. } export { boot, paint, act, sim }; diff --git a/fedac/native/pieces/notepat.mjs b/fedac/native/pieces/notepat.mjs index 0b07f23a00..9d4db2ed57 100644 --- a/fedac/native/pieces/notepat.mjs +++ b/fedac/native/pieces/notepat.mjs @@ -547,23 +547,10 @@ function act({ event: e, sound, wifi, system }) { return; } - // "os" button: top bar — hit zone set dynamically in paint() + // "os" button: jump to standalone os piece const ob = globalThis.__osBtn; if (ob && y < ob.h && x >= ob.x && x <= ob.x + ob.w) { - if (activeScreen === "os") { - activeScreen = "notepat"; - osState = "idle"; - } else { - activeScreen = "os"; - osState = "checking"; - osFetchPending = false; - osRemoteVersion = ""; - osError = ""; - // Cancel any in-flight fetch (clock sync, auto-update) so OS panel gets the slot - system.fetchCancel?.(); - autoUpdate.fetchPending = false; - if (autoUpdate.state === "checking") autoUpdate.state = "idle"; - } + system?.jump?.("os"); return; } @@ -1831,6 +1818,10 @@ function paint({ wipe, ink, box, line, write, screen, sound, system, trackpad, p const vGap = 1; const drawLane = (x0, phase) => { + // Single background tint per lane (not per-bar — avoids alpha overdraw) + ink(dark ? 30 : 220, dark ? 10 : 200, dark ? 50 : 180, 36); + box(x0, wfTop, laneW, wfH, true); + for (let i = 0; i < barsPerSide; i++) { const t = (i / barsPerSide) * 0.5 + phase; const si = Math.min((wf.length || 1) - 1, Math.floor(t * (wf.length || 1))); @@ -1841,11 +1832,10 @@ function paint({ wipe, ink, box, line, write, screen, sound, system, trackpad, p const bw = Math.max(1, Math.min(barW - vGap, x0 + laneW - bx)); if (bw <= 0 || bx >= x0 + laneW) break; - ink(dark ? 30 : 220, dark ? 10 : 200, dark ? 50 : 180, 36); - box(bx, wfTop, bw, wfH, true); - ink(dark ? 0 : 200, dark ? 200 : 40, dark ? 255 : 0, 140); + // Opaque bar fill (no alpha — fast path) + ink(dark ? 0 : 200, dark ? 200 : 40, dark ? 255 : 0); box(bx, barTop, bw, barH, true); - ink(dark ? 255 : 255, dark ? 60 : 0, dark ? 180 : 100, 200); + ink(dark ? 255 : 255, dark ? 60 : 0, dark ? 180 : 100); box(bx, barTop, bw, 2, true); } }; diff --git a/fedac/native/pieces/os.mjs b/fedac/native/pieces/os.mjs index 70a2498f7f..293ead4678 100644 --- a/fedac/native/pieces/os.mjs +++ b/fedac/native/pieces/os.mjs @@ -7,7 +7,9 @@ const OS_VERSION_URL = OS_BASE_URL + "native-notepat-latest.version"; const OS_VMLINUZ_URL = OS_BASE_URL + "native-notepat-latest.vmlinuz"; const OS_VMLINUZ_BYTES = 37_000_000; -let state = "idle"; // idle | checking | up-to-date | available | downloading | flashing | rebooting | error +// States: idle | checking | up-to-date | available | downloading | flashing +// | confirm-reboot | shutting-down | error +let state = "idle"; let currentVersion = ""; let remoteVersion = ""; let progress = 0; @@ -16,9 +18,25 @@ let fetchPending = false; let checkFrame = 0; let flashTargetIdx = 0; let frame = 0; +let shutdownFrame = 0; // frame counter for shutdown animation +let flashedMB = 0; // verified MB for display during confirm/shutdown + +// Telemetry lines that scroll by during flash +const telemetry = []; +let telemetryScroll = 0; + +function addTelemetry(msg) { + telemetry.push({ text: msg, frame, y: 0 }); + if (telemetry.length > 50) telemetry.shift(); +} function boot({ system }) { currentVersion = system?.version || "unknown"; + // Default flash target: prefer non-boot device (e.g., NVMe when booting from USB) + const targets = system?.flashTargets || []; + const bootDev = system?.bootDevice; + const nonBootIdx = targets.findIndex(t => t.device !== bootDev); + if (nonBootIdx >= 0) flashTargetIdx = nonBootIdx; // Auto-check on boot if online if (system?.fetchPending === false) { state = "checking"; @@ -29,48 +47,62 @@ function boot({ system }) { } function act({ event: e, sound, system }) { - if (!e.is("touch") && !e.is("keyboard:down")) return; + if (!e.is("keyboard:down")) return; - // Escape goes back to prompt + // Escape goes back to prompt (not during flash or shutdown) if (e.is("keyboard:down:escape") || e.is("keyboard:down:backspace")) { - system?.jump?.("prompt"); - return; + if (state !== "flashing" && state !== "shutting-down" && state !== "downloading") { + system?.jump?.("prompt"); + return; + } } - if (!e.is("touch")) return; - const { x, y } = e; - const w = e.screen?.width || 320; - - if (state === "available") { - // Cycle target button - const cb = globalThis.__osCycleBtn; - if (cb && y >= cb.y && y <= cb.y + cb.h && x >= cb.x && x <= cb.x + cb.w) { - const targets = system?.flashTargets || []; - flashTargetIdx = (flashTargetIdx + 1) % Math.max(1, targets.length); - sound?.synth({ type: "sine", tone: 440, duration: 0.04, volume: 0.12, attack: 0.002, decay: 0.03 }); + // Reboot confirmation: y = reboot, n = back to prompt + if (state === "confirm-reboot") { + if (e.is("keyboard:down:y") || e.is("keyboard:down:enter") || e.is("keyboard:down:return")) { + state = "shutting-down"; + shutdownFrame = 0; + sound?.synth({ type: "triangle", tone: 784, duration: 0.1, volume: 0.15, attack: 0.003, decay: 0.08 }); return; } - // Update now button - const ub = globalThis.__osUpdateBtn; - if (ub && y >= ub.y && y <= ub.y + ub.h && x >= ub.x && x <= ub.x + ub.w) { + if (e.is("keyboard:down:n") || e.is("keyboard:down:escape")) { + system?.jump?.("prompt"); + return; + } + return; + } + + // Touch-like key shortcuts for available state + if (state === "available") { + if (e.is("keyboard:down:enter") || e.is("keyboard:down:return")) { const targets = system?.flashTargets || []; const tgt = targets[flashTargetIdx]; const device = tgt?.device || undefined; globalThis.__osFlashDevice = device; state = "downloading"; progress = 0; + telemetry.length = 0; + addTelemetry("fetching " + OS_VMLINUZ_URL.split("/").pop()); system?.fetchBinary?.(OS_VMLINUZ_URL, "/tmp/vmlinuz.new", OS_VMLINUZ_BYTES); return; } + if (e.is("keyboard:down:tab")) { + const targets = system?.flashTargets || []; + flashTargetIdx = (flashTargetIdx + 1) % Math.max(1, targets.length); + sound?.synth({ type: "sine", tone: 440, duration: 0.04, volume: 0.12, attack: 0.002, decay: 0.03 }); + return; + } } // Tap to retry on error or re-check when up-to-date/idle if (state === "error" || state === "up-to-date" || state === "idle") { - if (!system?.fetchPending) { - state = "checking"; - fetchPending = true; - checkFrame = frame; - system?.fetch?.(OS_VERSION_URL); + if (e.is("keyboard:down:enter") || e.is("keyboard:down:return") || e.is("keyboard:down:space")) { + if (!system?.fetchPending) { + state = "checking"; + fetchPending = true; + checkFrame = frame; + system?.fetch?.(OS_VERSION_URL); + } } } } @@ -78,11 +110,63 @@ function act({ event: e, sound, system }) { function paint({ wipe, ink, box, line, write, screen, system, wifi }) { frame++; const w = screen.width, h = screen.height; - const dark = true; + const pad = 10; + const font = "font_1"; - wipe(dark ? 12 : 240, dark ? 16 : 235, dark ? 24 : 230); + // === Shutdown animation (full-screen takeover) === + if (state === "shutting-down") { + shutdownFrame++; + const t = shutdownFrame / 120; // 2 second animation - const pad = 10; + // Background: dark blue fading to black + const bg = Math.max(0, Math.floor(20 * (1 - t))); + wipe(0, bg, Math.floor(bg * 1.5)); + + // Scrolling telemetry lines flying upward + for (let i = 0; i < telemetry.length; i++) { + const entry = telemetry[i]; + const baseY = h - (shutdownFrame - i * 3) * 2; + if (baseY < -10 || baseY > h + 10) continue; + const alpha = Math.max(0, Math.min(255, Math.floor(200 * (1 - t)))); + const green = 80 + (i * 37 % 120); + ink(60, green, 100, alpha); + write(entry.text, { x: pad + (i % 3) * 2, y: baseY, size: 1, font }); + } + + // Central message + if (t < 0.8) { + const pulse = Math.floor(180 + 75 * Math.sin(shutdownFrame * 0.2)); + ink(pulse, 255, pulse, Math.floor(255 * (1 - t / 0.8))); + write("launching new os", { x: pad, y: h / 2 - 20, size: 2, font: "matrix" }); + + // Build name + const buildName = remoteVersion.split(" ")[0] || "update"; + ink(255, 200, 60, Math.floor(200 * (1 - t / 0.8))); + write(buildName, { x: pad, y: h / 2 + 4, size: 1, font }); + } + + // Verified size + if (t < 0.6) { + ink(80, 200, 120, Math.floor(180 * (1 - t / 0.6))); + write(`verified ${flashedMB}MB`, { x: pad, y: h / 2 + 20, size: 1, font }); + } + + // Progress bar shrinking to nothing + const barW = Math.max(0, Math.floor((w - pad * 2) * (1 - t))); + if (barW > 0) { + ink(60, 180, 100, Math.floor(200 * (1 - t))); + box(pad, h - 8, barW, 4, true); + } + + // Trigger reboot after animation + if (shutdownFrame >= 150) { // 2.5 seconds + system?.reboot?.(); + } + return; + } + + // === Normal UI === + wipe(12, 16, 24); // Title ink(200, 220, 200); @@ -91,32 +175,37 @@ function paint({ wipe, ink, box, line, write, screen, system, wifi }) { // Connection status if (!wifi?.connected) { ink(200, 80, 80); - write("offline", { x: pad, y: 34, size: 1, font: "font_1" }); + write("offline", { x: pad, y: 34, size: 1, font }); ink(100, 80, 80); - write("connect wifi first", { x: pad, y: 46, size: 1, font: "font_1" }); + write("connect wifi first", { x: pad, y: 46, size: 1, font }); } else { ink(100, 110, 100); - write("current", { x: pad, y: 34, size: 1, font: "font_1" }); + write("current", { x: pad, y: 34, size: 1, font }); ink(180, 180, 180); const maxChars = Math.floor((w - pad * 2) / 6) - 10; - write(currentVersion.slice(0, maxChars), { x: pad, y: 46, size: 1, font: "font_1" }); + write(currentVersion.slice(0, maxChars), { x: pad, y: 46, size: 1, font }); } const stateY = 66; if (state === "checking") { ink(200, 200, 80); - write("checking...", { x: pad, y: stateY, size: 1, font: "font_1" }); + const dots = ".".repeat((Math.floor(frame / 20) % 3) + 1); + write("checking" + dots, { x: pad, y: stateY, size: 1, font }); + } else if (state === "up-to-date") { ink(80, 200, 120); - write("up to date!", { x: pad, y: stateY, size: 1, font: "font_1" }); + write("up to date!", { x: pad, y: stateY, size: 1, font }); ink(100, 110, 100); - write(remoteVersion, { x: pad, y: stateY + 14, size: 1, font: "font_1" }); + write(remoteVersion, { x: pad, y: stateY + 14, size: 1, font }); + ink(80, 80, 100); + write("enter: recheck esc: back", { x: pad, y: stateY + 30, size: 1, font }); + } else if (state === "available") { ink(100, 110, 100); - write("available", { x: pad, y: stateY, size: 1, font: "font_1" }); + write("available", { x: pad, y: stateY, size: 1, font }); ink(255, 200, 60); - write(remoteVersion, { x: pad, y: stateY + 14, size: 1, font: "font_1" }); + write(remoteVersion, { x: pad, y: stateY + 14, size: 1, font }); // Flash target selector const targets = system?.flashTargets || []; @@ -126,81 +215,149 @@ function paint({ wipe, ink, box, line, write, screen, system, wifi }) { const tgtLabel = (tgt?.label || "?") + " (" + (tgt?.device || "?") + ")"; const isBoot = tgt?.device === system?.bootDevice; ink(80, 100, 120); - write("target:", { x: pad, y: stateY + 30, size: 1, font: "font_1" }); + write("target:", { x: pad, y: stateY + 30, size: 1, font }); ink(isBoot ? 80 : 200, isBoot ? 200 : 200, isBoot ? 255 : 80); - write(tgtLabel, { x: pad + 48, y: stateY + 30, size: 1, font: "font_1" }); + write(tgtLabel, { x: pad + 48, y: stateY + 30, size: 1, font }); if (isBoot) { ink(60, 140, 200); - write("(current boot)", { x: pad, y: stateY + 42, size: 1, font: "font_1" }); + write("(current boot)", { x: pad, y: stateY + 42, size: 1, font }); } if (targets.length > 1) { - ink(120, 120, 140); - const cycX = w - pad - 36; - box(cycX, stateY + 28, 32, 14, true); - ink(220, 220, 240); - write("next", { x: cycX + 4, y: stateY + 31, size: 1, font: "font_1" }); - globalThis.__osCycleBtn = { x: cycX, y: stateY + 28, w: 32, h: 14 }; - } else { - globalThis.__osCycleBtn = null; + ink(80, 80, 100); + write("tab: next target", { x: pad, y: stateY + 56, size: 1, font }); } } - // Update button - const btnW = Math.min(120, w - pad * 4); - const btnX = Math.floor((w - btnW) / 2); - const btnY = stateY + (targets.length > 0 ? 58 : 34); + // Keyboard hint + const hintY = stateY + (targets.length > 0 ? 72 : 34); ink(60, 180, 100); - box(btnX, btnY, btnW, 18, true); - ink(240, 255, 240); - write("update now", { x: btnX + Math.floor((btnW - 60) / 2), y: btnY + 4, size: 1, font: "font_1" }); - globalThis.__osUpdateBtn = { x: btnX, y: btnY, w: btnW, h: 18 }; + write("enter: install update", { x: pad, y: hintY, size: 1, font }); + ink(80, 80, 100); + write("esc: back", { x: pad, y: hintY + 14, size: 1, font }); } else if (state === "downloading") { ink(120, 140, 120); - write("downloading...", { x: pad, y: stateY, size: 1, font: "font_1" }); - const barW = w - pad * 2, barH = 8, barY = stateY + 16; + const dots = ".".repeat((Math.floor(frame / 15) % 3) + 1); + write("downloading" + dots, { x: pad, y: stateY, size: 1, font }); + + // File info + const expectedMB = (OS_VMLINUZ_BYTES / 1048576).toFixed(0); + const dlMB = ((progress || 0) * OS_VMLINUZ_BYTES / 1048576).toFixed(1); + ink(80, 100, 80); + write(`${dlMB} / ${expectedMB} MB`, { x: pad, y: stateY + 14, size: 1, font }); + + // Progress bar + const barW = w - pad * 2, barH = 8, barY = stateY + 30; ink(30, 40, 50); box(pad, barY, barW, barH, true); ink(60, 180, 100); box(pad, barY, Math.round(barW * (progress || 0)), barH, true); ink(160); - write(Math.round((progress || 0) * 100) + "%", { x: pad, y: barY + 12, size: 1, font: "font_1" }); + write(Math.round((progress || 0) * 100) + "%", { x: pad, y: barY + 12, size: 1, font }); + + // Target info + ink(60, 70, 80); + write("-> " + (globalThis.__osFlashDevice || system?.bootDevice || "?"), { x: pad, y: barY + 26, size: 1, font }); } else if (state === "flashing") { const phase = system?.flashPhase ?? 0; - const phaseText = phase === 1 ? "writing EFI..." - : phase === 2 ? "syncing to disk..." - : phase === 3 ? "verifying..." - : phase === 4 ? "done" : "preparing..."; - ink(...(phase === 3 ? [100, 200, 255] : [255, 160, 60])); - write(phaseText, { x: pad, y: stateY, size: 1, font: "font_1" }); + const phaseIcons = ["...", ">>>", "~~~", "???", "!!!"]; + const phaseNames = ["preparing", "writing EFI", "syncing to disk", "verifying", "complete"]; + const phaseText = phaseNames[phase] || "preparing"; + const icon = phaseIcons[phase] || "..."; + + // Phase indicator with animation + const dots = ".".repeat((Math.floor(frame / 10) % 3) + 1); + ink(...(phase === 3 ? [100, 200, 255] : phase === 4 ? [80, 255, 120] : [255, 160, 60])); + write(`${icon} ${phaseText}${phase < 4 ? dots : ""}`, { x: pad, y: stateY, size: 1, font }); + + // Target device ink(100); - write("-> " + (globalThis.__osFlashDevice || system?.bootDevice || "?"), { x: pad, y: stateY + 14, size: 1, font: "font_1" }); + write("-> " + (globalThis.__osFlashDevice || system?.bootDevice || "?"), { x: pad, y: stateY + 14, size: 1, font }); + + // Phase progress visualization + const phases = ["prepare", "write", "sync", "verify"]; + let px = pad; + for (let i = 0; i < phases.length; i++) { + const active = i === phase || (phase === 4 && i === 3); + const done = i < phase || phase === 4; + ink(done ? 60 : 30, done ? 140 : 40, done ? 80 : 50); + const pw = Math.floor((w - pad * 2 - 12) / 4); + box(px, stateY + 30, pw, 6, true); + if (active && !done) { + // Animated fill + const fill = Math.floor(pw * ((frame % 60) / 60)); + ink(255, 200, 60); + box(px, stateY + 30, fill, 6, true); + } + px += pw + 4; + } + + // Warning ink(140); - write("do not power off", { x: pad, y: stateY + 28, size: 1, font: "font_1" }); + write("do not power off", { x: pad, y: stateY + 44, size: 1, font }); + + // Scrolling telemetry at bottom + const telY = stateY + 60; + const maxLines = Math.floor((h - telY - 14) / 10); + const startIdx = Math.max(0, telemetry.length - maxLines); + for (let i = startIdx; i < telemetry.length; i++) { + const lineY = telY + (i - startIdx) * 10; + const age = frame - telemetry[i].frame; + const brightness = Math.max(40, Math.min(120, 120 - age)); + ink(brightness, Math.floor(brightness * 1.2), brightness); + write(telemetry[i].text, { x: pad, y: lineY, size: 1, font }); + } - } else if (state === "rebooting") { - const mb = ((system?.flashVerifiedBytes ?? 0) / 1048576).toFixed(1); + } else if (state === "confirm-reboot") { + // Flash complete — ask user to reboot + const mb = flashedMB; ink(80, 255, 120); - write(`verified ${mb}MB`, { x: pad, y: stateY, size: 1, font: "font_1" }); - ink(200, 100, 60); - write("rebooting...", { x: pad, y: stateY + 14, size: 1, font: "font_1" }); + write("update installed!", { x: pad, y: stateY, size: 2, font: "matrix" }); + + ink(120, 200, 140); + write(`verified ${mb}MB written`, { x: pad, y: stateY + 24, size: 1, font }); + + ink(200, 180, 100); + write(remoteVersion, { x: pad, y: stateY + 38, size: 1, font }); + + // Reboot prompt — pulsing + const pulse = Math.floor(200 + 55 * Math.sin(frame * 0.1)); + ink(pulse, pulse, 255); + write("reboot now?", { x: pad, y: stateY + 58, size: 2, font: "matrix" }); + + ink(60, 200, 80); + write("y: reboot to new os", { x: pad, y: stateY + 80, size: 1, font }); + ink(140, 100, 80); + write("n: back to prompt", { x: pad, y: stateY + 94, size: 1, font }); + + // Scrolling telemetry in background + const telY = stateY + 112; + const maxLines = Math.floor((h - telY - 14) / 10); + const startIdx = Math.max(0, telemetry.length - maxLines); + for (let i = startIdx; i < telemetry.length; i++) { + const lineY = telY + (i - startIdx) * 10; + ink(40, 50, 45); + write(telemetry[i].text, { x: pad, y: lineY, size: 1, font }); + } } else if (state === "error") { ink(220, 80, 80); - write(("error: " + errorMsg).slice(0, Math.floor((w - pad * 2) / 6)), { x: pad, y: stateY, size: 1, font: "font_1" }); + write(("error: " + errorMsg).slice(0, Math.floor((w - pad * 2) / 6)), { x: pad, y: stateY, size: 1, font }); ink(120); - write("tap to retry", { x: pad, y: stateY + 14, size: 1, font: "font_1" }); + write("enter: retry esc: back", { x: pad, y: stateY + 14, size: 1, font }); } else { // idle ink(100); - write("tap to check for updates", { x: pad, y: stateY, size: 1, font: "font_1" }); + write("enter: check for updates", { x: pad, y: stateY, size: 1, font }); } - // Bottom hint - ink(60, 80, 60); - write("esc: back", { x: pad, y: h - 12, size: 1, font: "font_1" }); + // Bottom hint (not during shutdown) + if (state !== "shutting-down") { + ink(60, 80, 60); + write("esc: back", { x: pad, y: h - 12, size: 1, font }); + } // === State machine: poll fetch/flash results === @@ -230,11 +387,19 @@ function paint({ wipe, ink, box, line, write, screen, system, wifi }) { // Download progress if (state === "downloading") { + const prevProgress = progress; progress = system?.fetchBinaryProgress ?? progress; + // Telemetry on progress milestones + if (progress > 0 && Math.floor(progress * 10) > Math.floor(prevProgress * 10)) { + const pct = Math.round(progress * 100); + addTelemetry(`download ${pct}% (${(progress * OS_VMLINUZ_BYTES / 1048576).toFixed(1)}MB)`); + } if (system?.fetchBinaryDone) { if (system?.fetchBinaryOk) { + addTelemetry("download complete, starting flash..."); state = "flashing"; const dev = globalThis.__osFlashDevice; + addTelemetry("target: " + (dev || system?.bootDevice || "auto")); if (dev) system?.flashUpdate?.("/tmp/vmlinuz.new", dev); else system?.flashUpdate?.("/tmp/vmlinuz.new"); } else { @@ -244,22 +409,28 @@ function paint({ wipe, ink, box, line, write, screen, system, wifi }) { } } - // Flash progress - if (state === "flashing" && system?.flashDone) { - if (system?.flashOk) { - state = "rebooting"; - globalThis.__osRebootFrame = frame + 120; - } else { - state = "error"; - errorMsg = "flash verify failed"; + // Flash progress — track phase transitions for telemetry + if (state === "flashing") { + const phase = system?.flashPhase ?? 0; + const prevPhase = globalThis.__osLastFlashPhase ?? -1; + if (phase !== prevPhase) { + globalThis.__osLastFlashPhase = phase; + const names = ["preparing flash", "writing EFI image", "syncing to disk", "verifying bytes", "flash complete"]; + addTelemetry(names[phase] || `phase ${phase}`); + if (phase === 1) addTelemetry("dst: EFI/BOOT/BOOTX64.EFI"); + } + if (system?.flashDone) { + if (system?.flashOk) { + flashedMB = ((system?.flashVerifiedBytes ?? 0) / 1048576).toFixed(1); + addTelemetry(`verified OK: ${flashedMB}MB`); + state = "confirm-reboot"; + } else { + state = "error"; + errorMsg = "flash verify failed"; + addTelemetry("VERIFY FAILED"); + } } } - - // Reboot trigger - if (globalThis.__osRebootFrame && frame >= globalThis.__osRebootFrame) { - globalThis.__osRebootFrame = 0; - system?.reboot?.(); - } } function sim() {} diff --git a/fedac/native/pieces/prompt.mjs b/fedac/native/pieces/prompt.mjs index b9cd04a4fe..9677075134 100644 --- a/fedac/native/pieces/prompt.mjs +++ b/fedac/native/pieces/prompt.mjs @@ -3,6 +3,7 @@ // Anything typed (except "notepat") is evaluated as KidLisp source. let input = ""; +let cursor = 0; // cursor position within input let cursorVisible = true; let cursorFrame = 0; let history = []; @@ -10,6 +11,19 @@ let historyIndex = -1; let message = ""; let messageFrame = 0; let shiftHeld = false; +let frame = 0; + +// WiFi auto-connect state +const AC_SSID = "aesthetic.computer"; +const AC_PASS = "aesthetic.computer"; +const FALLBACK_WIFI = [ + { ssid: "ATT2AWTpcr", pass: "t84q%7%g2h8u" }, + { ssid: "ATTcifXGXi", pass: "=dvt%mnk8h6z" }, +]; +const CREDS_PATH = "/mnt/wifi_creds.json"; +let savedCreds = []; +let autoConnectFrame = 0; +let connectStartFrame = -9999; const SHIFT_MAP = { "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", @@ -18,6 +32,27 @@ const SHIFT_MAP = { ";":":", "'":'"', ",":"<", ".":">", "/":"?", "`":"~", }; +// KidLisp syntax highlighting colors +const KL_KEYWORDS = new Set([ + "ink","line","circle","box","wipe","fade","write","grid","plot", + "spin","zoom","scroll","contrast","noise","blend","mirror", + "w","h","w/2","h/2","t","frame","pi","tau", + "sin","cos","tan","abs","sqrt","floor","ceil","round","min","max","pow","mod", + "?","...", +]); +const KL_COLORS = new Set([ + "red","green","blue","cyan","magenta","yellow","white","black", + "orange","pink","purple","gray","grey","rainbow", +]); + +function klTokenColor(token) { + if (KL_COLORS.has(token)) return [255, 140, 100]; // warm orange for color names + if (KL_KEYWORDS.has(token)) return [120, 180, 255]; // blue for keywords + if (/^-?\d+(\.\d+)?$/.test(token)) return [180, 220, 140]; // green for numbers + if (/^[a-z]/.test(token) && token.includes("/")) return [180, 220, 140]; // w/2 etc + return null; // default +} + // Built-in $code aliases const CODES = { "$roz": `fade:red-blue-black-blue-red @@ -35,8 +70,14 @@ function boot({ system }) { // Restore input from KidLisp return (backspace/escape preserves source) if (globalThis.__promptRestore) { input = globalThis.__promptRestore; + cursor = input.length; globalThis.__promptRestore = undefined; } + // Load saved WiFi credentials + try { + const raw = system?.readFile?.(CREDS_PATH); + if (raw) savedCreds = JSON.parse(raw); + } catch (_) {} } function act({ event: e, system }) { @@ -55,32 +96,51 @@ function act({ event: e, system }) { historyIndex = -1; execute(cmd, system); input = ""; + cursor = 0; } } else if (key === "backspace") { - input = input.slice(0, -1); + if (cursor > 0) { + input = input.slice(0, cursor - 1) + input.slice(cursor); + cursor--; + } + } else if (key === "delete") { + if (cursor < input.length) { + input = input.slice(0, cursor) + input.slice(cursor + 1); + } } else if (key === "escape") { input = ""; + cursor = 0; + } else if (key === "arrowleft") { + if (cursor > 0) cursor--; + } else if (key === "arrowright") { + if (cursor < input.length) cursor++; + } else if (key === "home") { + cursor = 0; + } else if (key === "end") { + cursor = input.length; } else if (key === "arrowup") { if (history.length > 0 && historyIndex < history.length - 1) { historyIndex++; input = history[historyIndex]; + cursor = input.length; } } else if (key === "arrowdown") { if (historyIndex > 0) { historyIndex--; input = history[historyIndex]; + cursor = input.length; } else if (historyIndex === 0) { historyIndex = -1; input = ""; + cursor = 0; } } else if (key === "space") { - input += " "; + input = input.slice(0, cursor) + " " + input.slice(cursor); + cursor++; } else if (key.length === 1) { - if (shiftHeld) { - input += SHIFT_MAP[key] ?? key.toUpperCase(); - } else { - input += key; - } + const ch = shiftHeld ? (SHIFT_MAP[key] ?? key.toUpperCase()) : key; + input = input.slice(0, cursor) + ch + input.slice(cursor); + cursor++; } } } @@ -157,48 +217,159 @@ function execute(cmd, system) { message = "~> lisp"; messageFrame = 0; globalThis.__kidlispSource = cmd; - globalThis.__kidlispLabel = cmd.length > 20 ? cmd.slice(0, 17) + "..." : cmd; + globalThis.__kidlispLabel = cmd; // full source, no truncation system?.jump?.("lisp"); } -function paint({ wipe, ink, box, write, screen, paintCount }) { +// Draw syntax-highlighted KidLisp text +function drawHighlighted(text, x0, y0, charW, ink, write, font) { + // Tokenize by spaces and parens, preserving positions + let cx = x0; + let i = 0; + while (i < text.length) { + // Skip whitespace + if (text[i] === " ") { + cx += charW; + i++; + continue; + } + // Parens get special color + if (text[i] === "(" || text[i] === ")") { + ink(180, 120, 200); // purple parens + write(text[i], { x: cx, y: y0, size: 1, font }); + cx += charW; + i++; + continue; + } + // Colon (fade separator) + if (text[i] === ":") { + ink(140, 140, 160); + write(":", { x: cx, y: y0, size: 1, font }); + cx += charW; + i++; + continue; + } + // Collect token + let token = ""; + const start = i; + while (i < text.length && text[i] !== " " && text[i] !== "(" && text[i] !== ")") { + token += text[i]; + i++; + } + const color = klTokenColor(token.toLowerCase()); + if (color) { + ink(color[0], color[1], color[2]); + } else { + ink(220, 220, 230); // default white + } + write(token, { x: cx, y: y0, size: 1, font }); + cx += token.length * charW; + } +} + +function paint({ wipe, ink, box, write, screen, paintCount, wifi, system }) { + frame++; wipe(40, 20, 60); const W = screen.width; const H = screen.height; + + // WiFi auto-connect (runs every frame, same logic as notepat) + if (wifi && !wifi.connected) { + autoConnectFrame++; + const knownCreds = [ + { ssid: AC_SSID, pass: AC_PASS }, + ...FALLBACK_WIFI, + ...savedCreds.filter(c => c.ssid !== AC_SSID && !FALLBACK_WIFI.find(f => f.ssid === c.ssid)), + ]; + const knownSSIDs = new Set(knownCreds.map(c => c.ssid)); + const isConnecting = wifi.state === 3 || wifi.state === 4; + const isIdle = !isConnecting; + + // Timeout connecting after 5s + if (isConnecting && frame - connectStartFrame > 300) { + wifi.disconnect?.(); + autoConnectFrame = -60; + } + + if (isIdle) { + if (autoConnectFrame % 300 === 0) wifi.scan?.(); + if (autoConnectFrame % 300 === 150) { + const nets = wifi.networks || []; + const matches = nets + .filter(n => n.ssid && knownSSIDs.has(n.ssid)) + .sort((a, b) => b.signal - a.signal); + if (matches.length > 0) { + const best = matches[0]; + const cred = knownCreds.find(c => c.ssid === best.ssid); + wifi.connect(cred.ssid, cred.pass); + connectStartFrame = frame; + } + } + } + } + + // WiFi status indicator (top-right) + { + const sx = W - 6; + if (wifi?.connected) { + ink(80, 200, 80); + box(sx, 2, 4, 4, true); + } else if (wifi) { + ink(frame % 60 < 30 ? 200 : 60, 80, 80); + box(sx, 2, 4, 4, true); + } + } + const charW = 6; // 6x10 font const charH = 10; const lineH = 12; const x0 = 4; const y0 = 4; + const font = "6x10"; // Cursor blink cursorFrame++; if (cursorFrame % 30 === 0) cursorVisible = !cursorVisible; - // Input text - ink(220, 220, 230); - write(input, { x: x0, y: y0, size: 1, font: "6x10" }); + // Input text with syntax highlighting + drawHighlighted(input, x0, y0, charW, ink, write, font); - // Pink block cursor after text + // Pink block cursor at cursor position if (cursorVisible) { - const cx = x0 + input.length * charW; - ink(220, 80, 140); + const cx = x0 + cursor * charW; + ink(220, 80, 140, 180); box(cx, y0, charW, charH, true); + // Draw character under cursor if not at end + if (cursor < input.length) { + ink(255, 255, 255); + write(input[cursor], { x: cx, y: y0, size: 1, font }); + } } - // History below input + // History below input (also syntax highlighted) let hy = y0 + lineH + 4; for (let i = 0; i < history.length && hy < H - 20; i++) { - ink(80, 60, 100); - write(history[i], { x: x0, y: hy, size: 1, font: "6x10" }); + // Dim the history entries + const entry = history[i]; + const lower = entry.toLowerCase(); + // Navigation commands in dim purple, KidLisp source highlighted but dimmed + if (["notepat","np","os","update","net","wifi","version","ver","help","claude","cl","ssh","reboot","clear","cls"].includes(lower)) { + ink(80, 60, 100); + write(entry, { x: x0, y: hy, size: 1, font }); + } else { + // KidLisp history — dim highlight + drawHighlighted(entry, x0, hy, charW, + (r, g, b) => ink(Math.floor(r * 0.4), Math.floor(g * 0.4), Math.floor(b * 0.4)), + write, font); + } hy += lineH; } // Message (bottom) if (message.length > 0) { ink(160, 140, 180); - write(message, { x: x0, y: H - 14, size: 1, font: "6x10" }); + write(message, { x: x0, y: H - 14, size: 1, font }); } } diff --git a/fedac/native/scripts/build-name.sh b/fedac/native/scripts/build-name.sh new file mode 100755 index 0000000000..3126b819df --- /dev/null +++ b/fedac/native/scripts/build-name.sh @@ -0,0 +1,107 @@ +#!/bin/bash +# build-name.sh — Generate a unique build name: adjective-animal +# Animal changes daily, adjective changes every build. Never repeats. +# Usage: ./build-name.sh → prints name (e.g., "swift-otter") +# ./build-name.sh --bump → increments counter and prints name +set -e + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +COUNTER_FILE="${SCRIPT_DIR}/../.build-counter" + +# 365 animals — one per day of year, then wraps to next category +ANIMALS=( + # Mammals (60) + otter fox wolf bear lynx puma deer hare mink vole + stoat badger ferret weasel moose bison yak ibex oryx kudu + okapi tapir sloth koala lemur loris gibbon chimp bonobo mandrill + ocelot serval caracal margay civet genet mongoose meerkat numbat quoll + dingo jackal coyote fennec arctic pangolin aardvark echidna platypus wombat + possum wallaby quokka bandicoot bilby dugong manatee narwhal beluga orca + # Birds (60) + hawk eagle falcon kite osprey owl heron crane stork ibis + egret rail coot loon grebe diver petrel shear gannet booby + tern skua gull puffin murre auk razorbill fulmar albatross condor + vulture kestrel merlin hobby harrier buzzard sparrow finch wren robin + thrush pipit wagtail dipper warbler flicker nuthatch creeper swift martin + swallow nightjar kingfisher roller bee-eater hoopoe hornbill toucan parrot macaw + # Reptiles & Amphibians (40) + gecko lizard skink iguana chameleon monitor tegu cobra mamba adder + viper python anaconda rattler copperhead racer kingsnake milksnake garter coral + tortoise turtle terrapin croc gator caiman gharial newt salamander axolotl + treefrog bullfrog poison dart glass mantella reed toad midwife spadefoot + # Fish & Marine (40) + trout salmon char pike perch bass walleye sturgeon paddlefish gar + bowfin shad herring anchovy sardine mackerel tuna marlin sailfish swordfish + barracuda grouper snapper wrasse goby blenny sculpin flounder sole halibut + ray skate shark hammerhead mako thresher whale catfish carp loach + # Invertebrates (40) + crab lobster shrimp prawn krill squid octopus nautilus cuttlefish clam + mussel oyster scallop conch whelk slug snail leech worm centipede + millipede scorpion spider beetle ant wasp hornet moth butterfly dragonfly + damsel cricket katydid mantis stick leaf cicada firefly ladybug weevil + # Mythical (30) + dragon phoenix griffin sphinx hydra chimera minotaur centaur pegasus unicorn + kraken leviathan basilisk wyvern roc thunderbird yeti sasquatch wendigo golem + djinn nymph sprite pixie sylph dryad selkie kelpie banshee wraith + # Dinosaurs (30) + raptor rex bronto stego trike ankylo ptero diplo allo spino + carno bary dilo parasaur iguano hadro pachycephalo theri oviraptor archaeo + compy gallimimus deinonych utahraptor micro giganoto acro sucho cerato maia + # Space (30) + pulsar quasar nebula nova comet meteor asteroid aurora corona flare + vortex prism zenith apex orbit lunar solar stellar cosmic photon + neutron proton quantum flux ion plasma ember cinder spark blaze + # Nature (35) + river brook creek delta marsh fjord glacier canyon mesa butte + ridge summit caldera geyser lagoon atoll reef tide current drift + breeze gale storm tempest zephyr monsoon aurora borealis solstice equinox + tundra steppe prairie savanna taiga +) + +# 200 adjectives — one per build, then wraps +ADJECTIVES=( + swift bold keen sharp bright vivid lucid agile nimble deft + brave calm clear crisp eager fierce gentle grand hardy jolly + lively merry noble proud quick quiet rapid sleek smooth snappy + steady sturdy subtle supple tender tough vital warm witty zesty + amber ashen azure blaze bronze cedar coral crimson dusk ember + flint frost golden hazel indigo ivory jade khaki lemon lilac + maple mossy navy opal pearl plum quartz russet sage scarlet + silver slate tawny umber velvet walnut zinc cobalt copper flax + dusty foggy hazy misty polar rustic stormy sunlit twilit wintry + ancient arcane astral cosmic cryptic digital feral hollow lunar mystic + neural orbital primal radiant sacred silent spectral temporal verdant woven + atomic binary cubic delta fractal harmonic infinite kinetic lattice modular + native oxide quantum reflex sonic turbo ultra vector wavelength xeric + ablaze acoustic alpine boreal carbon ceramic crystal dynamic elastic frozen + galactic hybrid igneous magnetic mineral organic prismatic resonant seismic thermal + alloy basalt chalk flint granite jasper marble obsidian pumice quartz + sandstone shale slate soapstone travertine basaltic chalky flinty granitic jaspery + lustrous matte opaque pearly polished rough satin silky textured uncut + aerial aquatic benthic coastal estuarine glacial insular littoral pelagic riparian + alpine arid boreal humid polar steppe sylvan tropic tundral volcanic +) + +NUM_ANIMALS=${#ANIMALS[@]} +NUM_ADJ=${#ADJECTIVES[@]} + +# Animal: based on day-of-year (changes daily) +DOY=$(date -u '+%j' | sed 's/^0*//') # strip leading zeros +ANIMAL_IDX=$(( (DOY - 1) % NUM_ANIMALS )) + +# Adjective: based on build counter (changes every build) +if [ -f "${COUNTER_FILE}" ]; then + BUILD_NUM=$(cat "${COUNTER_FILE}" 2>/dev/null || echo "0") +else + BUILD_NUM=0 +fi + +# Bump if requested +if [ "${1:-}" = "--bump" ]; then + BUILD_NUM=$(( BUILD_NUM + 1 )) + echo "${BUILD_NUM}" > "${COUNTER_FILE}" +fi + +ADJ_IDX=$(( BUILD_NUM % NUM_ADJ )) + +echo "${ADJECTIVES[$ADJ_IDX]}-${ANIMALS[$ANIMAL_IDX]}" diff --git a/fedac/native/scripts/track-build.mjs b/fedac/native/scripts/track-build.mjs new file mode 100644 index 0000000000..b409118e36 --- /dev/null +++ b/fedac/native/scripts/track-build.mjs @@ -0,0 +1,190 @@ +#!/usr/bin/env node +// track-build.mjs — Track OTA builds in MongoDB and generate unique build names +// Usage: +// node track-build.mjs next-name → get next build name (adjective-animal) +// node track-build.mjs record → record a build after upload +// +// Env: MONGODB_CONNECTION_STRING, MONGODB_NAME +// Stdin for "record": JSON { version, sha256, size, git_hash, build_ts, url } + +import { MongoClient } from "mongodb"; + +const ANIMALS = [ + // Mammals (60) + "otter","fox","wolf","bear","lynx","puma","deer","hare","mink","vole", + "stoat","badger","ferret","weasel","moose","bison","yak","ibex","oryx","kudu", + "okapi","tapir","sloth","koala","lemur","loris","gibbon","chimp","bonobo","mandrill", + "ocelot","serval","caracal","margay","civet","genet","mongoose","meerkat","numbat","quoll", + "dingo","jackal","coyote","fennec","arctic","pangolin","aardvark","echidna","platypus","wombat", + "possum","wallaby","quokka","bandicoot","bilby","dugong","manatee","narwhal","beluga","orca", + // Birds (60) + "hawk","eagle","falcon","kite","osprey","owl","heron","crane","stork","ibis", + "egret","rail","coot","loon","grebe","diver","petrel","shear","gannet","booby", + "tern","skua","gull","puffin","murre","auk","razorbill","fulmar","albatross","condor", + "vulture","kestrel","merlin","hobby","harrier","buzzard","sparrow","finch","wren","robin", + "thrush","pipit","wagtail","dipper","warbler","flicker","nuthatch","creeper","swift","martin", + "swallow","nightjar","kingfisher","roller","bee-eater","hoopoe","hornbill","toucan","parrot","macaw", + // Reptiles & Amphibians (40) + "gecko","lizard","skink","iguana","chameleon","monitor","tegu","cobra","mamba","adder", + "viper","python","anaconda","rattler","copperhead","racer","kingsnake","milksnake","garter","coral", + "tortoise","turtle","terrapin","croc","gator","caiman","gharial","newt","salamander","axolotl", + "treefrog","bullfrog","poison-dart","glass-frog","mantella","reed-frog","toad","midwife","spadefoot","hellbender", + // Fish & Marine (40) + "trout","salmon","char","pike","perch","bass","walleye","sturgeon","paddlefish","gar", + "bowfin","shad","herring","anchovy","sardine","mackerel","tuna","marlin","sailfish","swordfish", + "barracuda","grouper","snapper","wrasse","goby","blenny","sculpin","flounder","sole","halibut", + "ray","skate","shark","hammerhead","mako","thresher","whale","catfish","carp","loach", + // Invertebrates (40) + "crab","lobster","shrimp","prawn","krill","squid","octopus","nautilus","cuttlefish","clam", + "mussel","oyster","scallop","conch","whelk","slug","snail","leech","worm","centipede", + "millipede","scorpion","spider","beetle","ant","wasp","hornet","moth","butterfly","dragonfly", + "damsel","cricket","katydid","mantis","stick-bug","leaf-bug","cicada","firefly","ladybug","weevil", + // Mythical (30) + "dragon","phoenix","griffin","sphinx","hydra","chimera","minotaur","centaur","pegasus","unicorn", + "kraken","leviathan","basilisk","wyvern","roc","thunderbird","yeti","sasquatch","wendigo","golem", + "djinn","nymph","sprite","pixie","sylph","dryad","selkie","kelpie","banshee","wraith", + // Dinosaurs (30) + "raptor","rex","bronto","stego","trike","ankylo","ptero","diplo","allo","spino", + "carno","bary","dilo","parasaur","iguano","hadro","pachycephalo","theri","oviraptor","archaeo", + "compy","gallimimus","deinonych","utahraptor","micro","giganoto","acro","sucho","cerato","maia", + // Space (30) + "pulsar","quasar","nebula","nova","comet","meteor","asteroid","aurora","corona","flare", + "vortex","prism","zenith","apex","orbit","lunar","solar","stellar","cosmic","photon", + "neutron","proton","quantum","flux","ion","plasma","ember","cinder","spark","blaze", + // Nature (35) + "river","brook","creek","delta","marsh","fjord","glacier","canyon","mesa","butte", + "ridge","summit","caldera","geyser","lagoon","atoll","reef","tide","current","drift", + "breeze","gale","storm","tempest","zephyr","monsoon","cascade","terrace","solstice","equinox", + "tundra","steppe","prairie","savanna","taiga", +]; + +const ADJECTIVES = [ + "swift","bold","keen","sharp","bright","vivid","lucid","agile","nimble","deft", + "brave","calm","clear","crisp","eager","fierce","gentle","grand","hardy","jolly", + "lively","merry","noble","proud","quick","quiet","rapid","sleek","smooth","snappy", + "steady","sturdy","subtle","supple","tender","tough","vital","warm","witty","zesty", + "amber","ashen","azure","blaze","bronze","cedar","coral","crimson","dusk","ember", + "flint","frost","golden","hazel","indigo","ivory","jade","khaki","lemon","lilac", + "maple","mossy","navy","opal","pearl","plum","quartz","russet","sage","scarlet", + "silver","slate","tawny","umber","velvet","walnut","zinc","cobalt","copper","flax", + "dusty","foggy","hazy","misty","polar","rustic","stormy","sunlit","twilit","wintry", + "ancient","arcane","astral","cosmic","cryptic","digital","feral","hollow","lunar","mystic", + "neural","orbital","primal","radiant","sacred","silent","spectral","temporal","verdant","woven", + "atomic","binary","cubic","delta","fractal","harmonic","infinite","kinetic","lattice","modular", + "native","oxide","sonic","turbo","ultra","vector","wavelength","xeric","glacial","thermal", + "ablaze","acoustic","alpine","boreal","carbon","ceramic","crystal","dynamic","elastic","frozen", + "galactic","hybrid","igneous","magnetic","mineral","organic","prismatic","resonant","seismic","tidal", + "alloy","basalt","chalk","granite","jasper","marble","obsidian","pumice","sandstone","shale", + "lustrous","matte","opaque","pearly","polished","rough","satin","silky","textured","uncut", + "aerial","aquatic","benthic","coastal","estuarine","insular","littoral","pelagic","riparian","sylvan", + "arid","humid","tropic","volcanic","stellar","rugged","mossy","dusted","gilded","tempered", + "chromatic","iridescent","phosphor","titanium","tungsten","vanadium","zircon","rhodium","osmium","bismuth", +]; + +const COLLECTION = "builds"; + +async function getDb() { + const connStr = process.env.MONGODB_CONNECTION_STRING; + const dbName = process.env.MONGODB_NAME; + if (!connStr || !dbName) { + throw new Error("Missing MONGODB_CONNECTION_STRING or MONGODB_NAME"); + } + const client = new MongoClient(connStr); + await client.connect(); + return { db: client.db(dbName), client }; +} + +// Get day-of-year (1-indexed) +function dayOfYear() { + const now = new Date(); + const start = new Date(now.getFullYear(), 0, 0); + return Math.floor((now - start) / 86400000); +} + +async function nextName() { + const { db, client } = await getDb(); + try { + // Get or create counter document + const counters = db.collection("counters"); + const result = await counters.findOneAndUpdate( + { _id: "build_number" }, + { $inc: { seq: 1 } }, + { upsert: true, returnDocument: "after" } + ); + const buildNum = result.seq; + const doy = dayOfYear(); + + const animal = ANIMALS[doy % ANIMALS.length]; + const adj = ADJECTIVES[buildNum % ADJECTIVES.length]; + const name = `${adj}-${animal}`; + + // If we've exhausted all adjectives for this animal, the day will change + // and we get a new animal. With 200 adj * 365 animals = 73,000 unique names + // before any repeat. At that point we can add more words. + + return { name, buildNum }; + } finally { + await client.close(); + } +} + +async function recordBuild() { + // Read build info from stdin + let input = ""; + for await (const chunk of process.stdin) input += chunk; + const info = JSON.parse(input); + + const { db, client } = await getDb(); + try { + const builds = db.collection(COLLECTION); + await builds.insertOne({ + name: info.name, + buildNum: info.buildNum, + version: info.version, + sha256: info.sha256, + size: info.size, + gitHash: info.git_hash, + buildTs: info.build_ts, + url: info.url, + when: new Date(), + }); + // Also update a "latest" document for quick lookup + await builds.updateOne( + { _id: "latest" }, + { $set: { + name: info.name, + version: info.version, + sha256: info.sha256, + when: new Date(), + }}, + { upsert: true } + ); + } finally { + await client.close(); + } +} + +const cmd = process.argv[2]; +try { + if (cmd === "next-name") { + const { name, buildNum } = await nextName(); + // Output as JSON so caller can parse both + console.log(JSON.stringify({ name, buildNum })); + } else if (cmd === "record") { + await recordBuild(); + process.stderr.write("Build recorded in MongoDB\n"); + } else { + console.error("Usage: track-build.mjs {next-name|record}"); + process.exit(1); + } +} catch (e) { + // Don't block the build pipeline if MongoDB is down + process.stderr.write(`track-build: ${e.message}\n`); + if (cmd === "next-name") { + // Fallback: local-only name + const doy = dayOfYear(); + const fallbackNum = Date.now() % ADJECTIVES.length; + const name = `${ADJECTIVES[fallbackNum]}-${ANIMALS[doy % ANIMALS.length]}`; + console.log(JSON.stringify({ name, buildNum: -1 })); + } +} diff --git a/fedac/native/scripts/upload-release.sh b/fedac/native/scripts/upload-release.sh index ca909d9aeb..cf02bd2836 100755 --- a/fedac/native/scripts/upload-release.sh +++ b/fedac/native/scripts/upload-release.sh @@ -14,10 +14,30 @@ if [ ! -f "$VMLINUZ" ]; then exit 1 fi -# Credentials — source from vault if not already in env -VAULT_ENV="${SCRIPT_DIR}/../../../aesthetic-computer-vault/fedac/native/upload.env" -if [ -f "$VAULT_ENV" ]; then - set -a; source "$VAULT_ENV"; set +a +# Credentials — check env (set by ac-os), session cache, plaintext vault, or GPG decrypt +if [ -z "${DO_SPACES_KEY:-}" ] || [ -z "${DO_SPACES_SECRET:-}" ]; then + # Session cache (written by ac-os load_vault_creds) + [ -f "/tmp/.ac-upload-env" ] && { set -a; source "/tmp/.ac-upload-env"; set +a; } +fi +if [ -z "${DO_SPACES_KEY:-}" ] || [ -z "${DO_SPACES_SECRET:-}" ]; then + # Plaintext vault file + VAULT_ENV="${SCRIPT_DIR}/../../../aesthetic-computer-vault/fedac/native/upload.env" + [ -f "$VAULT_ENV" ] && { set -a; source "$VAULT_ENV"; set +a; } +fi +if [ -z "${DO_SPACES_KEY:-}" ] || [ -z "${DO_SPACES_SECRET:-}" ]; then + # GPG decrypt from vault + for gpg_file in \ + "${SCRIPT_DIR}/../upload.env.gpg" \ + "${SCRIPT_DIR}/../../../aesthetic-computer-vault/fedac/native/upload.env.gpg"; do + if [ -f "$gpg_file" ]; then + echo "[upload] Decrypting $(basename "$gpg_file")..." + DECRYPTED=$(gpg --pinentry-mode loopback -d "$gpg_file" 2>/dev/null | grep "=") || true + if [ -n "$DECRYPTED" ]; then + set -a; eval "$DECRYPTED"; set +a + break + fi + fi + done fi : "${DO_SPACES_KEY:?DO_SPACES_KEY not set}" @@ -27,8 +47,11 @@ DO_SPACES_REGION="${DO_SPACES_REGION:-sfo3}" BASE_URL="https://${DO_SPACES_BUCKET}.${DO_SPACES_REGION}.digitaloceanspaces.com" -# Build version string from git +# Build version string from git (append -dirty if uncommitted changes) GIT_HASH=$(git -C "$SCRIPT_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown") +if ! git -C "$SCRIPT_DIR" diff --quiet HEAD 2>/dev/null; then + GIT_HASH="${GIT_HASH}-dirty" +fi BUILD_TS=$(date -u '+%Y-%m-%dT%H:%M') # Format must match AC_GIT_HASH "-" AC_BUILD_TS in js-bindings.c / Makefile VERSION="${GIT_HASH}-${BUILD_TS}" @@ -37,7 +60,20 @@ VERSION="${GIT_HASH}-${BUILD_TS}" SHA256=$(sha256sum "$VMLINUZ" | awk '{print $1}') SIZE=$(stat -c%s "$VMLINUZ") +# Generate build name from MongoDB (global counter + day-of-year animal) +BUILD_NAME="" +BUILD_NUM="" +if command -v node &>/dev/null; then + NAME_JSON=$(node "$SCRIPT_DIR/track-build.mjs" next-name 2>/dev/null || echo '{}') + BUILD_NAME=$(echo "$NAME_JSON" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('name',''))" 2>/dev/null || true) + BUILD_NUM=$(echo "$NAME_JSON" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('buildNum',''))" 2>/dev/null || true) +fi +if [ -z "$BUILD_NAME" ]; then + BUILD_NAME="local-$(date -u +%s)" +fi + echo "Uploading notepat release: $VERSION" +echo " name: $BUILD_NAME (#${BUILD_NUM:-?})" echo " vmlinuz: $(du -sh "$VMLINUZ" | cut -f1)" echo " sha256: $SHA256" @@ -74,7 +110,9 @@ do_upload() { TMP=$(mktemp -d) trap "rm -rf $TMP" EXIT -printf '%s' "$VERSION" > "$TMP/version.txt" +# Include build name in version string for display on device +FULL_VERSION="${BUILD_NAME} ${VERSION}" +printf '%s' "$FULL_VERSION" > "$TMP/version.txt" printf '%s' "$SHA256" > "$TMP/sha256.txt" # Upload files (vmlinuz last — it's large, others are the canary) @@ -88,14 +126,15 @@ curl -sf "${BASE_URL}/os/releases.json" -o "$RELEASES_JSON" 2>/dev/null \ || echo '{"releases":[]}' > "$RELEASES_JSON" # Append new entry (keep last 50) -python3 - "$RELEASES_JSON" "$VERSION" "$SHA256" "$SIZE" "$GIT_HASH" "$BUILD_TS" <<'PYEOF' +python3 - "$RELEASES_JSON" "$FULL_VERSION" "$SHA256" "$SIZE" "$GIT_HASH" "$BUILD_TS" "$BUILD_NAME" <<'PYEOF' import sys, json -path, version, sha256, size, git_hash, build_ts = sys.argv[1:] +path, version, sha256, size, git_hash, build_ts, name = sys.argv[1:] with open(path) as f: data = json.load(f) releases = data.get("releases", []) releases.insert(0, { "version": version, + "name": name, "sha256": sha256, "size": int(size), "git_hash": git_hash, @@ -104,13 +143,20 @@ releases.insert(0, { }) data["releases"] = releases[:50] data["latest"] = version +data["latest_name"] = name with open(path, "w") as f: json.dump(data, f, indent=2) PYEOF do_upload "$RELEASES_JSON" "os/releases.json" "application/json" +# Record build in MongoDB +if command -v node &>/dev/null; then + echo "{\"name\":\"$BUILD_NAME\",\"buildNum\":$BUILD_NUM,\"version\":\"$FULL_VERSION\",\"sha256\":\"$SHA256\",\"size\":$SIZE,\"git_hash\":\"$GIT_HASH\",\"build_ts\":\"$BUILD_TS\",\"url\":\"${BASE_URL}/os/native-notepat-latest.vmlinuz\"}" \ + | node "$SCRIPT_DIR/track-build.mjs" record 2>&1 || true +fi + echo "" -echo "Release published: $VERSION" +echo "Release published: $BUILD_NAME ($FULL_VERSION)" echo " ${BASE_URL}/os/native-notepat-latest.vmlinuz" echo " ${BASE_URL}/os/releases.json" diff --git a/fedac/native/src/ac-native.c b/fedac/native/src/ac-native.c index 8c1701ab8e..c42df5a606 100644 --- a/fedac/native/src/ac-native.c +++ b/fedac/native/src/ac-native.c @@ -73,7 +73,7 @@ static void perf_record(PerfRecord *r) { // Write current buffer as a numbered chunk file, fsync, close, then // delete the oldest chunk if we exceed PERF_MAX_CHUNKS. -static void perf_flush(void) { +void perf_flush(void) { if (!perf_buf || perf_buf_count == 0) return; char path[128]; @@ -136,6 +136,14 @@ void ac_log(const char *fmt, ...) { va_end(args2); } +// Flush log file to disk without closing it +void ac_log_flush(void) { + if (logfile) { + fflush(logfile); + fsync(fileno(logfile)); + } +} + // Temporarily close the log file (e.g. before flash writes to same partition) void ac_log_pause(void) { if (logfile) { @@ -1093,6 +1101,26 @@ static void draw_boot_status(ACGraph *graph, ACFramebuffer *screen, uint8_t bg = dk ? 20 : 255; graph_wipe(graph, (ACColor){bg, bg, (uint8_t)(bg + (dk ? 5 : 0)), 255}); + // Zebra stripes — alternating black/white, scrolling diagonally + { + int stripe_h = 4; + int total = screen->height / stripe_h + 2; + int offset = boot_frame % (stripe_h * 2); + for (int s = 0; s < total; s++) { + int sy = s * stripe_h - offset; + if (s % 2 == 0) { + uint8_t v = 240; + graph_ink(graph, (ACColor){v, v, v, 60}); + } else { + uint8_t v = 10; + graph_ink(graph, (ACColor){v, v, v, 60}); + } + // Diagonal: shift x by row for zebra angle + int skew = (s * 8 + boot_frame) % screen->width; + graph_box(graph, 0, sy, screen->width, stripe_h, 1); + } + } + // Bounce: title oscillates with a decaying sine double bounce_t = (double)af / 20.0; int bounce_y = (int)(6.0 * sin(bounce_t * 3.14159 * 2) * (1.0 - bounce_t)); @@ -1177,6 +1205,7 @@ int main(int argc, char *argv[]) { ACDisplay *display = NULL; ACFramebuffer *screen = NULL; ACInput *input = NULL; + int pixel_scale = 3; // Default: 1/3 display resolution (3x nearest-neighbor) if (!headless) { display = drm_init(); @@ -1186,8 +1215,7 @@ int main(int argc, char *argv[]) { return 1; } - // 1/3 display resolution (3x nearest-neighbor scale) - screen = fb_create(display->width / 3, display->height / 3); + screen = fb_create(display->width / pixel_scale, display->height / pixel_scale); if (!screen) { drm_destroy(display); return 1; @@ -1229,7 +1257,7 @@ int main(int argc, char *argv[]) { // Init input if (!headless) { - input = input_init(display->width, display->height, 3); + input = input_init(display->width, display->height, pixel_scale); } // Find backlight path (scan /sys/class/backlight/ for any device) @@ -1333,7 +1361,7 @@ int main(int argc, char *argv[]) { char msg[256]; snprintf(msg, sizeof(msg), "Cannot load: %s", piece_path); font_draw(&graph, msg, 20, 20, 2); - display_present(display, screen, 3); + display_present(display, screen, pixel_scale); sleep(10); } js_destroy(rt); @@ -1417,11 +1445,28 @@ int main(int argc, char *argv[]) { } } // Hardware keys + static int ctrl_held = 0; int power_pressed = 0; + int scale_change = 0; // -1 = decrease density (bigger pixels), +1 = increase for (int i = 0; i < input->event_count; i++) { + // Track ctrl modifier + if (input->events[i].key_code == KEY_LEFTCTRL || input->events[i].key_code == KEY_RIGHTCTRL) { + ctrl_held = (input->events[i].type == AC_EVENT_KEYBOARD_DOWN) ? 1 : 0; + } if (input->events[i].type == AC_EVENT_KEYBOARD_DOWN) { + // Ctrl+= (or Ctrl++) → bigger pixels (increase scale number) + // Ctrl+- → smaller pixels (decrease scale number) + if (ctrl_held && (input->events[i].key_code == KEY_EQUAL || + input->events[i].key_code == KEY_KPPLUS)) { + scale_change = -1; // bigger pixels (lower res) + } else if (ctrl_held && (input->events[i].key_code == KEY_MINUS || + input->events[i].key_code == KEY_KPMINUS)) { + scale_change = 1; // smaller pixels (higher res) + } else if (ctrl_held && input->events[i].key_code == KEY_0) { + scale_change = 99; // reset to default (3) + } // Volume: KEY_VOLUMEUP/DOWN/MUTE or F1/F2/F3 as fallback - if (strcmp(input->events[i].key_name, "audiovolumeup") == 0 || + else if (strcmp(input->events[i].key_name, "audiovolumeup") == 0 || strcmp(input->events[i].key_name, "f3") == 0) { audio_volume_adjust(audio, 1); audio_synth(audio, WAVE_SINE, 1200.0, 0.04, 0.15, 0.001, 0.03, 0.0); @@ -1462,6 +1507,43 @@ int main(int argc, char *argv[]) { } } + // Pixel density scale change + if (scale_change && display) { + int new_scale = pixel_scale; + if (scale_change == 99) { + new_scale = 3; // reset to default + } else if (scale_change == 1) { + // Increase density: scale 6→4→3→2→1 + if (pixel_scale > 3) new_scale = pixel_scale - 2; + else if (pixel_scale > 1) new_scale = pixel_scale - 1; + } else if (scale_change == -1) { + // Decrease density: scale 1→2→3→4→6 + if (pixel_scale < 3) new_scale = pixel_scale + 1; + else if (pixel_scale < 6) new_scale = pixel_scale + 2; + } + if (new_scale != pixel_scale && new_scale >= 1 && new_scale <= 6) { + pixel_scale = new_scale; + // Recreate framebuffer at new resolution + ACFramebuffer *new_screen = fb_create(display->width / pixel_scale, + display->height / pixel_scale); + if (new_screen) { + fb_destroy(screen); + screen = new_screen; + graph_init(&graph, screen); + input->scale = pixel_scale; + // Update JS runtime's graph reference (holds framebuffer) + if (rt) { + rt->graph = &graph; + } + ac_log("[scale] pixel_scale=%d resolution=%dx%d", + pixel_scale, screen->width, screen->height); + audio_synth(audio, WAVE_SINE, + 440.0 + (6 - pixel_scale) * 150.0, + 0.06, 0.15, 0.002, 0.05, 0.0); + } + } + } + if (power_pressed) { // Say bye IMMEDIATELY (TTS + shutdown chime start before animation) char bye_title[80]; @@ -1522,13 +1604,13 @@ int main(int argc, char *argv[]) { screen->height / 2 + 10 + jy / 2, 1); } - display_present(display, screen, 3); + display_present(display, screen, pixel_scale); frame_sync_60fps(&anim_time); } // Final black frame graph_wipe(&graph, (ACColor){0, 0, 0, 255}); - display_present(display, screen, 3); + display_present(display, screen, pixel_scale); running = 0; break; @@ -1600,7 +1682,7 @@ int main(int argc, char *argv[]) { // Software cursor (AC precise cursor: teal crosshair + shadow + white center) if (input && (input->pointer_x || input->pointer_y)) { - int cx = input->pointer_x / 3, cy = input->pointer_y / 3; + int cx = input->pointer_x / pixel_scale, cy = input->pointer_y / pixel_scale; // Shadow (black, offset +1,+1) graph_ink(&graph, (ACColor){0, 0, 0, 180}); graph_line(&graph, cx+1, cy-9, cx+1, cy-4); // top @@ -1621,7 +1703,7 @@ int main(int argc, char *argv[]) { clock_gettime(CLOCK_MONOTONIC, &_pf_paint1); clock_gettime(CLOCK_MONOTONIC, &_pf_pres0); - display_present(display, screen, 3); + display_present(display, screen, pixel_scale); clock_gettime(CLOCK_MONOTONIC, &_pf_pres1); // HDMI: render waveform at ~7.5Hz (every 8 frames) — 4K dumb-buf is slow diff --git a/fedac/native/src/audio.c b/fedac/native/src/audio.c index a450dbeaf7..b8adb40ba7 100644 --- a/fedac/native/src/audio.c +++ b/fedac/native/src/audio.c @@ -1268,9 +1268,10 @@ void audio_sample_update(ACAudio *audio, uint64_t id, double freq, for (int i = 0; i < AUDIO_MAX_SAMPLE_VOICES; i++) { SampleVoice *sv = &audio->sample_voices[i]; if (sv->active && sv->id == id) { - sv->speed = (freq / base_freq) * ((double)audio->sample_rate / (double)audio->actual_rate); - sv->volume = volume; - sv->pan = pan; + if (freq > 0 && base_freq > 0) + sv->speed = (freq / base_freq) * ((double)audio->sample_rate / (double)audio->actual_rate); + if (volume >= 0) sv->volume = volume; + if (pan > -2) sv->pan = pan; break; } } diff --git a/fedac/native/src/graph.c b/fedac/native/src/graph.c index 365b686d40..7ae4685901 100644 --- a/fedac/native/src/graph.c +++ b/fedac/native/src/graph.c @@ -192,27 +192,27 @@ void graph_zoom(ACGraph *g, double level) { ACFramebuffer *fb = g->fb; if (!fb || level <= 0.0 || fabs(level - 1.0) < 1e-6) return; - size_t buf_size = (size_t)fb->width * fb->height * sizeof(uint32_t); + const int w = fb->width; + const int h = fb->height; + size_t buf_size = (size_t)w * h * sizeof(uint32_t); uint32_t *tmp = malloc(buf_size); if (!tmp) return; memcpy(tmp, fb->pixels, buf_size); - const double cx = (fb->width - 1) * 0.5; - const double cy = (fb->height - 1) * 0.5; + const double cx = (w - 1) * 0.5; + const double cy = (h - 1) * 0.5; const double inv = 1.0 / level; - for (int y = 0; y < fb->height; y++) { - for (int x = 0; x < fb->width; x++) { + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { const double src_xf = cx + (x - cx) * inv; const double src_yf = cy + (y - cy) * inv; - const int sx = (int)llround(src_xf); - const int sy = (int)llround(src_yf); + int sx = (int)llround(src_xf) % w; + int sy = (int)llround(src_yf) % h; + if (sx < 0) sx += w; + if (sy < 0) sy += h; - uint32_t out = 0xFF000000; - if (sx >= 0 && sx < fb->width && sy >= 0 && sy < fb->height) { - out = tmp[sy * fb->stride + sx]; - } - fb->pixels[y * fb->stride + x] = out; + fb->pixels[y * fb->stride + x] = tmp[sy * fb->stride + sx]; } } free(tmp); @@ -250,26 +250,26 @@ void graph_spin(ACGraph *g, double angle_radians) { if (!tmp) return; memcpy(tmp, fb->pixels, buf_size); - const double cx = (fb->width - 1) * 0.5; - const double cy = (fb->height - 1) * 0.5; + const int w = fb->width; + const int h = fb->height; + const double cx = (w - 1) * 0.5; + const double cy = (h - 1) * 0.5; const double c = cos(angle_radians); const double s = sin(angle_radians); - // Inverse mapping: destination -> source for hole-free rotation. - for (int y = 0; y < fb->height; y++) { - for (int x = 0; x < fb->width; x++) { + // Inverse mapping: destination -> source with toroidal wrapping. + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { const double dx = x - cx; const double dy = y - cy; const double src_xf = cx + (dx * c + dy * s); const double src_yf = cy + (-dx * s + dy * c); - const int sx = (int)llround(src_xf); - const int sy = (int)llround(src_yf); + int sx = (int)llround(src_xf) % w; + int sy = (int)llround(src_yf) % h; + if (sx < 0) sx += w; + if (sy < 0) sy += h; - uint32_t out = 0xFF000000; - if (sx >= 0 && sx < fb->width && sy >= 0 && sy < fb->height) { - out = tmp[sy * fb->stride + sx]; - } - fb->pixels[y * fb->stride + x] = out; + fb->pixels[y * fb->stride + x] = tmp[sy * fb->stride + sx]; } } free(tmp); diff --git a/fedac/native/src/js-bindings.c b/fedac/native/src/js-bindings.c index 374fd25c7f..5d6d4ce7b3 100644 --- a/fedac/native/src/js-bindings.c +++ b/fedac/native/src/js-bindings.c @@ -17,8 +17,10 @@ // Defined in ac-native.c — logs to USB mount extern void ac_log(const char *fmt, ...); +extern void ac_log_flush(void); extern void ac_log_pause(void); extern void ac_log_resume(void); +extern void perf_flush(void); // Thread-local reference to current runtime (for C callbacks from JS) static __thread ACRuntime *current_rt = NULL; @@ -622,6 +624,38 @@ static JSValue js_mic_sample_rate(JSContext *ctx, JSValueConst this_val) { return JS_NewInt32(ctx, current_rt->audio->sample_rate); } +// sampleObj.update({tone, base, volume, pan}) — update a playing sample voice +static JSValue js_sample_obj_update(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { + ACAudio *audio = current_rt->audio; + if (!audio || argc < 1 || !JS_IsObject(argv[0])) return JS_UNDEFINED; + + JSValue id_v = JS_GetPropertyStr(ctx, this_val, "id"); + double id_d = 0; + if (JS_IsNumber(id_v)) JS_ToFloat64(ctx, &id_d, id_v); + JS_FreeValue(ctx, id_v); + uint64_t id = (uint64_t)id_d; + if (id == 0) return JS_UNDEFINED; + + double freq = -1, base_freq = -1, vol = -1, pan = -3; + JSValue v; + v = JS_GetPropertyStr(ctx, argv[0], "tone"); + if (JS_IsNumber(v)) JS_ToFloat64(ctx, &freq, v); + JS_FreeValue(ctx, v); + v = JS_GetPropertyStr(ctx, argv[0], "base"); + if (JS_IsNumber(v)) JS_ToFloat64(ctx, &base_freq, v); + JS_FreeValue(ctx, v); + v = JS_GetPropertyStr(ctx, argv[0], "volume"); + if (JS_IsNumber(v)) JS_ToFloat64(ctx, &vol, v); + JS_FreeValue(ctx, v); + v = JS_GetPropertyStr(ctx, argv[0], "pan"); + if (JS_IsNumber(v)) JS_ToFloat64(ctx, &pan, v); + JS_FreeValue(ctx, v); + + if (freq > 0 && base_freq < 0) base_freq = 261.63; // default C4 + audio_sample_update(audio, id, freq, base_freq, vol, pan); + return JS_UNDEFINED; +} + // sound.sample.play({tone, base, volume, pan}) — play recorded sample at pitch static JSValue js_sample_play(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { (void)this_val; @@ -656,10 +690,11 @@ static JSValue js_sample_play(JSContext *ctx, JSValueConst this_val, int argc, J uint64_t id = audio_sample_play(audio, freq, base_freq, volume, pan, loop); if (id == 0) return JS_UNDEFINED; - // Return object with id, kill(), update() + // Return object with id, update(), isSample JSValue snd = JS_NewObject(ctx); JS_SetPropertyStr(ctx, snd, "id", JS_NewFloat64(ctx, (double)id)); JS_SetPropertyStr(ctx, snd, "isSample", JS_TRUE); + JS_SetPropertyStr(ctx, snd, "update", JS_NewCFunction(ctx, js_sample_obj_update, "update", 1)); return snd; } @@ -1838,6 +1873,21 @@ static void *flash_thread_fn(void *arg) { ac_log("[flash] starting: src=%s device=%s", rt->flash_src, rt->flash_device); + // Check if device node exists + { + struct stat dev_st; + if (stat(rt->flash_device, &dev_st) != 0) { + ac_log("[flash] device %s does not exist (errno=%d %s)", + rt->flash_device, errno, strerror(errno)); + rt->flash_phase = 4; + rt->flash_ok = 0; + rt->flash_pending = 0; + rt->flash_done = 1; + return NULL; + } + ac_log("[flash] device %s exists (mode=0%o)", rt->flash_device, dev_st.st_mode); + } + // Mount the EFI partition. Always mount fresh at /tmp/efi to avoid // confusion with the logging mount at /mnt (which may point at the same // partition but doesn't guarantee EFI/BOOT/ exists). @@ -1845,18 +1895,50 @@ static void *flash_thread_fn(void *arg) { int did_mount = 0; mkdir("/tmp/efi", 0755); umount("/tmp/efi"); // clean up any stale mount - if (mount(rt->flash_device, "/tmp/efi", "vfat", 0, NULL) == 0) { - efi_mount = "/tmp/efi"; - did_mount = 1; - ac_log("[flash] mounted %s at /tmp/efi", rt->flash_device); - } else { + + // Try vfat first, then ext4 (NVMe might have either) + const char *fstypes[] = {"vfat", "ext4", "ext2", NULL}; + for (int fi = 0; fstypes[fi] && !did_mount; fi++) { + int mr = mount(rt->flash_device, "/tmp/efi", fstypes[fi], 0, NULL); + if (mr == 0) { + efi_mount = "/tmp/efi"; + did_mount = 1; + ac_log("[flash] mounted %s at /tmp/efi (type=%s)", rt->flash_device, fstypes[fi]); + } else { + ac_log("[flash] mount %s as %s failed: errno=%d (%s)", + rt->flash_device, fstypes[fi], errno, strerror(errno)); + } + } + + // If all mounts failed and this is NVMe, try formatting as vfat (fresh drive) + if (!did_mount && strstr(rt->flash_device, "nvme")) { + ac_log("[flash] NVMe mount failed — attempting mkfs.vfat on %s", rt->flash_device); + char cmd[256]; + snprintf(cmd, sizeof(cmd), "mkfs.vfat -F 32 -n ACBOOT %s 2>&1", rt->flash_device); + FILE *p = popen(cmd, "r"); + if (p) { + char buf[256]; + while (fgets(buf, sizeof(buf), p)) ac_log("[flash] mkfs: %s", buf); + int rc = pclose(p); + ac_log("[flash] mkfs exit=%d", rc); + if (rc == 0) { + if (mount(rt->flash_device, "/tmp/efi", "vfat", 0, NULL) == 0) { + efi_mount = "/tmp/efi"; + did_mount = 1; + ac_log("[flash] mounted fresh vfat on %s", rt->flash_device); + } + } + } + } + + if (!did_mount) { // Fallback: /mnt might already have this partition if (access("/mnt/EFI/BOOT", F_OK) == 0) { efi_mount = "/mnt"; - ac_log("[flash] using existing /mnt mount (fresh mount failed errno=%d)", errno); + ac_log("[flash] using existing /mnt mount (fresh mount failed)"); } else { - ac_log("[flash] mount %s failed (errno=%d %s) and /mnt has no EFI/BOOT", - rt->flash_device, errno, strerror(errno)); + ac_log("[flash] ABORT: mount %s failed and /mnt has no EFI/BOOT", + rt->flash_device); rt->flash_phase = 4; rt->flash_ok = 0; rt->flash_pending = 0; @@ -1864,11 +1946,14 @@ static void *flash_thread_fn(void *arg) { return NULL; } } - // Validate EFI directory exists on the mount + // Create EFI directory structure if it doesn't exist (fresh NVMe install) char efi_dir[512]; + snprintf(efi_dir, sizeof(efi_dir), "%s/EFI", efi_mount); + mkdir(efi_dir, 0755); snprintf(efi_dir, sizeof(efi_dir), "%s/EFI/BOOT", efi_mount); + mkdir(efi_dir, 0755); if (access(efi_dir, F_OK) != 0) { - ac_log("[flash] ABORT: %s not found — wrong partition?", efi_dir); + ac_log("[flash] ABORT: %s could not be created", efi_dir); if (did_mount) umount("/tmp/efi"); rt->flash_phase = 4; rt->flash_ok = 0; @@ -2020,17 +2105,56 @@ static JSValue js_flash_update(JSContext *ctx, JSValueConst this_val, int argc, } // system.reboot() — triggers system reboot (direct syscall, no external binary needed) +// Hardened: triple sync with delays, pre-reboot EFI file size sanity check, +// perf flush, log flush before rebooting. static JSValue js_reboot(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { (void)ctx; (void)this_val; (void)argc; (void)argv; - ac_log("[system] reboot requested — executing syscall"); - // Play shutdown chime and let audio drain before rebooting + ac_log("[system] reboot requested"); + + // Pre-reboot sanity: verify EFI file exists and is >1MB (catch corrupted flash) + { + const char *efi_paths[] = { + "/mnt/EFI/BOOT/BOOTX64.EFI", + "/tmp/efi/EFI/BOOT/BOOTX64.EFI", + NULL + }; + int efi_ok = 0; + for (int i = 0; efi_paths[i]; i++) { + struct stat st; + if (stat(efi_paths[i], &st) == 0 && st.st_size > 1048576) { + ac_log("[reboot] EFI verified: %s (%ld bytes)", efi_paths[i], (long)st.st_size); + efi_ok = 1; + break; + } + } + if (!efi_ok) { + ac_log("[reboot] WARNING: no valid EFI file found on mount — rebooting anyway"); + } + } + + // Flush perf data before reboot + perf_flush(); + + // Play shutdown chime and let audio drain if (current_rt && current_rt->audio) { audio_shutdown_sound(current_rt->audio); usleep(500000); // 500ms for chime to play } + + // Flush log file + ac_log("[reboot] syncing filesystems..."); + ac_log_flush(); + + // Triple sync with delays — vfat write-back needs time sync(); - usleep(500000); // give block layer time to flush vfat - sync(); // second sync for safety + usleep(500000); + sync(); + usleep(500000); + sync(); + + ac_log("[reboot] executing reboot syscall"); + ac_log_flush(); + if (getpid() == 1) { reboot(LINUX_REBOOT_CMD_RESTART); } else {