AI and analysis services
AI and analysis services provide local model capabilities for media understanding and editor work. They keep model access behind stable service boundaries so the application can caption media, build search indexes, verify scene changes, and generate creative audio without tying feature code to one model or worker.
Service boundaries
The analysis layer separates user-facing workflows from model-specific runtimes. Feature code uses facades and provider contracts, while registries choose the active model and workers keep heavy model work off the main thread.
| Boundary | Responsibility | Consumer-facing result |
|---|---|---|
| LLM adapter | Runs local text chat generation | Text for an editing agent or future intelligent features |
| Captioning provider | Describes video frames or images | Time-based scene captions and structured scene data |
| Text embedding provider | Maps caption context and search text to vectors | Semantic text search |
| CLIP image provider | Maps thumbnails and visual queries to a shared vector space | Visual scene search |
| Scene detection service | Finds likely cuts and can ask a local vision-language model to verify them | Scene boundaries for editing workflows |
The public API names the capability rather than the concrete runtime. This lets a feature replace a model through the provider boundary instead of changing every caller. References: src/…/media-tagger.ts• L1-26, src/…/registry.ts• L1-14, src/…/analysis-contract.ts• L1-19
Local LLM worker
The local LLM worker runs a text model on the user's device. The main-thread adapter owns the worker and presents a promise-based chat API with progress, streamed text, cancellation, and disposal.
The current registry selects the Gemma adapter by default. The adapter checks for WebGPU before loading, shares one worker and one model across the application, and reuses browser-cached model weights. The worker loads the model and tokenizer, then performs generation away from the UI thread so model work does not block editor interaction.
sequenceDiagram
participant Feature as AI feature
participant Registry as LLM registry
participant Adapter as LLM adapter
participant Worker as Local LLM worker
participant Device as Browser GPU
Feature->>Registry: Resolve adapter
Registry-->>Feature: Default local adapter
Feature->>Adapter: Check support and load
Adapter->>Worker: Load model
Worker->>Device: Run local inference setup
Device-->>Worker: Ready
Worker-->>Adapter: Progress and ready events
Feature->>Adapter: Send chat messages
Adapter->>Worker: Generate with request id
Worker-->>Adapter: Stream token deltas
Worker-->>Adapter: Complete text or error
Adapter-->>Feature: Resolve or reject generation
The worker protocol is a narrow message contract. Request IDs keep concurrent generations separate, while cancel and dispose messages let the adapter stop work and release model memory. References: src/…/types.ts• L1-58, src/…/worker-protocol.ts• L1-75, src/…/gemma-llm-adapter.ts• L27-179, src/…/gemma-llm-worker.ts• L1-170
Model registry
The model registry is the swap point for local language models. Callers resolve an adapter by its stable ID or use the default and do not import a concrete worker implementation.
An adapter must report browser support, load its model, generate text from role-based messages, and release its resources. This contract also carries generation limits, sampling controls, abort signals, and token callbacks without exposing worker details to feature code.
The same boundary idea applies to media captioning and scene verification. The captioning registry selects the default caption provider and returns a shared MediaCaption shape. The verification registry maps the supported scene-verification model IDs to providers, with Gemma as the default. References: src/…/llm-registry.ts• L1-29, src/…/types.ts• L12-57, src/…/types.ts• L1-68, src/…/registry.ts• L1-14, src/…/registry.ts• L1-19, src/…/media-tagger.ts• L1-26
Model load progress
Model load progress turns download callbacks from local model runtimes into a stable progress signal for worker clients. Each model load gets its own callback, which reports the loading-model stage from 5% through 95% and limits update frequency so the UI receives useful progress without a message for every download event.
Scene workers use this shared progress boundary before they report readiness. This keeps model download feedback consistent across verification models and lets analysis flows show the difference between loading a model and processing media. References: src/…/model-load-progress.ts• L1-26, src/…/gemma-scene-worker.ts• L43-89, src/…/lfm-scene-worker.ts• L50-93
Media analysis pipeline
Media analysis turns an image or video into searchable scene data. The shared service is used by both per-item actions and Scene Browser batch actions, so both entry points produce the same captions, thumbnails, vectors, and stored metadata.
When the service analyzes media, it follows this sequence:
- It accepts only image and video media and derives the frame sampling interval from user settings.
- It checks the content-addressed cache. Matching source bytes and sampling settings can reuse an earlier analysis.
- It sends video frames or an image to the captioning provider. Video captions are tied to sampled times.
- It extracts dominant colors from captured scene thumbnails.
- It builds text embedding input from the caption and available context such as transcript data and colors.
- It creates text vectors and image vectors when their providers are ready.
- It stores captions, thumbnails, vectors, model metadata, and source identity for later sessions.
flowchart LR
Media[Image or video] --> Cache{Compatible cached analysis?}
Cache -- Yes --> Reuse[Reuse captions and derived data]
Cache -- No --> Caption[Caption sampled frames or image]
Caption --> Thumb[Capture scene thumbnails]
Thumb --> Color[Extract color palette]
Caption --> Text[Build caption context]
Color --> Text
Text --> TextVector[Create text vectors]
Thumb --> ImageVector[Create CLIP image vectors]
TextVector --> Store[Persist analysis records]
ImageVector --> Store
Caption --> Store
Reuse --> Store
Analysis runs one media item at a time in a batch. This protects shared GPU and model resources and keeps progress and cancellation state clear. Cancellation is cooperative: the active item finishes, then remaining items are skipped. References: src/…/media-analysis-service.ts• L1-10, src/…/media-analysis-service.ts• L60-93, src/…/media-analysis-service.ts• L95-161, src/…/media-analysis-service.ts• L166-337, src/…/media-analysis-service.ts• L349-429
Captioning and scene understanding
Captioning provides the language layer for media understanding. The current provider samples a video at a configured interval or handles one image, sends captured frames to a local vision-language worker, and returns only non-empty scene descriptions.
The result is useful beyond display text. Structured scene data preserves details such as subjects, action, setting, lighting, and shot type. The saved thumbnail gives image models and people a visual anchor for each caption.
Scene detection is a related but separate analysis path. It first finds likely cuts with either sparse histogram sampling or an adaptive frame pass. For adaptive detection, the default behavior can use the default Gemma vision-language verifier, while the registry also supports the LFM verifier. If verification fails, deterministic candidates remain available instead of failing the full scene pass.
References: src/…/types.ts• L1-68 src/…/registry.ts• L1-14 src/…/lfm-captioning-provider.ts• L142-269 src/…/scene-detection.ts• L1-10 src/…/scene-detection.ts• L40-80 src/…/scene-detection.ts• L109-179 src/…/scene-detection-types.ts• L3-45 src/…/registry.ts• L1-19
Semantic search infrastructure
Semantic search compares the meaning of a query with the meaning of indexed scene context. The text provider uses a 384-dimensional sentence model. The image provider uses a 512-dimensional CLIP space shared by scene thumbnails and text queries.
The indexer first hydrates vectors already stored on disk. It then fills missing text vectors and image vectors in separate passes. Text search becomes useful before the more costly visual pass completes, and the Scene Browser can fall back to keyword ranking while a query vector is loading or unavailable.
The text used for indexing is built from the same caption, transcript, scene, and color signals during both initial analysis and later indexing. This keeps vectors comparable across the library. Model IDs and dimensions travel with stored metadata so a future model change can trigger re-indexing rather than mixing incompatible vectors.
References: src/…/types.ts• L1-31 src/…/embeddings-provider.ts• L1-161 src/…/clip-provider.ts• L1-20 src/…/clip-provider.ts• L179-227 src/…/embeddings-cache.ts• L179-337 src/…/use-semantic-index.ts• L1-145
Editor AI capabilities
The editor AI tab exposes local generation tools that turn text prompts into audio assets. Text-to-speech uses a selected local engine with voice and language controls where supported. Music generation uses a local model and a prompt with a target duration.
Generated audio stays in the panel until the user chooses an action. The user can preview it, save it to the media library, or save it and insert it on a new timeline track at the playhead position. Saved assets carry AI and engine tags so their origin remains visible to downstream media workflows.
The editing-agent chat is not currently shown in the AI tab. The LLM boundary remains available for that capability and for future intelligent editor features without changing the model integration used by the rest of the application.
References: src/…/ai-tab.tsx• L1-18 src/…/ai-panel.tsx• L221-341 src/…/ai-panel.tsx• L343-470 src/…/ai-panel.tsx• L472-546 src/…/ai-panel.tsx• L565-645
Resource lifecycle
Local model work has an explicit lifecycle because model weights can use substantial browser memory. Providers load lazily, share workers where repeated access is expected, report progress, and expose disposal so the application can release model resources when they are no longer needed.
A failed model load can be retried. An unsupported browser is reported before heavy work starts. Long-running generation and analysis paths support abort signals or cooperative cancellation, while UI flows expose progress so model download and indexing delays are visible rather than mistaken for a stalled editor. References: src/…/gemma-llm-adapter.ts• L40-114, src/…/embeddings-provider.ts• L38-94, src/…/clip-provider.ts• L36-90, src/…/use-semantic-index.ts• L68-137, src/…/media-analysis-service.ts• L398-426
Change checklist
When these files or sections are changed, remember to consider these:
- Keep provider model IDs and vector dimensions aligned with stored embedding metadata. A model or dimension change requires a re-index path.
- Keep caption generation and retroactive indexing on the same embedding-text inputs. Divergence silently changes search quality across old and new media.
- Keep worker request IDs and response types aligned on both sides of each worker boundary. A mismatch can leave a pending request unresolved.
- Keep model ID lists and provider registries aligned when adding or removing a captioning or verification model. Feature settings must resolve to a registered provider.
- Keep batch progress and cancellation counts consistent when changing media analysis stages. The UI expects a run to reach a clean terminal state.
- Keep saved generated-audio URLs alive when timeline items refer to them. Releasing a blob URL too early can break inserted audio.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Browser has no WebGPU for a WebGPU-only model | Local generation cannot start | Check provider support before load and show the capability error |
| Model worker load times out or returns an error | Captioning, indexing, or generation stops | Reject the load, clear failed readiness state where supported, and allow a later retry |
| Caption analysis cannot load the source media | The item is marked failed and no new analysis is stored | Validate the media blob or object URL before sending it to a worker |
| Text or image vector creation fails | The related semantic search mode has incomplete data | Keep captions and keyword search usable; report or skip the failed vector pass |
| Captions use a different sampling interval from cached data | Search and scene counts can reflect stale analysis | Accept cache entries only when their recorded interval matches the requested interval |
| Re-analysis races with background indexing | New and old vectors can be mixed | Exclude tagged media and re-check ownership after model loading |
| LLM generation is aborted or the adapter is disposed | Pending generation rejects instead of returning partial text | Send cancel or dispose messages and clear pending requests |
Key files
| File | Why to read it |
|---|---|
| src/…/types.ts | Stable adapter capabilities and generation options |
| src/…/llm-registry.ts | Default selection and adapter replacement boundary |
| src/…/gemma-llm-adapter.ts | Main-thread lifecycle for the current local text model |
| src/…/gemma-llm-worker.ts | Worker-side model loading and text generation flow |
| src/…/media-tagger.ts | Captioning facade used by media features |
| src/…/types.ts | Shared caption and provider data shape |
| src/…/registry.ts | Default caption provider selection |
| src/…/model-load-progress.ts | Shared model download progress behavior |
| src/…/scene-detection.ts | Candidate scene detection and optional local verification flow |
| src/…/registry.ts | Scene-verification model selection boundary |
| src/…/embeddings-provider.ts | Shared text-vector runtime and lifecycle |
| src/…/clip-provider.ts | Shared image-vector runtime and visual query support |
| src/…/media-analysis-service.ts | End-to-end media analysis and persistence flow |
| src/…/embeddings-cache.ts | Vector hydration and retroactive indexing behavior |
| src/…/use-semantic-index.ts | Scene Browser indexing lifecycle and progress |
| src/…/ai-panel.tsx | Editor-facing local audio generation and asset handoff |