Files
EveFlow/src/lib/transport.ts
T
Claude 5f0fa7a1e2 fix: full review pass (main process, voice pipeline, Hermes client, HUD) and e2e-validated local voice (v2.1.0.1)
Electron main
- utility-process channel: sherpa output copied into V8 buffers (Electron rejects external
  buffers), audio exchanged as base64; worker restart on timeout, identity-safe exit handling,
  deterministic native unload by restart
- webhook: loopback by default without secret, UTF-8-safe body assembly, clean restart, port validation
- files IPC: realpath-based root check, openPath allow-list (reveal-only outside document folders),
  Windows reserved names; store: debounced async atomic writes with backup of corrupt files;
  logger: streaming writes with rotation; log message size cap
- HTTP stream proxy: socket released on idle timeout / renderer destroyed, id validation
- model manager: inactivity timeout, retrying rm/rename (Windows locks), engine stopped before
  replacing a model; WAV decoder handles float/24-bit; IPC payload validation
- window: opaque rounded window on Windows, navigation lock-down, visibility events;
  Ctrl+Alt+Escape instead of the Task Manager shortcut; single-instance guard; EVEFLOW_USER_DATA

Voice pipeline
- abort semantics (SendHandle.aborted), abort before the stream opens, session id prefixes per transport
- hands-free re-arm after replies without speech, start/stop race, no chime on auto re-arm,
  no silence shipped to STT (400 ms pre-roll), no transcription of empty manual stops
- TTS: bounded prefetch, cancellable segments, non-interrupting notices, volume applied at play time
- SSE CRLF split, usage in chat completions, finish_reason length, phonetic regex hoisted

HUD
- core renderer: no canvas shadows, cached colours, reusable spectrum buffer, theme read on change,
  30 fps idle, stops when the window is hidden; ping flashes on send / tool / speech
- deltas coalesced per animation frame; stable auto-scroll; narrow selectors everywhere
- bundled fonts (offline), reduce-motion fix, error toasts, ops drawer below 1180 px,
  interim transcript and first-token latency in the core caption, Ctrl+K, dialog semantics,
  switch/aria roles, compact widget cleanup, Whisper small recommended for French
- docs/ROADMAP.md: audit results, e2e results and the plan towards a real JARVIS

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017Wn5VX9HNbJ7N54hR24u9Y
2026-09-03 18:08:09 +00:00

133 lines
4.5 KiB
TypeScript

import type { HttpProxyRequest, HttpProxyResponse, HttpStreamEvent, HttpStreamStart } from '../../shared/ipc';
import { bridge } from './bridge';
import { uid } from './id';
export class HttpError extends Error {
constructor(public readonly status: number, message: string, public readonly body?: string) {
super(message);
this.name = 'HttpError';
}
}
/** One-shot HTTP request routed through the Electron main process (or fetch in a browser). */
export async function httpFetch(req: HttpProxyRequest): Promise<HttpProxyResponse> {
const api = bridge();
if (api) return api.http.fetch(req);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 60_000);
try {
const headers: Record<string, string> = { ...(req.headers ?? {}) };
let body: BodyInit | undefined;
if (req.multipart) {
const form = new FormData();
for (const [k, v] of Object.entries(req.multipart.fields)) form.append(k, v);
const f = req.multipart.file;
const bytes = new Uint8Array(f.data);
form.append(req.multipart.fileField ?? 'file', new Blob([bytes], { type: f.type }), f.name);
body = form;
delete headers['Content-Type'];
} else {
body = req.body;
}
const res = await fetch(req.url, { method: req.method ?? 'GET', headers, body, signal: controller.signal });
const outHeaders: Record<string, string> = {};
res.headers.forEach((v, k) => (outHeaders[k.toLowerCase()] = v));
const base = { ok: res.ok, status: res.status, statusText: res.statusText, headers: outHeaders };
if (req.responseType === 'binary') return { ...base, binary: new Uint8Array(await res.arrayBuffer()) };
return { ...base, text: await res.text() };
} finally {
clearTimeout(timer);
}
}
export interface StreamHandlers {
onChunk: (text: string) => void;
}
export interface StreamHandle {
start: HttpStreamStart;
done: Promise<void>;
abort: () => void;
}
// One global listener dispatches IPC stream events to per-request handlers.
const streamHandlers = new Map<string, { onChunk: (t: string) => void; onEnd: () => void; onError: (m: string) => void }>();
let listenerInstalled = false;
function installListener(): void {
if (listenerInstalled) return;
const api = bridge();
if (!api) return;
listenerInstalled = true;
api.http.onStreamEvent((event: HttpStreamEvent) => {
const h = streamHandlers.get(event.id);
if (!h) return;
if (event.type === 'chunk') h.onChunk(event.text);
else if (event.type === 'end') {
streamHandlers.delete(event.id);
h.onEnd();
} else {
streamHandlers.delete(event.id);
h.onError(event.message);
}
});
}
/**
* Streaming HTTP request. Resolves once headers are received; `done` resolves when the body ends.
* Text chunks are delivered incrementally (SSE parsing is up to the caller).
*/
export async function httpStream(req: HttpProxyRequest, handlers: StreamHandlers): Promise<StreamHandle> {
const api = bridge();
if (api) {
installListener();
const id = uid('stream');
let resolveDone!: () => void;
let rejectDone!: (err: Error) => void;
const done = new Promise<void>((resolve, reject) => {
resolveDone = resolve;
rejectDone = reject;
});
streamHandlers.set(id, {
onChunk: handlers.onChunk,
onEnd: () => resolveDone(),
onError: (message) => rejectDone(new Error(message))
});
let start: HttpStreamStart;
try {
start = await api.http.streamStart(id, req);
} catch (err) {
streamHandlers.delete(id);
throw err;
}
return { start, done, abort: () => api.http.streamAbort(id) };
}
// Browser fallback (Vite dev in a normal browser)
const controller = new AbortController();
const res = await fetch(req.url, {
method: req.method ?? 'GET',
headers: req.headers,
body: req.body,
signal: controller.signal
});
const headers: Record<string, string> = {};
res.headers.forEach((v, k) => (headers[k.toLowerCase()] = v));
const start: HttpStreamStart = { id: uid('stream'), ok: res.ok, status: res.status, statusText: res.statusText, headers };
const done = (async () => {
if (!res.body) return;
const reader = res.body.getReader();
const decoder = new TextDecoder();
for (;;) {
const { done: finished, value } = await reader.read();
if (finished) break;
handlers.onChunk(decoder.decode(value, { stream: true }));
}
const tail = decoder.decode();
if (tail) handlers.onChunk(tail);
})();
return { start, done, abort: () => controller.abort() };
}