AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { guardedHandleFor } from './guarded-handle'
import { notifyPerformanceChanged } from './performance-notify'
import { IPC } from '../../shared/ipc'
import type { AppContext } from '../services/context'
import type { DownloadJob } from '../../shared/types'
import { DownloadManager, type DownloadGates } from '../services/downloads'
import { createSettingsHashStore, discoverManifests } from '../services/models'
import { getSettings } from '../services/settings'
import { loadPolicy } from '../services/policy'
import { tMain } from '../services/i18n'
import { log } from '../services/logging'
// IPC for the in-app model downloader (architecture.md "In-app model downloader").
// Async-with-polling like the import jobs: `downloadModel` returns the job
// immediately, the renderer polls `getDownloadJob`. The gates are re-checked HERE, in
// the main process, on every start: the policy ceiling (`allow_model_downloads`) AND
// the user's `allowNetwork` setting (default on) — the renderer's confirmation dialog
// is UX, not the enforcement layer. `licenseAccepted` carries the dialog's explicit
// license acknowledgement through to the planner's license gate (`--accept-license`
// semantics) for manifests whose `license_review.status` is not `approved`.
export function registerDownloadIpc(ctx: AppContext, manager?: DownloadManager): void {
const ipcHandle = guardedHandleFor(ctx)
// Production injects the global fetch; tests pass a manager with a fake, and the one row
// that builds this default stubs the global first (CI is zero-network). The audit hook
// routes the manager's background started/verified/failed outcomes to the app
// audit recorder without the service touching the DB.
const downloads =
manager ??
new DownloadManager({
fetchImpl: fetch,
log: (m, meta) => log.info(m, meta),
audit: (type, message, metadata) => ctx.audit?.(type, message, metadata),
// Issue #40: a completed download re-runs the availability selectors that were frozen at
// startup (main/index.ts wires the ctx hook) — e.g. TranslateGemma activates without a
// restart. Read late off ctx (the audit-hook pattern) so registration order can't matter.
// #914: the Performance rows say which models are on this drive, so an open screen re-reads
// once the files are in place — after the selectors re-ran (performance-notify's "after the
// mutation" rule), and even if that hook throws (the manager swallows it). Only `done` calls
// this hook (verified, or a placeholder-hash completion: the files are in place either way);
// a failed or cancelled download puts nothing in place and pushes nothing.
onModelInstalled: (modelId) => {
try {
ctx.onModelInstalled?.(modelId)
} finally {
notifyPerformanceChanged()
}
}
})
// #782: switching internet access off stops the running download (settings:update calls this).
ctx.downloadsNetworkSwitched = (on, onStopped) => downloads.networkSwitched(on, onStopped)
// Both gates read at call time: the policy from disk (authoritative ceiling), the
// setting from the (possibly locked → treated as off) workspace DB.
const gates = (): DownloadGates => {
const { policy } = loadPolicy(ctx.paths.configPath, (m) => log.warn(m), { isDev: ctx.isDev })
const settingAllows = ctx.workspace.isUnlocked() && getSettings(ctx.db).allowNetwork
return { policyAllows: policy.network.allowModelDownloads, settingAllows }
}
ipcHandle(
IPC.downloadModel,
async (_e, modelId: string, opts?: { licenseAccepted?: boolean }): Promise<DownloadJob> => {
if (!ctx.manifestsDir) throw new Error(tMain('main.models.noManifests'))
const { manifests } = discoverManifests(ctx.manifestsDir)
const found = manifests.find((m) => m.manifest.id === modelId)
// #930: in the interface language, without the id (the log keeps it).
if (!found) {
log.warn('Download refused: unknown model id', { modelId })
throw new Error(tMain('main.models.unknown'))
}
return downloads.start({
rootPath: ctx.paths.rootPath,
manifest: found.manifest,
gates: gates(),
licenseAccepted: opts?.licenseAccepted === true,
// BE-2 (full-audit 2026-07-10): the getter resolves the LIVE handle per call, so a
// workspace lock mid-download (which closes the DB) degrades the cache instead of
// failing the finished job; no unlock guard needed — the store itself is lock-aware.
hashStore: createSettingsHashStore(() => ctx.db, ctx.paths.rootPath)
})
}
)
ipcHandle(IPC.getDownloadJob, (_e, jobId: string): DownloadJob => downloads.get(jobId))
ipcHandle(IPC.cancelDownload, (_e, jobId: string): DownloadJob => downloads.cancel(jobId))
// #314: reload recovery. Both are ungated on purpose — like `downloads:get`/`downloads:cancel`
// they only read or bookkeep this service's own in-memory job state (no network, no DB, no
// workspace artifact), so no policy/setting gate and no unlock check applies.
ipcHandle(IPC.listDownloadJobs, (): DownloadJob[] => downloads.list())
ipcHandle(IPC.dismissDownloadJob, (_e, jobId: string): void => downloads.dismiss(jobId))
}