diff --git a/CHANGELOG.md b/CHANGELOG.md index c219c581..8e21a660 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ Anything that changes what the dashboard, the admin or a widget can do gets a li rather than only the one that declared it. ### Added +- **Local Docker and AI models.** Registry widgets can show up to 200 local containers and observed Ollama or MLX models. Fremkit refuses remote Docker contexts, distinguishes a missing CLI from a stopped daemon, and keeps the container list when stats fail. - **Claude sessions: go to the session.** Touch a card and its window comes forward — the exact Orca pane, the Terminal.app or iTerm2 tab, the VS Code window on that folder, or at least the application — for every session, hooked or merely found running. The card also says which application the session lives in, which is what tells two panes of the diff --git a/README.md b/README.md index a9e60451..6e7b3d6d 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ The name is the Fremen survival kit from *Dune*. and the widgets all wear the one you pick. - **Two languages** — the whole interface is French or English, switched in the admin. - **A widget SDK** that is a folder, a JSON file and an HTML page. +- **Optional local operations** show Docker containers and Ollama/MLX models through registry widgets. See [docs/local-operations.md](docs/local-operations.md). ## Requirements diff --git a/docs/local-operations.md b/docs/local-operations.md new file mode 100644 index 00000000..6b13d61f --- /dev/null +++ b/docs/local-operations.md @@ -0,0 +1,17 @@ +# Local Docker and model observations + +Fremkit publishes two read-only channels only while a dashboard widget subscribes. Their widgets live in the registry. Neither channel starts a container or a model. + +## Docker + +`docker-local` resolves Docker from `/opt/homebrew/bin/docker`, `/usr/local/bin/docker` or `~/.docker/bin/docker`, then reads the selected context. Only a local Unix socket is accepted; TCP and SSH contexts return `remote-context`. A missing executable returns `unavailable`; a stopped daemon or failed query returns `offline`; malformed data returns `invalid`. The snapshot is `{data, stale, error, updatedAt}`. When no successful snapshot exists, `data` is null and `stale` is false. A later failure retains the previous data with `stale: true`. + +`data.containers` contains at most 200 records. Each record has `id`, `name`, `image`, `state`, `status` and `stats`. The optional `stats` object contains Docker's `cpu`, `memory`, `memoryPercent`, `pids`, `netIO` and `blockIO` strings. It is null for stopped containers and whenever stats cannot be collected. A container that stops after listing does not blank the rest of the snapshot. No commands, environment, labels, mounts or ports are published. + +The helper needs access to the local Docker socket. This channel cannot start, stop, remove or execute a container. + +## Local models + +`local-models` reads Ollama on `127.0.0.1:11434` and selected local MLX or oMLX server processes. Its snapshot has independent `installed`, `loaded` and `mlx` parts, each with `{data, stale, error, updatedAt}`. `installed` and `loaded` contain at most 200 Ollama model records with `name`, `size`, `size_vram`, `context_length` and `expires_at`. `mlx` contains at most 20 process records with `pid`, `backend`, a path-free `model` label, `port`, `cpu` and `memoryBytes`. A missing or stopped Ollama daemon returns `offline` on its two parts without hiding MLX processes. Invalid Ollama JSON returns `invalid`. + +A listed model or process does not prove inference is running. HTTP responses are limited to 1 MiB, redirects are refused, and no prompts or responses are read. diff --git a/docs/writing-widgets.md b/docs/writing-widgets.md index 95501a98..38a1a168 100644 --- a/docs/writing-widgets.md +++ b/docs/writing-widgets.md @@ -279,7 +279,7 @@ document.documentElement.style.setProperty('--h', Fremkit.size.px.height + 'px') `system`, `processes`, `volume`, `spotify`, `mutedeck`, `clipboard`, `shortcuts`, `cleanshot`, `network`, `battery`, `service-status`, `config`, `claude-sessions`, `claude-usage`, -`claude-account`, `dock`, plus one per connection: `azure-devops:`, +`claude-account`, `dock`, `docker-local`, `local-models`, plus one per connection: `azure-devops:`, `bambu:`, `github:`, `synology:`, and `calendar:` for an ICS connection. diff --git a/server/src/providers/index.ts b/server/src/providers/index.ts index cf935cee..fa5970d8 100644 --- a/server/src/providers/index.ts +++ b/server/src/providers/index.ts @@ -1,3 +1,4 @@ +import { createDockerProvider, createLocalModelsProvider } from './local-operations.js' import type { Provider } from './types.js' import { systemProvider } from './system.js' import { processesProvider } from './processes.js' @@ -10,6 +11,8 @@ import { createNetworkProvider } from './network.js' import { createBatteryProvider } from './battery.js' export const providers: Provider[] = [ + createDockerProvider(), + createLocalModelsProvider(), systemProvider, processesProvider, createVolumeProvider(), diff --git a/server/src/providers/local-operations.ts b/server/src/providers/local-operations.ts new file mode 100644 index 00000000..95b822e2 --- /dev/null +++ b/server/src/providers/local-operations.ts @@ -0,0 +1,194 @@ +import { execFile } from 'node:child_process' +import { access, constants } from 'node:fs/promises' +import { homedir } from 'node:os' +import { basename, isAbsolute, join } from 'node:path' +import si from 'systeminformation' +import { z } from 'zod' +import type { Provider } from './types.js' + +const localEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => { + const safe: NodeJS.ProcessEnv = {} + for (const key of ['HOME', 'PATH', 'TMPDIR', 'LANG', 'LC_ALL', 'USER', 'LOGNAME']) { + if (env[key] !== undefined) safe[key] = env[key] + } + return safe +} + +interface Part { + data: T | null + stale: boolean + error: string | null + updatedAt: number | null +} +const empty = (): Part => ({ data: null, stale: false, error: null, updatedAt: null }) +const fresh = (data: T): Part => ({ data, stale: false, error: null, updatedAt: Date.now() }) +const failed = (part: Part, error: string): Part => ({ ...part, stale: part.data !== null, error }) + +function mlxBackend(command: string, params: string): 'oMLX' | 'MLX' | null { + const executable = basename(command) + if (executable === 'omlx') return 'oMLX' + if (executable === 'mlx-server' || executable === 'mlx_lm.server') return 'MLX' + const launch = params.match(/^(?:-u\s+|-B\s+)*(?:-m\s+)?(?:\S*\/)?(omlx|mlx-server|mlx_lm\.server)(?:\s|$)/) + return launch?.[1] === 'omlx' ? 'oMLX' : launch ? 'MLX' : null +} +const text = z.string().max(2048) +const identifier = z.string().regex(/^[a-f0-9]{4,64}$/i) +const Container = z.object({ ID: identifier, Names: text, Image: text, State: text, Status: text }) +const Stats = z.object({ ID: identifier, CPUPerc: text, MemUsage: text, MemPerc: text, PIDs: text, NetIO: text, BlockIO: text }) + +type DockerContainer = { + id: string + name: string + image: string + state: string + status: string + stats: { cpu: string; memory: string; memoryPercent: string; pids: string; netIO: string; blockIO: string } | null +} + +function jsonLines(raw: string): unknown[] { + if (Buffer.byteLength(raw) > 1048576) throw new Error('invalid') + const lines = raw.trim() ? raw.trim().split(/\r?\n/) : [] + return lines.slice(0, 200).map((line) => JSON.parse(line)) +} + +/** Resolve a local executable from a closed path list, without PATH lookup. */ +export async function resolveDockerBinary(canExecute: (path: string) => Promise = (path) => access(path, constants.X_OK)): Promise { + for (const path of ['/opt/homebrew/bin/docker', '/usr/local/bin/docker', join(homedir(), '.docker/bin/docker')]) { + try { await canExecute(path); return path } catch { /* Try the next known install. */ } + } + throw new Error('unavailable') +} + +const dockerRun = async (args: string[]): Promise => { + const binary = await resolveDockerBinary() + return new Promise((resolve, reject) => execFile(binary, args, { + env: localEnv(process.env), timeout: 10000, maxBuffer: 1048576, shell: false, + }, (error, stdout) => error ? reject(new Error('offline')) : resolve(stdout))) +} + +/** Publish local Docker state only, with nullable per-container stats. */ +export function createDockerProvider(opts: { run?: (args: string[]) => Promise } = {}): Provider> { + const run = opts.run ?? dockerRun + let last = empty<{ containers: DockerContainer[] }>() + let generation = 0 + return { + channel: 'docker-local', intervalMs: 10000, + stop() { generation++ }, + async poll() { + const epoch = generation + try { + const host = (await run(['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'])).trim() + if (host.length > 4096 || !/^unix:\/\/\/[^\0]+$/.test(host)) { + if (epoch === generation) last = failed(empty(), 'remote-context') + return last + } + const rows = jsonLines(await run(['--host', host, 'ps', '-a', '--last', '200', '--no-trunc', '--format', '{{json .}}'])) + const containers = rows.map((row) => Container.parse(row)) + const running = containers.filter((row) => row.State === 'running') + let stats: z.infer[] = [] + if (running.length) { + try { + stats = jsonLines(await run(['--host', host, 'stats', '--no-stream', '--no-trunc', '--format', '{{json .}}', ...running.map((row) => row.ID)])) + .map((row) => Stats.parse(row)) + } catch { /* A container can stop between list and stats. Keep its state. */ } + } + const byId = new Map(stats.map((stat) => [stat.ID, stat])) + const data = { containers: containers.map((row): DockerContainer => { + const stat = row.State === 'running' ? byId.get(row.ID) : undefined + return { + id: row.ID, name: row.Names, image: row.Image, state: row.State, status: row.Status, + stats: stat ? { cpu: stat.CPUPerc, memory: stat.MemUsage, memoryPercent: stat.MemPerc, pids: stat.PIDs, netIO: stat.NetIO, blockIO: stat.BlockIO } : null, + } + }) } + if (epoch === generation) last = fresh(data) + } catch (error) { + const reason = error instanceof z.ZodError || error instanceof SyntaxError ? 'invalid' + : error instanceof Error && error.message === 'unavailable' ? 'unavailable' : 'offline' + if (epoch === generation) last = failed(last, reason) + } + return last + }, + } +} + +const Model = z.object({ + name: z.string().max(512), size: z.number().nonnegative(), + size_vram: z.number().nonnegative().nullish().transform((value) => value ?? null), + context_length: z.number().int().nonnegative().nullish().transform((value) => value ?? null), + expires_at: z.string().max(100).nullish().transform((value) => value ?? null), +}) +interface ModelProcess { pid: number; name: string; command: string; params: string; cpu: number; mem: number; memRss: number } +interface MlxProcess { pid: number; backend: 'MLX' | 'oMLX'; model: string | null; port: number | null; cpu: number; memoryBytes: number } +interface LocalModelsSnapshot { + installed: Part[]> + loaded: Part[]> + mlx: Part +} + +function safeModelLabel(value: string | undefined): string | null { + if (!value) return null + const candidate = isAbsolute(value) ? basename(value) : value + return /^[\w.-]+(?:\/[\w.-]+)?$/.test(candidate) ? candidate : null +} + +/** Publish bounded Ollama and local MLX process observations, never prompts or paths. */ +export function createLocalModelsProvider(opts: { fetchFn?: typeof fetch; processes?: () => Promise } = {}): Provider { + const fetchFn = opts.fetchFn ?? fetch + const processes = opts.processes ?? (async () => (await si.processes()).list) + let installed = empty[]>() + let loaded = empty[]>() + let mlx = empty() + let generation = 0 + + async function models(path: string, previous: Part[]>): Promise[]>> { + try { + const response = await fetchFn('http://127.0.0.1:11434/api/' + path, { signal: AbortSignal.timeout(3000), redirect: 'error' }) + if (!response.ok) { await response.body?.cancel(); return failed(previous, 'offline') } + const reader = response.body?.getReader() + if (!reader) return failed(previous, 'invalid') + let raw = '', bytes = 0 + const decoder = new TextDecoder() + try { + while (true) { + const chunk = await reader.read() + if (chunk.done) break + bytes += chunk.value.byteLength + if (bytes > 1048576) throw new Error('invalid') + raw += decoder.decode(chunk.value, { stream: true }) + } + raw += decoder.decode() + } finally { await reader.cancel().catch(() => {}) } + return fresh(z.object({ models: z.array(Model).max(200) }).parse(JSON.parse(raw)).models) + } catch (error) { + return failed(previous, error instanceof z.ZodError || error instanceof SyntaxError ? 'invalid' : 'offline') + } + } + + return { + channel: 'local-models', intervalMs: 15000, + stop() { generation++ }, + async poll() { + const epoch = generation + const [nextInstalled, nextLoaded, nextMlx] = await Promise.all([ + models('tags', installed), models('ps', loaded), + (async (): Promise> => { + try { + const all = await processes() + return fresh(all.filter((process) => mlxBackend(process.command, process.params) !== null).slice(0, 20).map((process) => { + const model = process.params.match(/(?:^|\s)--model(?:=|\s+)([^\s]{1,512})/) + const port = process.params.match(/(?:^|\s)--port(?:=|\s+)(\d{1,5})/) + const number = port ? Number(port[1]) : null + return { + pid: process.pid, backend: mlxBackend(process.command, process.params)!, + model: safeModelLabel(model?.[1]), port: number && number < 65536 ? number : null, + cpu: process.cpu, memoryBytes: process.memRss * 1024, + } + })) + } catch { return failed(mlx, 'offline') } + })(), + ]) + if (epoch === generation) { installed = nextInstalled; loaded = nextLoaded; mlx = nextMlx } + return { installed, loaded, mlx } + }, + } +} diff --git a/server/test/local-operations.test.ts b/server/test/local-operations.test.ts new file mode 100644 index 00000000..c65f76f6 --- /dev/null +++ b/server/test/local-operations.test.ts @@ -0,0 +1,123 @@ +import { describe, it, expect } from 'vitest' +import { createDockerProvider, createLocalModelsProvider, resolveDockerBinary } from '../src/providers/local-operations.js' + +const container = (state = 'running') => JSON.stringify({ ID: 'abcd', Names: 'example', Image: 'example:latest', State: state, Status: state === 'running' ? 'Up' : 'Exited', Command: 'PRIVATE' }) +const stats = JSON.stringify({ ID: 'abcd', CPUPerc: '2.3%', MemUsage: '12MiB / 2GiB', MemPerc: '1%', PIDs: '3', NetIO: '1kB / 2kB', BlockIO: '0B / 0B' }) + +describe('Docker observation', () => { + it('joins container state with its stats by ID without leaking private fields', async () => { + const calls: string[][] = [] + const provider = createDockerProvider({ run: async (args) => { + calls.push(args) + if (args[0] === 'context') return 'unix:///path/to/docker.sock' + if (args.includes('ps')) return container() + return stats + } }) + const snapshot = await provider.poll!() + expect(snapshot.data?.containers[0]).toMatchObject({ id: 'abcd', name: 'example', state: 'running', stats: { cpu: '2.3%', memory: '12MiB / 2GiB' } }) + expect(JSON.stringify(snapshot)).not.toContain('PRIVATE') + expect(calls.filter((args) => args.includes('ps') || args.includes('stats')).every((args) => args[0] === '--host' && args[1] === 'unix:///path/to/docker.sock')).toBe(true) + expect(calls.every((args) => !args.includes('start') && !args.includes('inspect-env'))).toBe(true) + }) + + it('refuses a remote context before querying containers', async () => { + const calls: string[][] = [] + const provider = createDockerProvider({ run: async (args) => { calls.push(args); return 'ssh://example.com' } }) + expect(await provider.poll!()).toMatchObject({ data: null, error: 'remote-context' }) + expect(calls).toHaveLength(1) + }) + + it('keeps stopped containers without inventing usage and marks retained data stale', async () => { + let offline = false + const provider = createDockerProvider({ run: async (args) => { + if (offline) throw new Error('PRIVATE') + if (args[0] === 'context') return 'unix:///example.sock' + if (args.includes('ps')) return container('exited') + throw new Error('stats must not run') + } }) + const snapshot = await provider.poll!() + expect(snapshot.data?.containers[0].stats).toBeNull() + offline = true + expect(await provider.poll!()).toMatchObject({ data: snapshot.data, stale: true, error: 'offline' }) + }) + + it('preserves the container list when stats fail after a container stops', async () => { + const provider = createDockerProvider({ run: async (args) => { + if (args[0] === 'context') return 'unix:///example.sock' + if (args.includes('ps')) return container() + throw new Error('container stopped') + } }) + const snapshot = await provider.poll!() + expect(snapshot.data?.containers[0]).toMatchObject({ id: 'abcd', stats: null }) + expect(snapshot.error).toBeNull() + }) + + it('caps large container lists to 200 rows and distinguishes a missing CLI', async () => { + const provider = createDockerProvider({ run: async (args) => { + if (args[0] === 'context') return 'unix:///example.sock' + if (args.includes('ps')) return Array.from({ length: 201 }, () => container('exited')).join('\n') + return '' + } }) + expect((await provider.poll!()).data?.containers).toHaveLength(200) + const unavailable = createDockerProvider({ run: async () => { throw new Error('unavailable') } }) + expect(await unavailable.poll!()).toMatchObject({ data: null, stale: false, error: 'unavailable' }) + }) + + it('resolves only known absolute Docker executable paths', async () => { + const paths: string[] = [] + const binary = await resolveDockerBinary(async (path) => { + paths.push(path) + if (path !== '/usr/local/bin/docker') throw new Error('missing') + }) + expect(binary).toBe('/usr/local/bin/docker') + expect(paths).toEqual(['/opt/homebrew/bin/docker', '/usr/local/bin/docker']) + await expect(resolveDockerBinary(async () => { throw new Error('missing') })).rejects.toThrow('unavailable') + }) +}) + +describe('Local model observation', () => { + const modelResponse = async () => new Response(JSON.stringify({ models: [{ name: 'example-model', size: 100, size_vram: 80, context_length: 4096 }] })) + + it('separates installed Ollama models, loaded models and MLX process evidence', async () => { + const urls: string[] = [] + const provider = createLocalModelsProvider({ + fetchFn: (async (url) => { urls.push(String(url)); return modelResponse() }) as typeof fetch, + processes: async () => [{ pid: 12, name: 'python', command: 'python', params: '-m mlx_lm.server --model example/model --port 8080 --api-key PRIVATE', cpu: 3, mem: 2, memRss: 1024 }], + }) + const snapshot = await provider.poll!() + expect(snapshot.installed.data?.[0].name).toBe('example-model') + expect(snapshot.loaded.data?.[0].size_vram).toBe(80) + expect(snapshot.mlx.data?.[0]).toMatchObject({ model: 'example/model', port: 8080, cpu: 3 }) + expect(JSON.stringify(snapshot)).not.toContain('PRIVATE') + expect(urls).toEqual(['http://127.0.0.1:11434/api/tags', 'http://127.0.0.1:11434/api/ps']) + }) + + it('does not publish an absolute model path and detects console-script launches', async () => { + const provider = createLocalModelsProvider({ + fetchFn: modelResponse as typeof fetch, + processes: async () => [{ pid: 14, name: 'python', command: '/opt/homebrew/bin/python3', params: '/Users/example/bin/mlx_lm.server --model /Users/example/models/llama-3 --port 8080', cpu: 4, mem: 1, memRss: 100 }], + }) + const snapshot = await provider.poll!() + expect(snapshot.mlx.data?.[0].model).toBe('llama-3') + expect(JSON.stringify(snapshot)).not.toContain('/Users/example') + }) + + it('detects Python-launched oMLX and mlx-server scripts', async () => { + const provider = createLocalModelsProvider({ + fetchFn: modelResponse as typeof fetch, + processes: async () => [ + { pid: 15, name: 'python3', command: 'python3', params: '/opt/example/bin/omlx serve --port 8000', cpu: 1, mem: 1, memRss: 100 }, + { pid: 16, name: 'python3', command: 'python3', params: '/opt/example/bin/mlx-server --port 8001', cpu: 1, mem: 1, memRss: 100 }, + ], + }) + expect((await provider.poll!()).mlx.data?.map((entry) => entry.backend)).toEqual(['oMLX', 'MLX']) + }) + + it('keeps MLX independent when Ollama is offline', async () => { + const provider = createLocalModelsProvider({ fetchFn: (async () => { throw new Error('PRIVATE') }) as typeof fetch, processes: async () => [] }) + const snapshot = await provider.poll!() + expect(snapshot.loaded).toMatchObject({ data: null, error: 'offline' }) + expect(snapshot.mlx).toMatchObject({ data: [], stale: false }) + expect(JSON.stringify(snapshot)).not.toContain('PRIVATE') + }) +})