From 73ce6c9df92296d4d23a215b2181daff081e6cc2 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:35:50 +0100 Subject: [PATCH 1/2] Queue clips with drawings and caption them like drawings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clips used their own video queue and worker, so they rendered on GPU1 next to drawings and VIP users had no priority for them. Clips now join the drawing queues: VIP clips go to image-vip with the VIP priority, the rest to image-regular, and the image generation workers render them in queue order through a video runner. Taskman arbitration treats VideoGen as accelerator work, so a clip and a drawing never run side by side. Scheduling uses the drawing plan: the per-user active limit counts drawings and clips together, and the drawing frequency limit, enqueue limit and queue-position notice apply to clips. The clip caption now uses the drawing caption: title, author with the VIP badge, #nsfw for adult clips and the support link, sent as HTML. A short `!видео ...` request keeps the user's words as the title, and an empty dialog caption is sent back for a retry, as for drawings. --- crates/openplotva-app/src/dialog_messages.rs | 20 +- crates/openplotva-app/src/dialog_tools.rs | 186 +++++++++++-- crates/openplotva-app/src/image_jobs.rs | 131 ++++++++- crates/openplotva-app/src/lib.rs | 76 +++--- crates/openplotva-app/src/video_jobs.rs | 264 ++++++++++--------- crates/openplotva-dialog/src/dispatch.rs | 65 ++++- crates/openplotva-dialog/src/lib.rs | 12 +- crates/openplotva-taskman/src/lib.rs | 121 +++++++-- prompts/aifarm/system.prompt | 2 +- 9 files changed, 660 insertions(+), 217 deletions(-) diff --git a/crates/openplotva-app/src/dialog_messages.rs b/crates/openplotva-app/src/dialog_messages.rs index 19e18c8..ff68d88 100644 --- a/crates/openplotva-app/src/dialog_messages.rs +++ b/crates/openplotva-app/src/dialog_messages.rs @@ -1880,7 +1880,7 @@ where "Requested tool: make_video. Prompt: {}", parsed.rest_text.trim() ), - String::new(), + parsed.rest_text.trim().to_owned(), )) } else { direct_image_shortcut( @@ -6772,9 +6772,21 @@ mod tests { ("!song", "generate_song", ""), ("/song@plotva_bot neon rain", "generate_song", ""), ("@plotva_bot песня про море", "generate_song", ""), - ("!video кот ловит снежинку", "make_video", ""), - ("!видео кот ловит снежинку", "make_video", ""), - ("/video@plotva_bot кот ловит снежинку", "make_video", ""), + ( + "!video кот ловит снежинку", + "make_video", + "кот ловит снежинку", + ), + ( + "!видео кот ловит снежинку", + "make_video", + "кот ловит снежинку", + ), + ( + "/video@plotva_bot кот ловит снежинку", + "make_video", + "кот ловит снежинку", + ), ("!draw red fish", "draw_image", "red fish"), ("@plotva_bot нарисуй рыбу", "draw_image", "рыбу"), ("@plotva_bot пожалуйста, нарисуй рыбу", "draw_image", "рыбу"), diff --git a/crates/openplotva-app/src/dialog_tools.rs b/crates/openplotva-app/src/dialog_tools.rs index d72bb32..2c32ad1 100644 --- a/crates/openplotva-app/src/dialog_tools.rs +++ b/crates/openplotva-app/src/dialog_tools.rs @@ -18,15 +18,15 @@ use openplotva_dialog::{ TOOL_RESULT_STATUS_QUEUED, ToolError, ToolResult, ToolSideEffect, ToolboxError, ToolboxFuture, VIDEO_GENERATION_NOT_SCHEDULED_MESSAGE, VideoRequest, VisionRequest, is_internal_not_scheduled_instruction, sanitize_tool_text, user_facing_not_scheduled_message, - verbatim_draw_caption, + verbatim_draw_caption, verbatim_video_caption, }; use openplotva_history::{StoredSummary, SummaryContent}; use openplotva_taskman::{ DEFAULT_PRIORITY, HIGHEST_PRIORITY, IMAGE_REGULAR_QUEUE_NAME, IMAGE_VIP_PRIORITY, IMAGE_VIP_QUEUE_NAME, ImageEditJobParams, ImageGenJobParams, InMemoryTaskQueue, - MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, VIDEO_QUEUE_NAME, VideoGenJobParams, - fallback_queue_time_estimate, format_duration_ru, format_go_duration, new_image_edit_job_at, - new_image_gen_job_at, new_music_gen_job_at, new_video_gen_job_at, + MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, VideoGenJobParams, fallback_queue_time_estimate, + format_duration_ru, format_go_duration, new_image_edit_job_at, new_image_gen_job_at, + new_music_gen_job_at, new_video_gen_job_at, }; use serde_json::json; use time::{OffsetDateTime, UtcOffset, format_description::well_known::Rfc3339}; @@ -949,8 +949,10 @@ pub struct VideoScheduleResult { pub enum VideoScheduleRejection { /// Bot cannot send videos in this chat. VideoNotAllowed, - /// The user's previous clip is still in progress. + /// The user already has the maximum of queued drawings and clips. ActiveLimit, + /// The per-user generation frequency limit shared with drawings. + GenerationRateLimited, /// Enqueue throttled by the task-enqueue rate limit. RateLimited, } @@ -961,6 +963,7 @@ impl VideoScheduleRejection { match self { Self::VideoNotAllowed => "video_not_allowed", Self::ActiveLimit => "active_job_limit", + Self::GenerationRateLimited => "generation_rate_limited", Self::RateLimited => "enqueue_rate_limited", } } @@ -972,7 +975,10 @@ impl VideoScheduleRejection { "В этот чат нельзя отправлять видео. Ролик не поставлен в очередь." } Self::ActiveLimit => { - "Предыдущее видео пользователя ещё делается. Новый ролик не поставлен в очередь: пусть дождётся готового." + "У пользователя уже выполняется максимум задач генерации картинок и роликов. Новый ролик не поставлен в очередь." + } + Self::GenerationRateLimited => { + "Сработал лимит частоты генерации. Ролик не поставлен в очередь." } Self::RateLimited => { "Слишком много запросов подряд, сработал лимит очереди. Задача не поставлена в очередь." @@ -1630,6 +1636,8 @@ impl SongScheduler for TaskmanDialogToolAdapter { } impl VideoScheduler for TaskmanDialogToolAdapter { + /// Clips join the drawing queue: the same VIP plan, per-user limits, rate limits and + /// queue notice as `draw_image`. fn schedule_video<'a>(&'a self, request: VideoScheduleRequest) -> ScheduleVideoFuture<'a> { Box::pin(async move { if let Some(permission) = self.video_permission.as_deref() @@ -1637,10 +1645,40 @@ impl VideoScheduler for TaskmanDialogToolAdapter { { return Ok(not_scheduled_video(VideoScheduleRejection::VideoNotAllowed)); } + let has_vip = match self.draw_image_vip_status.as_deref() { + Some(vip_status) => vip_status.is_draw_image_vip(request.user_id).await, + None => false, + }; + let plan = image_gen_queue_plan(has_vip); + if self + .queue + .user_active_count(plan.queue_name, request.user_id) + >= plan.max_active_jobs + { + return Ok(not_scheduled_video(VideoScheduleRejection::ActiveLimit)); + } + if let Some(rate_limit) = self.draw_image_rate_limit.as_deref() { + let report = rate_limit + .check_draw_image_rate_limit( + &request.brief, + request.user_id, + has_vip, + OffsetDateTime::now_utc(), + ) + .await; + if report.limited { + return Ok(VideoScheduleResult { + message: draw_rate_limit_response_text(&report.notice_text, has_vip), + ..not_scheduled_video(VideoScheduleRejection::GenerationRateLimited) + }); + } + } let chat_id = request.chat_id; let user_id = request.user_id; + let message_id = request.message_id; + let thread_id = request.thread_id; if self - .task_enqueue_limited(VIDEO_QUEUE_NAME, chat_id, user_id) + .task_enqueue_limited(plan.queue_name, chat_id, user_id) .await { return Ok(not_scheduled_video(VideoScheduleRejection::RateLimited)); @@ -1648,10 +1686,10 @@ impl VideoScheduler for TaskmanDialogToolAdapter { let job = new_video_gen_job_at( VideoGenJobParams { chat_id, - message_id: request.message_id, + message_id, user_id, user_full_name: request.user_full_name, - thread_id: request.thread_id, + thread_id, request_text: request.message_text.trim().to_owned(), brief: request.brief, caption: request.caption, @@ -1659,23 +1697,37 @@ impl VideoScheduler for TaskmanDialogToolAdapter { OffsetDateTime::now_utc(), ) .with_name("video") - .with_priority(DEFAULT_PRIORITY); - match self.queue.assign_with_user_limit(VIDEO_QUEUE_NAME, job, 1) { + .with_priority(plan.priority); + let queue_position = self.image_queue_position(plan); + match self.assign_image_job(plan.queue_name, job, plan.max_active_jobs) { Ok(Some(job_id)) => { self.persist_generation_handoff(job_id).await?; - self.grow_task_enqueue(VIDEO_QUEUE_NAME, chat_id, user_id) + self.grow_task_enqueue(plan.queue_name, chat_id, user_id) .await; + if let Some(rate_limit) = self.draw_image_rate_limit.as_deref() { + rate_limit + .grow_draw_image_rate_limit(user_id, OffsetDateTime::now_utc()) + .await; + } self.record_delivery_obligation( openplotva_dialog::turn::SIDE_EFFECT_KIND_VIDEO, job_id, chat_id, - request.thread_id, + thread_id, user_id, - request.message_id, + message_id, + ) + .await; + self.ack_queued_generation(chat_id, message_id).await; + self.maybe_send_draw_queue_notice( + DrawQueueNoticeKind::Generation, + plan, + queue_position, + chat_id, + message_id, + thread_id, ) .await; - self.ack_queued_generation(chat_id, request.message_id) - .await; Ok(VideoScheduleResult { status: "scheduled".to_owned(), job_id: Some(job_id), @@ -2808,7 +2860,8 @@ where user_id: req.context.user_id, user_full_name: req.context.user_full_name, brief: sanitize_tool_text(&req.prompt), - caption: sanitize_tool_text(&req.caption), + caption: verbatim_video_caption(&req.context.message_meta) + .unwrap_or_else(|| sanitize_tool_text(&req.caption)), message_text: req.context.message_text, }; match scheduler.schedule_video(request).await { @@ -5348,13 +5401,31 @@ mod tests { } } + fn queued_drawing(user_id: i64, message_id: i32) -> openplotva_taskman::StatelessJobItem { + new_image_gen_job_at( + ImageGenJobParams { + chat_id: -100, + message_id, + user_id, + prompt: "castle".to_owned(), + ..ImageGenJobParams::default() + }, + OffsetDateTime::now_utc(), + ) + } + #[tokio::test] - async fn taskman_dialog_tool_adapter_queues_one_video_per_user_with_an_obligation() + async fn taskman_dialog_tool_adapter_queues_videos_in_the_drawing_queue_with_an_obligation() -> Result<(), ToolboxError> { let queue = Arc::new(InMemoryTaskQueue::new()); let recorder = Arc::new(ObligationRecorderStub::default()); + let rate_limit = Arc::new(DrawImageRateLimitStub::new( + DrawImageRateLimitReport::default(), + )); let adapter = TaskmanDialogToolAdapter::new(Arc::clone(&queue)) .with_video_permission(Arc::new(VideoPermissionStub(true))) + .with_draw_image_vip_status(Arc::new(DrawImageVipStatusStub::new(false))) + .with_draw_image_rate_limit(rate_limit.clone()) .with_delivery_obligations(recorder.clone(), 1200, 1800); let scheduled = adapter.schedule_video(video_request(11)).await?; @@ -5363,7 +5434,8 @@ mod tests { assert_eq!(records.len(), 1); assert_eq!(scheduled.status, "scheduled"); assert_eq!(scheduled.job_id, Some(records[0].id)); - assert_eq!(records[0].queue_name, VIDEO_QUEUE_NAME); + assert_eq!(records[0].queue_name, IMAGE_REGULAR_QUEUE_NAME); + assert_eq!(records[0].job.priority, DEFAULT_PRIORITY); assert_eq!( openplotva_taskman::video_gen_job_params_from_payload(&records[0].job.data), Ok(VideoGenJobParams { @@ -5377,6 +5449,11 @@ mod tests { caption: "Кот и снежинка".to_owned(), }) ); + assert_eq!( + rate_limit.checks(), + vec![("A grey cat catches a snowflake".to_owned(), 42, false)] + ); + assert_eq!(rate_limit.grows(), vec![42]); let recorded = recorder.recorded(); assert_eq!(recorded.len(), 1); assert_eq!(recorded[0].kind, "video_generation_job"); @@ -5389,14 +5466,44 @@ mod tests { .map(|effect| (effect.kind, effect.ticket_id)), Some(("video_generation_job".to_owned(), records[0].id.to_string())) ); + Ok(()) + } - let second = adapter.schedule_video(video_request(12)).await?; - assert_eq!(second.rejection, Some(VideoScheduleRejection::ActiveLimit)); - assert_eq!(queue.records().len(), 1); - let refused = dialog_make_video_tool_result(&second); - assert_eq!(refused.status, TOOL_RESULT_STATUS_FAILED); + #[tokio::test] + async fn taskman_dialog_tool_adapter_gives_vip_videos_the_vip_queue() -> Result<(), ToolboxError> + { + let queue = Arc::new(InMemoryTaskQueue::new()); + let adapter = TaskmanDialogToolAdapter::new(Arc::clone(&queue)) + .with_video_permission(Arc::new(VideoPermissionStub(true))) + .with_draw_image_vip_status(Arc::new(DrawImageVipStatusStub::new(true))); + + let scheduled = adapter.schedule_video(video_request(11)).await?; + + assert_eq!(scheduled.status, "scheduled"); + let records = queue.records(); + assert_eq!(records[0].queue_name, IMAGE_VIP_QUEUE_NAME); + assert_eq!(records[0].job.priority, IMAGE_VIP_PRIORITY); + Ok(()) + } + + #[tokio::test] + async fn taskman_dialog_tool_adapter_counts_drawings_and_videos_against_one_limit() + -> Result<(), ToolboxError> { + let queue = Arc::new(InMemoryTaskQueue::new()); + for message_id in 1..=5 { + queue.assign(IMAGE_REGULAR_QUEUE_NAME, queued_drawing(42, message_id)); + } + let adapter = TaskmanDialogToolAdapter::new(Arc::clone(&queue)) + .with_video_permission(Arc::new(VideoPermissionStub(true))); + + let refused = adapter.schedule_video(video_request(11)).await?; + + assert_eq!(refused.rejection, Some(VideoScheduleRejection::ActiveLimit)); + assert_eq!(queue.records().len(), 5); + let result = dialog_make_video_tool_result(&refused); + assert_eq!(result.status, TOOL_RESULT_STATUS_FAILED); assert_eq!( - refused + result .data .as_ref() .and_then(|data| data["reason"].as_str()), @@ -5405,6 +5512,35 @@ mod tests { Ok(()) } + #[tokio::test] + async fn taskman_dialog_tool_adapter_applies_the_draw_rate_limit_to_videos() + -> Result<(), ToolboxError> { + let queue = Arc::new(InMemoryTaskQueue::new()); + let rate_limit = Arc::new(DrawImageRateLimitStub::new(DrawImageRateLimitReport { + limited: true, + notice_text: "Вы часто повторяете этот запрос. Попробуйте снова через 1 мин." + .to_owned(), + })); + let adapter = TaskmanDialogToolAdapter::new(Arc::clone(&queue)) + .with_video_permission(Arc::new(VideoPermissionStub(true))) + .with_draw_image_rate_limit(rate_limit.clone()); + + let refused = adapter.schedule_video(video_request(11)).await?; + + assert_eq!( + refused.rejection, + Some(VideoScheduleRejection::GenerationRateLimited) + ); + assert!( + refused + .message + .starts_with("Вы часто повторяете этот запрос. Попробуйте снова через 1 мин.\n\nПриобретите VIP-подписку") + ); + assert!(rate_limit.grows().is_empty()); + assert!(queue.records().is_empty()); + Ok(()) + } + #[tokio::test] async fn taskman_dialog_tool_adapter_refuses_video_where_the_chat_forbids_it() -> Result<(), ToolboxError> { diff --git a/crates/openplotva-app/src/image_jobs.rs b/crates/openplotva-app/src/image_jobs.rs index b5f72e4..26b4f1e 100644 --- a/crates/openplotva-app/src/image_jobs.rs +++ b/crates/openplotva-app/src/image_jobs.rs @@ -50,6 +50,7 @@ use crate::routed_attempts::{ use crate::telegram_activity::{ TelegramActivityAction, TelegramActivityPulse, TelegramActivitySnapshot, }; +use crate::video_jobs::{VideoJobOutcome, VideoJobRunner, VideoQueuePoll}; use crate::vision::TelegramVisionDataUrlProvider; /// Boxed future returned by image generation providers. @@ -3260,6 +3261,8 @@ impl ImageEditWorkerRunReport { pub struct ImageQueuePollOptions<'a> { pub max_llm_job_attempts: i32, pub activity_pulse: Option<&'a TelegramActivityPulse>, + /// Takes `VideoGen` tickets from the same queue when set. + pub video: Option<&'a dyn VideoJobRunner>, pub now: OffsetDateTime, } @@ -3269,6 +3272,7 @@ impl ImageQueuePollOptions<'_> { Self { max_llm_job_attempts: DEFAULT_LLM_JOB_MAX_ATTEMPTS, activity_pulse: None, + video: None, now, } } @@ -3279,6 +3283,8 @@ pub struct ImageWorkerRunOptions<'a> { pub interval: StdDuration, pub max_llm_job_attempts: i32, pub activity_pulse: Option<&'a TelegramActivityPulse>, + /// Takes `VideoGen` tickets from the same queues when set. + pub video: Option<&'a dyn VideoJobRunner>, } impl ImageWorkerRunOptions<'_> { @@ -3288,6 +3294,7 @@ impl ImageWorkerRunOptions<'_> { interval, max_llm_job_attempts: DEFAULT_LLM_JOB_MAX_ATTEMPTS, activity_pulse: None, + video: None, } } } @@ -3862,8 +3869,10 @@ where Generator: ImageGenerator + Sync, Effects: ImageJobEffects + Sync, { + let takes_clips = options.video.is_some(); let Some(work) = queue.dequeue_matching(queue_name, worker_id, options.now, |job| { job.data.job_type == JobType::ImageGen + || (takes_clips && job.data.job_type == JobType::VideoGen) }) else { return ImageGenQueuePollReport { queue_name: queue_name.to_owned(), @@ -3873,6 +3882,15 @@ where activity: TelegramActivitySnapshot::default(), }; }; + if let Some(video) = options.video + && work.job.data.job_type == JobType::VideoGen + { + let vip = queue_name == IMAGE_VIP_QUEUE_NAME; + let poll = video + .run_video_job(queue, work, vip, options.activity_pulse) + .await; + return video_poll_report(queue_name, poll); + } let params = match image_gen_job_params_from_stateless_job(&work.job) { Ok(params) => params, @@ -4419,6 +4437,7 @@ where ImageQueuePollOptions { max_llm_job_attempts: options.max_llm_job_attempts, activity_pulse: options.activity_pulse, + video: options.video, now: OffsetDateTime::now_utc(), }, ).await; @@ -4510,6 +4529,7 @@ where ImageQueuePollOptions { max_llm_job_attempts: options.max_llm_job_attempts, activity_pulse: options.activity_pulse, + video: None, now: OffsetDateTime::now_utc(), }, ).await; @@ -4523,6 +4543,28 @@ where report } +fn video_poll_report(queue_name: &str, poll: VideoQueuePoll) -> ImageGenQueuePollReport { + let (job_id, outcome, error) = match poll { + VideoQueuePoll::Finished { + job_id, + outcome: VideoJobOutcome::Blocked { .. }, + } => (job_id, ImageGenQueuePollOutcome::SafetyBlocked, None), + VideoQueuePoll::Finished { job_id, .. } => { + (job_id, ImageGenQueuePollOutcome::Completed, None) + } + VideoQueuePoll::Failed { job_id, error } => { + (job_id, ImageGenQueuePollOutcome::Failed, Some(error)) + } + }; + ImageGenQueuePollReport { + queue_name: queue_name.to_owned(), + job_id: Some(job_id), + outcome, + error, + activity: TelegramActivitySnapshot::default(), + } +} + fn finalize_completed( queue: &InMemoryTaskQueue, job_id: i64, @@ -5501,13 +5543,96 @@ mod tests { DEFAULT_LLM_JOB_MAX_ATTEMPTS, DEFAULT_PRIORITY, HIGHEST_PRIORITY, IMAGE_REGULAR_QUEUE_NAME, IMAGE_VIP_QUEUE_NAME, ImageEditJobParams, ImageGenJobParams, ImageJobData, JobPayload, JobStatus, LLM_JOB_RETRY_EXHAUSTED_STAGE, LLM_JOB_RETRY_STAGE, StatelessJobItem, - TaskQueueJobEvent, TelegramData, new_image_edit_job_at, new_image_gen_job_at, + TaskQueueJobEvent, TelegramData, VideoGenJobParams, new_image_edit_job_at, + new_image_gen_job_at, new_video_gen_job_at, }; use openplotva_telegram::TelegramOutboundMethodKind; use serde_json::json; use super::*; + #[derive(Default)] + struct VideoRunnerStub { + runs: Mutex>, + } + + impl VideoJobRunner for VideoRunnerStub { + fn run_video_job<'a>( + &'a self, + queue: &'a InMemoryTaskQueue, + work: TaskQueueWorkItem, + vip: bool, + _activity_pulse: Option<&'a TelegramActivityPulse>, + ) -> crate::video_jobs::VideoJobFuture<'a, VideoQueuePoll> { + self.runs.lock().expect("runs").push((work.id, vip)); + let _ = queue.complete(work.id, OffsetDateTime::now_utc()); + Box::pin(async move { + VideoQueuePoll::Finished { + job_id: work.id, + outcome: VideoJobOutcome::Delivered { + message_id: Some(1), + }, + } + }) + } + } + + fn queued_clip(queue: &InMemoryTaskQueue, queue_name: &str, now: OffsetDateTime) -> i64 { + queue.assign( + queue_name, + new_video_gen_job_at( + VideoGenJobParams { + chat_id: -100, + message_id: 20, + user_id: 30, + brief: "кот ловит снежинку".to_owned(), + ..VideoGenJobParams::default() + }, + now, + ), + ) + } + + #[tokio::test] + async fn image_generation_workers_render_clips_from_their_shared_queue() { + let now = OffsetDateTime::now_utc(); + let runner = VideoRunnerStub::default(); + for (queue_name, vip) in [ + (IMAGE_REGULAR_QUEUE_NAME, false), + (IMAGE_VIP_QUEUE_NAME, true), + ] { + let queue = InMemoryTaskQueue::new(); + let clip = queued_clip(&queue, queue_name, now); + + let without_runner = run_image_gen_queue_once_with_max_attempts( + &queue, + queue_name, + &GeneratorStub::success("https://img.test/unused.png"), + &EffectsStub::new(), + "image-worker", + ImageQueuePollOptions::at(now), + ) + .await; + assert_eq!(without_runner.outcome, ImageGenQueuePollOutcome::Idle); + + let report = run_image_gen_queue_once_with_max_attempts( + &queue, + queue_name, + &GeneratorStub::success("https://img.test/unused.png"), + &EffectsStub::new(), + "image-worker", + ImageQueuePollOptions { + video: Some(&runner), + ..ImageQueuePollOptions::at(now) + }, + ) + .await; + assert_eq!(report.job_id, Some(clip)); + assert_eq!(report.outcome, ImageGenQueuePollOutcome::Completed); + assert_eq!(runner.runs.lock().expect("runs").last(), Some(&(clip, vip))); + } + } + fn encode_solid_png(width: u32, height: u32, color: image::Rgba) -> Vec { let mut encoded = Cursor::new(Vec::new()); image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, color)) @@ -7385,6 +7510,7 @@ mod tests { ImageQueuePollOptions { max_llm_job_attempts: DEFAULT_LLM_JOB_MAX_ATTEMPTS, activity_pulse: Some(&pulse), + video: None, now, }, ); @@ -7635,6 +7761,7 @@ mod tests { ImageQueuePollOptions { max_llm_job_attempts: DEFAULT_LLM_JOB_MAX_ATTEMPTS, activity_pulse: Some(&pulse), + video: None, now, }, ); @@ -7770,6 +7897,7 @@ mod tests { ImageQueuePollOptions { max_llm_job_attempts: 2, activity_pulse: None, + video: None, now, }, ) @@ -7824,6 +7952,7 @@ mod tests { ImageQueuePollOptions { max_llm_job_attempts: 2, activity_pulse: None, + video: None, now, }, ) diff --git a/crates/openplotva-app/src/lib.rs b/crates/openplotva-app/src/lib.rs index 6bea004..85a0a61 100644 --- a/crates/openplotva-app/src/lib.rs +++ b/crates/openplotva-app/src/lib.rs @@ -1516,10 +1516,6 @@ fn admin_queue_config_from_app_config(config: &AppConfig) -> admin::AdminQueueCo queue_name: openplotva_taskman::MUSIC_VIP_QUEUE_NAME.to_owned(), worker_count: queue.music_vip_workers, }, - admin::AdminQueueWorkerConfig { - queue_name: openplotva_taskman::VIDEO_QUEUE_NAME.to_owned(), - worker_count: i32::from(config.video.enabled), - }, admin::AdminQueueWorkerConfig { queue_name: openplotva_taskman::MEMORY_CONSOLIDATION_QUEUE_NAME.to_owned(), worker_count: queue.memory_consolidation_workers, @@ -4429,6 +4425,30 @@ async fn start_runtime_workers( memory_store.clone(), )), )); + // Clips ride the image queues: the VIP and regular generation workers render them + // in queue order instead of next to the drawings. + let video_runner: Option> = + config.video.enabled.then(|| { + Arc::new(video_jobs::VideoPipeline { + optimizer: media::RoutedMediaPromptOptimizer::new( + attempt_walker.clone(), + config, + Arc::clone(&prompt_store), + ), + generator: image_jobs::AifarmDrawApiImageGenerator::new( + image_jobs::AifarmDrawApiConfig { + endpoint_name: image_jobs::AIFARM_DRAW_API_FASTFRAMES_ENDPOINT_NAME + .to_owned(), + ..image_jobs::aifarm_draw_api_config_from_app_config(config) + }, + ), + effects: video_jobs::TelegramVideoJobEffects::new( + Arc::clone(&permission_policy), + telegram.clone(), + ) + .with_reaction_ux(Arc::clone(&generation_reactions)), + }) as Arc + }); let vip_image_queue = Arc::clone(&task_queue_for_updates); let image_attempt_walker = attempt_walker.clone(); let vip_slot = |workflow_key: &str| { @@ -4462,6 +4482,7 @@ async fn start_runtime_workers( } let vip_image_stop = worker_stops.subscribe(RuntimeWorkerPhase::Processor); let vip_image_activity_pulse = Arc::clone(&telegram_activity_pulse); + let vip_video_runner = video_runner.clone(); let vip_image_worker = tokio::spawn(async move { let report = image_jobs::run_image_gen_worker_every_until_with_max_attempts( vip_image_queue.as_ref(), @@ -4472,6 +4493,7 @@ async fn start_runtime_workers( interval: image_jobs::IMAGE_JOB_POLL_INTERVAL, max_llm_job_attempts: media_max_llm_job_attempts, activity_pulse: Some(vip_image_activity_pulse.as_ref()), + video: vip_video_runner.as_deref(), }, wait_for_runtime_stop(vip_image_stop), ) @@ -4519,6 +4541,7 @@ async fn start_runtime_workers( interval: image_jobs::IMAGE_JOB_POLL_INTERVAL, max_llm_job_attempts: media_max_llm_job_attempts, activity_pulse: Some(vip_image_edit_activity_pulse.as_ref()), + video: None, }, wait_for_runtime_stop(vip_image_edit_stop), ) @@ -4560,6 +4583,7 @@ async fn start_runtime_workers( } let regular_image_stop = worker_stops.subscribe(RuntimeWorkerPhase::Processor); let regular_image_activity_pulse = Arc::clone(&telegram_activity_pulse); + let regular_video_runner = video_runner.clone(); let regular_image_worker = tokio::spawn(async move { let report = image_jobs::run_image_gen_worker_every_until_with_max_attempts( regular_image_queue.as_ref(), @@ -4570,6 +4594,7 @@ async fn start_runtime_workers( interval: image_jobs::IMAGE_JOB_POLL_INTERVAL, max_llm_job_attempts: media_max_llm_job_attempts, activity_pulse: Some(regular_image_activity_pulse.as_ref()), + video: regular_video_runner.as_deref(), }, wait_for_runtime_stop(regular_image_stop), ) @@ -4669,50 +4694,11 @@ async fn start_runtime_workers( "ACESTEP_ENABLED=false", )); } - if config.video.enabled { - let video_queue = Arc::clone(&task_queue_for_updates); - let video_optimizer = media::RoutedMediaPromptOptimizer::new( - attempt_walker.clone(), - config, - Arc::clone(&prompt_store), - ); - let video_generator = - image_jobs::AifarmDrawApiImageGenerator::new(image_jobs::AifarmDrawApiConfig { - endpoint_name: image_jobs::AIFARM_DRAW_API_FASTFRAMES_ENDPOINT_NAME.to_owned(), - ..image_jobs::aifarm_draw_api_config_from_app_config(config) - }); - let video_effects = video_jobs::TelegramVideoJobEffects::new( - Arc::clone(&permission_policy), - telegram.clone(), - ) - .with_reaction_ux(Arc::clone(&generation_reactions)); - let video_stop = worker_stops.subscribe(RuntimeWorkerPhase::Processor); - let video_activity_pulse = Arc::clone(&telegram_activity_pulse); - let video_worker = tokio::spawn(async move { - let report = video_jobs::run_video_worker_until( - video_queue.as_ref(), - &video_optimizer, - &video_generator, - &video_effects, - Some(video_activity_pulse.as_ref()), - wait_for_runtime_stop(video_stop), - ) - .await; - tracing::info!(?report, "video generation taskman worker stopped"); - }); - worker_registry.register( - "video-generation-worker", - RuntimeWorkerPhase::Processor, - video_worker, - ); + if video_runner.is_some() { readiness_checks.push(ReadinessCheck::ok( "video_jobs", - "Video taskman worker started for the video queue with FastFrames on draw-api", + "Clips share the image-vip and image-regular queues and their generation workers, rendered by FastFrames on draw-api", )); - shared_taskman_worker_counts - .entry(openplotva_taskman::VIDEO_QUEUE_NAME.to_owned()) - .and_modify(|count| *count += 1) - .or_insert(1); } else { readiness_checks.push(ReadinessCheck::skipped( "video_jobs", diff --git a/crates/openplotva-app/src/video_jobs.rs b/crates/openplotva-app/src/video_jobs.rs index 698a1e2..aef2189 100644 --- a/crates/openplotva-app/src/video_jobs.rs +++ b/crates/openplotva-app/src/video_jobs.rs @@ -1,29 +1,30 @@ -//! Video jobs: the optimizer writes a FastFrames prompt, draw-api renders the clip, and the -//! bot replies with it as a Telegram animation. +//! Video jobs share the image queues: the image generation worker hands every dequeued +//! `VideoGen` ticket to a [`VideoJobRunner`]. The optimizer writes a FastFrames prompt, +//! draw-api renders the clip, and the bot replies with it as a Telegram animation captioned +//! like a drawing. -use std::{future::Future, pin::Pin, sync::Arc, time::Duration as StdDuration}; +use std::{future::Future, pin::Pin, sync::Arc}; use openplotva_llm::aifarm::AifarmHttpTransport; use openplotva_media::{NsfwResult, video::VideoOptimize}; use openplotva_server::ACTION_SEND_VIDEO; use openplotva_taskman::{ - InMemoryTaskQueue, JobType, VIDEO_QUEUE_NAME, VideoGenJobParams, - video_gen_job_params_from_payload, + InMemoryTaskQueue, TaskQueueWorkItem, VideoGenJobParams, video_gen_job_params_from_payload, }; use openplotva_telegram::{ - ChatRef, ReplyParametersPlan, TelegramClient, TelegramOutboundMethod, UploadMessageRequest, - build_animation_message_method, build_text_message_methods, ensure_telegram_safe_text, + ChatRef, ReplyParametersPlan, TELEGRAM_PARSE_MODE_HTML, TelegramClient, TelegramOutboundMethod, + UploadMessageRequest, build_animation_message_method, build_text_message_methods, }; use time::OffsetDateTime; -use crate::image_jobs::{AifarmDrawApiImageGenerator, DrawApiVideo, ImageJobTelegramSender}; +use crate::image_jobs::{ + AifarmDrawApiImageGenerator, DrawApiVideo, ImageJobTelegramSender, + build_image_generation_caption, +}; use crate::permissions::{ChatPermissionPolicy, ChatPermissionStore}; use crate::telegram_activity::{TelegramActivityAction, TelegramActivityPulse}; -pub const VIDEO_JOB_POLL_INTERVAL: StdDuration = StdDuration::from_secs(1); -const VIDEO_WORKER_ID: &str = "video-worker"; const VIDEO_FILE_NAME: &str = "video.mp4"; -const TELEGRAM_CAPTION_MAX_CHARS: usize = 1024; pub type VideoJobFuture<'a, T> = Pin + Send + 'a>>; @@ -227,7 +228,7 @@ fn animation_method(delivery: &VideoDelivery) -> Result( effects: &Effects, params: &VideoGenJobParams, job_id: i64, + vip: bool, ) -> Result where Optimizer: VideoPromptOptimizer + ?Sized, @@ -302,14 +304,20 @@ where return Ok(VideoJobOutcome::Blocked { message_id }); } let video = generator.generate_video(&optimized.prompt, job_id).await?; + let adult = optimized.nsfw_result == NsfwResult::Adult; let message_id = effects .send_video(VideoDelivery { chat_id: params.chat_id, thread_id: params.thread_id, reply_to_message_id: params.message_id, - caption: video_caption(¶ms.caption), + caption: build_image_generation_caption( + video_caption_text(params), + ¶ms.user_full_name, + vip, + adult, + ), video, - spoiler: optimized.nsfw_result == NsfwResult::Adult, + spoiler: adult, }) .await?; effects @@ -318,17 +326,18 @@ where Ok(VideoJobOutcome::Delivered { message_id }) } -fn video_caption(caption: &str) -> String { - ensure_telegram_safe_text(caption.trim()) - .chars() - .take(TELEGRAM_CAPTION_MAX_CHARS) - .collect() +/// The clip title shown like a drawing's: the dialog caption, else the brief. +fn video_caption_text(params: &VideoGenJobParams) -> &str { + [¶ms.caption, ¶ms.brief, ¶ms.request_text] + .into_iter() + .map(|text| text.trim()) + .find(|text| !text.is_empty()) + .unwrap_or_default() } -/// What one poll of the video queue did. +/// What one video ticket ended with. #[derive(Clone, Debug, Eq, PartialEq)] pub enum VideoQueuePoll { - Idle, Finished { job_id: i64, outcome: VideoJobOutcome, @@ -339,37 +348,80 @@ pub enum VideoQueuePoll { }, } -/// Dequeue and run one video job. -pub async fn run_video_queue_once( +/// Runs video tickets that a shared image-queue worker dequeued. +pub trait VideoJobRunner: Send + Sync { + /// Run one dequeued `VideoGen` ticket to a terminal state. `vip` marks a ticket + /// from the VIP queue, which gets the VIP caption. + fn run_video_job<'a>( + &'a self, + queue: &'a InMemoryTaskQueue, + work: TaskQueueWorkItem, + vip: bool, + activity_pulse: Option<&'a TelegramActivityPulse>, + ) -> VideoJobFuture<'a, VideoQueuePoll>; +} + +/// The FastFrames clip pipeline. +pub struct VideoPipeline { + pub optimizer: Optimizer, + pub generator: Generator, + pub effects: Effects, +} + +impl VideoJobRunner for VideoPipeline +where + Optimizer: VideoPromptOptimizer, + Generator: VideoGenerator, + Effects: VideoJobEffects, +{ + fn run_video_job<'a>( + &'a self, + queue: &'a InMemoryTaskQueue, + work: TaskQueueWorkItem, + vip: bool, + activity_pulse: Option<&'a TelegramActivityPulse>, + ) -> VideoJobFuture<'a, VideoQueuePoll> { + Box::pin(run_dequeued_video_job( + queue, + work, + vip, + &self.optimizer, + &self.generator, + &self.effects, + activity_pulse, + )) + } +} + +/// Run one dequeued video ticket and record its terminal state. +pub async fn run_dequeued_video_job( queue: &InMemoryTaskQueue, + work: TaskQueueWorkItem, + vip: bool, optimizer: &Optimizer, generator: &Generator, effects: &Effects, activity_pulse: Option<&TelegramActivityPulse>, - now: OffsetDateTime, ) -> VideoQueuePoll where Optimizer: VideoPromptOptimizer + ?Sized, Generator: VideoGenerator + ?Sized, Effects: VideoJobEffects + ?Sized, { - let Some(work) = queue.dequeue_matching(VIDEO_QUEUE_NAME, VIDEO_WORKER_ID, now, |job| { - job.data.job_type == JobType::VideoGen - }) else { - return VideoQueuePoll::Idle; - }; + let started_at = OffsetDateTime::now_utc(); let params = match video_gen_job_params_from_payload(&work.job.data) { Ok(params) => params, Err(error) => { let error = error.to_string(); - let _ = queue.fail(work.id, error.clone(), now); + let _ = queue.fail(work.id, error.clone(), started_at); + tracing::warn!(job_id = work.id, %error, "video job payload is invalid"); return VideoQueuePoll::Failed { job_id: work.id, error, }; } }; - let _ = queue.set_execution_started(work.id, now); + let _ = queue.set_execution_started(work.id, started_at); let activity = activity_pulse.map(|pulse| { pulse.start( params.chat_id, @@ -377,7 +429,7 @@ where TelegramActivityAction::UploadVideo, ) }); - let result = execute_video_gen_job(optimizer, generator, effects, ¶ms, work.id).await; + let result = execute_video_gen_job(optimizer, generator, effects, ¶ms, work.id, vip).await; drop(activity); let finished_at = OffsetDateTime::now_utc(); match result { @@ -386,6 +438,7 @@ where let _ = queue.update_job_result_message(work.id, Some(message_id)); } let _ = queue.complete(work.id, finished_at); + tracing::info!(job_id = work.id, vip, ?outcome, "video job finished"); VideoQueuePoll::Finished { job_id: work.id, outcome, @@ -393,6 +446,7 @@ where } Err(error) => { let _ = queue.fail(work.id, error.clone(), finished_at); + tracing::warn!(job_id = work.id, vip, %error, "video job failed"); VideoQueuePoll::Failed { job_id: work.id, error, @@ -401,70 +455,11 @@ where } } -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct VideoWorkerRunReport { - pub delivered: u64, - pub blocked: u64, - pub skipped_permission: u64, - pub failed: u64, -} - -/// Run the video worker until `stop` resolves. -pub async fn run_video_worker_until( - queue: &InMemoryTaskQueue, - optimizer: &Optimizer, - generator: &Generator, - effects: &Effects, - activity_pulse: Option<&TelegramActivityPulse>, - stop: Stop, -) -> VideoWorkerRunReport -where - Optimizer: VideoPromptOptimizer + ?Sized, - Generator: VideoGenerator + ?Sized, - Effects: VideoJobEffects + ?Sized, - Stop: Future, -{ - let mut report = VideoWorkerRunReport::default(); - let mut stop = std::pin::pin!(stop); - loop { - tokio::select! { - () = &mut stop => break, - () = tokio::time::sleep(VIDEO_JOB_POLL_INTERVAL) => { - let poll = run_video_queue_once( - queue, - optimizer, - generator, - effects, - activity_pulse, - OffsetDateTime::now_utc(), - ) - .await; - match poll { - VideoQueuePoll::Idle => {} - VideoQueuePoll::Finished { job_id, outcome } => { - tracing::info!(job_id, ?outcome, "video job finished"); - match outcome { - VideoJobOutcome::Delivered { .. } => report.delivered += 1, - VideoJobOutcome::Blocked { .. } => report.blocked += 1, - VideoJobOutcome::SkippedPermission => report.skipped_permission += 1, - } - } - VideoQueuePoll::Failed { job_id, error } => { - tracing::warn!(job_id, %error, "video job failed"); - report.failed += 1; - } - } - } - } - } - report -} - #[cfg(test)] mod tests { use std::sync::Mutex; - use openplotva_taskman::new_video_gen_job_at; + use openplotva_taskman::{IMAGE_REGULAR_QUEUE_NAME, JobType, new_video_gen_job_at}; use super::*; @@ -603,27 +598,36 @@ mod tests { fn queue_with_job() -> (InMemoryTaskQueue, i64) { let queue = InMemoryTaskQueue::new(); let job_id = queue.assign( - VIDEO_QUEUE_NAME, + IMAGE_REGULAR_QUEUE_NAME, new_video_gen_job_at(params(), OffsetDateTime::UNIX_EPOCH), ); (queue, job_id) } + async fn run_next( + queue: &InMemoryTaskQueue, + optimizer: &FixedOptimizer, + generator: &RecordingGenerator, + effects: &RecordingEffects, + ) -> VideoQueuePoll { + let work = queue + .dequeue_matching( + IMAGE_REGULAR_QUEUE_NAME, + "image-regular-worker", + OffsetDateTime::now_utc(), + |job| job.data.job_type == JobType::VideoGen, + ) + .expect("queued clip"); + run_dequeued_video_job(queue, work, false, optimizer, generator, effects, None).await + } + #[tokio::test] async fn a_clip_is_rendered_from_the_optimized_prompt_and_replies_to_the_request() { let (queue, job_id) = queue_with_job(); let generator = RecordingGenerator::default(); let effects = RecordingEffects::default(); - let poll = run_video_queue_once( - &queue, - &optimized(NsfwResult::Safe), - &generator, - &effects, - None, - OffsetDateTime::now_utc(), - ) - .await; + let poll = run_next(&queue, &optimized(NsfwResult::Safe), &generator, &effects).await; assert_eq!( poll, @@ -640,16 +644,24 @@ mod tests { ); assert_eq!(effects.events(), ["progress", "video", "clear"]); let sent = effects.sent.lock().expect("sent"); + assert_eq!(sent.len(), 1); + let delivery = &sent[0]; assert_eq!( - sent.as_slice(), - [VideoDelivery { - chat_id: -100, - thread_id: Some(3), - reply_to_message_id: 42, - caption: "Кот и снежинка".to_owned(), - video: clip(), - spoiler: false, - }] + ( + delivery.chat_id, + delivery.thread_id, + delivery.reply_to_message_id + ), + (-100, Some(3), 42) + ); + assert_eq!(delivery.video, clip()); + assert!(!delivery.spoiler); + assert!( + delivery + .caption + .starts_with("Кот и снежинка \nза авторством Alice\n"), + "{}", + delivery.caption ); let record = queue.record(job_id).expect("video job"); assert_eq!(record.status, openplotva_taskman::JobStatus::Completed); @@ -659,13 +671,11 @@ mod tests { #[tokio::test] async fn a_blocked_request_records_the_refusal_as_the_result_message() { let (queue, job_id) = queue_with_job(); - let poll = run_video_queue_once( + let poll = run_next( &queue, &optimized(NsfwResult::Forbidden), &RecordingGenerator::default(), &RecordingEffects::default(), - None, - OffsetDateTime::now_utc(), ) .await; @@ -684,7 +694,7 @@ mod tests { } #[tokio::test] - async fn an_adult_clip_is_sent_under_a_spoiler() { + async fn an_adult_vip_clip_is_sent_under_a_spoiler_with_the_drawing_tags() { let effects = RecordingEffects::default(); let outcome = execute_video_gen_job( &optimized(NsfwResult::Adult), @@ -692,6 +702,7 @@ mod tests { &effects, ¶ms(), 9, + true, ) .await; assert_eq!( @@ -700,7 +711,20 @@ mod tests { message_id: Some(VIDEO_MESSAGE_ID) }) ); - assert!(effects.sent.lock().expect("sent")[0].spoiler); + let sent = effects.sent.lock().expect("sent"); + assert!(sent[0].spoiler); + assert!(sent[0].caption.contains( + "за авторством VIP-персоны 👑 Alice\n#nsfw 18+" + )); + } + + #[test] + fn a_clip_without_a_dialog_caption_is_titled_by_its_brief() { + let untitled = VideoGenJobParams { + caption: " ".to_owned(), + ..params() + }; + assert_eq!(video_caption_text(&untitled), "кот ловит снежинку"); } #[tokio::test] @@ -713,6 +737,7 @@ mod tests { &effects, ¶ms(), 9, + false, ) .await; assert_eq!( @@ -738,6 +763,7 @@ mod tests { &effects, ¶ms(), 9, + false, ) .await; assert_eq!(outcome, Ok(VideoJobOutcome::SkippedPermission)); @@ -748,13 +774,11 @@ mod tests { async fn optimizer_and_render_failures_fail_the_job_and_keep_the_progress_signal() { let (queue, job_id) = queue_with_job(); let effects = RecordingEffects::default(); - let poll = run_video_queue_once( + let poll = run_next( &queue, &FixedOptimizer(Err("video prompt optimizer: all attempts failed".to_owned())), &RecordingGenerator::default(), &effects, - None, - OffsetDateTime::now_utc(), ) .await; assert_eq!( @@ -779,6 +803,7 @@ mod tests { &RecordingEffects::default(), ¶ms(), 9, + false, ) .await; assert_eq!(render_failure, Err("draw-api provider timeout".to_owned())); @@ -802,6 +827,7 @@ mod tests { "height: Some(480)", "duration: Some(5)", "message_thread_id: Some(3)", + "parse_mode: Some(Html)", ] { assert!(debug.contains(expected), "missing {expected} in {debug}"); } diff --git a/crates/openplotva-dialog/src/dispatch.rs b/crates/openplotva-dialog/src/dispatch.rs index f58f773..1453d44 100644 --- a/crates/openplotva-dialog/src/dispatch.rs +++ b/crates/openplotva-dialog/src/dispatch.rs @@ -28,6 +28,16 @@ pub fn verbatim_draw_caption(meta: &ChatMessageMeta) -> Option { (words > 0 && words <= VERBATIM_DRAW_CAPTION_MAX_WORDS).then_some(request) } +/// Caption for a short explicit clip request such as `!видео кот`: the user's own words, +/// unchanged, by the same rule as drawings. +#[must_use] +pub fn verbatim_video_caption(meta: &ChatMessageMeta) -> Option { + if meta.requested_tool != STEP_MAKE_VIDEO { + return None; + } + verbatim_draw_caption(meta) +} + /// Dispatch one tool step to the toolbox. pub async fn dispatch_dialog_tool( toolbox: &dyn DialogToolbox, @@ -96,6 +106,14 @@ pub async fn dispatch_dialog_tool( "make_video prompt is empty", )); } + if crate::sanitize_tool_text(&step.caption).is_empty() + && verbatim_video_caption(&meta.message_meta).is_none() + { + return Ok(ToolResult::failed( + "video_caption_required", + "Retry with a nonempty caption naming the requested clip in the user's language. Remove the bot address and the request to make a video. Keep generation instructions in prompt.", + )); + } toolbox .make_video(VideoRequest { context: meta.clone(), @@ -597,6 +615,7 @@ mod tests { }, ToolStep { step: STEP_MAKE_VIDEO.to_owned(), + caption: "Кот ловит снежинку".to_owned(), ..ToolStep::default() }, ] { @@ -611,11 +630,55 @@ mod tests { ), ( "сделай видео как кот ловит снежинку".to_owned(), - String::new() + "Кот ловит снежинку".to_owned() ), ] ); + let untitled = poll_ready(dispatch_dialog_tool( + &toolbox, + &meta, + &ToolStep { + step: STEP_MAKE_VIDEO.to_owned(), + prompt: "A grey cat catches a snowflake".to_owned(), + ..ToolStep::default() + }, + )) + .expect("dispatch"); + assert_eq!( + untitled.error.as_ref().map(|e| e.code.as_str()), + Some("video_caption_required") + ); + + let shortcut = ToolContext { + message_meta: ChatMessageMeta { + requested_tool: STEP_MAKE_VIDEO.to_owned(), + draw_request: "кот ловит снежинку".to_owned(), + ..ChatMessageMeta::default() + }, + ..meta.clone() + }; + poll_ready(dispatch_dialog_tool( + &toolbox, + &shortcut, + &ToolStep { + step: STEP_MAKE_VIDEO.to_owned(), + prompt: "A grey cat catches a snowflake".to_owned(), + ..ToolStep::default() + }, + )) + .expect("dispatch"); + assert_eq!(toolbox.0.lock().expect("videos").len(), 3); + assert_eq!( + verbatim_video_caption(&shortcut.message_meta).as_deref(), + Some("кот ловит снежинку") + ); + assert_eq!( + verbatim_video_caption(&draw_request_meta("кот ловит снежинку")), + None, + "a drawing shortcut does not title a clip" + ); + let empty = poll_ready(dispatch_dialog_tool( &toolbox, &ToolContext::default(), diff --git a/crates/openplotva-dialog/src/lib.rs b/crates/openplotva-dialog/src/lib.rs index f0296fa..df92e3a 100644 --- a/crates/openplotva-dialog/src/lib.rs +++ b/crates/openplotva-dialog/src/lib.rs @@ -15,7 +15,10 @@ pub mod tool_telemetry; pub mod transcript; pub mod turn; -pub use dispatch::{VERBATIM_DRAW_CAPTION_MAX_WORDS, dispatch_dialog_tool, verbatim_draw_caption}; +pub use dispatch::{ + VERBATIM_DRAW_CAPTION_MAX_WORDS, dispatch_dialog_tool, verbatim_draw_caption, + verbatim_video_caption, +}; pub use leak_guard::{DialogLeak, ReplyLeakGuard, ReplyLeakGuardBuilder}; pub use history::{ @@ -683,9 +686,10 @@ const MAKE_VIDEO_ARGS: &[ToolArgSpec] = &[ ToolArgSpec { name: "caption", required: true, - description: "Short clip title in the user's language. Preserve the requested subject and \ - names. Remove the bot address, the request to make a video and politeness. \ - Start with a capital letter.", + description: "Short clip title in the user's language. Preserve the requested subject, \ + names and details. Remove the bot address, the request to make a video and \ + politeness. Start with a capital letter. Never include technical instructions \ + or details added for generation.", }, ]; diff --git a/crates/openplotva-taskman/src/lib.rs b/crates/openplotva-taskman/src/lib.rs index e96316a..9db77a9 100644 --- a/crates/openplotva-taskman/src/lib.rs +++ b/crates/openplotva-taskman/src/lib.rs @@ -32,7 +32,6 @@ pub const TEXT_QUEUE_NAME: &str = "text"; pub const IMAGE_REGULAR_QUEUE_NAME: &str = "image-regular"; pub const IMAGE_VIP_QUEUE_NAME: &str = "image-vip"; pub const MUSIC_VIP_QUEUE_NAME: &str = "music-vip"; -pub const VIDEO_QUEUE_NAME: &str = "video"; pub const ASR_GPU1_QUEUE_NAME: &str = "asr-gpu1"; pub const DIALOG_AIFARM_QUEUE_NAME: &str = "dialog-aifarm"; pub const MEMORY_CONSOLIDATION_QUEUE_NAME: &str = "memory-consolidation"; @@ -3475,7 +3474,7 @@ fn next_pending_index_matching( .map(|(index, _record)| index) } -/// Arbitrate separate ASR, VIP-image, and regular-image workers while the queue +/// Arbitrate separate ASR, VIP-media, and regular-media workers while the queue /// state is locked. Waiting jobs age to the ASR priority ceiling, after which /// the existing creation-time and ID order guarantees eventual eligibility. fn accelerator_work_blocked_by_higher_ranked_work( @@ -3499,7 +3498,7 @@ fn accelerator_work_blocked_by_higher_ranked_work( fn is_accelerator_record(record: &TaskQueueRecord) -> bool { matches!( record.job.data.job_type, - JobType::Asr | JobType::ImageGen | JobType::ImageEdit + JobType::Asr | JobType::ImageGen | JobType::ImageEdit | JobType::VideoGen ) } @@ -3515,12 +3514,12 @@ fn compare_accelerator_records( } fn accelerator_effective_priority(record: &TaskQueueRecord, now: OffsetDateTime) -> Priority { - let is_vip_image = record.queue_name == IMAGE_VIP_QUEUE_NAME + let is_vip_media = record.queue_name == IMAGE_VIP_QUEUE_NAME && matches!( record.job.data.job_type, - JobType::ImageGen | JobType::ImageEdit + JobType::ImageGen | JobType::ImageEdit | JobType::VideoGen ); - let (base_priority, ceiling) = if is_vip_image { + let (base_priority, ceiling) = if is_vip_media { // The floor upgrades already-persisted priority-4 VIP jobs without rewriting queue state. ( record.job.priority.max(IMAGE_VIP_PRIORITY), @@ -3798,7 +3797,6 @@ pub fn fallback_queue_time_estimate(queue_name: &str, depth: usize) -> std::time } let base_secs = match queue_name { IMAGE_REGULAR_QUEUE_NAME | IMAGE_VIP_QUEUE_NAME | MUSIC_VIP_QUEUE_NAME => 8 * 60, - VIDEO_QUEUE_NAME => 60, CONTROL_QUEUE_NAME | TEXT_QUEUE_NAME => 2 * 60, _ => 5 * 60, }; @@ -3890,21 +3888,22 @@ mod tests { CONTROL_QUEUE_NAME, ControlJobData, ControlJobParams, ControlJobPayloadError, ControlKind, DEFAULT_PRIORITY, DIALOG_AIFARM_QUEUE_NAME, DialogJobData, DialogJobParams, DialogJobPayloadError, HIGH_PRIORITY, HIGHEST_PRIORITY, IMAGE_REGULAR_QUEUE_NAME, - IMAGE_VIP_QUEUE_NAME, ImageEditJobParams, ImageEditJobPayloadError, ImageGenJobParams, - ImageGenJobPayloadError, ImageJobData, InMemoryTaskQueue, JobPayload, JobStatus, JobType, - LOWEST_PRIORITY, MAX_JOB_EVENTS, MESSAGE_STATUS_COMPLETED, MESSAGE_STATUS_FAILED, - MESSAGE_STATUS_PLACEHOLDER, MESSAGE_TYPE_RESULT, MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, - MusicGenJobPayloadError, QUEUE_ESTIMATE_DEFAULT_SAMPLE_SIZE, - QUEUE_ESTIMATE_MIN_SAMPLE_SIZE, STUCK_JOB_ERROR_MESSAGE, TASK_QUEUE_SNAPSHOT_FORMAT, - TEXT_QUEUE_NAME, TaskQueueError, TaskQueueJobEvent, TaskQueueJobMessageParams, - TaskQueueRecord, TaskQueueSchedule, TaskQueueScheduleDisposition, TaskQueueWalRecord, - TaskQueueWalSink, accelerator_effective_priority, asr_job_params_from_stateless_job, + IMAGE_VIP_PRIORITY, IMAGE_VIP_QUEUE_NAME, ImageEditJobParams, ImageEditJobPayloadError, + ImageGenJobParams, ImageGenJobPayloadError, ImageJobData, InMemoryTaskQueue, JobPayload, + JobStatus, JobType, LOWEST_PRIORITY, MAX_JOB_EVENTS, MESSAGE_STATUS_COMPLETED, + MESSAGE_STATUS_FAILED, MESSAGE_STATUS_PLACEHOLDER, MESSAGE_TYPE_RESULT, + MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, MusicGenJobPayloadError, + QUEUE_ESTIMATE_DEFAULT_SAMPLE_SIZE, QUEUE_ESTIMATE_MIN_SAMPLE_SIZE, + STUCK_JOB_ERROR_MESSAGE, StatelessJobItem, TASK_QUEUE_SNAPSHOT_FORMAT, TEXT_QUEUE_NAME, + TaskQueueError, TaskQueueJobEvent, TaskQueueJobMessageParams, TaskQueueRecord, + TaskQueueSchedule, TaskQueueScheduleDisposition, TaskQueueWalRecord, TaskQueueWalSink, + VideoGenJobParams, accelerator_effective_priority, asr_job_params_from_stateless_job, decode_task_queue_snapshot, encode_task_queue_snapshot, fallback_queue_time_estimate, format_duration_ru, image_edit_job_params_from_stateless_job, image_gen_job_params_from_stateless_job, music_gen_job_params_from_stateless_job, new_agent_job_at, new_asr_job_at, new_control_job_at, new_dialog_job_at, new_image_edit_job_at, new_image_gen_job_at, new_memory_consolidation_job_at, - new_music_gen_job_at, replay_task_queue_wal_records, + new_music_gen_job_at, new_video_gen_job_at, replay_task_queue_wal_records, }; #[derive(Default)] @@ -5071,6 +5070,94 @@ mod tests { Ok(()) } + #[test] + fn clips_share_accelerator_arbitration_with_images() -> Result<(), Box> { + let now = OffsetDateTime::from_unix_timestamp(1_779_193_800)?; + let clip = |message_id| { + new_video_gen_job_at( + VideoGenJobParams { + chat_id: 1, + message_id, + user_id: 2, + brief: "cat".to_owned(), + ..VideoGenJobParams::default() + }, + now, + ) + }; + let picture = |message_id| { + new_image_gen_job_at( + ImageGenJobParams { + chat_id: 1, + message_id, + user_id: 2, + prompt: "cat".to_owned(), + ..ImageGenJobParams::default() + }, + now, + ) + }; + let is_media = |job: &StatelessJobItem| { + matches!(job.data.job_type, JobType::ImageGen | JobType::VideoGen) + }; + + let queue = InMemoryTaskQueue::new(); + queue.assign(IMAGE_REGULAR_QUEUE_NAME, picture(10)); + let vip_clip = queue.assign( + IMAGE_VIP_QUEUE_NAME, + clip(11).with_priority(IMAGE_VIP_PRIORITY), + ); + let vip_clip_record = queue.record(vip_clip).expect("VIP clip record"); + assert_eq!( + accelerator_effective_priority(&vip_clip_record, now), + IMAGE_VIP_PRIORITY + ); + assert!( + queue + .dequeue_matching(IMAGE_REGULAR_QUEUE_NAME, "regular-worker", now, is_media) + .is_none(), + "a waiting VIP clip must hold back regular images" + ); + assert_eq!( + queue + .dequeue_matching(IMAGE_VIP_QUEUE_NAME, "vip-worker", now, is_media) + .map(|work| work.id), + Some(vip_clip) + ); + assert!( + queue + .dequeue_matching(IMAGE_REGULAR_QUEUE_NAME, "regular-worker", now, is_media) + .is_none(), + "a running VIP clip must not render next to a regular image" + ); + + let regular = InMemoryTaskQueue::new(); + let first = regular.assign(IMAGE_REGULAR_QUEUE_NAME, clip(20)); + let second = regular.assign(IMAGE_REGULAR_QUEUE_NAME, picture(21)); + assert_eq!( + regular + .dequeue_matching(IMAGE_REGULAR_QUEUE_NAME, "regular-worker", now, is_media) + .map(|work| work.id), + Some(first), + "clips and images leave the shared queue in arrival order" + ); + assert_eq!( + regular + .dequeue_matching(IMAGE_REGULAR_QUEUE_NAME, "regular-worker", now, is_media) + .map(|work| work.id), + None, + "the image waits while the earlier clip renders" + ); + regular.complete(first, now)?; + assert_eq!( + regular + .dequeue_matching(IMAGE_REGULAR_QUEUE_NAME, "regular-worker", now, is_media) + .map(|work| work.id), + Some(second) + ); + Ok(()) + } + #[test] fn legacy_vip_priority_four_uses_new_claim_ceiling() -> Result<(), Box> { let now = OffsetDateTime::from_unix_timestamp(1_779_193_800)?; diff --git a/prompts/aifarm/system.prompt b/prompts/aifarm/system.prompt index ca1a0c8..2423014 100644 --- a/prompts/aifarm/system.prompt +++ b/prompts/aifarm/system.prompt @@ -10,7 +10,7 @@ Команды и разговорные шорткаты задают намерение пользователя: выполни соответствующее действие через инструмент. Прямая просьба нарисовать, сгенерировать, переделать или отредактировать изображение требует вызова draw_image (draw_api для %). Не заменяй действие рассуждением, описанием, обещанием или вопросом «начать?». По известному запросу сразу вызови инструмент; уточняй только недостающую деталь, без которой результат нельзя получить. Обычное рисование не требует предварительного get_user_status: исполнитель сам проверит доступ и лимиты. Действующие ограничения контента и результат инструмента сохраняют силу. Графики, диаграммы, схемы и планы по данным или размерам, таблицы, конвертацию файлов, обработку аудио и видео и точные расчёты делай через run_python: draw_image рисует иллюстрации, а не данные. Заголовки, подписи и текст на графиках пиши на языке собеседника. Чтобы поправить прежний результат run_python, возьми его код из истории и измени только то, о чём просят. - Для draw_image и draw_api всегда передавай caption: короткое название запрошенного изображения на языке пользователя. Убери обращение к боту, просьбу рисовать и слова вежливости. Сохрани смысл, имена и детали пользователя; название оформи естественно, с заглавной буквы. «Плотва, нарисуй собаквака» → caption «Собака-квака»; «Плотва, а нарисуй же мне, пожалуйста, золотую рыбку в кляре» → caption «Золотая рыбка в кляре». В prompt передавай отдельные, при необходимости обогащённые инструкции генератору. Не добавляй в caption придуманные для генератора детали и технический промпт. Если вызов вернул image_caption_required, добавь подпись и повтори вызов: генерация ещё не началась. + Для draw_image, draw_api и make_video всегда передавай caption: короткое название запрошенного изображения или ролика на языке пользователя. Убери обращение к боту, просьбу рисовать или сделать видео и слова вежливости. Сохрани смысл, имена и детали пользователя; название оформи естественно, с заглавной буквы. «Плотва, нарисуй собаквака» → caption «Собака-квака»; «Плотва, а нарисуй же мне, пожалуйста, золотую рыбку в кляре» → caption «Золотая рыбка в кляре». В prompt передавай отдельные, при необходимости обогащённые инструкции генератору. Не добавляй в caption придуманные для генератора детали и технический промпт. Если вызов вернул image_caption_required или video_caption_required, добавь подпись и повтори вызов: генерация ещё не началась. {{#ifEquals toolMode "native"}} From 19531586df4be798e7fc1bc76a7a8a5a17fcb230 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:42:25 +0100 Subject: [PATCH 2/2] Fail clips that no runner can render instead of blocking drawings A VideoGen ticket is accelerator work. Left pending after video generation is switched off, it would hold back every drawing ranked below it. Image generation workers now always take clips and fail them when no video runner is configured. --- crates/openplotva-app/src/image_jobs.rs | 74 +++++++++++++++++-------- 1 file changed, 50 insertions(+), 24 deletions(-) diff --git a/crates/openplotva-app/src/image_jobs.rs b/crates/openplotva-app/src/image_jobs.rs index 26b4f1e..fe98664 100644 --- a/crates/openplotva-app/src/image_jobs.rs +++ b/crates/openplotva-app/src/image_jobs.rs @@ -3261,7 +3261,7 @@ impl ImageEditWorkerRunReport { pub struct ImageQueuePollOptions<'a> { pub max_llm_job_attempts: i32, pub activity_pulse: Option<&'a TelegramActivityPulse>, - /// Takes `VideoGen` tickets from the same queue when set. + /// Renders `VideoGen` tickets from the same queue; without it they fail. pub video: Option<&'a dyn VideoJobRunner>, pub now: OffsetDateTime, } @@ -3283,7 +3283,7 @@ pub struct ImageWorkerRunOptions<'a> { pub interval: StdDuration, pub max_llm_job_attempts: i32, pub activity_pulse: Option<&'a TelegramActivityPulse>, - /// Takes `VideoGen` tickets from the same queues when set. + /// Renders `VideoGen` tickets from the same queues; without it they fail. pub video: Option<&'a dyn VideoJobRunner>, } @@ -3869,10 +3869,8 @@ where Generator: ImageGenerator + Sync, Effects: ImageJobEffects + Sync, { - let takes_clips = options.video.is_some(); let Some(work) = queue.dequeue_matching(queue_name, worker_id, options.now, |job| { - job.data.job_type == JobType::ImageGen - || (takes_clips && job.data.job_type == JobType::VideoGen) + matches!(job.data.job_type, JobType::ImageGen | JobType::VideoGen) }) else { return ImageGenQueuePollReport { queue_name: queue_name.to_owned(), @@ -3882,13 +3880,25 @@ where activity: TelegramActivitySnapshot::default(), }; }; - if let Some(video) = options.video - && work.job.data.job_type == JobType::VideoGen - { - let vip = queue_name == IMAGE_VIP_QUEUE_NAME; - let poll = video - .run_video_job(queue, work, vip, options.activity_pulse) - .await; + if work.job.data.job_type == JobType::VideoGen { + let poll = match options.video { + Some(video) => { + let vip = queue_name == IMAGE_VIP_QUEUE_NAME; + video + .run_video_job(queue, work, vip, options.activity_pulse) + .await + } + // A clip left over after video generation was switched off would otherwise + // hold back every drawing ranked below it. + None => { + let error = "video generation is disabled".to_owned(); + let _ = queue.fail(work.id, error.clone(), options.now); + VideoQueuePoll::Failed { + job_id: work.id, + error, + } + } + }; return video_poll_report(queue_name, poll); } @@ -5603,18 +5613,6 @@ mod tests { ] { let queue = InMemoryTaskQueue::new(); let clip = queued_clip(&queue, queue_name, now); - - let without_runner = run_image_gen_queue_once_with_max_attempts( - &queue, - queue_name, - &GeneratorStub::success("https://img.test/unused.png"), - &EffectsStub::new(), - "image-worker", - ImageQueuePollOptions::at(now), - ) - .await; - assert_eq!(without_runner.outcome, ImageGenQueuePollOutcome::Idle); - let report = run_image_gen_queue_once_with_max_attempts( &queue, queue_name, @@ -5633,6 +5631,34 @@ mod tests { } } + #[tokio::test] + async fn a_clip_left_after_video_is_switched_off_fails_instead_of_blocking_drawings() { + let now = OffsetDateTime::now_utc(); + let queue = InMemoryTaskQueue::new(); + let clip = queued_clip(&queue, IMAGE_REGULAR_QUEUE_NAME, now); + + let report = run_image_gen_queue_once_with_max_attempts( + &queue, + IMAGE_REGULAR_QUEUE_NAME, + &GeneratorStub::success("https://img.test/unused.png"), + &EffectsStub::new(), + "image-worker", + ImageQueuePollOptions::at(now), + ) + .await; + + assert_eq!(report.job_id, Some(clip)); + assert_eq!(report.outcome, ImageGenQueuePollOutcome::Failed); + assert_eq!( + report.error.as_deref(), + Some("video generation is disabled") + ); + assert_eq!( + queue.record(clip).map(|record| record.status), + Some(JobStatus::Failed) + ); + } + fn encode_solid_png(width: u32, height: u32, color: image::Rgba) -> Vec { let mut encoded = Cursor::new(Vec::new()); image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(width, height, color))