Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: video input support for llamacpp (router mode)

Akarshan Biswasa555a3f186d8
diff --git a/core/src/types/message/messageEntity.ts b/core/src/types/message/messageEntity.ts
index c90481525..2d6267b84 100644
--- a/core/src/types/message/messageEntity.ts
+++ b/core/src/types/message/messageEntity.ts
@@ -141,6 +141,7 @@ export enum ContentType {
Reasoning = 'reasoning',
Image = 'image_url',
InputAudio = 'input_audio',
+ InputVideo = 'input_video',
ToolCall = 'tool_call',
}
@@ -171,6 +172,17 @@ export type InputAudioContentValue = {
format: 'wav' | 'mp3'
}
+/**
+ * The `InputVideoContentValue` type carries base64-encoded video for OAI-compatible
+ * `input_video` content parts (llama.cpp mtmd with a vision encoder + ffmpeg).
+ * The wire shape sent to llama-server is `{ data }`; `format` (the source MIME,
+ * e.g. `video/mp4`) is retained only to reconstruct the data URL for UI re-render.
+ */
+export type InputVideoContentValue = {
+ data: string
+ format?: string
+}
+
/**
* The `ThreadContent` type defines the shape of a message's content object
* @data_transfer_object
@@ -183,6 +195,8 @@ export type ThreadContent = {
image_url?: ImageContentValue
// For input_audio content
input_audio?: InputAudioContentValue
+ // For input_video content
+ input_video?: InputVideoContentValue
// For tool call content
tool_call_id?: string
tool_name?: string
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index af72e31bd..27f6cac1c 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -732,7 +732,14 @@ export default class llamacpp_extension extends AIEngine {
* the post-fit value — what `fit_ctx` settled on — so it's the right
* denominator for the token-usage popup.
*/
- async getModelProps(modelId: string): Promise<ModelProps | undefined> {
+ async getModelProps(
+ modelId: string
+ ): Promise<
+ | (ModelProps & {
+ modalities?: { vision: boolean; video: boolean; audio: boolean }
+ })
+ | undefined
+ > {
const router = await this.getRouterInfo()
if (!router || !modelId) return undefined
// Router runs with models_autoload=true, so `/props?model=X` against an
@@ -754,15 +761,20 @@ export default class llamacpp_extension extends AIEngine {
total_slots?: number
model_alias?: string
is_sleeping?: boolean
+ modalities?: { vision?: boolean; video?: boolean; audio?: boolean }
}
const n = json?.default_generation_settings?.n_ctx
if (typeof n !== 'number' || n <= 0) return undefined
+ const m = json.modalities
return {
nCtx: n,
totalSlots:
typeof json.total_slots === 'number' ? json.total_slots : undefined,
modelAlias: json.model_alias,
isSleeping: !!json.is_sleeping,
+ modalities: m
+ ? { vision: !!m.vision, video: !!m.video, audio: !!m.audio }
+ : undefined,
}
} catch {
return undefined
@@ -1939,6 +1951,10 @@ export default class llamacpp_extension extends AIEngine {
)
if (caps.vision) capabilities.push('vision')
if (caps.audio) capabilities.push('audio')
+ // 'video' is intentionally NOT derived from the mmproj here — video
+ // support also depends on the backend being built with MTMD_VIDEO,
+ // which the GGUF can't reveal. It's reconciled from /props after the
+ // model loads (see useReconcileVideoCapability).
}
const mp = modelConfig.model_path ?? ''
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 6c9593cfa..2596c846d 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -20,6 +20,7 @@ import { ArrowRight, PlusIcon } from 'lucide-react'
import {
IconPhoto,
IconMusic,
+ IconVideo,
IconBrain,
IconTool,
IconCodeCircle2,
@@ -38,6 +39,7 @@ import { BotIcon } from 'lucide-react'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { useGeneralSetting } from '@/hooks/useGeneralSetting'
import { useModelProvider } from '@/hooks/useModelProvider'
+import { useReconcileVideoCapability } from '@/hooks/useReconcileVideoCapability'
import { useAppState } from '@/hooks/useAppState'
import { MovingBorder } from './MovingBorder'
@@ -80,6 +82,7 @@ import {
createImageAttachment,
createDocumentAttachment,
createAudioAttachment,
+ createVideoAttachment,
} from '@/types/attachment'
import JanBrowserExtensionDialog from '@/containers/dialogs/JanBrowserExtensionDialog'
import { useJanBrowserExtension } from '@/hooks/useJanBrowserExtension'
@@ -99,6 +102,23 @@ type ChatInputProps = {
chatStatus?: ChatStatus
}
+// Video containers llama-server can decode via ffmpeg/ffprobe into frames.
+const VIDEO_EXTS = ['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']
+const videoMimeForExt = (ext: string | undefined): string => {
+ switch (ext) {
+ case 'mov':
+ return 'video/quicktime'
+ case 'webm':
+ return 'video/webm'
+ case 'mkv':
+ return 'video/x-matroska'
+ case 'avi':
+ return 'video/x-msvideo'
+ default:
+ return 'video/mp4'
+ }
+}
+
const ChatInput = memo(function ChatInput({
className,
initialMessage,
@@ -180,6 +200,9 @@ const ChatInput = memo(function ChatInput({
const activeModels = useAppState(useShallow((state) => state.activeModels))
// Check if selected model is currently loaded/active
const isModelActive = selectedModel?.id ? activeModels.includes(selectedModel.id) : false
+
+ // Reconcile video capability from /props once the model is loaded.
+ useReconcileVideoCapability(selectedModel?.id, selectedProvider, isModelActive)
const [selectedAssistantId, setSelectedAssistantId] = useState<
string | undefined
>(loading ? undefined : currentAssistant?.id || '')
@@ -242,7 +265,9 @@ const ChatInput = memo(function ChatInput({
)
const ingestingAny = attachments.some((a) => a.processing)
const hasSendableMedia = attachments.some(
- (a) => (a.type === 'image' || a.type === 'audio') && !!a.dataUrl
+ (a) =>
+ (a.type === 'image' || a.type === 'audio' || a.type === 'video') &&
+ !!a.dataUrl
)
const [, setFileIngestProgress] = useState<{
@@ -348,37 +373,32 @@ const ChatInput = memo(function ChatInput({
mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
url: att.dataUrl!,
}))
- const files = [...imageFiles, ...audioFiles]
+ const videoFiles = attachments
+ .filter((att) => att.type === 'video' && att.dataUrl)
+ .map((att) => ({
+ type: 'file',
+ mediaType: att.mimeType ?? 'video/mp4',
+ url: att.dataUrl!,
+ }))
+ const files = [...imageFiles, ...audioFiles, ...videoFiles]
onSubmit(prompt, files.length > 0 ? files : undefined)
setPrompt('')
clearAttachmentsForThread(attachmentsKey)
} else {
- // No onSubmit provided - create a new thread and navigate to it
- // Store the initial message in sessionStorage for the thread page to read
+ // No onSubmit provided - create a new thread and navigate to it.
+ // Media attachments (image/audio/video) are NOT serialized into
+ // sessionStorage — their base64 data URLs blow past the ~5MB quota
+ // (esp. video). They live in the in-memory attachments store and are
+ // transferred to the new thread's key on the detail page (see the
+ // transferAttachments effect); processAndSendMessage reads them there.
const isTemporaryChat = window.location.search.includes(
`${TEMPORARY_CHAT_QUERY_ID}=true`
)
- const imageFiles = attachments
- .filter((att) => att.type === 'image' && att.dataUrl)
- .map((att) => ({
- type: 'file',
- mediaType: att.mimeType ?? 'image/jpeg',
- url: att.dataUrl!,
- }))
- const audioFiles = attachments
- .filter((att) => att.type === 'audio' && att.dataUrl)
- .map((att) => ({
- type: 'file',
- mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
- url: att.dataUrl!,
- }))
- const files = [...imageFiles, ...audioFiles]
-
const messagePayload = {
text: prompt,
- files: files.length > 0 ? files : [],
+ files: [] as Array<{ type: string; mediaType: string; url: string }>,
}
if (isTemporaryChat) {
@@ -545,6 +565,8 @@ const ChatInput = memo(function ChatInput({
const fileInputRef = useRef<HTMLInputElement>(null)
const audioInputRef = useRef<HTMLInputElement>(null)
const audioSupported = !!selectedModel?.capabilities?.includes('audio')
+ const videoInputRef = useRef<HTMLInputElement>(null)
+ const videoSupported = !!selectedModel?.capabilities?.includes('video')
const processNewDocumentAttachments = useCallback(
async (docs: Attachment[]) => {
@@ -1270,6 +1292,139 @@ const ChatInput = memo(function ChatInput({
}
}, [serviceHub, processAudioFiles])
+ const processVideoFiles = useCallback(
+ async (files: File[]) => {
+ const maxBytes = 100 * 1024 * 1024
+ const oversized: string[] = []
+ const invalid: string[] = []
+ const prepared: Attachment[] = []
+
+ for (const file of Array.from(files)) {
+ const ext = file.name.toLowerCase().split('.').pop()
+ const isVideo =
+ file.type.startsWith('video/') || VIDEO_EXTS.includes(ext ?? '')
+ if (!isVideo) {
+ invalid.push(file.name)
+ continue
+ }
+ if (file.size > maxBytes) {
+ oversized.push(file.name)
+ continue
+ }
+ const mimeType = file.type.startsWith('video/')
+ ? file.type
+ : videoMimeForExt(ext)
+ const dataUrl: string = await new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => {
+ const r = reader.result
+ if (typeof r === 'string') resolve(r)
+ else reject(new Error('read failed'))
+ }
+ reader.onerror = () => reject(reader.error ?? new Error('read failed'))
+ reader.readAsDataURL(file)
+ })
+ const base64 = dataUrl.split(',')[1] ?? ''
+ prepared.push(
+ createVideoAttachment({
+ name: file.name,
+ base64,
+ dataUrl,
+ mimeType,
+ size: file.size,
+ })
+ )
+ }
+
+ const current = useChatAttachments.getState().getAttachments(attachmentsKey)
+ const existingNames = new Set(
+ current.filter((a) => a.type === 'video').map((a) => a.name)
+ )
+ const duplicates: string[] = []
+ const newOnes: Attachment[] = []
+ for (const att of prepared) {
+ if (existingNames.has(att.name)) {
+ duplicates.push(att.name)
+ continue
+ }
+ newOnes.push(att)
+ }
+
+ if (newOnes.length > 0) {
+ setAttachmentsForThread(attachmentsKey, (prev) => [...prev, ...newOnes])
+ }
+
+ if (duplicates.length > 0) {
+ toast.warning('Some video files already attached', {
+ description: `${duplicates.join(', ')} ${duplicates.length === 1 ? 'is' : 'are'} already in the list`,
+ })
+ }
+ const errors: string[] = []
+ if (oversized.length > 0) {
+ errors.push(
+ `Video file${oversized.length > 1 ? 's' : ''} too large (max 100MB): ${oversized.join(', ')}`
+ )
+ }
+ if (invalid.length > 0) {
+ errors.push(
+ `Invalid video type${invalid.length > 1 ? 's' : ''}: ${invalid.join(', ')}`
+ )
+ }
+ if (errors.length > 0) {
+ setMessage(errors.join(' | '))
+ if (videoInputRef.current) videoInputRef.current.value = ''
+ }
+ },
+ [attachmentsKey, setAttachmentsForThread]
+ )
+
+ const handleVideoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = e.target.files
+ if (files && files.length > 0) {
+ void processVideoFiles(Array.from(files))
+ if (videoInputRef.current) videoInputRef.current.value = ''
+ }
+ if (textareaRef.current) textareaRef.current.focus()
+ }
+
+ const openVideoPicker = useCallback(async () => {
+ if (isPlatformTauri()) {
+ try {
+ const selected = await serviceHub.dialog().open({
+ multiple: true,
+ filters: [{ name: 'Video', extensions: VIDEO_EXTS }],
+ })
+ if (selected) {
+ const paths = Array.isArray(selected) ? selected : [selected]
+ const files: File[] = []
+ for (const path of paths) {
+ try {
+ const { convertFileSrc } = await import('@tauri-apps/api/core')
+ const fileUrl = convertFileSrc(path)
+ const response = await fetch(fileUrl)
+ if (!response.ok) throw new Error(response.statusText)
+ const blob = await response.blob()
+ const fileName = path.split(/[\\/]/).filter(Boolean).pop() || 'video'
+ const ext = fileName.toLowerCase().split('.').pop()
+ files.push(new File([blob], fileName, { type: videoMimeForExt(ext) }))
+ } catch (error) {
+ console.error('Failed to read video file:', error)
+ toast.error('Failed to read video file', {
+ description: error instanceof Error ? error.message : String(error),
+ })
+ }
+ }
+ if (files.length > 0) await processVideoFiles(files)
+ }
+ } catch (error) {
+ console.error('Failed to open video dialog:', error)
+ }
+ if (textareaRef.current) textareaRef.current.focus()
+ } else {
+ videoInputRef.current?.click()
+ }
+ }, [serviceHub, processVideoFiles])
+
// Open the image picker dialog (extracted for reuse)
const openImagePicker = useCallback(async () => {
if (isPlatformTauri()) {
@@ -1339,7 +1494,7 @@ const ChatInput = memo(function ChatInput({
}
}, [serviceHub, processImageFiles])
- const dropAcceptsAnything = hasMmproj || audioSupported
+ const dropAcceptsAnything = hasMmproj || audioSupported || videoSupported
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
@@ -1394,8 +1549,16 @@ const ChatInput = memo(function ChatInput({
)
}
+ const isVideoFile = (f: File) => {
+ const ext = f.name.toLowerCase().split('.').pop()
+ return f.type.startsWith('video/') || VIDEO_EXTS.includes(ext ?? '')
+ }
+
const audioOnes = audioSupported ? dropped.filter(isAudioFile) : []
- const otherOnes = dropped.filter((f) => !audioOnes.includes(f))
+ const videoOnes = videoSupported ? dropped.filter(isVideoFile) : []
+ const otherOnes = dropped.filter(
+ (f) => !audioOnes.includes(f) && !videoOnes.includes(f)
+ )
if (otherOnes.length > 0 && hasMmproj) {
const dt = new DataTransfer()
@@ -1408,6 +1571,9 @@ const ChatInput = memo(function ChatInput({
if (audioOnes.length > 0) {
void processAudioFiles(audioOnes)
}
+ if (videoOnes.length > 0) {
+ void processVideoFiles(videoOnes)
+ }
}
const handlePaste = async (e: React.ClipboardEvent) => {
@@ -1579,6 +1745,7 @@ const ChatInput = memo(function ChatInput({
.map(({ att, idx }) => {
const isImage = att.type === 'image'
const isAudio = att.type === 'audio'
+ const isVideo = att.type === 'video'
const ext = att.fileType || att.mimeType?.split('/')[1]
const durLabel =
isAudio && typeof att.durationSec === 'number'
@@ -1614,6 +1781,10 @@ const ChatInput = memo(function ChatInput({
</span>
)}
</div>
+ ) : isVideo ? (
+ <div className="flex flex-col items-center justify-center text-muted-foreground">
+ <IconVideo size={20} />
+ </div>
) : (
<div className="flex flex-col items-center justify-center text-muted-foreground">
<IconPaperclip size={18} />
@@ -1807,6 +1978,20 @@ const ChatInput = memo(function ChatInput({
/>
</DropdownMenuItem>
)}
+ {videoSupported && (
+ <DropdownMenuItem onClick={() => void openVideoPicker()}>
+ <IconVideo size={18} className="text-muted-foreground" />
+ <span>Add Video</span>
+ <input
+ type="file"
+ ref={videoInputRef}
+ className="hidden"
+ multiple
+ accept="video/mp4,video/quicktime,video/webm,video/x-matroska,video/x-msvideo,.mp4,.mov,.webm,.mkv,.avi,.m4v"
+ onChange={handleVideoFileChange}
+ />
+ </DropdownMenuItem>
+ )}
{/* RAG document attachments - desktop-only via dialog; shown when feature enabled */}
<DropdownMenuItem
onClick={handleAttachDocsIngest}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 0971121ab..29dd3361f 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -308,6 +308,7 @@ export const MessageItem = memo(
const isImage = part.mediaType?.startsWith('image/')
const isAudio =
part.mediaType === 'audio/wav' || part.mediaType === 'audio/mpeg'
+ const isVideo = part.mediaType?.startsWith('video/')
if (isAudio && part.url) {
const justify =
@@ -326,6 +327,23 @@ export const MessageItem = memo(
)
}
+ if (isVideo && part.url) {
+ const justify =
+ message.role === 'user' ? 'justify-end' : 'justify-start'
+ return (
+ <div
+ key={`${message.id}-${partIndex}`}
+ className={`flex ${justify} w-full my-2`}
+ >
+ <video
+ controls
+ src={part.url}
+ className="max-w-[80%] max-h-80 rounded-md border"
+ />
+ </div>
+ )
+ }
+
if (message.role === 'user' && isImage && part.url) {
return (
<div
diff --git a/web-app/src/containers/dialogs/EditModel.tsx b/web-app/src/containers/dialogs/EditModel.tsx
index 642631ffb..2b8c46ced 100644
--- a/web-app/src/containers/dialogs/EditModel.tsx
+++ b/web-app/src/containers/dialogs/EditModel.tsx
@@ -18,6 +18,7 @@ import {
IconAlertTriangle,
IconLoader2,
IconHeadphones,
+ IconVideo,
} from '@tabler/icons-react'
import { useState, useEffect } from 'react'
import { useTranslation } from '@/i18n/react-i18next-compat'
@@ -47,6 +48,7 @@ export const DialogEditModel = ({
vision: false,
tools: false,
audio: false,
+ video: false,
})
// Initialize with the provided model ID or the first model if available
@@ -70,6 +72,7 @@ export const DialogEditModel = ({
vision: capabilitiesList.includes('vision'),
tools: capabilitiesList.includes('tools'),
audio: capabilitiesList.includes('audio'),
+ video: capabilitiesList.includes('video'),
})
// Initialize capabilities and display name from selected model
@@ -288,6 +291,23 @@ export const DialogEditModel = ({
disabled={isLoading}
/>
</div>
+
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-2">
+ <IconVideo className="size-4 text-muted-foreground" />
+ <span className="text-sm">
+ {t('providers:editModel.video')}
+ </span>
+ </div>
+ <Switch
+ id="video-capability"
+ checked={capabilities.video}
+ onCheckedChange={(checked) =>
+ handleCapabilityChange('video', checked)
+ }
+ disabled={isLoading}
+ />
+ </div>
</div>
</div>
diff --git a/web-app/src/hooks/useReconcileVideoCapability.ts b/web-app/src/hooks/useReconcileVideoCapability.ts
new file mode 100644
index 000000000..fe9dc1ec5
--- /dev/null
+++ b/web-app/src/hooks/useReconcileVideoCapability.ts
@@ -0,0 +1,86 @@
+import { useEffect } from 'react'
+import { ExtensionManager } from '@/lib/extension'
+import { useModelProvider } from './useModelProvider'
+
+// `/props.modalities.video` is the only authoritative signal for video input:
+// it reflects both the model's vision encoder AND whether the backend binary
+// was built with MTMD_VIDEO — something the GGUF can't reveal. We can only read
+// it once the model is loaded into the router, so video capability is
+// reconciled here (post-load) rather than derived offline at list time.
+
+type ModalitiesProps = {
+ modalities?: { vision: boolean; video: boolean; audio: boolean }
+}
+
+type LlamacppLike = {
+ getModelProps?: (modelId: string) => Promise<ModalitiesProps | undefined>
+}
+
+const getLlamacppExtension = (): LlamacppLike | undefined => {
+ const mgr = ExtensionManager.getInstance()
+ const candidates = [
+ mgr.getByName('@janhq/llamacpp-extension'),
+ mgr.getByName('llamacpp-extension'),
+ ]
+ for (const c of candidates) {
+ if (c && typeof (c as LlamacppLike).getModelProps === 'function')
+ return c as LlamacppLike
+ }
+ return undefined
+}
+
+/**
+ * Reconcile the selected llamacpp model's `video` capability against the
+ * router's `/props`. Runs whenever the model or `trigger` (e.g. chat status)
+ * changes; no-ops until the model is loaded (getModelProps returns undefined).
+ * Self-healing: persists the correction to the provider store.
+ */
+export function useReconcileVideoCapability(
+ modelId: string | undefined,
+ selectedProvider: string,
+ trigger?: unknown
+) {
+ useEffect(() => {
+ if (selectedProvider !== 'llamacpp' || !modelId) return
+ const ext = getLlamacppExtension()
+ if (!ext?.getModelProps) return
+
+ let cancelled = false
+ ext
+ .getModelProps(modelId)
+ .then((props) => {
+ if (cancelled || !props?.modalities) return
+ const supportsVideo = props.modalities.video
+
+ const store = useModelProvider.getState()
+ const provider = store.getProviderByName('llamacpp')
+ const model = provider?.models.find((m) => m.id === modelId)
+ if (!provider || !model) return
+
+ const caps = model.capabilities ?? []
+ const hasVideo = caps.includes('video')
+ if (hasVideo === supportsVideo) return // already correct
+
+ const nextCaps = supportsVideo
+ ? [...caps, 'video']
+ : caps.filter((c) => c !== 'video')
+
+ store.updateProvider('llamacpp', {
+ ...provider,
+ models: provider.models.map((m) =>
+ m.id === modelId
+ ? {
+ ...m,
+ capabilities: nextCaps.length > 0 ? nextCaps : undefined,
+ }
+ : m
+ ),
+ })
+ })
+ .catch(() => {})
+
+ return () => {
+ cancelled = true
+ }
+ }, [modelId, selectedProvider, trigger])
+}
diff --git a/web-app/src/lib/__tests__/video-sentinel.test.ts b/web-app/src/lib/__tests__/video-sentinel.test.ts
new file mode 100644
index 000000000..21cf4b7b2
--- /dev/null
+++ b/web-app/src/lib/__tests__/video-sentinel.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect } from 'vitest'
+import {
+ encodeVideoSentinel,
+ hasVideoSentinel,
+ splitVideoSentinels,
+ parseVideoDataUrl,
+} from '../video-sentinel'
+import { encodeAudioSentinel } from '../audio-sentinel'
+import {
+ decodeVideoSentinelsInBody,
+ decodeAudioSentinelsInBody,
+} from '../model-factory'
+
+describe('video-sentinel', () => {
+ it('round-trips a single sentinel back to an input_video part', () => {
+ const encoded = encodeVideoSentinel('QUFB')
+ expect(hasVideoSentinel(encoded)).toBe(true)
+ expect(splitVideoSentinels(encoded)).toEqual([
+ { type: 'input_video', input_video: { data: 'QUFB' } },
+ ])
+ })
+
+ it('preserves surrounding text and ordering', () => {
+ const encoded = `hello${encodeVideoSentinel('WlpaWg==')}world`
+ expect(splitVideoSentinels(encoded)).toEqual([
+ { type: 'text', text: 'hello' },
+ { type: 'input_video', input_video: { data: 'WlpaWg==' } },
+ { type: 'text', text: 'world' },
+ ])
+ })
+
+ it('returns null for plain text', () => {
+ expect(splitVideoSentinels('just a message')).toBeNull()
+ })
+
+ it('parses video data URLs across container MIME types', () => {
+ expect(parseVideoDataUrl('data:video/mp4;base64,QUFB')).toEqual({ data: 'QUFB' })
+ expect(parseVideoDataUrl('data:video/quicktime;base64,WlpaWg==')).toEqual({
+ data: 'WlpaWg==',
+ })
+ expect(parseVideoDataUrl('data:image/png;base64,XXXX')).toBeNull()
+ })
+
+ describe('decodeVideoSentinelsInBody', () => {
+ it('rewrites a bare-string user content to input_video + text parts', () => {
+ const body = {
+ messages: [
+ {
+ role: 'user',
+ content: `describe: ${encodeVideoSentinel('QUFB')}`,
+ },
+ ],
+ }
+ decodeVideoSentinelsInBody(body)
+ expect(body.messages[0].content).toEqual([
+ { type: 'text', text: 'describe: ' },
+ { type: 'input_video', input_video: { data: 'QUFB' } },
+ ])
+ })
+
+ it('ignores assistant messages even if they accidentally match', () => {
+ const body = {
+ messages: [
+ { role: 'assistant', content: encodeVideoSentinel('QUFB') },
+ ],
+ }
+ decodeVideoSentinelsInBody(body)
+ expect(body.messages[0].content).toBe(encodeVideoSentinel('QUFB'))
+ })
+
+ it('co-exists with audio decode in the same body (disjoint markers)', () => {
+ const body = {
+ messages: [
+ {
+ role: 'user',
+ content: `q ${encodeAudioSentinel('mp3', 'QUFB')}${encodeVideoSentinel('WlpaWg==')}`,
+ },
+ ],
+ }
+ decodeAudioSentinelsInBody(body)
+ decodeVideoSentinelsInBody(body)
+ expect(body.messages[0].content).toEqual([
+ { type: 'text', text: 'q ' },
+ { type: 'input_audio', input_audio: { data: 'QUFB', format: 'mp3' } },
+ { type: 'input_video', input_video: { data: 'WlpaWg==' } },
+ ])
+ })
+ })
+})
diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.ts
index 52f57957c..026f8e873 100644
--- a/web-app/src/lib/attachmentProcessing.ts
+++ b/web-app/src/lib/attachmentProcessing.ts
@@ -172,6 +172,15 @@ export const processAttachmentsForSend = async (
})
}
+ const videos = attachments.filter((a) => a.type === 'video')
+ for (const vid of videos) {
+ processedAttachments.push({
+ ...vid,
+ processed: true,
+ processing: false,
+ })
+ }
+
const documents = attachments.filter((a) => a.type === 'document')
for (const doc of documents) {
try {
diff --git a/web-app/src/lib/completion.ts b/web-app/src/lib/completion.ts
index ec4640728..75db7eaf5 100644
--- a/web-app/src/lib/completion.ts
+++ b/web-app/src/lib/completion.ts
@@ -23,9 +23,10 @@ export const newUserThreadContent = (
attachments?: Attachment[],
id?: string
): ThreadMessage => {
- // Separate images, audio, and documents
+ // Separate images, audio, video, and documents
const images = attachments?.filter((a) => a.type === 'image') || []
const audios = attachments?.filter((a) => a.type === 'audio') || []
+ const videos = attachments?.filter((a) => a.type === 'video') || []
const documents = attachments?.filter((a) => a.type === 'document') || []
const inlineDocuments = documents.filter(
@@ -81,6 +82,18 @@ export const newUserThreadContent = (
}
})
+ videos.forEach((vid) => {
+ if (vid.base64 && vid.mimeType) {
+ contentParts.push({
+ type: ContentType.InputVideo,
+ input_video: {
+ data: vid.base64,
+ format: vid.mimeType,
+ },
+ } as any)
+ }
+ })
+
return {
type: 'text',
role: ChatCompletionRole.User,
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 730f072a4..0d88506eb 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -35,6 +35,7 @@ import {
import { mcpOrchestrator } from '@/lib/mcp-orchestrator'
import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'
import { encodeAudioSentinel, parseAudioDataUrl } from '@/lib/audio-sentinel'
+import { encodeVideoSentinel, parseVideoDataUrl } from '@/lib/video-sentinel'
import { extractFilesFromPrompt, type FileMetadata } from '@/lib/fileMetadata'
import { isPredefinedRemoteProvider, getProviderApiType } from '@/lib/providerCaps'
import { paramsSettings } from '@/lib/predefinedParams'
@@ -1041,10 +1042,12 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const baseMessages = await convertToModelMessages(
coalesceMessagesForAlternation(
resolveOrphanToolCalls(
- this.encodeAudioAttachments(
- stripUnsupportedImageParts(
- this.mapUserInlineAttachments(effectiveMessages),
- modelSupportsVision
+ this.encodeVideoAttachments(
+ this.encodeAudioAttachments(
+ stripUnsupportedImageParts(
+ this.mapUserInlineAttachments(effectiveMessages),
+ modelSupportsVision
+ )
)
)
)
@@ -1237,6 +1240,33 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
})
}
+ // Replace video `file` parts on user messages with sentinel-bearing `text`
+ // parts, same mechanism as encodeAudioAttachments. The fetch wrapper in
+ // model-factory.ts decodes these into llama-server `input_video` content
+ // parts (frames decoded via the vision encoder + ffmpeg on the server).
+ encodeVideoAttachments(messages: UIMessage[]): UIMessage[] {
+ return messages.map((message) => {
+ if (message.role !== 'user' || !Array.isArray(message.parts)) return message
+ let touched = false
+ const nextParts = message.parts.map((part) => {
+ if (
+ part?.type === 'file' &&
+ typeof (part as { mediaType?: string }).mediaType === 'string' &&
+ (part as { mediaType: string }).mediaType.startsWith('video/') &&
+ typeof (part as { url?: string }).url === 'string'
+ ) {
+ const parsed = parseVideoDataUrl((part as { url: string }).url)
+ if (!parsed) return part
+ touched = true
+ return { type: 'text' as const, text: encodeVideoSentinel(parsed.data) }
+ }
+ return part
+ })
+ if (!touched) return message
+ return { ...message, parts: nextParts } as UIMessage
+ })
+ }
+
/**
* Map user messages to include inline attachments in the message parts
* @param messages
diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.ts
index fd99ff80d..74f518ebe 100644
--- a/web-app/src/lib/messages.ts
+++ b/web-app/src/lib/messages.ts
@@ -68,6 +68,16 @@ export function convertUIMessageToThreadMessage(
type: ContentType.InputAudio,
input_audio: { data, format },
})
+ } else if (mediaType?.startsWith('video/')) {
+ const url = part.url as string | undefined
+ const data =
+ typeof url === 'string' && url.startsWith('data:')
+ ? url.slice(url.indexOf(',') + 1)
+ : (url ?? '')
+ content.push({
+ type: ContentType.InputVideo,
+ input_video: { data, format: mediaType },
+ })
}
}
}
@@ -262,6 +272,13 @@ export function convertThreadMessageToUIMessage(
mediaType,
url: `data:${mediaType};base64,${content.input_audio.data}`,
})
+ } else if (content.type === 'input_video' && content.input_video?.data) {
+ const mediaType = content.input_video.format || 'video/mp4'
+ parts.push({
+ type: 'file',
+ mediaType,
+ url: `data:${mediaType};base64,${content.input_video.data}`,
+ })
} else if (content.type === 'tool_call') {
// Handle tool call content items - direct conversion from flat structure
// Use AI SDK v5 UIToolInvocation format: toolCallId, state: 'output-available'/'input-available'
@@ -392,6 +409,8 @@ export function threadMessageIsEmpty(message: ThreadMessage): boolean {
return false
} else if (c.type === ContentType.InputAudio && c.input_audio?.data) {
return false
+ } else if (c.type === ContentType.InputVideo && c.input_video?.data) {
+ return false
} else if (c.type === ContentType.ToolCall) {
return false
}
@@ -469,6 +488,16 @@ export function extractContentPartsFromUIMessage(message: UIMessage): ThreadCont
type: 'input_audio' as ContentType.InputAudio,
input_audio: { data, format },
})
+ } else if (mediaType?.startsWith('video/')) {
+ const url = part.url as string | undefined
+ const data =
+ typeof url === 'string' && url.startsWith('data:')
+ ? url.slice(url.indexOf(',') + 1)
+ : (url ?? '')
+ content.push({
+ type: 'input_video' as ContentType.InputVideo,
+ input_video: { data, format: mediaType },
+ })
}
} else if (part.type.startsWith('tool-')) {
// Handle tool call parts - flatten structure to match parts format
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index 22081ad5b..f4709e654 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -60,6 +60,7 @@ import { invoke } from '@tauri-apps/api/core'
import { SessionInfo } from '@janhq/core'
import { fetch as httpFetch } from '@tauri-apps/plugin-http'
import { hasAudioSentinel, splitAudioSentinels } from './audio-sentinel'
+import { hasVideoSentinel, splitVideoSentinels } from './video-sentinel'
import { isPlatformTauri } from '@/lib/platform/utils'
import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'
import {
@@ -352,6 +353,7 @@ export function createCustomFetch(
): Record<string, unknown> => {
if (!includeOurParams) {
decodeAudioSentinelsInBody(rawBody)
+ decodeVideoSentinelsInBody(rawBody)
return rawBody
}
const normalised: Record<string, unknown> = {}
@@ -373,6 +375,7 @@ export function createCustomFetch(
merged.max_tokens = -1
}
decodeAudioSentinelsInBody(merged)
+ decodeVideoSentinelsInBody(merged)
return merged
}
@@ -572,6 +575,48 @@ export function decodeAudioSentinelsInBody(body: Record<string, unknown>): void
}
}
+// Rewrites any sentinel-bearing text content (planted by
+// CustomChatTransport.encodeVideoAttachments) back into llama-server
+// `input_video` content parts. Mutates `body.messages` in place. Runs after
+// decodeAudioSentinelsInBody, so it also handles content already promoted to
+// an array by the audio pass; the two sentinel markers are disjoint.
+export function decodeVideoSentinelsInBody(body: Record<string, unknown>): void {
+ const messages = body.messages
+ if (!Array.isArray(messages)) return
+ for (const msg of messages) {
+ if (!msg || typeof msg !== 'object') continue
+ const m = msg as { role?: string; content?: unknown }
+ if (m.role !== 'user') continue
+ if (typeof m.content === 'string') {
+ if (!hasVideoSentinel(m.content)) continue
+ const split = splitVideoSentinels(m.content)
+ if (split) m.content = split
+ continue
+ }
+ if (!Array.isArray(m.content)) continue
+ const next: unknown[] = []
+ let touched = false
+ for (const part of m.content) {
+ if (
+ part &&
+ typeof part === 'object' &&
+ (part as { type?: string }).type === 'text' &&
+ typeof (part as { text?: string }).text === 'string' &&
+ hasVideoSentinel((part as { text: string }).text)
+ ) {
+ const split = splitVideoSentinels((part as { text: string }).text)
+ if (split) {
+ next.push(...split)
+ touched = true
+ continue
+ }
+ }
+ next.push(part)
+ }
+ if (touched) m.content = next
+ }
+}
+
type ApiKeyHeaderMode = 'authorization-bearer' | 'x-api-key'
/** Retries with the next key when the upstream returns 401, 403, or 429. */
diff --git a/web-app/src/lib/video-sentinel.ts b/web-app/src/lib/video-sentinel.ts
new file mode 100644
index 000000000..7a03f7be9
--- /dev/null
+++ b/web-app/src/lib/video-sentinel.ts
@@ -0,0 +1,55 @@
+// Video attachments enter the AI SDK as `file` parts with video mediaType,
+// but `@ai-sdk/openai-compatible` rejects any non-image file part. To bypass
+// that converter without forking the provider, we encode each video part as a
+// text sentinel before `streamText` and decode it back into an llama-server
+// `input_video` content part inside the request fetch. Mirrors audio-sentinel,
+// but llama-server's `input_video` wire shape is `{ data }` with no format.
+
+const PREFIX = ' __JAN_VIDEO__'
+const SUFFIX = ' '
+
+const SENTINEL_REGEX = / __JAN_VIDEO__([A-Za-z0-9+/=]+) /g
+
+export function encodeVideoSentinel(base64: string): string {
+ return `${PREFIX}${base64}${SUFFIX}`
+}
+
+export function hasVideoSentinel(text: string): boolean {
+ return text.includes(PREFIX)
+}
+
+export type VideoPart = { type: 'input_video'; input_video: { data: string } }
+
+// Splits a sentinel-bearing string into an ordered array of content parts.
+// Returns null when no sentinel is present so callers can keep the original
+// string form.
+export function splitVideoSentinels(
+ text: string
+): Array<{ type: 'text'; text: string } | VideoPart> | null {
+ if (!hasVideoSentinel(text)) return null
+ const parts: Array<{ type: 'text'; text: string } | VideoPart> = []
+ let lastIndex = 0
+ SENTINEL_REGEX.lastIndex = 0
+ for (let m = SENTINEL_REGEX.exec(text); m !== null; m = SENTINEL_REGEX.exec(text)) {
+ const [match, data] = m
+ if (m.index > lastIndex) {
+ const chunk = text.slice(lastIndex, m.index)
+ if (chunk.length > 0) parts.push({ type: 'text', text: chunk })
+ }
+ parts.push({ type: 'input_video', input_video: { data } })
+ lastIndex = m.index + match.length
+ }
+ if (lastIndex < text.length) {
+ const tail = text.slice(lastIndex)
+ if (tail.length > 0) parts.push({ type: 'text', text: tail })
+ }
+ return parts
+}
+
+// Extracts the base64 payload from a `data:video/<x>;base64,...` URL.
+// Returns null on shapes we don't recognise.
+export function parseVideoDataUrl(url: string): { data: string } | null {
+ const match = /^data:video\/[a-z0-9.+-]+;base64,(.+)$/i.exec(url)
+ if (!match) return null
+ return { data: match[1] }
+}
diff --git a/web-app/src/locales/en/providers.json b/web-app/src/locales/en/providers.json
index 33625f3ac..53f92320a 100644
--- a/web-app/src/locales/en/providers.json
+++ b/web-app/src/locales/en/providers.json
@@ -75,6 +75,7 @@
"tools": "Tools",
"vision": "Vision",
"audio": "Audio",
+ "video": "Video",
"proactive": "Proactive (Experimental)",
"embeddings": "Embeddings",
"notAvailable": "Not available yet",
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 3717f2c90..19cea9b5a 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -39,7 +39,11 @@ import {
ChatCompletionRole,
ContentType,
} from '@janhq/core'
-import { createImageAttachment } from '@/types/attachment'
+import {
+ createImageAttachment,
+ createAudioAttachment,
+ createVideoAttachment,
+} from '@/types/attachment'
import {
useChatAttachments,
NEW_THREAD_ATTACHMENT_KEY,
@@ -671,24 +675,54 @@ function ThreadDetail() {
titleAbortRef.current?.abort()
titleAbortRef.current = null
- // Get all attachments from the store (includes both images and documents)
+ // Get all attachments from the store (media transferred from the
+ // new-thread key, plus documents).
const allAttachments = getAttachments(attachmentsKey)
- // Convert image files to attachments for persistence
- const imageAttachments = files?.map((file) => {
+ // In-thread sends pass media inline via `files`; reconstruct typed by
+ // mediaType (image/audio/video — not all images). New-thread sends pass
+ // no media in `files` (quota), so fall back to media already in the store.
+ const fileMediaAttachments = (files ?? []).map((file) => {
const base64 = file.url.split(',')[1] || ''
+ const size = Math.ceil((base64.length * 3) / 4) // Estimate from base64
+ if (file.mediaType.startsWith('audio/')) {
+ return createAudioAttachment({
+ name: `audio-${Date.now()}`,
+ mimeType: file.mediaType,
+ dataUrl: file.url,
+ base64,
+ audioFormat: file.mediaType === 'audio/mpeg' ? 'mp3' : 'wav',
+ size,
+ })
+ }
+ if (file.mediaType.startsWith('video/')) {
+ return createVideoAttachment({
+ name: `video-${Date.now()}`,
+ mimeType: file.mediaType,
+ dataUrl: file.url,
+ base64,
+ size,
+ })
+ }
return createImageAttachment({
name: `image-${Date.now()}`,
mimeType: file.mediaType,
dataUrl: file.url,
base64,
- size: Math.ceil((base64.length * 3) / 4), // Estimate size from base64
+ size,
})
})
- // Combine image attachments with document attachments from the store
+ const storeMediaAttachments = allAttachments.filter(
+ (a) => a.type === 'image' || a.type === 'audio' || a.type === 'video'
+ )
+ const mediaAttachments = fileMediaAttachments.length
+ ? fileMediaAttachments
+ : storeMediaAttachments
+
+ // Combine media attachments with document attachments from the store
const combinedAttachments = [
- ...(imageAttachments || []),
+ ...mediaAttachments,
...allAttachments.filter((a) => a.type === 'document'),
]
diff --git a/web-app/src/types/attachment.ts b/web-app/src/types/attachment.ts
index a7d02e665..90a71dfd4 100644
--- a/web-app/src/types/attachment.ts
+++ b/web-app/src/types/attachment.ts
@@ -3,11 +3,11 @@
*/
export type Attachment = {
name: string
- type: 'image' | 'document' | 'audio'
+ type: 'image' | 'document' | 'audio' | 'video'
/** For audio attachments: 'wav' or 'mp3' per llama.cpp mtmd support. */
audioFormat?: 'wav' | 'mp3'
- /** Audio duration in seconds (decoded client-side for the chip preview). */
+ /** Audio/video duration in seconds (decoded client-side for the chip preview). */
durationSec?: number
// Common fields
@@ -68,6 +68,23 @@ export function createAudioAttachment(data: {
}
}
+/**
+ * Helper to create video attachment
+ */
+export function createVideoAttachment(data: {
+ name: string
+ base64: string
+ dataUrl: string
+ mimeType: string
+ size: number
+ durationSec?: number
+}): Attachment {
+ return {
+ ...data,
+ type: 'video',
+ }
+}
+
/**
* Helper to create document attachment
*/