diff --git a/changelog.d/desktop-api-catch-up.md b/changelog.d/desktop-api-catch-up.md new file mode 100644 index 0000000000..5151eb9f0e --- /dev/null +++ b/changelog.d/desktop-api-catch-up.md @@ -0,0 +1,8 @@ +### The desktop API reads clusters, Darkbloom Sandbox, waitlists and local serving, and runs their actions + +- New resources: `cluster` (`darkbloom cluster status --json` as this build prints it; when it can't be read, the same shape with `state: "unknown"` and why), `sandbox` (the add-on's status, with its last update check in Unix seconds), `sandbox-logs` (the agent log's last 200 lines, without terminal escapes) and `waitlists` (`darkbloom waitlist --json`, or why there is no list and whether linking the Mac helps). Each is read only when the app asks, and repeated reads share one run. +- The state snapshot adds `local`: how this Mac serves (`[local]` in provider.toml), where your requests go, whether an account key is saved (never the key), and how long Darkbloom stays paused for you. +- New actions: start with `network` (`--network`) or, on a paired Mac, `solo` (`start --solo` with its models); `cluster_leave`; `waitlist_join`; `sandbox_pause`, `sandbox_resume`, `sandbox_uninstall` and `sandbox_setup`, which reports its lines, the installer's stage and the one browser approval while it runs and can be cancelled; `route`; `route_key`, whose key goes to `darkbloom route key --stdin` on standard input only and never reaches the operation journal, an operation, a snapshot or an error; `local_settings` (me first, applied at the next start); `tool_setup` (`start --opencode` or `--hermes`); and `update_rollback` (`update --rollback --yes`). Contradictory starts (two ways to serve) are refused before anything runs. +- `darkbloom sandbox setup --json-events` (hidden, for the app) writes each line and each installer event as one JSON object per line; a SIGTERM ends it, or reaches a running installer as Ctrl-C so an enrollment waiting for approval goes on. +- `darkbloom sandbox setup` shows the installer's approval link, code and progress as soon as the installer prints them. It read the installer's output 16 KiB at a time, so they could appear only once that much had arrived or the installer had ended. +- `capabilities` names `cluster`, `sandbox`, `waitlists`, `local_serving`, `tool_setup` and `update_rollback`. diff --git a/changelog.d/desktop-chat.md b/changelog.d/desktop-chat.md new file mode 100644 index 0000000000..4f37c2b047 --- /dev/null +++ b/changelog.d/desktop-chat.md @@ -0,0 +1,5 @@ +### Chat in Darkbloom for Mac + +- A Chat tab talks to the models this Mac serves on its local API (Only me, or Both, me first), with the iPhone app's look and motion: the Darkbloom mark over a faint field of blue pixel tiles and a new line each launch, your words in a quiet blue slab, replies as plain text with code blocks, reasoning folded into "Thought for N s", and streamed text that settles from faint to full ink. Everything stays still with Reduce Motion. +- Choose a model (this Mac's first, then your other Macs' and the Darkbloom network's, which is billed) and, for a model that reasons, its reasoning effort. Chats stay on this Mac, titled from their first message. Stop ends an answer; a refused one shows the local API's own words, such as a busy Mac's. +- Without a local API, Chat says so and opens Studio, where you turn it on. The app calls only this Mac's loopback address, and the local API key never reaches the page. diff --git a/changelog.d/desktop-cluster-setup-session.md b/changelog.d/desktop-cluster-setup-session.md new file mode 100644 index 0000000000..64d2b5ce0c --- /dev/null +++ b/changelog.d/desktop-cluster-setup-session.md @@ -0,0 +1,6 @@ +### The desktop app can run the two-Mac cluster setup with its own screens + +- The local API runs the cluster setup for the app: `POST /control/v1/cluster/session` starts `darkbloom cluster` (or `darkbloom cluster local` with a model and an address) without a terminal, and the app reads its screen, answers its questions and follows it as it pairs the Macs, chooses the pair's model and how it serves, and starts serving. One setup runs at a time, and other actions wait for it. +- The setup's questions are the ones Terminal asks, in the same words: the pairing code, the model, how both Macs split it, how the pair serves, a copy, and the clusters waitlist. A wait offers its key only where Terminal acts on it (q cancels the pairing's wait; q leaves the start's wait), and the app's Cancel ends the setup at its next question or wait, as q does. +- A step the app can't take, such as sudo where macOS shows no prompt, says to run `darkbloom cluster` in Terminal. A runtime without this support says it needs a newer runtime. +- New hidden flag for the app: `darkbloom cluster --app-console` (and `darkbloom cluster local --app-console`) writes the setup's screen as JSON lines and reads its answers as JSON lines. diff --git a/changelog.d/desktop-clusters.md b/changelog.d/desktop-clusters.md new file mode 100644 index 0000000000..c343d98205 --- /dev/null +++ b/changelog.d/desktop-clusters.md @@ -0,0 +1,6 @@ +### The desktop app's Clusters page sets up a two-Mac pair and runs it + +- A new **Clusters** page sets up a pair with `darkbloom cluster`'s own steps, questions and words, without Terminal. **Set up a pair** (once your account is approved on the Clusters waitlist, which the page shows) and **Serve on my own Macs only** (no approval needed) open a guided setup: each step as the CLI says it, live work with one row per Mac, copy and download bars, the pairing code large with its Yes or No, and the questions as lists you move through with ↑ and ↓ and take with Enter, such as how the pair serves (Only me, Darkbloom network or Both, me first), the model with its split ("tensor parallel", "pipeline") and how both Macs split it. It ends with the ✓ or ✗ card. **Cancel** asks first while a pairing is in progress, and leaving the page doesn't stop a setup: it's there again when you come back. +- On a paired Mac the page shows both Macs and which one leads, whether the other Mac answers, the model with its mode and each Mac's share, how the pair serves, its state with the CLI's reason and next step, and the cluster service. **Start serving**, **Stop serving** and **Restart serving** act on the pair. **Change model or how it serves** opens the setup on the Mac that leads. **Serve this Mac alone** and **Leave the pair** ask first; leaving says what `darkbloom cluster leave` does. +- This Mac's overview shows the pair in one line, with a link to Clusters. +- With a Darkbloom CLI from before clusters, the page says it needs a newer CLI; with one that can't run the setup from the app, it names the Terminal commands to copy. diff --git a/changelog.d/desktop-early-access.md b/changelog.d/desktop-early-access.md new file mode 100644 index 0000000000..8b15f9f77e --- /dev/null +++ b/changelog.d/desktop-early-access.md @@ -0,0 +1,4 @@ +### The desktop app shows Early access: where your account stands on each waitlist + +- A new **Early access** page lists every waitlist the coordinator offers, such as Clusters and Darkbloom Sandbox, and where your account stands, as `darkbloom waitlist` says it: not joined, with **Join the waitlist**; your place in line and the day you joined; approved since a day, with **Open** for a feature that has a page in the app or else the command that starts it, to copy; or revoked, which joining again doesn't restore. +- When the list can't be shown, the page says why: a Mac that isn't linked links from the page with the app's own code, a coordinator without waitlists has nothing to join, and anything else shows the reason with **Try again**. A Darkbloom CLI without waitlists gets a one-line note to update it. diff --git a/changelog.d/desktop-local-serving.md b/changelog.d/desktop-local-serving.md new file mode 100644 index 0000000000..775aa5ba8e --- /dev/null +++ b/changelog.d/desktop-local-serving.md @@ -0,0 +1,8 @@ +### The app's Studio serves the CLI's way, and Updates can roll back + +- This Mac > Studio asks the start question in its own words: **Only me**, **Darkbloom network** or **Both, me first** (recommended), with the saved choice marked. **Apply** saves the new choice and restarts serving with the models serving now (or one you choose when none serves), and says so first. Before, Studio offered only "Alongside the network" and "Local only", and the network alone couldn't be chosen in the app. +- With **Both, me first**, Studio turns me first on or off and sets the minutes with none of your requests before Darkbloom comes back (1 to 120); a change applies when serving restarts, and **Restart serving** is offered. It says when Darkbloom is paused for you and when it comes back. +- **When this Mac can't take a request**: Only this Mac, Only my Macs (free) or My Macs first (then the network, billed to your balance), saved as `darkbloom route` saves it. The last two need your account API key: paste it once and **Save key**. The app sends it to the Keychain and keeps no copy; it shows only "Key saved". +- **Use it in your tools**: **Set up OpenCode** and **Set up Hermes** run `darkbloom --opencode` and `--hermes`; with an older CLI, Studio shows those commands to copy. Connection details add the port and address the local API listens on. +- Updates offers **Return to the previous release** (`darkbloom update --rollback`), asked first. +- With a CLI from before these, Studio stays as it was, with one line saying a newer Darkbloom CLI adds me first, request routing and tool setup. diff --git a/changelog.d/desktop-sandboxes.md b/changelog.d/desktop-sandboxes.md new file mode 100644 index 0000000000..f92d1c0427 --- /dev/null +++ b/changelog.d/desktop-sandboxes.md @@ -0,0 +1,6 @@ +### The desktop app sets up and manages Darkbloom Sandbox + +- The app's new **Sandboxes** page does what `darkbloom sandbox` does, in its words. Without the add-on it says what Darkbloom Sandbox is (approved GitHub Actions jobs in Linux and macOS VMs; each job pays its price minus a 10% fee into your Darkbloom balance, and inference pauses while a job runs), what this Mac needs and what loses jobs, and offers setup once Darkbloom approved your account from the waitlist: jobs at a time (automatic, or your own Linux and macOS counts), an optional work disk such as `/Volumes/FastSSD`, and whether to wait for the VM images. +- While setup runs, the page shows the installer's stages, the one browser approval with its code and **Open approval page**, and the waitlist; it says when the app can close because this Mac enrolls by itself. A setup that ends early says why: this Mac can't host it as it is, it was not enrolled, or a job is running so nothing changed. +- Once installed, the page shows the add-on's state and what it means for inference, free Linux and macOS slots, running jobs, images and work disks, with **Open console**, **Pause** and **Resume**, **Change jobs at a time**, the add-on's log, and **Uninstall** (running jobs end unpaid, so it asks first). +- A Darkbloom CLI without Darkbloom Sandbox support gets one line saying it needs a newer one. diff --git a/desktop-app/src/main/backend.ts b/desktop-app/src/main/backend.ts index 7b9a3af161..f8ccda4ce8 100644 --- a/desktop-app/src/main/backend.ts +++ b/desktop-app/src/main/backend.ts @@ -35,6 +35,10 @@ const resources = new Set([ 'insights-month', 'request-history', 'hardware', + 'cluster', + 'sandbox', + 'sandbox-logs', + 'waitlists', ]); export function validateDiscovery(value: unknown): { port: number; @@ -215,6 +219,15 @@ export class Backend extends EventEmitter { redirect: 'error', }); } + // The guided cluster setup's stream: the whole session on every change. + async openClusterSessionEvents(signal: AbortSignal) { + if (!this.connection) throw new Error('Runtime is not connected'); + return fetch(`http://127.0.0.1:${this.connection.port}/control/v1/cluster/session/events`, { + headers: { Authorization: `Bearer ${this.connection.token}` }, + signal, + redirect: 'error', + }); + } async watch() { while (!this.stopped) { try { diff --git a/desktop-app/src/main/chat.ts b/desktop-app/src/main/chat.ts new file mode 100644 index 0000000000..faa5ea8f78 --- /dev/null +++ b/desktop-app/src/main/chat.ts @@ -0,0 +1,438 @@ +import { randomUUID } from 'node:crypto'; +import { + reasoningEfforts, + validateChatRequest, + type ChatEvent, + type ChatModel, + type ChatModels, + type ChatRequest, +} from '../shared/chat'; +import type { NativeModel, Snapshot } from '../shared/contracts'; +import { splitFrames } from './sse'; + +// Chat with this Mac's local API. The main process holds the local API key and makes every +// request, so the renderer never sees it; only a loopback base URL from the native snapshot is +// ever called. Each streamed answer is published as ChatEvents tagged with its stream ID. + +// What the relay reads from Backend: the live snapshot (`endpoint`, and this Mac's model names) +// and the local API key (`GET /control/v1/endpoint-key`, `{ key }`). +export interface ChatBackend { + readonly snapshot?: Snapshot; + read(resource: 'endpoint-key'): Promise; +} + +type Fetch = (url: string, init: RequestInit) => Promise; +type Usage = { prompt_tokens?: number; completion_tokens?: number }; + +// How long each step may take. A streamed answer's head waits while a cold model loads, and on a +// busy Mac through the engine's 120 s admission lease (docs/provider/direct-mode.md#routes). +export interface ChatTimeouts { + models: number; + head: number; + idle: number; +} +const defaultTimeouts: ChatTimeouts = { models: 5_000, head: 10 * 60_000, idle: 5 * 60_000 }; +const maxStreams = 2; +const maxListBytes = 2_000_000; +const maxErrorBytes = 64_000; +const maxFrameCharacters = 1_000_000; +const maxAnswerCharacters = 4_000_000; +const maxModels = 500; +const loopbackHosts = new Set(['127.0.0.1', 'localhost', '[::1]']); + +const notRunning = 'This Mac’s local API isn’t running.'; +const notLoopback = 'Chat calls this Mac’s local API only on this Mac’s loopback address.'; +const noAnswer = 'This Mac’s local API didn’t answer.'; +const keyUnreadable = 'Couldn’t read this Mac’s local API key.'; +const stoppedEarly = 'The answer stopped before it finished.'; +const stalled = 'This Mac’s local API stopped answering.'; +const tooMany = 'Two answers are already streaming. Wait for one to finish.'; +const tooLong = 'This answer is too long to show.'; + +// A failure whose message is meant for the person. +class ChatFailure extends Error {} + +// The base URL to call, without a trailing slash, or undefined for anything that isn't plain +// http on this Mac's loopback address (`127.0.0.1`, `localhost`, `[::1]`). +export function loopbackBase(value: unknown): string | undefined { + if (typeof value !== 'string' || value.length > 2048) return undefined; + let url: URL; + try { + url = new URL(value); + } catch { + return undefined; + } + if (url.protocol !== 'http:' || !loopbackHosts.has(url.hostname)) return undefined; + if (url.username || url.password) return undefined; + return `${url.origin}${url.pathname.replace(/\/+$/, '')}`; +} + +// Text from the local API for the person: no control characters, bounded. +const plain = (text: string) => + text + .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '') + .trim() + .slice(0, 600); + +// The local API's own message from its OpenAI error envelope (`{"error": {"message"}}`), such as +// the 503 when this Mac's memory can't hold a request now; else the status in plain words. +export function apiErrorMessage(body: string, status: number): string { + try { + const value = JSON.parse(body) as { error?: unknown; message?: unknown } | null; + const error = value?.error; + const message = + typeof error === 'string' + ? error + : error && typeof error === 'object' + ? (error as { message?: unknown }).message + : value?.message; + if (typeof message === 'string' && plain(message)) return plain(message); + } catch {} + if (status === 401) return 'This Mac’s local API didn’t accept its key.'; + return `This Mac’s local API answered ${status}.`; +} + +const text = (value: unknown, limit: number) => + typeof value === 'string' && value.trim() && value.length <= limit ? value : undefined; +const positive = (value: unknown) => + typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined; +const strings = (value: unknown) => + Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string' && item.length <= 64) + : undefined; +const count = (value: unknown) => + typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : undefined; + +// The local API's model list as ChatModels: `supported_features` says which reason (each of those +// takes every reasoning effort), `owned_by` where each runs. This Mac's own names fill in a model +// the list doesn't name. +export function parseModelList(value: unknown, known: NativeModel[] = []): ChatModel[] { + const data = (value as { data?: unknown } | null)?.data; + if (!Array.isArray(data)) throw new ChatFailure('This Mac’s local API sent no model list.'); + const names = new Map(known.map((model) => [model.id, model.display_name])); + const seen = new Set(); + const models: ChatModel[] = []; + for (const entry of data.slice(0, maxModels)) { + if (!entry || typeof entry !== 'object') continue; + const item = entry as Record; + const id = text(item.id, 256); + if (!id || seen.has(id)) continue; + seen.add(id); + const features = strings(item.supported_features); + const reasoning = features + ? features.some((feature) => feature.toLowerCase() === 'reasoning') + : null; + const listed = text(item.name, 200); + models.push({ + id, + name: (listed !== id ? listed : undefined) ?? text(names.get(id), 200) ?? null, + owned_by: text(item.owned_by, 40) ?? null, + reasoning, + reasoning_efforts: reasoning ? [...reasoningEfforts] : null, + context_length: positive(item.context_length) ?? positive(item.max_model_len) ?? null, + max_output_length: positive(item.max_output_length) ?? null, + input_modalities: strings(item.input_modalities) ?? null, + }); + } + return models; +} + +// One server-sent event's data (its `data:` lines joined), or undefined for a frame without data, +// such as a keepalive comment. +export function eventData(frame: string): string | undefined { + let data: string[] | undefined; + for (const line of frame.split('\n')) { + if (!line.startsWith('data:')) continue; + (data ??= []).push(line.slice(line.startsWith('data: ') ? 6 : 5)); + } + return data?.join('\n'); +} + +export interface ChatChunk { + reasoning?: string; + content?: string; + finish?: string; + usage?: Usage; + error?: string; + done?: boolean; +} + +const nonEmpty = (value: unknown) => (typeof value === 'string' && value ? value : undefined); + +// One streamed chat completion chunk. The local API sends each piece of reasoning twice, as +// `reasoning_content` and `reasoning` (the same text, for clients that read either); one is used. +// A failure mid-answer arrives as a chunk with `error` (MLXLMServer `ChatStreamFailure`). +export function parseChatData(data: string): ChatChunk { + if (data.trim() === '[DONE]') return { done: true }; + let value: Record; + try { + value = JSON.parse(data); + } catch { + return {}; + } + if (!value || typeof value !== 'object') return {}; + const chunk: ChatChunk = {}; + if (value.error) { + const error = value.error as { message?: unknown } | string; + const message = typeof error === 'string' ? error : error.message; + chunk.error = + typeof message === 'string' && plain(message) ? plain(message) : 'The answer failed.'; + } + const choice = (Array.isArray(value.choices) ? value.choices[0] : undefined) as + { delta?: Record; finish_reason?: unknown } | undefined; + const delta = choice?.delta; + if (delta && typeof delta === 'object') { + const reasoning = nonEmpty(delta.reasoning_content) ?? nonEmpty(delta.reasoning); + if (reasoning) chunk.reasoning = reasoning; + const content = nonEmpty(delta.content); + if (content) chunk.content = content; + } + if (typeof choice?.finish_reason === 'string') chunk.finish = choice.finish_reason; + const usage = value.usage as Record | null | undefined; + if (usage && typeof usage === 'object') + chunk.usage = { + prompt_tokens: count(usage.prompt_tokens), + completion_tokens: count(usage.completion_tokens), + }; + return chunk; +} + +// Reads a response body up to `limit` bytes: an error body is cut there, a list refused past it. +async function readText(response: Response, limit: number, cut = false): Promise { + if (!response.body) return ''; + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let result = ''; + let size = 0; + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > limit) { + await reader.cancel().catch(() => {}); + if (cut) break; + throw new ChatFailure('This Mac’s local API sent too much.'); + } + result += decoder.decode(value, { stream: true }); + } + return result + decoder.decode(); +} + +// One streamed request: its abort and why it ended early, and one timer for how long it may wait. +class Stream { + readonly controller = new AbortController(); + reason?: 'cancel' | 'reset' | 'timeout'; + ended = false; + private timer?: ReturnType; + arm(ms: number) { + this.disarm(); + this.timer = setTimeout(() => this.abort('timeout'), ms); + } + disarm() { + if (this.timer) clearTimeout(this.timer); + this.timer = undefined; + } + abort(reason: 'cancel' | 'reset' | 'timeout') { + this.reason ??= reason; + this.controller.abort(); + } +} + +export class ChatRelay { + private streams = new Map(); + + constructor( + private backend: ChatBackend, + private publish: (event: ChatEvent) => void, + private fetcher: Fetch = (url, init) => fetch(url, init), + private timeouts: ChatTimeouts = defaultTimeouts, + ) {} + + // The models this Mac's local API lists, or why there are none to chat with. + async models(): Promise { + const endpoint = this.backend.snapshot?.endpoint; + if (!endpoint) return { models: [], code: 'no_endpoint', error: notRunning }; + const base = loopbackBase(endpoint.base_url); + if (!base) return { models: [], code: 'unavailable', error: notLoopback }; + try { + const headers = await this.headers(endpoint.authenticated); + const response = await this.fetcher(`${base}/models`, { + headers: { ...headers, Accept: 'application/json' }, + redirect: 'error', + signal: AbortSignal.timeout(this.timeouts.models), + }); + if (!response.ok) { + const body = await readText(response, maxErrorBytes, true).catch(() => ''); + return { + base_url: base, + models: [], + code: 'unavailable', + error: apiErrorMessage(body, response.status), + }; + } + const list = JSON.parse(await readText(response, maxListBytes)); + return { base_url: base, models: parseModelList(list, this.backend.snapshot?.models) }; + } catch (error) { + return { + base_url: base, + models: [], + code: 'unavailable', + error: error instanceof ChatFailure ? error.message : noAnswer, + }; + } + } + + // Starts one streamed answer and returns its ID at once; its events follow through `publish`. + async send(value: unknown): Promise<{ stream: string }> { + const request: ChatRequest = validateChatRequest(value); + const endpoint = this.backend.snapshot?.endpoint; + if (!endpoint) throw new Error(notRunning); + const base = loopbackBase(endpoint.base_url); + if (!base) throw new Error(notLoopback); + if (this.streams.size >= maxStreams) throw new Error(tooMany); + const id = randomUUID(); + const stream = new Stream(); + this.streams.set(id, stream); + const body = { + model: request.model, + messages: request.messages, + stream: true, + stream_options: { include_usage: true }, + ...(request.reasoning_effort ? { reasoning_effort: request.reasoning_effort } : {}), + ...(request.max_tokens ? { max_tokens: request.max_tokens } : {}), + ...(request.temperature !== undefined ? { temperature: request.temperature } : {}), + }; + // Begins after this call returns, so the renderer has the stream ID before its first event. + setTimeout(() => void this.run(id, stream, base, endpoint.authenticated, body), 0); + return { stream: id }; + } + + // Stops one answer; it ends with `done` and `finish_reason: 'cancelled'`. + async cancel(id: unknown) { + if (typeof id === 'string') this.streams.get(id)?.abort('cancel'); + } + + // Ends every stream without another event, such as when the window navigates or closes. + reset() { + for (const stream of this.streams.values()) stream.abort('reset'); + this.streams.clear(); + } + + private async headers(authenticated: boolean): Promise> { + if (!authenticated) return {}; + let value: unknown; + try { + value = await this.backend.read('endpoint-key'); + } catch { + throw new ChatFailure(keyUnreadable); + } + const key = (value as { key?: unknown } | null)?.key; + if (typeof key !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(key)) + throw new ChatFailure(keyUnreadable); + return { Authorization: `Bearer ${key}` }; + } + + private end(stream: Stream, event: ChatEvent) { + if (stream.ended || stream.reason === 'reset') return; + stream.ended = true; + this.publish(event); + } + + private async run( + id: string, + stream: Stream, + base: string, + authenticated: boolean, + body: Record, + ) { + let finish: string | null = null; + let usage: Usage | null = null; + let characters = 0; + const emit = (event: ChatEvent) => { + if (!stream.ended && stream.reason !== 'reset') this.publish(event); + }; + try { + const headers = await this.headers(authenticated); + stream.arm(this.timeouts.head); + const response = await this.fetcher(`${base}/chat/completions`, { + method: 'POST', + redirect: 'error', + signal: stream.controller.signal, + headers: { ...headers, 'Content-Type': 'application/json', Accept: 'text/event-stream' }, + body: JSON.stringify(body), + }); + if (!response.ok) { + const text = await readText(response, maxErrorBytes, true).catch(() => ''); + return this.end(stream, { + stream: id, + type: 'error', + message: apiErrorMessage(text, response.status), + }); + } + if (!response.body) throw new ChatFailure(noAnswer); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + for (;;) { + stream.arm(this.timeouts.idle); + const { value, done } = await reader.read(); + if (done) break; + buffer = (buffer + decoder.decode(value, { stream: true })).replace(/\r\n/g, '\n'); + if (buffer.length > maxFrameCharacters) { + await reader.cancel().catch(() => {}); + throw new ChatFailure(stoppedEarly); + } + const { frames, rest } = splitFrames(buffer); + buffer = rest; + for (const frame of frames) { + const data = eventData(frame); + if (data === undefined) continue; + const chunk = parseChatData(data); + if (chunk.reasoning) { + characters += chunk.reasoning.length; + emit({ stream: id, type: 'reasoning', text: chunk.reasoning }); + } + if (chunk.content) { + characters += chunk.content.length; + emit({ stream: id, type: 'content', text: chunk.content }); + } + if (chunk.finish) finish = chunk.finish; + if (chunk.usage) usage = chunk.usage; + const last: ChatEvent | undefined = chunk.error + ? { stream: id, type: 'error', message: chunk.error } + : chunk.done + ? { stream: id, type: 'done', finish_reason: finish, usage } + : characters > maxAnswerCharacters + ? { stream: id, type: 'error', message: tooLong } + : undefined; + if (last) { + await reader.cancel().catch(() => {}); + return this.end(stream, last); + } + } + } + // Closed without `[DONE]`: an answer that said how it finished is still complete. + this.end( + stream, + finish + ? { stream: id, type: 'done', finish_reason: finish, usage } + : { stream: id, type: 'error', message: stoppedEarly }, + ); + } catch (error) { + if (stream.reason === 'cancel') + return this.end(stream, { stream: id, type: 'done', finish_reason: 'cancelled', usage }); + if (stream.reason === 'timeout') + return this.end(stream, { stream: id, type: 'error', message: stalled }); + this.end(stream, { + stream: id, + type: 'error', + message: error instanceof ChatFailure ? error.message : noAnswer, + }); + } finally { + stream.disarm(); + if (this.streams.get(id) === stream) this.streams.delete(id); + } + } +} + +export type { ChatRequest }; diff --git a/desktop-app/src/main/clusterSession.ts b/desktop-app/src/main/clusterSession.ts new file mode 100644 index 0000000000..9c3de7b732 --- /dev/null +++ b/desktop-app/src/main/clusterSession.ts @@ -0,0 +1,248 @@ +import { isIPv4, isIPv6 } from 'node:net'; +import type { ClusterSession, ClusterSessionAnswer, ClusterSessionStart } from '../shared/cluster'; +import type { Backend } from './backend'; +import { eventPayload, sleep, splitFrames } from './sse'; + +// Each frame carries the whole session; a long transcript stays far below this. +const maxBufferedBytes = 4_000_000; +// A stream that says nothing for this long is opened again (any frame or keepalive resets it). +const idleTimeoutMs = 120_000; +const reconnectMs = 250; +const retryMs = 2000; +const maxRetryMs = 30_000; + +const isRecord = (value: unknown): value is Record => + !!value && typeof value === 'object' && !Array.isArray(value); + +const controlCharacter = /[\u0000-\u001f\u007f]/; + +// A model as `darkbloom cluster local ` takes it: an id or listed name, never a path or a +// flag. +export const validModel = (model: unknown): model is string => + typeof model === 'string' && + /^[A-Za-z0-9._/-]{1,256}$/.test(model) && + !model.includes('..') && + !/^[-/]/.test(model); + +// Where the leading Mac's API listens (`--bind`): `localhost` or a numeric IPv4 or IPv6 address, +// as `ClusterServingScope.isValidBind` takes it (no zone index). +export const validBind = (bind: unknown): bind is string => + typeof bind === 'string' && + bind.length <= 64 && + (bind === 'localhost' || isIPv4(bind) || (isIPv6(bind) && !bind.includes('%'))); + +// The only shapes the renderer may start a session with, rebuilt from their checked fields. +export function sessionStart(value: unknown): ClusterSessionStart { + if (!isRecord(value)) throw new Error('Invalid cluster setup request'); + const { kind, model, bind, ...rest } = value; + if (Object.keys(rest).length || (kind !== 'setup' && kind !== 'local')) + throw new Error('Invalid cluster setup request'); + if (kind === 'setup' && (model !== undefined || bind !== undefined)) + throw new Error('Only a local setup takes a model or an address'); + const start: ClusterSessionStart = { kind }; + if (model !== undefined) { + if (!validModel(model)) throw new Error('Invalid model'); + start.model = model; + } + if (bind !== undefined) { + if (!validBind(bind)) throw new Error('Invalid address'); + start.bind = bind; + } + return start; +} + +const validQuestion = (question: unknown): question is string => + typeof question === 'string' && + question.length > 0 && + question.length <= 128 && + !controlCharacter.test(question); + +// An answer to the question on screen (`choice` or `key`), or `cancel`; nothing else crosses. +export function sessionAnswer(value: unknown): ClusterSessionAnswer { + if (!isRecord(value)) throw new Error('Invalid answer'); + const keys = Object.keys(value).sort().join(','); + if (keys === 'cancel' && value.cancel === true) return { cancel: true }; + if (!validQuestion(value.question)) throw new Error('Invalid answer'); + const question = value.question; + if (keys === 'choice,question') { + const choice = value.choice; + if (typeof choice !== 'number' || !Number.isInteger(choice) || choice < 0 || choice > 999) + throw new Error('Invalid answer'); + return { question, choice }; + } + if (keys === 'key,question') { + const key = value.key; + if (typeof key !== 'string' || key.length < 1 || key.length > 16) + throw new Error('Invalid answer'); + return { question, key }; + } + throw new Error('Invalid answer'); +} + +const sessionKinds = new Set(['setup', 'local']); +const sessionStates = new Set(['running', 'succeeded', 'failed', 'cancelled']); + +const isQuestion = (question: unknown) => + isRecord(question) && + typeof question.id === 'string' && + ((question.type === 'choose' && + Array.isArray(question.options) && + question.options.every( + (rows) => Array.isArray(rows) && rows.every((row) => typeof row === 'string'), + ) && + typeof question.selected === 'number') || + (question.type === 'key' && + Array.isArray(question.keys) && + question.keys.every( + (key) => isRecord(key) && typeof key.key === 'string' && typeof key.label === 'string', + ))); + +// A session the renderer can read without checking it again. Events it can't show are skipped +// there, one at a time. +export function isClusterSession(value: unknown): value is ClusterSession { + return ( + isRecord(value) && + typeof value.id === 'string' && + sessionKinds.has(value.kind as string) && + sessionStates.has(value.state as string) && + typeof value.started_at === 'number' && + Array.isArray(value.events) && + value.events.every(isRecord) && + (value.question === null || isQuestion(value.question)) && + (value.error === undefined || typeof value.error === 'string') + ); +} + +function checked(value: unknown): ClusterSession { + if (!isClusterSession(value)) throw new Error('The cluster setup answered unreadably'); + return value; +} + +// One `event: cluster-session` frame's session; undefined for anything else. +export const sessionFrame = (frame: string) => + eventPayload(frame, 'cluster-session', isClusterSession); + +// The guided cluster setup session, run by the native API (`/control/v1/cluster/session`). This +// relays the session's routes with checked shapes and holds one event stream while the renderer +// watches it, publishing the whole session on every change. +export class ClusterSessionRelay { + private subscribers = 0; + private controller?: AbortController; + + constructor( + private backend: Backend, + private publish: (session: ClusterSession) => void, + private open: (signal: AbortSignal) => Promise = (signal) => + backend.openClusterSessionEvents(signal), + ) {} + + get active() { + return !!this.controller; + } + + // The running or last session; null when none ran since the API started. + async current(): Promise { + const session = await this.backend.request('cluster/session'); + return session === null ? null : checked(session); + } + + async start(start: unknown): Promise { + return checked(await this.backend.request('cluster/session', sessionStart(start))); + } + + async answer(answer: unknown): Promise { + return checked( + await this.backend.request('cluster/session/answer', sessionAnswer(answer)), + ); + } + + acquire() { + this.subscribers += 1; + if (!this.controller) { + this.controller = new AbortController(); + void this.run(this.controller.signal); + } + } + + release() { + this.subscribers = Math.max(0, this.subscribers - 1); + if (this.subscribers === 0) this.stop(); + } + + // Drops every subscription, such as when the renderer navigates or crashes. + reset() { + this.subscribers = 0; + this.stop(); + } + + private stop() { + this.controller?.abort(); + this.controller = undefined; + } + + private async run(signal: AbortSignal) { + let failures = 0; + while (!signal.aborted) { + const idle = new AbortController(); + let timer: ReturnType | undefined; + const touch = () => { + clearTimeout(timer); + timer = setTimeout(() => idle.abort(), idleTimeoutMs); + }; + let delay = reconnectMs; + try { + touch(); + const response = await this.open(AbortSignal.any([signal, idle.signal])); + if (!response.ok || !response.body) throw new Error('Cluster setup stream unavailable'); + failures = 0; + await this.read(response.body.getReader(), signal, touch); + } catch { + // A quiet stream is opened again at once; anything else waits longer each time. + if (!idle.signal.aborted) { + failures += 1; + delay = Math.min(retryMs * 2 ** (failures - 1), maxRetryMs); + } + } finally { + clearTimeout(timer); + } + if (!signal.aborted) await sleep(delay, signal); + } + } + + private async read( + reader: ReadableStreamDefaultReader, + signal: AbortSignal, + touch: () => void, + ) { + // The session as it is now, for a change made while no stream was open; a frame that comes + // first is newer. + let framed = false; + this.current().then( + (session) => { + if (session && !framed && !signal.aborted) this.publish(session); + }, + () => {}, + ); + const decoder = new TextDecoder(); + let buffer = ''; + for (;;) { + const { value, done } = await reader.read(); + if (done) return; + touch(); + buffer += decoder.decode(value, { stream: true }); + if (buffer.length > maxBufferedBytes) { + await reader.cancel(); + throw new Error('Cluster setup event too large'); + } + const { frames, rest } = splitFrames(buffer); + buffer = rest; + for (const frame of frames) { + const session = sessionFrame(frame); + if (session && !signal.aborted) { + framed = true; + this.publish(session); + } + } + } + } +} diff --git a/desktop-app/src/main/hardware.ts b/desktop-app/src/main/hardware.ts index 94269557f8..98526aea77 100644 --- a/desktop-app/src/main/hardware.ts +++ b/desktop-app/src/main/hardware.ts @@ -1,5 +1,5 @@ import { isHardwareSample, type HardwareSample } from '../shared/hardware'; -import { frameData, splitFrames } from './sse'; +import { eventPayload, sleep, splitFrames } from './sse'; // A frame carries one ~1 KB sample; anything far larger is not ours. const maxBufferedBytes = 256_000; @@ -8,30 +8,7 @@ const streamTimeoutMs = 150_000; const reconnectMs = 250; const retryMs = 2000; -export function hardwareFrame(frame: string): HardwareSample | undefined { - if (!frame.split('\n').includes('event: hardware')) return undefined; - const data = frameData(frame); - if (data === undefined) return undefined; - try { - const value: unknown = JSON.parse(data); - return isHardwareSample(value) ? value : undefined; - } catch { - return undefined; - } -} - -const sleep = (ms: number, signal: AbortSignal) => - new Promise((resolve) => { - const timer = setTimeout(resolve, ms); - signal.addEventListener( - 'abort', - () => { - clearTimeout(timer); - resolve(); - }, - { once: true }, - ); - }); +export const hardwareFrame = (frame: string) => eventPayload(frame, 'hardware', isHardwareSample); // Reference-counted hardware stream: connected while at least one renderer // subscription is held, so the runtime samples only while someone is looking. diff --git a/desktop-app/src/main/ipc.ts b/desktop-app/src/main/ipc.ts index 02f41db44a..00d60cb40c 100644 --- a/desktop-app/src/main/ipc.ts +++ b/desktop-app/src/main/ipc.ts @@ -2,10 +2,18 @@ import { app, clipboard, ipcMain, shell } from 'electron'; import path from 'node:path'; import type { Backend } from './backend'; import { HardwareWatch } from './hardware'; +import { ChatRelay } from './chat'; +import { ClusterSessionRelay } from './clusterSession'; import type { desktopUpdates } from './updates'; import type { MainWindow } from './window'; import type { SystemInfo } from '../shared/macos'; -import { clipboardText, externalURL, isTrustedSender, softwareUpdateURL } from './security'; +import { + approvalURL, + clipboardText, + externalURL, + isTrustedSender, + softwareUpdateURL, +} from './security'; function installScript() { return path.join( @@ -61,14 +69,43 @@ export function registerIPC(options: { (signal) => backend.openHardwareEvents(signal), (sample) => window.send('hardware:sample', sample), ); + const chat = new ChatRelay(backend, (event) => window.send('chat:event', event)); + const clusterSession = new ClusterSessionRelay(backend, (session) => + window.send('cluster:session', session), + ); + // A reloaded or crashed renderer can't release its streams or stop its answers. + const resetRelays = () => { + hardware.reset(); + chat.reset(); + clusterSession.reset(); + }; window.webContents?.on('did-start-navigation', (details) => { - if (details.isMainFrame && !details.isSameDocument) hardware.reset(); + if (details.isMainFrame && !details.isSameDocument) resetRelays(); }); - window.webContents?.on('render-process-gone', () => hardware.reset()); + window.webContents?.on('render-process-gone', resetRelays); handle('hardware:watch', () => { if (!smokeTest) hardware.acquire(); }); handle('hardware:unwatch', () => hardware.release()); + handle('chat:models', () => chat.models()); + handle('chat:send', (request) => { + if (smokeTest) throw new Error('Chat is disabled in UI smoke tests'); + return chat.send(request); + }); + handle('chat:cancel', (stream) => chat.cancel(stream)); + handle('cluster:session', () => clusterSession.current()); + handle('cluster:session-start', (start) => { + if (smokeTest) throw new Error('Native actions are disabled in UI smoke tests'); + return clusterSession.start(start); + }); + handle('cluster:session-answer', (answer) => clusterSession.answer(answer)); + handle('cluster:session-watch', () => { + if (!smokeTest) clusterSession.acquire(); + }); + handle('cluster:session-unwatch', () => clusterSession.release()); + handle('app:approval', async (url) => { + await shell.openExternal(approvalURL(url)); + }); handle('app:update-status', () => updates.status()); handle('app:update', () => updates.check()); handle('app:apply-update', () => updates.apply()); diff --git a/desktop-app/src/main/security.ts b/desktop-app/src/main/security.ts index 9e701f5bc5..05ac3ef980 100644 --- a/desktop-app/src/main/security.ts +++ b/desktop-app/src/main/security.ts @@ -70,6 +70,25 @@ export function externalURL(target: unknown, deviceLinkURL: string | undefined) return url; } +// A sandbox setup's browser approval page, from the installer's own event: https on a +// Darkbloom host only (darkbloom.dev, darkbloom.ai and their subdomains), without credentials. +export function approvalURL(value: unknown) { + if (typeof value !== 'string' || value.length > 2048) throw new Error('Unsupported link'); + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error('Unsupported link'); + } + const host = url.hostname; + const darkbloom = ['darkbloom.dev', 'darkbloom.ai'].some( + (domain) => host === domain || host.endsWith('.' + domain), + ); + if (url.protocol !== 'https:' || !darkbloom || url.username || url.password) + throw new Error('Unsupported link'); + return url.toString(); +} + export function clipboardText(text: unknown) { if (typeof text !== 'string' || text.length > 65536) throw new Error('Invalid clipboard value'); return text; diff --git a/desktop-app/src/main/sse.ts b/desktop-app/src/main/sse.ts index 83c6755984..eb7ea6de9e 100644 --- a/desktop-app/src/main/sse.ts +++ b/desktop-app/src/main/sse.ts @@ -1,4 +1,5 @@ -// Server-sent event framing shared by the runtime's state and hardware streams. +// Server-sent event streams from the runtime: the framing its state, hardware and cluster setup +// streams share, and the wait before a stream opens again. // Splits complete frames off the front of `buffer`. export function splitFrames(buffer: string): { frames: string[]; rest: string } { @@ -17,3 +18,35 @@ export const frameData = (frame: string) => .split('\n') .find((line) => line.startsWith('data: ')) ?.slice(6); + +// An `event: ` frame's JSON, when `accept` takes it; undefined for any other frame, and for +// a payload that is unreadable or not what `accept` checks for. +export function eventPayload( + frame: string, + name: string, + accept: (value: unknown) => value is T, +): T | undefined { + if (!frame.split('\n').includes(`event: ${name}`)) return undefined; + const data = frameData(frame); + if (data === undefined) return undefined; + try { + const value: unknown = JSON.parse(data); + return accept(value) ? value : undefined; + } catch { + return undefined; + } +} + +// Waits `ms`, or less when `signal` aborts first. +export const sleep = (ms: number, signal: AbortSignal) => + new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + signal.addEventListener( + 'abort', + () => { + clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + }); diff --git a/desktop-app/src/preload/index.ts b/desktop-app/src/preload/index.ts index 18547870d4..d84b2eec32 100644 --- a/desktop-app/src/preload/index.ts +++ b/desktop-app/src/preload/index.ts @@ -29,5 +29,21 @@ const api: DesktopAPI = { void ipcRenderer.invoke('hardware:unwatch'); }; }, + chatModels: () => ipcRenderer.invoke('chat:models'), + chatSend: (request) => ipcRenderer.invoke('chat:send', request), + chatCancel: (stream) => ipcRenderer.invoke('chat:cancel', stream), + onChat: (callback) => subscribe('chat:event', callback), + clusterSession: () => ipcRenderer.invoke('cluster:session'), + startClusterSession: (start) => ipcRenderer.invoke('cluster:session-start', start), + answerClusterSession: (answer) => ipcRenderer.invoke('cluster:session-answer', answer), + onClusterSession: (callback) => { + const unsubscribe = subscribe('cluster:session', callback); + void ipcRenderer.invoke('cluster:session-watch'); + return () => { + unsubscribe(); + void ipcRenderer.invoke('cluster:session-unwatch'); + }; + }, + openApproval: (url) => ipcRenderer.invoke('app:approval', url), }; contextBridge.exposeInMainWorld('darkbloom', api); diff --git a/desktop-app/src/renderer/App.tsx b/desktop-app/src/renderer/App.tsx index a1c84f7edc..fc087f6678 100644 --- a/desktop-app/src/renderer/App.tsx +++ b/desktop-app/src/renderer/App.tsx @@ -1,5 +1,15 @@ import { useCallback, useEffect, useLayoutEffect, useState } from 'react'; -import { Box, Home as HomeIcon, Monitor, Trophy, Zap } from 'lucide-react'; +import { + Box, + Boxes, + Home as HomeIcon, + MessageCircle, + Monitor, + Network, + Ticket, + Trophy, + Zap, +} from 'lucide-react'; import type { Route } from '../shared/contracts'; import { api, isPreview, useBackend } from './useBackend'; import { Home } from './features/Home'; @@ -17,11 +27,19 @@ import { GetHelp, HelpControl } from './components/Help'; import { AccountControl } from './components/AccountControl'; import { SocialLinks } from './components/SocialLinks'; import { useFocusRecovery } from './useFocusRecovery'; +import { Chat } from './features/chat/Chat'; +import { Cluster } from './features/cluster/Cluster'; +import { Sandboxes } from './features/sandboxes/Sandboxes'; +import { Waitlists } from './features/waitlists/Waitlists'; const navigation = [ { id: 'home', label: 'Home', icon: HomeIcon }, + { id: 'chat', label: 'Chat', icon: MessageCircle }, { id: 'machines', label: 'My Macs', icon: Monitor }, + { id: 'cluster', label: 'Clusters', icon: Network }, + { id: 'sandboxes', label: 'Sandboxes', icon: Boxes }, { id: 'leaderboard', label: 'Leaderboard', icon: Trophy }, { id: 'updates', label: 'Updates', icon: Box }, + { id: 'waitlists', label: 'Early access', icon: Ticket }, ] as const; export default function App() { const [{ route, machine }, setView] = useState<{ route: Route; machine: MachineSelection }>({ @@ -109,7 +127,7 @@ export default function App() {
{backend.status.state !== 'ready' && ( @@ -135,6 +153,10 @@ export default function App() { {route === 'earnings' && } {route === 'updates' && } {route === 'leaderboard' && } + {route === 'chat' && } + {route === 'cluster' && } + {route === 'sandboxes' && } + {route === 'waitlists' && }