Self-hosted camera AI with Ollama, Moondream and LLaVA
SafeOS has an optional server you run on your own machine with Docker. It takes camera frames over a WebSocket, keeps each one for 10 minutes, and asks two vision models about them through Ollama: Moondream first, then llava:7b when Moondream reports a concern. This post follows a frame through the server’s code, and says where the web app’s side of that path stops at the commit it describes.
The short version, beside the rest of SafeOS, is the server section of how SafeOS watches a room in your browser. The path, from the message the server reads:
- A client with a session sends a frame message that names an active stream it owns.
- The server refuses anything that is not one JPEG, PNG or WebP within its size and pixel limits.
- It keeps the frame 10 minutes, then deletes it.
- Motion 10 or more, or sound 15 or more? Then it queues the frame.
- Moondream looks first; when it reports a concern, llava:7b looks closer.
- If Ollama is down or fails and a cloud key is set: OpenRouter, then OpenAI, then Anthropic.
- A result of medium or higher becomes an alert, sent by the channels its owner set up.
What the server runs, and how to start it
The server is TypeScript on Node.js 20, run from its sources by tsx inside an Alpine image (Dockerfile, Dockerfile). It is Express for HTTP, ws for the WebSocket, cors for the origin check and sharp for decoding pictures (server.ts), and it keeps its records in SQLite through @framers/sql-storage-adapter, trying better-sqlite3 first and sql.js after it (index.ts). The compose file at the repository’s root starts it:
# SafeOS Guardian - full local stack.
#
# cp .env.example .env # optional: fill in only the keys you want
# docker compose up -d --build
#
# Startup order is enforced by health/completion gates:
# ollama (healthy) -> ollama-pull (models cached) -> api (healthy) -> ui
#
# NVIDIA GPU: docker compose -f docker-compose.yml -f docker-compose.gpu.yml up -d --build
# With Redis: docker compose --profile with-redis up -d --build
#
# Values written as ${VAR:-default} are read from ./.env automatically.
#
# This stack is for one machine. The UI, the API and Ollama are published on
# 127.0.0.1 only (open http://localhost:3000 on the same machine); Redis is
# not published. To serve other machines, use docker-compose.prod.yml, where
# only the Caddy proxy is published (docs/DEPLOYMENT.md).docker-compose.yml, lines 1–17 at commit 017b33bThe order is held by health checks. Ollama starts first; a one-shot container then pulls the models named in OLLAMA_MODELS, moondream and llava:7b unless you set others, into a volume that keeps them between restarts (docker-compose.yml); the API waits for that container to finish, and the web app waits for the API. Ollama lists the two models at 1.7 GB and 4.7 GB (moondream, llava), so the first start downloads both before the API comes up.
Each published port is bound to 127.0.0.1: the web app on 3000, the API on 3001 and Ollama on 11434 (docker-compose.yml, docker-compose.yml, docker-compose.yml). Redis starts only with the with-redis profile and is never published (docker-compose.yml). Loopback matters with Docker in particular: Docker’s own documentation says traffic to a published port is routed “before the firewall rules can be applied, effectively ignoring your firewall configuration” for ufw (Docker, Packet filtering and firewalls). So a CI job resolves every compose file in the repository and fails one that publishes a port beyond loopback, except the Caddy proxy of the production file, and checks that its own reject fixtures fail (check-compose-ports.sh, ci.yml). To serve other machines, the production compose file publishes only that proxy.
You do not have to build anything: every push to master that touches code builds safeos-api and safeos-ui for linux/amd64 and linux/arm64 and pushes them to ghcr.io, so a 64-bit Raspberry Pi pulls the same tags as a PC (docker-publish.yml, docker-publish.yml).
What the browser sends, and when
In the web app, only the Motion and sound page opens the server’s WebSocket to send frames (page.tsx); People and Wildlife send it nothing. The page connects only when a server address is saved in this browser and the server has given it a session (env.ts, websocket.ts), and its first message is that session’s token (websocket.ts). The server closes a connection that sends anything else first, or nothing within five seconds (server.ts, server.ts).
With the processing mode on Settings, Models set to anything but Local instant, the camera part of the page checks once each analysis interval, at least 250 ms apart, whether a check is over its line, and only then encodes a frame (page.tsx):
// Only send frames when there's significant activity
if (motion < motionGateThreshold && audio < audioGateThreshold && !pixelTriggered) {
return;
}
// Capture and send frame
if (canvasRef.current && onFrameRef.current) {
const imageData = canvasRef.current.toDataURL('image/jpeg', 0.7);
onFrameRef.current({
imageData,
motionScore: motion,
audioLevel: audio,
timestamp: Date.now(),
hasCrying: crying,
pixelChangePercent: lastPixelResultRef.current?.difference,
pixelChangedPixelCount: lastPixelResultRef.current?.changedPixelCount,
pixelTriggeredBy: lastPixelResultRef.current?.triggeredBy,
});CameraFeed.tsx, lines 570–587 at commit 017b33bThe frame is the page’s canvas as a JPEG at quality 0.7, with the motion and sound readings beside it. The default setting, Maximum Alert, uses the Hybrid mode and an interval of 5 s, so saving a server address is enough to start (settings-store.ts, settings-store.ts). The page then sends it like this:
const handleFrame = (data: { imageData: string; motionScore: number; audioLevel: number }) => {
if (!isStreaming || !captureRequestedRef.current || !serverRequestedRef.current || !wsConnected ||
useSettingsStore.getState().globalSettings.processingMode === 'local') return;
sendMessage({
type: 'frame',
payload: {
frame: data.imageData,
motionScore: data.motionScore,
audioLevel: data.audioLevel,
},
});
};page.tsx, lines 748–760 at commit 017b33bBefore the server reads a frame message at all, it checks the stream the message names:
private async handleWSMessage(client: WSClient, message: WSMessage): Promise<void> {
if (['join_stream', 'frame', 'audio_level', 'offer', 'answer', 'ice-candidate'].includes(message.type)) {
if (!await this.ownsStream(client, message.streamId)) {
this.streamForbidden(client);
return;
}
}server.ts, lines 408–414 at commit 017b33bThose two do not meet at this commit. The page’s message carries no streamId, and its picture is under frame where the server reads imageData (server.ts). The page never creates a stream on the server: it sends a start-stream message, which the server’s message switch has no case for (page.tsx, server.ts), and nothing in the web app calls POST /api/streams. So the server answers each frame with STREAM_FORBIDDEN, “Stream unavailable”, and keeps none of them. The web app’s WebSocket hook holds a sendFrame that sends the shape the server reads (websocket.ts), and the monitor does not call it. The server’s own tests create a stream with POST /api/streams and send frames in that shape (server-hardening.test.ts, server-hardening.test.ts). Everything below is what happens to a frame that arrives that way, from the web app once it sends that shape or from a client of your own.
What the server checks, and how long it keeps a frame
Each profile gets 30 frame attempts a minute, shared by all its sockets and counted before any decoding, so a second connection buys no more (server.ts). The picture may come as a data URL or as plain base64, and must be canonical base64 of at most 2 MiB (server.ts). At most two pictures decode at once in the whole process, and a third gets “Frame decoder busy” (server.ts). Then sharp decodes it:
try {
if (bytes.toString('base64') !== imageData) throw new Error('Invalid base64');
const image = sharp(bytes, { limitInputPixels: MAX_FRAME_PIXELS, failOn: 'warning' });
const metadata = await image.metadata();
if (!['jpeg', 'png', 'webp'].includes(metadata.format || '') || (metadata.pages || 1) !== 1) {
throw new Error('Unsupported image');
}
// Statistics scan the decoded pixels without returning a full bitmap
// to JavaScript. Metadata alone cannot establish image integrity.
await image.stats();
} catch {
this.frameError(client, 'INVALID_FRAME');
return;
} finally {
activeFrameDecodes--;
}server.ts, lines 539–554 at commit 017b33blimitInputPixels stops sharp before it processes a picture with more pixels than the limit, here 16 million, and failOn: 'warning' is the most sensitive of its four levels for invalid pixel data (sharp’s constructor documentation). The format must be JPEG, PNG or WebP, with one page, and stats() reads every decoded pixel, because a file’s header alone says nothing about the rest of it. Anything that fails gets one error, “Use a decodable JPEG, PNG or WebP up to 2 MiB and 16 megapixels” (server.ts), and is not kept.
The server checks the session and the stream once more after the decode, since a decode takes time, and only then writes the frame into the frame_buffer table with its two readings (server.ts). That table is a buffer of 10 minutes. Once when the server starts, and every second after, it runs:
export async function cleanupOldFrames(db: Database): Promise<void> {
const threshold = new Date(Date.now() - BUFFER_MINUTES * 60 * 1000).toISOString();
await db.run('DELETE FROM frame_buffer WHERE created_at <= ?', [threshold]);
}index.ts, lines 444–448 at commit 017b33bBUFFER_MINUTES is 10 (index.ts; server.ts). A queued job reads its frame back only while it is younger than that, so a job that waited longer finds nothing and stops (analysis-queue.ts). What outlives the frame is what was learned from it: the analysis result, with the model’s description, and any alert.
Not every kept frame is read by a model. The server queues a frame when its motion reading is 10 or more or its sound reading 15 or more, and gives a frame with motion over 50 the higher priority (server.ts). It runs 2 analyses at once and gives each job three tries (analysis-queue.ts, analysis-queue.ts).
A first look, then a closer one
Each job asks Ollama whether it is up, then:
if (ollamaAvailable) {
// Local analysis with Ollama
try {
// Step 1: Quick triage with Moondream
const triageResult = await this.ollamaClient.triage(
imageData,
TRIAGE_PROMPTS[scenario]
);
modelUsed = 'moondream';
const triageConcern = this.parseConcernLevel(triageResult);
// Step 2: If concern detected, do detailed analysis with LLaVA
if (triageConcern !== 'none') {
const analysisResult = await this.ollamaClient.analyze(
imageData,
ANALYSIS_PROMPTS[scenario]
);
modelUsed = 'llava:7b';
analysis-queue.ts, lines 274–293 at commit 017b33bMoondream, the small model, answers a short prompt chosen by the stream’s scenario that ends by asking for a concern level from none to critical. Only when its answer is not “none” does llava:7b get the frame with a longer prompt (analysis-queue.ts). Both calls go to Ollama’s /api/generate at OLLAMA_HOST, http://localhost:11434 unless set otherwise, with the frame as base64 in images, stream: false, a temperature of 0.2, at most 500 tokens and a two-minute timeout (client.ts, client.ts). Ollama’s API takes images as “a list of base64-encoded images (for multimodal models such as llava)”, and with stream false it returns one response object rather than a stream of them (Ollama API).
A result of medium, high or critical becomes an alert; none and low are stored as results and go no further (analysis-queue.ts). Nothing measures how often either model’s answer is right.
Moondream is under the Apache License 2.0, as its makers list it (moondream2), and LLaVA’s makers add usage notices for its training data and base model (LLaVA). Ollama pulls both on your own server.
When Ollama is down
When Ollama does not answer its health check, or the local analysis throws, the job goes to the cloud fallback instead (analysis-queue.ts):
const openrouter = getOpenRouterClient();
if (openrouter) {
try {
return await analyzeWithOpenRouter(openrouter, imageBase64, prompt);
} catch (error) {
console.warn('OpenRouter analysis failed, trying OpenAI:', error);
}
}
const openai = getOpenAIClient();
if (openai) {
try {
return await analyzeWithOpenAI(openai, imageBase64, prompt);
} catch (error) {
console.warn('OpenAI analysis failed, trying Anthropic:', error);
}
}
const anthropic = getAnthropicClient();
if (anthropic) {
try {
return await analyzeWithAnthropic(anthropic, imageBase64, prompt);
} catch (error) {
console.error('Anthropic analysis failed:', error);
throw error;
}
}
throw new Error('No cloud LLM providers available');cloud-fallback.ts, lines 77–105 at commit 017b33bEach provider is tried only when its key is set in the server’s environment (cloud-fallback.ts, docker-compose.yml). With no key set, the job fails and is retried, and no frame goes anywhere. With a key set, the frame goes to the first provider the server has a key for and, if that one fails, to the next, and whoever runs that provider receives it. Leave the three keys empty to keep every frame on the machine that runs the server.
How an alert goes out
An alert is saved against the stream’s owner, and its channels depend on its severity: medium goes to browser push, Telegram and email, and high and critical add SMS (notification-manager.ts). Three rules hold it back:
- Quiet hours hold low and medium alerts only, and only with a saved time zone, so a high or critical alert is sent at any hour (
notification-manager.ts). - A cooldown of 5 minutes: an alert is not sent while the same stream has an unacknowledged alert of the same or a higher severity that was raised in that time and delivered. A delivery that failed or is still pending starts no cooldown (
analysis-queue.ts). - At most 32 deliveries run at once in the process, and a critical alert passes that limit (
analysis-queue.ts,analysis-queue.ts).
Each channel has 15 seconds, and a slow one never holds up another (notification-manager.ts). The keys for Twilio, Telegram, Resend and web push are optional environment variables of the API container (docker-compose.yml).
Which pages may call it
The HTTP side answers browser pages from a list of origins. With SAFEOS_ALLOWED_ORIGINS empty, the list is safeos.sh, the phone app shells and plain http on localhost, 127.0.0.1 and [::1] at any port; set it, and only the origins it names are allowed:
function allowedOrigins(value: string | undefined): (origin: string) => boolean {
const entries = (value ?? '').split(',').map((origin) => origin.trim().replace(/\/+$/, '')).filter(Boolean);
const listed = entries.map(asBrowserSendsIt);
const notOrigins = entries.filter((origin) => !AN_ORIGIN.test(origin.toLowerCase()));
if (notOrigins.length) {
console.warn(
`SAFEOS_ALLOWED_ORIGINS: ${notOrigins.map((origin) => `"${origin}"`).join(', ')} ` +
'can never be allowed: an origin is a scheme and a host, with a port if any, such as https://safeos.example.com'
);
}
if (listed.length) {
const allowed = new Set(listed);
return (origin) => allowed.has(origin);
}
const allowed = new Set(DEFAULT_ALLOWED_ORIGINS);
return (origin) => allowed.has(origin) || LOCAL_DEVELOPMENT_ORIGIN.test(origin);
}server.ts, lines 117–133 at commit 017b33bEach entry is compared as a browser sends it, in small letters and without the default port, and an entry that is not an origin is reported when the server starts (server.ts). The function goes to the cors middleware as its origin option, whose callback takes an error and a yes or no (server.ts; cors README). An answer to any other page carries no Access-Control-Allow-Origin header, and a browser shares a cross-origin response with a page’s script only when the server opts in with that header (MDN on CORS). The WebSocket reads no origin; it rests on the session token, which a browser sends as its first message and a native client may send in a header (server.ts).
What to keep in mind
- At this commit the Motion and sound page’s frames do not reach the server’s buffer, as the second section shows.
- A frame stays 10 minutes. Its analysis, the model’s description and any alert stay after it.
- With a cloud key set, frames can reach that cloud provider.
- Nothing measures the server models’ answers or how long they take.
SafeOS adds an alert. It does not replace a person nearby. A phone or a browser can sleep, lose power or drop the camera, so stay within reach.
Next: Playwright fake camera: testing a webcam app in CI, how the web app’s camera paths are walked in a browser on every pull request, and what those walks leave out.
Docker and the Docker logo are trademarks or registered trademarks of Docker, Inc. in the United States and/or other countries. Ollama, OpenRouter, OpenAI, Anthropic, Telegram, Twilio, Resend, GitHub and Raspberry Pi are named to describe what SafeOS works with. Product names belong to their owners; SafeOS is not affiliated with them.
— The Frame.dev Team