Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix: chat-media / kb-file protocols add HTTP Range support (videos freeze a few seconds in)
wyt5503307eb87f
diff --git a/src/main/index.ts b/src/main/index.tsindex 2c791bf0..dd82d67d 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -22,6 +22,7 @@import * as path from 'node:path';import * as fs from 'node:fs';+import { Readable } from 'node:stream';import { app, BrowserWindow, Menu, ipcMain, nativeImage, protocol, shell } from 'electron';// Force the user-visible app name to "Orkas" before anything else@@ -46,9 +47,11 @@ protocol.registerSchemesAsPrivileged([},// `chat-media://cid/<encCid>/<encName>` — serves image + video bytes out// of the active user's `<uid>/cloud/chat_attachments/<cid>/`. `stream:true`- // lets Chromium do byte-range requests on `<video>` seek without us- // manually implementing Range handling (we hand back a normal Response- // and Chromium / Electron handles scroll + seek over it).+ // only enables a streamed Response body — it does NOT make Chromium issue+ // byte-range requests on its own; the handler must advertise+ // `Accept-Ranges: bytes` and serve `206` itself (see `serveFileRange`).+ // Without that, `<video preload="metadata">` freezes a few seconds in+ // because Chromium can't resume past the cancelled metadata-probe fetch.{scheme: 'chat-media',privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true },@@ -63,6 +66,7 @@ protocol.registerSchemesAsPrivileged([// resolution + Windows pin + source-run migration logic lives in// `src/main/install-data-root.cjs`.import * as paths from './paths';+import { parseByteRange } from './util/http-range';// `CORE_AGENT_AUTH_DIR` is pinned per-uid by `features/users.activateUser()`// (runs inside `runBootSelfCheck` below). `resolveAuthDir()` in core-agent@@ -326,6 +330,70 @@ const _KB_FILE_MIME: Record<string, string> = {'.json': 'application/json',};+/**+ * Stream a file on disk back through a `protocol.handle` callback with HTTP+ * Range support — shared by `kb-file://` and `chat-media://`.+ *+ * Why this exists: a `protocol.handle` reply that returns `200` + a+ * `Content-Length` but no `Accept-Ranges` makes Chromium treat the resource+ * as non-seekable. For `<video preload="metadata">` that is fatal — Chromium's+ * metadata probe fetches only the head of the file and then *cancels* its+ * request; when playback later runs past that prefetched head buffer it has no+ * way to resume (the resource is "not range-capable" and the original request+ * is gone), so the `<video>` freezes a few seconds in with no error in the UI.+ * Advertising `Accept-Ranges: bytes` + honouring `206` requests is the fix; it+ * also makes seeking work and lets PDFium fetch only the pages it shows.+ *+ * Also switches the body from `fs.readFileSync` — the old handlers buffered the+ * whole file into memory, so a 200 MB video spiked RSS by 200 MB — to a lazy+ * `fs.createReadStream`.+ *+ * `totalSize` is the caller's already-statted byte length, so we don't `stat`+ * the file a second time.+ */+function serveFileRange(+ request: Request,+ absPath: string,+ contentType: string,+ totalSize: number,+): Response {+ const baseHeaders: Record<string, string> = {+ 'Content-Type': contentType,+ 'Accept-Ranges': 'bytes',+ 'Cache-Control': 'private, max-age=60',+ };+ const range = parseByteRange(request.headers.get('Range'), totalSize);++ if (range === 'unsatisfiable') {+ return new Response('requested range not satisfiable', {+ status: 416,+ headers: { ...baseHeaders, 'Content-Range': `bytes */${totalSize}` },+ });+ }++ const nodeStream = range+ ? fs.createReadStream(absPath, { start: range.start, end: range.end })+ : fs.createReadStream(absPath);+ nodeStream.on('error', (err) => {+ log.warn('media stream error', { absPath, error: (err as Error).message });+ });+ const body = Readable.toWeb(nodeStream) as unknown as ReadableStream;++ if (range) {+ return new Response(body, {+ status: 206,+ headers: {+ ...baseHeaders,+ 'Content-Range': `bytes ${range.start}-${range.end}/${totalSize}`,+ 'Content-Length': String(range.end - range.start + 1),+ },+ });+ }+ return new Response(body, {+ headers: { ...baseHeaders, 'Content-Length': String(totalSize) },+ });+}+function registerKbFileProtocol(): void {protocol.handle('kb-file', async (request) => {const reqUrl = request.url;@@ -357,22 +425,16 @@ function registerKbFileProtocol(): void {log.warn('kb-file: traversal blocked', { reqUrl, rel });return new Response('forbidden', { status: 403 });}- if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {+ let st: fs.Stats | undefined;+ try { st = fs.statSync(abs); } catch { /* falls through to 404 below */ }+ if (!st || !st.isFile()) {log.warn('kb-file: not found', { reqUrl, rel, abs });return new Response('not found', { status: 404 });}- log.info('kb-file: serving', { reqUrl, abs });+ log.info('kb-file: serving', { reqUrl, abs, bytes: st.size });const ext = path.extname(abs).toLowerCase();const contentType = _KB_FILE_MIME[ext] || 'application/octet-stream';- const buf = fs.readFileSync(abs);- return new Response(buf, {- headers: {- 'Content-Type': contentType,- 'Content-Length': String(buf.length),- // Let Chromium's PDFium cache range fetches for scroll.- 'Cache-Control': 'private, max-age=60',- },- });+ return serveFileRange(request, abs, contentType, st.size);} catch (err) {log.warn('kb-file serve failed', { reqUrl, error: (err as Error).message });return new Response('error', { status: 500 });@@ -442,14 +504,9 @@ function registerChatMediaProtocol(): void {log.warn('chat-media/cid: reject', { reqUrl, code, error: (resolved as { error?: string }).error });return new Response(String((resolved as { error?: string }).error || code || 'error'), { status: _statusFor(code) });}- const buf = fs.readFileSync(resolved.absPath);- return new Response(buf, {- headers: {- 'Content-Type': chatAttachments.mediaMimeFor(name),- 'Content-Length': String(buf.length),- 'Cache-Control': 'private, max-age=60',- },- });+ const st = fs.statSync(resolved.absPath);+ log.info('chat-media/cid: serving', { abs: resolved.absPath, kind: resolved.kind, bytes: st.size });+ return serveFileRange(request, resolved.absPath, chatAttachments.mediaMimeFor(name), st.size);}if (host === 'local') {@@ -461,15 +518,9 @@ function registerChatMediaProtocol(): void {log.warn('chat-media/local: reject', { reqUrl, code: resolved.code, error: resolved.error });return new Response(resolved.error, { status: _statusFor(resolved.code) });}- const buf = fs.readFileSync(resolved.absPath);- log.info('chat-media/local: serving', { abs: resolved.absPath, kind: resolved.kind, bytes: buf.length });- return new Response(buf, {- headers: {- 'Content-Type': chatAttachments.mediaMimeFor(resolved.absPath),- 'Content-Length': String(buf.length),- 'Cache-Control': 'private, max-age=60',- },- });+ const st = fs.statSync(resolved.absPath);+ log.info('chat-media/local: serving', { abs: resolved.absPath, kind: resolved.kind, bytes: st.size });+ return serveFileRange(request, resolved.absPath, chatAttachments.mediaMimeFor(resolved.absPath), st.size);}log.warn('chat-media: unknown host', { reqUrl, host });diff --git a/src/main/util/http-range.ts b/src/main/util/http-range.tsnew file mode 100644index 00000000..d790b29f--- /dev/null+++ b/src/main/util/http-range.ts@@ -0,0 +1,69 @@+/**+ * Single-range `Range: bytes=...` header parser for the local-media protocol+ * handlers (`chat-media://`, `kb-file://`).+ *+ * Chromium's `<video>` / `<audio>` element only ever sends simple `bytes=N-`+ * (and occasionally `bytes=N-M` / suffix `bytes=-N`) ranges, so we honour+ * exactly that family and treat anything fancier (multi-range comma lists,+ * units other than `bytes`, malformed syntax) as "no range". The contract is+ * intentionally three-valued so the caller can pick the right status code:+ *+ * - `null` → no usable Range header. Caller serves the full+ * entity with `200` (still advertise `Accept-Ranges`).+ * - `'unsatisfiable'` → a well-formed `bytes` range that selects no byte in+ * `[0, total)`. Caller returns `416` with a+ * `Content-Range` of `bytes` + `*` + `/` + total.+ * - `{ start, end }` → inclusive byte offsets clamped to `[0, total-1]`.+ * Caller returns `206` with+ * `Content-Range: bytes start-end/total` and a body of+ * exactly `end - start + 1` bytes.+ *+ * `total <= 0` (e.g. a zero-byte file) always yields `null` — there is nothing+ * to range over and an empty `200` is friendlier than a `416`.+ *+ * Why a dedicated module with fixtures: Range parsing is the kind of+ * pattern-matching code that breaks silently when a guard is widened — the+ * accepted-shape set (`set A`) and the look-alike-reject set (`set B`) are+ * pinned by `test/main/util/http-range.test.ts`.+ */++export interface ByteRange {+ /** First byte offset to send, inclusive. */+ start: number;+ /** Last byte offset to send, inclusive. */+ end: number;+}++export function parseByteRange(+ header: string | null | undefined,+ total: number,+): null | 'unsatisfiable' | ByteRange {+ if (!header || !Number.isFinite(total) || total <= 0) return null;++ // One range only: `bytes=` then `START-END`, either side optionally empty.+ // A comma list, a non-`bytes` unit, or any other junk fails this match and+ // is treated as "no range" (serve the full entity).+ const m = /^\s*bytes\s*=\s*([0-9]*)\s*-\s*([0-9]*)\s*$/.exec(header);+ if (!m) return null;+ const startStr = m[1];+ const endStr = m[2];+ if (startStr === '' && endStr === '') return null; // `bytes=-` is meaningless++ if (startStr === '') {+ // Suffix range: the final `endStr` bytes of the entity.+ const suffix = Number(endStr);+ if (!Number.isFinite(suffix)) return null;+ if (suffix === 0) return 'unsatisfiable'; // `bytes=-0`+ return { start: Math.max(0, total - suffix), end: total - 1 };+ }++ const start = Number(startStr);+ if (!Number.isFinite(start)) return null;+ if (start >= total) return 'unsatisfiable'; // first requested byte past EOF++ let end = endStr === '' ? total - 1 : Number(endStr);+ if (!Number.isFinite(end)) return null;+ if (end < start) return null; // inverted range → ignore the header entirely+ if (end > total - 1) end = total - 1; // clamp to EOF+ return { start, end };+}diff --git a/test/main/util/http-range.test.ts b/test/main/util/http-range.test.tsnew file mode 100644index 00000000..8662723c--- /dev/null+++ b/test/main/util/http-range.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect } from 'vitest';++import { parseByteRange } from '../../../src/main/util/http-range';++// `parseByteRange` is a header parser feeding the `chat-media://` / `kb-file://`+// protocol handlers, so it follows the §9 "set A / set B" discipline:+// - set A: the request shapes Chromium's <video>/<audio>/PDFium actually send+// (`bytes=N-`, `bytes=N-M`, suffix `bytes=-N`), each must yield a+// clamped {start,end} or 'unsatisfiable';+// - set B: look-alike strings (wrong unit, multi-range, inverted, junk,+// missing `=`) that must be treated as "no range" → null, so the+// handler falls back to a plain 200 instead of mis-slicing.++describe('parseByteRange › set A — real range shapes', () => {+ it('open-ended `bytes=N-` covers N..EOF (Chromium media probe shape)', () => {+ expect(parseByteRange('bytes=0-', 100)).toEqual({ start: 0, end: 99 });+ expect(parseByteRange('bytes=500-', 2000)).toEqual({ start: 500, end: 1999 });+ });++ it('closed `bytes=N-M` is inclusive on both ends', () => {+ expect(parseByteRange('bytes=500-999', 2000)).toEqual({ start: 500, end: 999 });+ expect(parseByteRange('bytes=0-0', 100)).toEqual({ start: 0, end: 0 });+ });++ it('clamps the end down to EOF when M runs past the file', () => {+ expect(parseByteRange('bytes=500-99999', 2000)).toEqual({ start: 500, end: 1999 });+ });++ it('suffix `bytes=-N` selects the last N bytes', () => {+ expect(parseByteRange('bytes=-500', 2000)).toEqual({ start: 1500, end: 1999 });+ });++ it('suffix larger than the file collapses to the whole file', () => {+ expect(parseByteRange('bytes=-5000', 2000)).toEqual({ start: 0, end: 1999 });+ });++ it('tolerates whitespace around the unit, `=` and `-`', () => {+ expect(parseByteRange(' bytes = 0 - 10 ', 100)).toEqual({ start: 0, end: 10 });+ });+});++describe('parseByteRange › set A — unsatisfiable but well-formed', () => {+ it('start at or past EOF → unsatisfiable (caller returns 416)', () => {+ expect(parseByteRange('bytes=2000-3000', 2000)).toBe('unsatisfiable');+ expect(parseByteRange('bytes=2000-', 2000)).toBe('unsatisfiable');+ expect(parseByteRange('bytes=5000-', 2000)).toBe('unsatisfiable');+ });++ it('zero-length suffix `bytes=-0` → unsatisfiable', () => {+ expect(parseByteRange('bytes=-0', 100)).toBe('unsatisfiable');+ });+});++describe('parseByteRange › set B — look-alikes that must NOT be honoured', () => {+ it('absent / empty header → null', () => {+ expect(parseByteRange(undefined, 100)).toBeNull();+ expect(parseByteRange(null, 100)).toBeNull();+ expect(parseByteRange('', 100)).toBeNull();+ });++ it('a unit other than `bytes` → null', () => {+ expect(parseByteRange('items=0-10', 100)).toBeNull();+ });++ it('missing `=` separator → null', () => {+ expect(parseByteRange('bytes 0-10', 100)).toBeNull();+ });++ it('multi-range comma list → null (we never emit multipart/byteranges)', () => {+ expect(parseByteRange('bytes=0-10,20-30', 100)).toBeNull();+ });++ it('inverted range (start > end) → null', () => {+ expect(parseByteRange('bytes=10-5', 100)).toBeNull();+ });++ it('empty on both sides `bytes=-` → null', () => {+ expect(parseByteRange('bytes=-', 100)).toBeNull();+ });++ it('non-numeric / non-integer offsets → null', () => {+ expect(parseByteRange('bytes=abc-def', 100)).toBeNull();+ expect(parseByteRange('bytes=1.5-2.5', 100)).toBeNull();+ });+});++describe('parseByteRange › degenerate totals', () => {+ it('a zero-byte entity has nothing to range over → null (serve empty 200)', () => {+ expect(parseByteRange('bytes=0-', 0)).toBeNull();+ expect(parseByteRange('bytes=-10', 0)).toBeNull();+ });++ it('a non-finite or negative total → null', () => {+ expect(parseByteRange('bytes=0-', Number.NaN)).toBeNull();+ expect(parseByteRange('bytes=0-', -5)).toBeNull();+ });+});