Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517<script lang="ts"> import { onMount, tick } from 'svelte'; import { Terminal } from '@xterm/xterm'; import { FitAddon } from '@xterm/addon-fit'; import { WebLinksAddon } from '@xterm/addon-web-links'; import { WebglAddon } from '@xterm/addon-webgl'; import '@xterm/xterm/css/xterm.css'; import { windowBoard } from '../boards.svelte'; import { PtyClient, type TerminalReady } from '../terminals.svelte'; import { prefs } from '../prefs.svelte'; import { option } from '../keys'; import { MINIMUM_CONTRAST, terminalColors, toHex } from '../terminal-theme';
let { terminalId, cwd = '', sessionId = '', windowId, onready, onexit, }: { terminalId: string; cwd?: string; sessionId?: string; /** The board window it is drawn in, whose zoom it undoes. */ windowId?: string; onready?: (ready: TerminalReady) => void; onexit?: (code: number) => void; } = $props();
const FONT_SIZE = 13; /** How long the zoom holds still before the text is drawn at it. */ const SETTLE = 150;
// A zoomed canvas is a stretched bitmap, so the terminal is drawn at the // zoom it is shown at, in a box that many times larger scaled back down. // Mid-pinch the old bitmap stretches; once the zoom holds still the font // follows, and the glyph atlas is drawn again once per gesture. const getBoard = windowBoard(); const zoom = $derived((windowId && getBoard()?.zoomOf(windowId)) || 1); // svelte-ignore state_referenced_locally let drawn = $state(zoom); $effect(() => { const next = zoom; const timer = setTimeout(() => (drawn = next), SETTLE); return () => clearTimeout(timer); });
let container = $state<HTMLElement>();
// A bitmap at a fraction of a pixel is sampled between pixels and its text // blurs, and a canvas's pan and zoom put windows anywhere. Once a gesture // settles, the screen is nudged onto the pixel grid; a whole pixel more or // less is still on it, so the nudge stays under one. let nudge = $state({ x: 0, y: 0 }); function snap() { const bitmap = container?.querySelector('canvas'); if (!bitmap) return; const { left, top } = bitmap.getBoundingClientRect(); const ratio = devicePixelRatio; const along = (from: number, at: number) => { const off = from * zoom * ratio + Math.round(at * ratio) - at * ratio; return (off - Math.round(off)) / ratio / zoom; }; nudge = { x: along(nudge.x, left), y: along(nudge.y, top) }; } $effect(() => { void drawn; void getBoard()?.viewport; let timer = setTimeout(snap, SETTLE); const later = () => { clearTimeout(timer); timer = setTimeout(snap, SETTLE); }; const settles = ['pointerup', 'keyup', 'wheel', 'resize']; for (const type of settles) addEventListener(type, later, { passive: true }); return () => { clearTimeout(timer); for (const type of settles) removeEventListener(type, later); }; });
let term: Terminal | null = null; let fitAddon: FitAddon | null = null; let client: PtyClient | null = null;
let cols = $state(80); let rows = $state(24); let running = $state(true); let exitCode = $state<number | null>(null); let shell = $state('sh'); // svelte-ignore state_referenced_locally let currentCwd = $state(cwd); let error = $state<string | null>(null);
// The client's colours are color-mix() expressions; a probe's computed colour // painted on a 1×1 canvas gives the hex the contrast maths needs. function resolveColors(names: string[]): string[] { const context = document .createElement('canvas') .getContext('2d', { willReadFrequently: true }); if (!container || !context) return []; const probe = container.appendChild(document.createElement('span')); const colors = names.map((name) => { probe.style.color = `var(${name})`; context.fillStyle = getComputedStyle(probe).color; context.fillRect(0, 0, 1, 1); const [r, g, b] = context.getImageData(0, 0, 1, 1).data; return toHex([r, g, b]); }); probe.remove(); return colors; }
function resolveTheme() { const [background, foreground, accent, added, danger] = resolveColors([ '--well', '--text', '--accent', '--added', '--danger', ]); if (!background) return undefined; return terminalColors({ mode: prefs.resolved, background, foreground, accent, added, danger, }); }
function applyTheme() { if (!term || !container) return; const theme = resolveTheme(); if (theme) term.options.theme = theme; if (prefs.fonts.code) term.options.fontFamily = prefs.fonts.code; }
function fitTerminal() { if (!fitAddon || !term || !container) return; try { fitAddon.fit(); if (term.cols !== cols || term.rows !== rows) { cols = term.cols; rows = term.rows; client?.resize(cols, rows); } } catch {} }
// A WebGL context the browser takes back (Chrome keeps sixteen per page and // drops the oldest) leaves the terminal on the DOM renderer, as does a // browser without WebGL2. function drawWithWebgl(terminal: Terminal) { try { const webgl = new WebglAddon(); webgl.onContextLoss(() => webgl.dispose()); terminal.loadAddon(webgl); } catch {} }
export function restart() { if (!client) return; exitCode = null; running = true; term?.reset(); client.restart(cols, rows); fitTerminal(); }
export function clear() { term?.clear(); }
export function interrupt() { client?.signal('SIGINT'); }
onMount(() => { if (!container) return;
client = new PtyClient(terminalId, { cwd, sessionId, cols: 80, rows: 24 });
const terminal = new Terminal({ cursorBlink: prefs.blinkCursor, cursorStyle: 'bar', cursorWidth: 2, fontFamily: prefs.fonts.code || 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace', fontSize: FONT_SIZE * drawn, lineHeight: 1.35, allowTransparency: true, drawBoldTextInBrightColors: true, minimumContrastRatio: MINIMUM_CONTRAST, scrollback: 10000, }); term = terminal;
const fit = new FitAddon(); fitAddon = fit; terminal.loadAddon(fit); terminal.loadAddon(new WebLinksAddon());
terminal.open(container); drawWithWebgl(terminal); applyTheme();
// The shell gets every key, Esc and Tab too, so the app's keys need one // way out: ⌥Esc leaves the focus to the board, the window still selected. terminal.attachCustomKeyEventHandler((event) => { if (event.key !== 'Escape' || !event.altKey) return true; if (event.type === 'keydown') terminal.blur(); return false; });
// Replayed history still holds the shell's old queries (reedline's CSI 6n // before every prompt); answering them again hands the shell stale cursor // positions, and it draws its prompt over the output. let replaying = false;
terminal.onData((data) => { if (!replaying) client?.sendInput(data); });
terminal.onBinary((data) => { if (!replaying) client?.sendInput( new Uint8Array(data.split('').map((c) => c.charCodeAt(0))), ); });
client.onOutput((chunk, replay) => { if (!replay) return terminal.write(chunk); // A reconnect replays everything again; on top of what is shown it would repeat. terminal.reset(); replaying = true; terminal.write(chunk, () => (replaying = false)); });
client.onExit((code) => { running = false; exitCode = code; onexit?.(code); });
// After the first fit, so the shell starts at the size it is shown at. requestAnimationFrame(() => { fitTerminal(); client?.connect(); terminal.focus(); });
const observer = new ResizeObserver(() => { requestAnimationFrame(fitTerminal); }); observer.observe(container);
return () => { observer.disconnect(); client?.dispose(); terminal.dispose(); term = null; fitAddon = null; client = null; }; });
// Follow client state reactively $effect(() => { if (!client) return; if (client.ready) { currentCwd = client.ready.cwd; shell = client.ready.shell; running = client.ready.state === 'running'; if (client.ready.exit_code !== null) exitCode = client.ready.exit_code; onready?.(client.ready); } error = client.error; });
$effect(() => { const size = FONT_SIZE * drawn; if (!term || term.options.fontSize === size) return; term.options.fontSize = size; fitTerminal(); });
// Follow theme changes $effect(() => { prefs.resolved; prefs.fonts.code; JSON.stringify(prefs.palettes[prefs.resolved]); // After the client's own variables have changed, which applyTheme reads. const frame = requestAnimationFrame(applyTheme); return () => cancelAnimationFrame(frame); });</script>
<div class="pty-view holds-wheel"> <div class="terminal-container"> <div class="screen" class:settled={drawn === zoom} bind:this={container} style:--zoom={drawn} style:transform={drawn === 1 && !nudge.x && !nudge.y ? undefined : `translate(${nudge.x}px, ${nudge.y}px) scale(${1 / drawn})`} ></div> </div>
{#if error} <div class="error-banner"> <span>(。•︿•。) {error}</span> <button class="retry-btn" onclick={restart}>retry</button> </div> {/if}
{#if !running && exitCode !== null} <div class="exit-banner"> <span>(・_・ ) process exited (code {exitCode})</span> <button class="restart-btn" onclick={restart}>restart shell</button> </div> {/if}
<footer class="terminal-bar"> <span class="dims">{cols} × {rows}</span> <div class="actions"> <span class="leave">{option('esc')} leave</span> <button class="action-btn" title="Send Ctrl+C to running process" onclick={interrupt}>^C</button > <button class="action-btn" title="Clear terminal screen" onclick={clear} >clear</button > <button class="action-btn" title="Restart shell session" onclick={restart} >restart</button > </div> </footer></div>
<style> .pty-view { position: relative; display: flex; flex: 1; flex-direction: column; min-height: 0; width: 100%; height: 100%; background: var(--well); overflow: hidden; border-radius: 0 0 14px 14px; }
.terminal-container { position: relative; flex: 1; min-height: 0; width: 100%; overflow: hidden; }
.screen { position: absolute; top: 0; left: 0; width: calc(100% * var(--zoom)); height: calc(100% * var(--zoom)); transform-origin: 0 0; }
/* Window zoom and its undoing multiply to a hair off 1 at most zooms, and a smoothed bitmap blurs at that; at rest each pixel is copied instead. */ .screen.settled :global(canvas) { image-rendering: pixelated; }
:global(.terminal-container .xterm) { position: absolute; inset: 0; padding: calc(8px * var(--zoom)) calc(12px * var(--zoom)); }
:global(.pty-view .xterm .xterm-viewport) { background-color: transparent !important; scrollbar-width: thin; overscroll-behavior: contain; }
:global(.pty-view .xterm .xterm-screen) { /* crisp text rendering */ -webkit-font-smoothing: subpixel-antialiased; }
.error-banner, .exit-banner { position: absolute; top: 10px; right: 14px; z-index: 20; display: flex; align-items: center; gap: 10px; padding: 6px 12px; font-size: calc(var(--type-sm) * var(--canvas-scale)); background: var(--surface); border: 1px solid var(--border); border-radius: 8px; box-shadow: var(--shadow); animation: fadeIn 150ms ease-out; }
.error-banner { color: var(--danger); border-color: color-mix(in oklab, var(--danger) 30%, transparent); }
.exit-banner { color: var(--muted); }
.restart-btn, .retry-btn { height: 22px; padding: 0 8px; font: inherit; font-size: calc(var(--type-xs) * var(--canvas-scale)); font-weight: var(--weight-strong); color: var(--surface); background: var(--accent); border: 0; border-radius: 5px; cursor: pointer; transition: opacity 120ms ease; }
.restart-btn:hover, .retry-btn:hover { opacity: 0.9; }
.terminal-bar { display: flex; flex: none; align-items: center; justify-content: space-between; height: 28px; padding: 0 12px; background: var(--title-bar); border-top: 1px solid color-mix(in oklab, var(--border) 40%, transparent); font-size: calc(var(--type-sm) * var(--canvas-scale)); color: var(--muted); user-select: none; }
.dims { font-variant-numeric: tabular-nums; opacity: 0.75; }
.actions { display: flex; align-items: center; gap: 6px; }
.leave { margin-right: 4px; font-family: var(--mono); font-size: calc(var(--type-xs) * var(--canvas-scale)); opacity: 0.75; }
.action-btn { height: 20px; padding: 0 6px; font: inherit; font-size: calc(var(--type-xs) * var(--canvas-scale)); font-family: var(--mono); color: var(--muted); background: none; border: 1px solid color-mix(in oklab, var(--border) 60%, transparent); border-radius: 4px; cursor: pointer; transition: all 120ms ease; }
.action-btn:hover { color: var(--text); background: var(--hover); border-color: var(--border); }
.action-btn:active { transform: scale(0.96); }
@keyframes fadeIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }</style>