mirror of
https://github.com/block/buzz.git
synced 2026-11-28 20:22:39 +00:00
fix(desktop): optimize video upload pipeline
Co-authored-by: npub1rf6fvdj6ut0c4kcmjv4p5mmgh89nj58n69uu3fz3cvk3jn500hqs7emz79 <1a7496365ae2df8adb1b932a1a6f68b9cb3950f3d179c8a451c32d194e8f7dc1@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1rf6fvdj6ut0c4kcmjv4p5mmgh89nj58n69uu3fz3cvk3jn500hqs7emz79 <1a7496365ae2df8adb1b932a1a6f68b9cb3950f3d179c8a451c32d194e8f7dc1@sprout-oss.stage.blox.sqprod.co>
This commit is contained in:
parent
a26245b310
commit
e54e5fed1e
@@ -12,7 +12,7 @@ use crate::relay::{
|
||||
|
||||
use super::media_transcode::{
|
||||
has_heic_extension, is_heic_file, is_video_file, transcode_and_extract_poster,
|
||||
transcode_and_extract_poster_path, transcode_heic_path_to_jpeg_bytes,
|
||||
transcode_and_extract_poster_path, transcode_heic_path_to_jpeg_bytes, TranscodeProgress,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -383,7 +383,7 @@ async fn send_upload_attempt(
|
||||
sent += chunk.len() as u64;
|
||||
let _ = app.emit(
|
||||
"media-upload-progress",
|
||||
serde_json::json!({ "id": progress_id, "sent": sent, "total": total }),
|
||||
serde_json::json!({ "id": progress_id, "phase": "uploading", "sent": sent, "total": total }),
|
||||
);
|
||||
Ok::<bytes::Bytes, std::io::Error>(chunk)
|
||||
}));
|
||||
@@ -429,7 +429,7 @@ async fn send_upload_file_attempt(
|
||||
let sent = sent.fetch_add(bytes.len() as u64, Ordering::Relaxed) + bytes.len() as u64;
|
||||
let _ = app.emit(
|
||||
"media-upload-progress",
|
||||
serde_json::json!({ "id": progress_id, "sent": sent, "total": total }),
|
||||
serde_json::json!({ "id": progress_id, "phase": "uploading", "sent": sent, "total": total }),
|
||||
);
|
||||
}
|
||||
chunk
|
||||
@@ -632,6 +632,7 @@ pub(super) async fn process_picked_path(
|
||||
state: &State<'_, AppState>,
|
||||
images_only: bool,
|
||||
progress: Option<(tauri::AppHandle, String)>,
|
||||
cancel: Option<tokio_util::sync::CancellationToken>,
|
||||
) -> Result<BlobDescriptor, String> {
|
||||
// Pin the inode by opening the fd BEFORE spawn_blocking. This prevents a
|
||||
// local attacker from swapping the file between dialog return and read.
|
||||
@@ -643,6 +644,12 @@ pub(super) async fn process_picked_path(
|
||||
// the closure since `path` isn't moved in.
|
||||
let heic_by_ext = has_heic_extension(&path);
|
||||
|
||||
let transcode_progress = progress.as_ref().map(|(app, id)| TranscodeProgress {
|
||||
app: app.clone(),
|
||||
id: id.clone(),
|
||||
cancel,
|
||||
});
|
||||
|
||||
// All sync I/O (sniff, transcode, read) runs off the async runtime to
|
||||
// avoid blocking Tokio worker threads during long ffmpeg transcodes.
|
||||
let (prepared, poster_bytes) = tokio::task::spawn_blocking(
|
||||
@@ -657,7 +664,8 @@ pub(super) async fn process_picked_path(
|
||||
return Err("Please choose an image file.".to_string());
|
||||
}
|
||||
let fd_path = fd_real_path(&file)?;
|
||||
let (path, poster) = transcode_and_extract_poster_path(&fd_path)?;
|
||||
let (path, poster) =
|
||||
transcode_and_extract_poster_path(&fd_path, transcode_progress)?;
|
||||
drop(file);
|
||||
Ok((
|
||||
PreparedUpload::File {
|
||||
@@ -761,7 +769,7 @@ pub async fn pick_and_upload_media(
|
||||
let mut descriptors = Vec::with_capacity(file_paths.len());
|
||||
for file_path in file_paths {
|
||||
let path = file_path.as_path().ok_or("invalid path")?.to_path_buf();
|
||||
let descriptor = process_picked_path(path, &state, false, None).await?;
|
||||
let descriptor = process_picked_path(path, &state, false, None, None).await?;
|
||||
descriptors.push(descriptor);
|
||||
}
|
||||
|
||||
@@ -802,7 +810,7 @@ pub async fn pick_and_upload_image(
|
||||
};
|
||||
|
||||
let path = file_path.as_path().ok_or("invalid path")?.to_path_buf();
|
||||
let descriptor = process_picked_path(path, &state, true, None).await?;
|
||||
let descriptor = process_picked_path(path, &state, true, None, None).await?;
|
||||
Ok(Some(descriptor))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use tauri::State;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::app_state::AppState;
|
||||
|
||||
use super::media::{process_picked_path, sanitize_filename, BlobDescriptor};
|
||||
|
||||
fn active_uploads() -> &'static Mutex<std::collections::HashMap<String, CancellationToken>> {
|
||||
static ACTIVE: OnceLock<Mutex<std::collections::HashMap<String, CancellationToken>>> =
|
||||
OnceLock::new();
|
||||
ACTIVE.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn begin_staged_media_upload() -> Result<String, String> {
|
||||
let upload_id = uuid::Uuid::new_v4().to_string();
|
||||
@@ -23,18 +32,38 @@ fn staged_upload_path(upload_id: &str) -> Result<std::path::PathBuf, String> {
|
||||
Ok(std::env::temp_dir().join(format!("buzz-staged-upload-{parsed}")))
|
||||
}
|
||||
|
||||
/// Append one chunk to a staged upload.
|
||||
///
|
||||
/// The chunk rides Tauri's **raw binary IPC** (the request body is an
|
||||
/// `ArrayBuffer`, not a JSON `number[]`). The old JSON path turned every
|
||||
/// megabyte into a ~1M-element JS array + `JSON.stringify`/parse on the
|
||||
/// webview's render thread, which visibly janked typing during an upload.
|
||||
/// The `upload_id` travels as a request header so the body stays pure bytes.
|
||||
#[tauri::command]
|
||||
pub async fn append_staged_media_chunk(upload_id: String, data: Vec<u8>) -> Result<(), String> {
|
||||
pub async fn append_staged_media_chunk(request: tauri::ipc::Request<'_>) -> Result<(), String> {
|
||||
let upload_id = request
|
||||
.headers()
|
||||
.get("upload-id")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or("missing upload-id header")?;
|
||||
|
||||
let data = match request.body() {
|
||||
tauri::ipc::InvokeBody::Raw(bytes) => bytes.as_slice(),
|
||||
tauri::ipc::InvokeBody::Json(_) => {
|
||||
return Err("staged chunk must be sent as raw bytes".to_string())
|
||||
}
|
||||
};
|
||||
if data.is_empty() || data.len() > 1024 * 1024 {
|
||||
return Err("upload chunk must contain 1 byte to 1 MiB".to_string());
|
||||
}
|
||||
let path = staged_upload_path(&upload_id)?;
|
||||
|
||||
let path = staged_upload_path(upload_id)?;
|
||||
let mut file = tokio::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(path)
|
||||
.await
|
||||
.map_err(|e| format!("failed to open staged upload: {e}"))?;
|
||||
file.write_all(&data)
|
||||
file.write_all(data)
|
||||
.await
|
||||
.map_err(|e| format!("failed to write staged upload: {e}"))
|
||||
}
|
||||
@@ -42,6 +71,13 @@ pub async fn append_staged_media_chunk(upload_id: String, data: Vec<u8>) -> Resu
|
||||
#[tauri::command]
|
||||
pub async fn cancel_staged_media_upload(upload_id: String) -> Result<(), String> {
|
||||
let path = staged_upload_path(&upload_id)?;
|
||||
if let Some(cancel) = active_uploads()
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.get(&upload_id)
|
||||
{
|
||||
cancel.cancel();
|
||||
}
|
||||
match tokio::fs::remove_file(path).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
@@ -59,7 +95,16 @@ pub async fn finish_staged_media_upload(
|
||||
) -> Result<BlobDescriptor, String> {
|
||||
let path = staged_upload_path(&upload_id)?;
|
||||
let progress = progress_id.map(|id| (app, id));
|
||||
let result = process_picked_path(path.clone(), &state, false, progress).await;
|
||||
let cancel = CancellationToken::new();
|
||||
active_uploads()
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.insert(upload_id.clone(), cancel.clone());
|
||||
let result = process_picked_path(path.clone(), &state, false, progress, Some(cancel)).await;
|
||||
active_uploads()
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.remove(&upload_id);
|
||||
let _ = tokio::fs::remove_file(path).await;
|
||||
let mut descriptor = result?;
|
||||
descriptor.filename = filename.as_deref().map(sanitize_filename);
|
||||
|
||||
@@ -173,85 +173,215 @@ pub(super) fn run_ffmpeg_with_timeout(
|
||||
}
|
||||
}
|
||||
|
||||
/// Transcode any video file to H.264/AAC/MP4/fast-start via ffmpeg.
|
||||
/// Correlates ffmpeg progress with one renderer upload job.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct TranscodeProgress {
|
||||
pub app: tauri::AppHandle,
|
||||
pub id: String,
|
||||
pub cancel: Option<tokio_util::sync::CancellationToken>,
|
||||
}
|
||||
|
||||
fn probe_video_duration(source: &std::path::Path) -> Option<f64> {
|
||||
let ffprobe = resolve_command("ffprobe")?;
|
||||
let output = ffmpeg_command(&ffprobe)
|
||||
.args([
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration",
|
||||
"-of",
|
||||
"default=noprint_wrappers=1:nokey=1",
|
||||
])
|
||||
.arg(source)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()?
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|seconds| seconds.is_finite() && *seconds > 0.0)
|
||||
}
|
||||
|
||||
fn emit_transcode_progress(progress: &TranscodeProgress, processed_us: u64, total_us: u64) {
|
||||
use tauri::Emitter;
|
||||
let _ = progress.app.emit(
|
||||
"media-upload-progress",
|
||||
serde_json::json!({
|
||||
"id": progress.id,
|
||||
"phase": "processing",
|
||||
"sent": processed_us.min(total_us),
|
||||
"total": total_us,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Transcode any video file to a web-compatible, size-efficient MP4.
|
||||
///
|
||||
/// Always re-encodes — handles HEVC, VP9, ProRes, non-faststart MP4, 10-bit,
|
||||
/// wrong pixel format, MOV containers, etc. Output is guaranteed to pass the
|
||||
/// relay's `validate_video_file()`.
|
||||
/// Video is capped at 1920×1080 without upscaling, encoded as H.264 CRF 24
|
||||
/// with AAC audio, and stripped of source metadata. H.264/AAC is deliberately
|
||||
/// preferred over smaller but less interoperable HEVC/AV1 output because the
|
||||
/// result must play in every supported Buzz webview and browser.
|
||||
///
|
||||
/// Returns the path to a temp file. Caller must clean up.
|
||||
pub(super) fn transcode_to_mp4(
|
||||
source: &std::path::Path,
|
||||
ffmpeg: &std::path::Path,
|
||||
progress: Option<TranscodeProgress>,
|
||||
) -> Result<std::path::PathBuf, String> {
|
||||
// UUID-based temp path — unique across concurrent uploads.
|
||||
let output = std::env::temp_dir().join(format!("buzz-transcode-{}.mp4", uuid::Uuid::new_v4()));
|
||||
let duration_us = probe_video_duration(source).map(|seconds| (seconds * 1_000_000.0) as u64);
|
||||
|
||||
let result = run_ffmpeg_with_timeout(
|
||||
ffmpeg_command(ffmpeg)
|
||||
.args([
|
||||
"-y",
|
||||
"-nostdin",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-protocol_whitelist",
|
||||
"file,pipe",
|
||||
]) // suppress progress spam — prevents stderr pipe deadlock
|
||||
.arg("-i")
|
||||
.arg(source) // OsStr — handles non-UTF-8 paths on Unix
|
||||
.args([
|
||||
"-map",
|
||||
"0:v:0",
|
||||
"-map",
|
||||
"0:a:0?",
|
||||
"-map_metadata",
|
||||
"-1",
|
||||
"-map_chapters",
|
||||
"-1",
|
||||
"-sn",
|
||||
"-dn",
|
||||
"-fflags",
|
||||
"+bitexact",
|
||||
"-flags:v",
|
||||
"+bitexact",
|
||||
"-flags:a",
|
||||
"+bitexact",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"fast",
|
||||
"-crf",
|
||||
"23",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-vf",
|
||||
"pad=ceil(iw/2)*2:ceil(ih/2)*2",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"128k",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-metadata",
|
||||
"encoder=",
|
||||
])
|
||||
.arg(&output)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped()),
|
||||
FFMPEG_TIMEOUT,
|
||||
)?;
|
||||
let mut command = ffmpeg_command(ffmpeg);
|
||||
command
|
||||
.args([
|
||||
"-y",
|
||||
"-nostdin",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-nostats",
|
||||
"-protocol_whitelist",
|
||||
"file,pipe",
|
||||
])
|
||||
.arg("-i")
|
||||
.arg(source)
|
||||
.args([
|
||||
"-map",
|
||||
"0:v:0",
|
||||
"-map",
|
||||
"0:a:0?",
|
||||
"-map_metadata",
|
||||
"-1",
|
||||
"-map_chapters",
|
||||
"-1",
|
||||
"-sn",
|
||||
"-dn",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"medium",
|
||||
"-crf",
|
||||
"24",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-vf",
|
||||
"scale=w=min(1920\\,iw):h=min(1080\\,ih):force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"96k",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-metadata",
|
||||
"encoder=",
|
||||
"-progress",
|
||||
"pipe:1",
|
||||
])
|
||||
.arg(&output)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
|
||||
if !result.status.success() {
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| format!("failed to spawn ffmpeg: {e}"))?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or("failed to read ffmpeg progress")?;
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.ok_or("failed to read ffmpeg diagnostics")?;
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
use std::io::BufRead;
|
||||
for line in std::io::BufReader::new(stdout)
|
||||
.lines()
|
||||
.map_while(Result::ok)
|
||||
{
|
||||
if let Some(value) = line.strip_prefix("out_time_us=") {
|
||||
if let Ok(value) = value.parse::<u64>() {
|
||||
let _ = tx.send(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let stderr_reader = std::thread::spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
let mut pipe = stderr;
|
||||
let _ = std::io::Read::read_to_end(&mut pipe, &mut bytes);
|
||||
bytes
|
||||
});
|
||||
|
||||
let deadline = std::time::Instant::now() + FFMPEG_TIMEOUT;
|
||||
let mut last_percent = u64::MAX;
|
||||
let status = loop {
|
||||
while let Ok(processed_us) = rx.try_recv() {
|
||||
if let (Some(progress), Some(total_us)) = (&progress, duration_us) {
|
||||
let percent = processed_us.saturating_mul(100) / total_us.max(1);
|
||||
if percent != last_percent {
|
||||
last_percent = percent;
|
||||
emit_transcode_progress(progress, processed_us, total_us);
|
||||
}
|
||||
}
|
||||
}
|
||||
if progress
|
||||
.as_ref()
|
||||
.and_then(|progress| progress.cancel.as_ref())
|
||||
.is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
|
||||
{
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = reader.join();
|
||||
let _ = stderr_reader.join();
|
||||
let _ = std::fs::remove_file(&output);
|
||||
return Err("Video conversion canceled".to_string());
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) if std::time::Instant::now() <= deadline => {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
Ok(None) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = reader.join();
|
||||
let _ = stderr_reader.join();
|
||||
let _ = std::fs::remove_file(&output);
|
||||
return Err(format!(
|
||||
"ffmpeg timed out after {}s",
|
||||
FFMPEG_TIMEOUT.as_secs()
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = reader.join();
|
||||
let _ = stderr_reader.join();
|
||||
let _ = std::fs::remove_file(&output);
|
||||
return Err(format!("failed to wait on ffmpeg: {error}"));
|
||||
}
|
||||
}
|
||||
};
|
||||
let _ = reader.join();
|
||||
let stderr = stderr_reader.join().unwrap_or_default();
|
||||
|
||||
if !status.success() {
|
||||
let _ = std::fs::remove_file(&output);
|
||||
let stderr = String::from_utf8_lossy(&result.stderr);
|
||||
let stderr = String::from_utf8_lossy(&stderr);
|
||||
let detail = stderr
|
||||
.lines()
|
||||
.rev()
|
||||
.find(|l| !l.is_empty() && !l.starts_with(" "))
|
||||
.find(|line| !line.is_empty() && !line.starts_with(" "))
|
||||
.unwrap_or("unknown error");
|
||||
return Err(format!("Video conversion failed: {detail}"));
|
||||
}
|
||||
|
||||
if let (Some(progress), Some(total_us)) = (&progress, duration_us) {
|
||||
emit_transcode_progress(progress, total_us, total_us);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
@@ -417,9 +547,10 @@ pub(super) fn extract_poster_frame(
|
||||
/// best-effort because the video remains usable without a thumbnail.
|
||||
pub(super) fn transcode_and_extract_poster_path(
|
||||
source: &std::path::Path,
|
||||
progress: Option<TranscodeProgress>,
|
||||
) -> Result<(std::path::PathBuf, Option<Vec<u8>>), String> {
|
||||
let ffmpeg_path = find_ffmpeg()?;
|
||||
let transcoded = transcode_to_mp4(source, &ffmpeg_path)?;
|
||||
let transcoded = transcode_to_mp4(source, &ffmpeg_path, progress)?;
|
||||
|
||||
let poster_bytes = match extract_poster_frame(&transcoded, &ffmpeg_path) {
|
||||
Ok(poster_path) => {
|
||||
@@ -440,7 +571,7 @@ pub(super) fn transcode_and_extract_poster_path(
|
||||
pub(super) fn transcode_and_extract_poster(
|
||||
source: &std::path::Path,
|
||||
) -> Result<(Vec<u8>, Option<Vec<u8>>), String> {
|
||||
let (transcoded, poster_bytes) = transcode_and_extract_poster_path(source)?;
|
||||
let (transcoded, poster_bytes) = transcode_and_extract_poster_path(source, None)?;
|
||||
let video_bytes =
|
||||
std::fs::read(&transcoded).map_err(|e| format!("failed to read transcoded file: {e}"));
|
||||
let _ = std::fs::remove_file(&transcoded);
|
||||
@@ -576,6 +707,55 @@ mod tests {
|
||||
assert!(!has_heic_extension(Path::new("noextension")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transcode_to_mp4_caps_at_1080p_without_upscaling() {
|
||||
let Ok(ffmpeg) = find_ffmpeg() else {
|
||||
eprintln!("skipping dimension round-trip: ffmpeg not found");
|
||||
return;
|
||||
};
|
||||
let Some(ffprobe) = resolve_command("ffprobe") else {
|
||||
eprintln!("skipping dimension round-trip: ffprobe not found");
|
||||
return;
|
||||
};
|
||||
let source =
|
||||
std::env::temp_dir().join(format!("buzz-dimension-test-{}.mp4", uuid::Uuid::new_v4()));
|
||||
let generated = std::process::Command::new(&ffmpeg)
|
||||
.args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"])
|
||||
.arg("color=c=blue:s=2560x1440:r=1:d=0.1")
|
||||
.args(["-frames:v", "1", "-c:v", "libx264"])
|
||||
.arg(&source)
|
||||
.output()
|
||||
.expect("generate oversized fixture");
|
||||
if !generated.status.success() {
|
||||
eprintln!("skipping dimension round-trip: ffmpeg cannot encode H.264");
|
||||
let _ = std::fs::remove_file(&source);
|
||||
return;
|
||||
}
|
||||
|
||||
let output = transcode_to_mp4(&source, &ffmpeg, None).expect("transcode fixture");
|
||||
let dimensions = std::process::Command::new(ffprobe)
|
||||
.args([
|
||||
"-v",
|
||||
"error",
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=width,height",
|
||||
"-of",
|
||||
"csv=s=x:p=0",
|
||||
])
|
||||
.arg(&output)
|
||||
.output()
|
||||
.expect("probe output dimensions");
|
||||
let _ = std::fs::remove_file(&source);
|
||||
let _ = std::fs::remove_file(&output);
|
||||
assert!(dimensions.status.success());
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&dimensions.stdout).trim(),
|
||||
"1920x1080"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transcode_to_mp4_drops_source_metadata() {
|
||||
let Ok(ffmpeg) = find_ffmpeg() else {
|
||||
@@ -606,7 +786,7 @@ mod tests {
|
||||
return;
|
||||
}
|
||||
|
||||
let output = transcode_to_mp4(&source, &ffmpeg).expect("transcode fixture");
|
||||
let output = transcode_to_mp4(&source, &ffmpeg, None).expect("transcode fixture");
|
||||
let bytes = std::fs::read(&output).expect("read transcoded video");
|
||||
let _ = std::fs::remove_file(&source);
|
||||
let _ = std::fs::remove_file(&output);
|
||||
|
||||
@@ -29,6 +29,7 @@ import { msgContextKey } from "@/features/channels/readState/readStateFormat";
|
||||
import { useMembershipNotifications } from "@/features/channels/useMembershipNotifications";
|
||||
import { useFeedItemState } from "@/features/home/useFeedItemState";
|
||||
import { useThreadFollows } from "@/features/messages/lib/useThreadFollows";
|
||||
import { UploadIndicator } from "@/features/messages/ui/UploadIndicator";
|
||||
import {
|
||||
useHomeFeedNotifications,
|
||||
useHomeFeedNotificationState,
|
||||
@@ -89,7 +90,6 @@ import { useMessageDeepLinks } from "@/shared/useMessageDeepLinks";
|
||||
import { SidebarInset, SidebarProvider } from "@/shared/ui/sidebar";
|
||||
import { RelayConnectionOverlay } from "@/app/RelayConnectionOverlay";
|
||||
import { useSidebarRelayConnectionCard } from "@/features/sidebar/ui/useSidebarRelayConnectionCard";
|
||||
|
||||
const LazySettingsScreen = React.lazy(async () => {
|
||||
const module = await import("@/features/settings/ui/SettingsScreen");
|
||||
return { default: module.SettingsScreen };
|
||||
@@ -153,7 +153,6 @@ export function AppShell() {
|
||||
() => deriveShellRoute(location.pathname),
|
||||
[location.pathname],
|
||||
);
|
||||
// Settings lives in history so back returns to the previous app entry.
|
||||
const settingsOpen = location.pathname === "/settings";
|
||||
const locationSearchSection = (location.search as { section?: unknown })
|
||||
.section;
|
||||
@@ -757,6 +756,7 @@ export function AppShell() {
|
||||
className="buzz-huddle-shell relative h-dvh overflow-hidden overscroll-none"
|
||||
data-huddle-open={isHuddleDrawerOpen}
|
||||
>
|
||||
<UploadIndicator onOpenChannel={goChannel} />
|
||||
<div
|
||||
className={cn(
|
||||
"buzz-huddle-app-surface z-10 flex min-h-0 flex-row overflow-hidden bg-background",
|
||||
|
||||
@@ -174,7 +174,7 @@ export const ChannelPane = React.memo(function ChannelPane({
|
||||
activeChannel,
|
||||
currentPubkey,
|
||||
);
|
||||
const mainComposerMedia = useMediaUpload();
|
||||
const mainComposerMedia = useMediaUpload(activeChannel?.id ?? null);
|
||||
const isNonMemberView =
|
||||
activeChannel !== null &&
|
||||
!activeChannel.isMember &&
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getOverrides } from "@/shared/features";
|
||||
import { resetMediaCaches } from "@/shared/lib/mediaUrl";
|
||||
import { clearSearchHitEventCache } from "@/app/navigation/searchHitEventCache";
|
||||
import { initDraftStore } from "@/features/messages/lib/useDrafts";
|
||||
import { resetUploadJobs } from "@/features/messages/lib/uploadJobsStore";
|
||||
import { resetRenderScopedReactionHydration } from "@/features/messages/lib/renderScopedReactions";
|
||||
import {
|
||||
resetActiveAgentTurnsStore,
|
||||
@@ -40,6 +41,7 @@ function resetCommunityState(): void {
|
||||
resetRenderScopedReactionHydration();
|
||||
clearSearchHitEventCache();
|
||||
clearMarkdownNodeCache();
|
||||
resetUploadJobs();
|
||||
}
|
||||
|
||||
type CommunityInitResult =
|
||||
|
||||
391
desktop/src/features/messages/lib/uploadJobsStore.ts
Normal file
391
desktop/src/features/messages/lib/uploadJobsStore.ts
Normal file
@@ -0,0 +1,391 @@
|
||||
import * as React from "react";
|
||||
|
||||
import {
|
||||
type BlobDescriptor,
|
||||
appendStagedMediaChunk,
|
||||
beginStagedMediaUpload,
|
||||
cancelStagedMediaUpload,
|
||||
finishStagedMediaUpload,
|
||||
} from "@/shared/api/tauri";
|
||||
|
||||
import { captureVideoPosterFrame } from "./videoPoster";
|
||||
|
||||
/**
|
||||
* Background upload-jobs store.
|
||||
*
|
||||
* Media uploads used to live in component-local state inside `useMediaUpload`,
|
||||
* so an in-flight upload's spinner vanished the moment you navigated away from
|
||||
* its channel, and its completion (the descriptor) was written into unmounted
|
||||
* state and lost. This module hoists the whole upload lifecycle into a
|
||||
* workspace-scoped singleton:
|
||||
*
|
||||
* • The upload **driver** (stage → transcode/upload) runs here, independent of
|
||||
* any React component, so it survives navigation.
|
||||
* • Each job is tagged with the `channelId` it was started in. The composer
|
||||
* renders only its own channel's jobs, so uploads stay attached to the
|
||||
* entry field where they began and never follow you to another channel.
|
||||
* • Finished descriptors land in a per-channel completion buffer; the composer
|
||||
* drains it on mount (or immediately, if already mounted), so a video that
|
||||
* finishes while you're elsewhere is waiting in the right composer when you
|
||||
* return.
|
||||
* • A channel-independent indicator can subscribe to *all* active jobs.
|
||||
*
|
||||
* Reset on community switch via `resetUploadJobs()` (wired into
|
||||
* `resetCommunityState`), matching the other workspace-scoped singletons.
|
||||
*/
|
||||
|
||||
const MEDIA_UPLOAD_CHUNK_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Store job ids live in a high numeric range so they never collide with the
|
||||
* composer's own small, per-mount preview ids. `cancelUpload` routes by range,
|
||||
* which lets store-driven previews and local (annotation/paperclip) previews
|
||||
* share the numeric `UploadingAttachmentPreview.id` space without a refactor.
|
||||
*/
|
||||
export const UPLOAD_JOB_ID_BASE = 1_000_000_000;
|
||||
|
||||
export type UploadPhase =
|
||||
| "reading"
|
||||
| "processing"
|
||||
| "uploading"
|
||||
| "done"
|
||||
| "error";
|
||||
|
||||
export type UploadJob = {
|
||||
/** Numeric id ≥ UPLOAD_JOB_ID_BASE (see note above). */
|
||||
id: number;
|
||||
channelId: string;
|
||||
filename: string;
|
||||
mediaType: string;
|
||||
posterUrl?: string;
|
||||
/** Monotonic 0–100. */
|
||||
pct: number;
|
||||
phase: UploadPhase;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type Completion = { jobId: number; descriptor: BlobDescriptor };
|
||||
|
||||
// ── Module state ─────────────────────────────────────────────────────────────
|
||||
let jobs = new Map<number, UploadJob>();
|
||||
let completedByChannel = new Map<string, Completion[]>();
|
||||
const canceledIds = new Set<number>();
|
||||
const uploadIdByJob = new Map<number, string>();
|
||||
let nextJobId = UPLOAD_JOB_ID_BASE;
|
||||
|
||||
// ── Reactivity (mirrors useDrafts' version-counter pattern) ──────────────────
|
||||
const subscribers = new Set<() => void>();
|
||||
let version = 0;
|
||||
|
||||
function bump(): void {
|
||||
version += 1;
|
||||
for (const sub of subscribers) sub();
|
||||
}
|
||||
|
||||
export function subscribeUploadJobs(callback: () => void): () => void {
|
||||
subscribers.add(callback);
|
||||
return () => {
|
||||
subscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export function getUploadJobsVersion(): number {
|
||||
return version;
|
||||
}
|
||||
|
||||
// ── Rust progress events → uploading phase ───────────────────────────────────
|
||||
let listenerReady = false;
|
||||
let unlisten: (() => void) | null = null;
|
||||
|
||||
/** Correlation id the Rust `media-upload-progress` events carry for a job. */
|
||||
function progressId(jobId: number): string {
|
||||
return `composer-upload-${jobId}`;
|
||||
}
|
||||
|
||||
function parseJobProgressId(id: string): number | null {
|
||||
const match = /^composer-upload-(\d+)$/.exec(id);
|
||||
if (!match) return null;
|
||||
const jobId = Number(match[1]);
|
||||
return jobId >= UPLOAD_JOB_ID_BASE ? jobId : null;
|
||||
}
|
||||
|
||||
function ensureProgressListener(): void {
|
||||
if (listenerReady) return;
|
||||
listenerReady = true;
|
||||
void (async () => {
|
||||
try {
|
||||
const { listen } = await import("@tauri-apps/api/event");
|
||||
const dispose = await listen<{
|
||||
id: string;
|
||||
phase?: "processing" | "uploading";
|
||||
sent: number;
|
||||
total: number;
|
||||
}>("media-upload-progress", (event) => {
|
||||
const { id, phase = "uploading", sent, total } = event.payload;
|
||||
if (total <= 0) return;
|
||||
const jobId = parseJobProgressId(id);
|
||||
if (jobId === null) return;
|
||||
const frac = Math.min(1, sent / total);
|
||||
if (phase === "processing") {
|
||||
// Staging is 0–10%; measured ffmpeg work occupies 10–80%.
|
||||
setPhasePct(jobId, "processing", 10 + frac * 70);
|
||||
} else {
|
||||
// Actual HTTP body bytes occupy 80–99%.
|
||||
setPhasePct(jobId, "uploading", 80 + frac * 19);
|
||||
}
|
||||
});
|
||||
if (listenerReady) {
|
||||
unlisten = dispose;
|
||||
} else {
|
||||
dispose();
|
||||
}
|
||||
} catch {
|
||||
// Non-Tauri runtime (web dev, e2e mock) — no byte-level progress.
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// ── Percentage model ─────────────────────────────────────────────────────────
|
||||
// Phases use measurements rather than pretending elapsed wall time is progress:
|
||||
// reading/staging → 0–10% (source bytes handed to Rust)
|
||||
// processing → 10–80% (ffmpeg out_time / probed duration)
|
||||
// uploading → 80–99% (actual HTTP bytes-sent / output size)
|
||||
// done → 100%
|
||||
function setPhasePct(jobId: number, phase: UploadPhase, pct: number): void {
|
||||
const job = jobs.get(jobId);
|
||||
if (!job) return;
|
||||
const next = Math.max(job.pct, Math.min(100, Math.round(pct)));
|
||||
if (job.phase === phase && job.pct === next) return;
|
||||
job.phase = phase;
|
||||
job.pct = next;
|
||||
bump();
|
||||
}
|
||||
|
||||
// ── The upload driver ────────────────────────────────────────────────────────
|
||||
const CANCELED = Symbol("upload-canceled");
|
||||
|
||||
async function runUpload(
|
||||
jobId: number,
|
||||
channelId: string,
|
||||
file: File,
|
||||
): Promise<void> {
|
||||
const total = file.size || 0;
|
||||
let uploadId: string | undefined;
|
||||
try {
|
||||
uploadId = await beginStagedMediaUpload();
|
||||
if (canceledIds.has(jobId)) throw CANCELED;
|
||||
uploadIdByJob.set(jobId, uploadId);
|
||||
|
||||
const reader = file.stream().getReader();
|
||||
let staged = 0;
|
||||
let pending = new Uint8Array(0);
|
||||
for (;;) {
|
||||
if (canceledIds.has(jobId)) throw CANCELED;
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
let bytes = value;
|
||||
if (pending.length > 0) {
|
||||
const combined = new Uint8Array(pending.length + value.length);
|
||||
combined.set(pending);
|
||||
combined.set(value, pending.length);
|
||||
bytes = combined;
|
||||
pending = new Uint8Array(0);
|
||||
}
|
||||
let offset = 0;
|
||||
while (bytes.length - offset >= MEDIA_UPLOAD_CHUNK_BYTES) {
|
||||
const chunk = bytes.subarray(offset, offset + MEDIA_UPLOAD_CHUNK_BYTES);
|
||||
await appendStagedMediaChunk(uploadId, chunk);
|
||||
staged += chunk.length;
|
||||
offset += MEDIA_UPLOAD_CHUNK_BYTES;
|
||||
if (total > 0) setPhasePct(jobId, "reading", (staged / total) * 10);
|
||||
}
|
||||
pending = bytes.slice(offset);
|
||||
}
|
||||
if (pending.length > 0) {
|
||||
await appendStagedMediaChunk(uploadId, pending);
|
||||
staged += pending.length;
|
||||
if (total > 0) setPhasePct(jobId, "reading", (staged / total) * 10);
|
||||
}
|
||||
|
||||
if (canceledIds.has(jobId)) throw CANCELED;
|
||||
setPhasePct(jobId, "processing", 10);
|
||||
|
||||
const descriptor = await finishStagedMediaUpload(
|
||||
uploadId,
|
||||
file.name,
|
||||
progressId(jobId),
|
||||
);
|
||||
if (canceledIds.has(jobId)) throw CANCELED;
|
||||
|
||||
const job = jobs.get(jobId);
|
||||
if (job) {
|
||||
job.phase = "done";
|
||||
job.pct = 100;
|
||||
}
|
||||
const list = completedByChannel.get(channelId) ?? [];
|
||||
list.push({ jobId, descriptor });
|
||||
completedByChannel.set(channelId, list);
|
||||
bump();
|
||||
} catch (error) {
|
||||
if (uploadId) await cancelStagedMediaUpload(uploadId);
|
||||
uploadIdByJob.delete(jobId);
|
||||
if (error === CANCELED || canceledIds.has(jobId)) {
|
||||
jobs.delete(jobId);
|
||||
canceledIds.delete(jobId);
|
||||
bump();
|
||||
return;
|
||||
}
|
||||
const job = jobs.get(jobId);
|
||||
if (job) {
|
||||
job.phase = "error";
|
||||
job.error = String(error);
|
||||
bump();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** Start a background upload for `file`, attached to `channelId`. Returns the job id. */
|
||||
export function startChannelUpload(channelId: string, file: File): number {
|
||||
ensureProgressListener();
|
||||
const id = ++nextJobId;
|
||||
jobs.set(id, {
|
||||
id,
|
||||
channelId,
|
||||
filename: file.name,
|
||||
mediaType: file.type,
|
||||
pct: 0,
|
||||
phase: "reading",
|
||||
});
|
||||
bump();
|
||||
|
||||
if (file.type.startsWith("video/")) {
|
||||
void captureVideoPosterFrame(file).then((poster) => {
|
||||
const job = jobs.get(id);
|
||||
if (poster && job) {
|
||||
job.posterUrl = poster.posterUrl;
|
||||
bump();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void runUpload(id, channelId, file);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Cancel a job — stops staging, deletes its temp file, discards any result. */
|
||||
export function cancelUploadJob(jobId: number): void {
|
||||
canceledIds.add(jobId);
|
||||
const uploadId = uploadIdByJob.get(jobId);
|
||||
if (uploadId) void cancelStagedMediaUpload(uploadId);
|
||||
const job = jobs.get(jobId);
|
||||
// If already terminal, the driver won't observe the flag — remove directly.
|
||||
if (job && (job.phase === "done" || job.phase === "error")) {
|
||||
jobs.delete(jobId);
|
||||
canceledIds.delete(jobId);
|
||||
dropCompletion(job.channelId, jobId);
|
||||
}
|
||||
bump();
|
||||
}
|
||||
|
||||
function dropCompletion(channelId: string, jobId: number): void {
|
||||
const list = completedByChannel.get(channelId);
|
||||
if (!list) return;
|
||||
const next = list.filter((c) => c.jobId !== jobId);
|
||||
if (next.length === 0) completedByChannel.delete(channelId);
|
||||
else completedByChannel.set(channelId, next);
|
||||
}
|
||||
|
||||
/** Jobs currently attached to `channelId` (excludes claimed/done). */
|
||||
export function getChannelUploadJobs(channelId: string): UploadJob[] {
|
||||
const out: UploadJob[] = [];
|
||||
for (const job of jobs.values()) {
|
||||
if (job.channelId === channelId && job.phase !== "done") out.push(job);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** All in-flight jobs across every channel (for the global indicator). */
|
||||
export function getActiveUploadJobs(): UploadJob[] {
|
||||
const out: UploadJob[] = [];
|
||||
for (const job of jobs.values()) {
|
||||
if (
|
||||
job.phase === "reading" ||
|
||||
job.phase === "processing" ||
|
||||
job.phase === "uploading"
|
||||
) {
|
||||
out.push(job);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Drain finished descriptors for a channel. Removes the drained jobs. */
|
||||
export function takeChannelCompletions(channelId: string): BlobDescriptor[] {
|
||||
const list = completedByChannel.get(channelId);
|
||||
if (!list || list.length === 0) return EMPTY_DESCRIPTORS;
|
||||
completedByChannel.delete(channelId);
|
||||
for (const { jobId } of list) jobs.delete(jobId);
|
||||
bump();
|
||||
return list.map((c) => c.descriptor);
|
||||
}
|
||||
|
||||
/** Drain errored jobs for a channel. Removes the drained jobs. */
|
||||
export function takeChannelErrors(channelId: string): string[] {
|
||||
const errors: string[] = [];
|
||||
const drained: number[] = [];
|
||||
for (const job of jobs.values()) {
|
||||
if (job.channelId === channelId && job.phase === "error") {
|
||||
errors.push(job.error ?? "Upload failed");
|
||||
drained.push(job.id);
|
||||
}
|
||||
}
|
||||
if (drained.length === 0) return EMPTY_ERRORS;
|
||||
for (const id of drained) jobs.delete(id);
|
||||
bump();
|
||||
return errors;
|
||||
}
|
||||
|
||||
const EMPTY_DESCRIPTORS: BlobDescriptor[] = [];
|
||||
const EMPTY_ERRORS: string[] = [];
|
||||
|
||||
/** Tear down on community switch. */
|
||||
export function resetUploadJobs(): void {
|
||||
jobs = new Map();
|
||||
completedByChannel = new Map();
|
||||
canceledIds.clear();
|
||||
uploadIdByJob.clear();
|
||||
nextJobId = UPLOAD_JOB_ID_BASE;
|
||||
if (unlisten) {
|
||||
unlisten();
|
||||
unlisten = null;
|
||||
}
|
||||
listenerReady = false;
|
||||
bump();
|
||||
}
|
||||
|
||||
// ── React hooks ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** Jobs for one channel, re-rendering as they progress. */
|
||||
export function useChannelUploadJobs(channelId: string | null): UploadJob[] {
|
||||
const v = React.useSyncExternalStore(
|
||||
subscribeUploadJobs,
|
||||
getUploadJobsVersion,
|
||||
);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: `v` (the store version) is the recompute trigger — the selector reads live module state.
|
||||
return React.useMemo(
|
||||
() => (channelId ? getChannelUploadJobs(channelId) : []),
|
||||
[channelId, v],
|
||||
);
|
||||
}
|
||||
|
||||
/** All active jobs, for the channel-independent indicator. */
|
||||
export function useActiveUploadJobs(): UploadJob[] {
|
||||
const v = React.useSyncExternalStore(
|
||||
subscribeUploadJobs,
|
||||
getUploadJobsVersion,
|
||||
);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: `v` (the store version) is the recompute trigger — the selector reads live module state.
|
||||
return React.useMemo(() => getActiveUploadJobs(), [v]);
|
||||
}
|
||||
@@ -4,9 +4,20 @@ import {
|
||||
type BlobDescriptor,
|
||||
pickAndUploadMedia,
|
||||
uploadMediaBytes,
|
||||
uploadMediaFile,
|
||||
} from "@/shared/api/tauri";
|
||||
|
||||
import { captureVideoPosterFrame } from "./videoPoster";
|
||||
import {
|
||||
UPLOAD_JOB_ID_BASE,
|
||||
cancelUploadJob,
|
||||
getUploadJobsVersion,
|
||||
startChannelUpload,
|
||||
subscribeUploadJobs,
|
||||
takeChannelCompletions,
|
||||
takeChannelErrors,
|
||||
useChannelUploadJobs,
|
||||
} from "./uploadJobsStore";
|
||||
|
||||
/**
|
||||
* First 4 hex chars of the sha256 — used as a short display name.
|
||||
* Note: 4 hex chars = 65,536 possible values. Collision is unlikely
|
||||
@@ -44,97 +55,14 @@ function isFileDrag(event: React.DragEvent<HTMLElement>): boolean {
|
||||
return event.dataTransfer?.types.includes("Files") ?? false;
|
||||
}
|
||||
|
||||
function waitForMediaEvent(
|
||||
element: HTMLMediaElement,
|
||||
eventName: string,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error(`Timed out waiting for ${eventName}`));
|
||||
}, timeoutMs);
|
||||
|
||||
function cleanup() {
|
||||
window.clearTimeout(timeoutId);
|
||||
element.removeEventListener(eventName, onEvent);
|
||||
element.removeEventListener("error", onError);
|
||||
}
|
||||
|
||||
function onEvent() {
|
||||
cleanup();
|
||||
resolve();
|
||||
}
|
||||
|
||||
function onError() {
|
||||
cleanup();
|
||||
reject(new Error(`Could not load media for ${eventName}`));
|
||||
}
|
||||
|
||||
element.addEventListener(eventName, onEvent, { once: true });
|
||||
element.addEventListener("error", onError, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
type CapturedVideoPoster = {
|
||||
dim: string;
|
||||
posterUrl: string;
|
||||
};
|
||||
|
||||
async function captureVideoPosterFrame(
|
||||
file: File,
|
||||
): Promise<CapturedVideoPoster | null> {
|
||||
if (!file.type.startsWith("video/")) return null;
|
||||
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
const video = document.createElement("video");
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.preload = "metadata";
|
||||
|
||||
try {
|
||||
video.src = objectUrl;
|
||||
await waitForMediaEvent(video, "loadedmetadata", 3_000);
|
||||
|
||||
const duration = Number.isFinite(video.duration) ? video.duration : 0;
|
||||
const seekTime = duration > 0.2 ? 0.1 : 0;
|
||||
if (seekTime > 0) {
|
||||
const seeked = waitForMediaEvent(video, "seeked", 2_000);
|
||||
video.currentTime = seekTime;
|
||||
await seeked.catch(() => undefined);
|
||||
} else if (video.readyState < 2) {
|
||||
await waitForMediaEvent(video, "loadeddata", 2_000).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
|
||||
if (video.videoWidth === 0 || video.videoHeight === 0) return null;
|
||||
|
||||
const maxWidth = 640;
|
||||
const scale = Math.min(1, maxWidth / video.videoWidth);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
|
||||
canvas.height = Math.max(1, Math.round(video.videoHeight * scale));
|
||||
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return null;
|
||||
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
return {
|
||||
dim: `${video.videoWidth}x${video.videoHeight}`,
|
||||
posterUrl: canvas.toDataURL("image/jpeg", 0.82),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
video.removeAttribute("src");
|
||||
video.load();
|
||||
}
|
||||
}
|
||||
|
||||
export function useMediaUpload() {
|
||||
/**
|
||||
* @param channelId The channel this composer is attached to. Background upload
|
||||
* jobs are keyed by it so in-flight uploads stay with the entry field where
|
||||
* they began, survive navigating away and back, and never follow you to
|
||||
* another channel. Falls back to a shared key when absent.
|
||||
*/
|
||||
export function useMediaUpload(channelId?: string | null) {
|
||||
const channelKey = channelId ?? "__composer__";
|
||||
const [uploadState, setUploadState] = React.useState<UploadState>({
|
||||
status: "idle",
|
||||
});
|
||||
@@ -250,6 +178,40 @@ export function useMediaUpload() {
|
||||
const nextSlotRef = React.useRef(0);
|
||||
const nextUploadingPreviewIdRef = React.useRef(0);
|
||||
|
||||
// ── Background upload jobs (drag/drop, paste, editor paste) ──────────────
|
||||
// These run in the workspace-scoped store, keyed by channel, so they survive
|
||||
// navigation and feed the global indicator. This composer renders only its
|
||||
// own channel's jobs and drains their finished descriptors into `imetaSlots`.
|
||||
const storeJobs = useChannelUploadJobs(channelId ?? null);
|
||||
const jobsVersion = React.useSyncExternalStore(
|
||||
subscribeUploadJobs,
|
||||
getUploadJobsVersion,
|
||||
);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: jobsVersion is the reactive trigger — it re-runs the drain whenever the store changes (mount, or a job finishing while this channel is open).
|
||||
React.useEffect(() => {
|
||||
const done = takeChannelCompletions(channelKey);
|
||||
if (done.length > 0) {
|
||||
nextSlotRef.current += done.length;
|
||||
setImetaSlots((prev) => [...prev, ...done]);
|
||||
}
|
||||
const errors = takeChannelErrors(channelKey);
|
||||
if (errors.length > 0) {
|
||||
setUploadState({ status: "error", message: errors[errors.length - 1] });
|
||||
}
|
||||
}, [channelKey, jobsVersion]);
|
||||
|
||||
const storePreviews = React.useMemo<UploadingAttachmentPreview[]>(
|
||||
() =>
|
||||
storeJobs.map((job) => ({
|
||||
id: job.id,
|
||||
filename: job.filename,
|
||||
type: job.mediaType,
|
||||
posterUrl: job.posterUrl,
|
||||
progress: job.pct,
|
||||
})),
|
||||
[storeJobs],
|
||||
);
|
||||
|
||||
const isUploadCanceled = React.useCallback(
|
||||
(previewId?: number) =>
|
||||
previewId !== undefined &&
|
||||
@@ -301,6 +263,12 @@ export function useMediaUpload() {
|
||||
|
||||
const cancelUpload = React.useCallback(
|
||||
(previewId: number) => {
|
||||
// Store-driven jobs live in a high id range — hand them to the store,
|
||||
// which aborts staging, deletes the temp file, and discards any result.
|
||||
if (previewId >= UPLOAD_JOB_ID_BASE) {
|
||||
cancelUploadJob(previewId);
|
||||
return;
|
||||
}
|
||||
canceledUploadingPreviewIdsRef.current.add(previewId);
|
||||
const slotIndex = uploadingPreviewsRef.current.find(
|
||||
(preview) => preview.id === previewId,
|
||||
@@ -318,46 +286,6 @@ export function useMediaUpload() {
|
||||
[finishUpload],
|
||||
);
|
||||
|
||||
/** Reserve `count` null slots at the end; returns the starting index. */
|
||||
const reserveSlots = React.useCallback((count: number): number => {
|
||||
const startIndex = nextSlotRef.current;
|
||||
nextSlotRef.current += count;
|
||||
setImetaSlots((prev) => {
|
||||
// Pad prev if needed (should already be the right length, but be safe)
|
||||
const padded =
|
||||
prev.length < startIndex
|
||||
? [...prev, ...new Array<null>(startIndex - prev.length).fill(null)]
|
||||
: prev;
|
||||
return [...padded, ...new Array<null>(count).fill(null)];
|
||||
});
|
||||
return startIndex;
|
||||
}, []);
|
||||
|
||||
/** Fill a previously-reserved slot by index. */
|
||||
const fillSlot = React.useCallback(
|
||||
(index: number, descriptor: BlobDescriptor, previewId?: number) => {
|
||||
if (isUploadCanceled(previewId)) return;
|
||||
setImetaSlots((prev) => {
|
||||
const next = [...prev];
|
||||
next[index] = descriptor;
|
||||
return next;
|
||||
});
|
||||
finishUpload(previewId);
|
||||
},
|
||||
[finishUpload, isUploadCanceled],
|
||||
);
|
||||
|
||||
/** Append a single descriptor (no pre-reserved slot). */
|
||||
const onUploaded = React.useCallback(
|
||||
(descriptor: BlobDescriptor, previewId?: number) => {
|
||||
if (isUploadCanceled(previewId)) return;
|
||||
nextSlotRef.current += 1;
|
||||
setImetaSlots((prev) => [...prev, descriptor]);
|
||||
finishUpload(previewId);
|
||||
},
|
||||
[finishUpload, isUploadCanceled],
|
||||
);
|
||||
|
||||
const onUploadError = React.useCallback(
|
||||
(err: unknown, previewId?: number) => {
|
||||
if (isUploadCanceled(previewId)) return;
|
||||
@@ -389,7 +317,7 @@ export function useMediaUpload() {
|
||||
}, [finishUpload, isUploadCanceled, onUploadError, reserveUploadingPreview]);
|
||||
|
||||
const handleDrop = React.useCallback(
|
||||
async (event: React.DragEvent<HTMLElement>) => {
|
||||
(event: React.DragEvent<HTMLElement>) => {
|
||||
event.preventDefault();
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOver(false);
|
||||
@@ -398,30 +326,14 @@ export function useMediaUpload() {
|
||||
|
||||
// Accept any file. The Tauri layer and the relay enforce the deny-list
|
||||
// (active-content + executables) and size caps; everything else uploads.
|
||||
const validFiles = files;
|
||||
|
||||
setUploadingCount((c) => c + validFiles.length);
|
||||
const baseIndex = reserveSlots(validFiles.length);
|
||||
|
||||
for (let i = 0; i < validFiles.length; i++) {
|
||||
const file = validFiles[i];
|
||||
const slotIndex = baseIndex + i;
|
||||
const previewId = reserveUploadingPreview(file, slotIndex);
|
||||
// Fire-and-forget each upload concurrently — slot preserves order
|
||||
(async () => {
|
||||
try {
|
||||
const descriptor = await uploadMediaFile(
|
||||
file,
|
||||
uploadProgressId(previewId),
|
||||
);
|
||||
fillSlot(slotIndex, descriptor, previewId);
|
||||
} catch (err) {
|
||||
onUploadError(err, previewId);
|
||||
}
|
||||
})();
|
||||
// Each upload becomes a background job attached to this channel — it runs
|
||||
// independent of this component's lifetime and its descriptor is drained
|
||||
// back into `imetaSlots` on completion.
|
||||
for (const file of files) {
|
||||
startChannelUpload(channelKey, file);
|
||||
}
|
||||
},
|
||||
[reserveSlots, fillSlot, onUploadError, reserveUploadingPreview],
|
||||
[channelKey],
|
||||
);
|
||||
|
||||
const handleDragEnter = React.useCallback(
|
||||
@@ -489,45 +401,19 @@ export function useMediaUpload() {
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
setUploadingCount((c) => c + mediaFiles.length);
|
||||
const baseIndex = reserveSlots(mediaFiles.length);
|
||||
|
||||
for (let i = 0; i < mediaFiles.length; i++) {
|
||||
const file = mediaFiles[i];
|
||||
const slotIndex = baseIndex + i;
|
||||
const previewId = reserveUploadingPreview(file, slotIndex);
|
||||
(async () => {
|
||||
try {
|
||||
const descriptor = await uploadMediaFile(
|
||||
file,
|
||||
uploadProgressId(previewId),
|
||||
);
|
||||
fillSlot(slotIndex, descriptor, previewId);
|
||||
} catch (err) {
|
||||
onUploadError(err, previewId);
|
||||
}
|
||||
})();
|
||||
for (const file of mediaFiles) {
|
||||
startChannelUpload(channelKey, file);
|
||||
}
|
||||
},
|
||||
[reserveSlots, fillSlot, onUploadError, reserveUploadingPreview],
|
||||
[channelKey],
|
||||
);
|
||||
|
||||
/** Upload a File directly — used by Tiptap's editorProps.handlePaste. */
|
||||
const uploadFile = React.useCallback(
|
||||
async (file: File) => {
|
||||
const previewId = reserveUploadingPreview(file);
|
||||
setUploadingCount((c) => c + 1);
|
||||
try {
|
||||
const descriptor = await uploadMediaFile(
|
||||
file,
|
||||
uploadProgressId(previewId),
|
||||
);
|
||||
onUploaded(descriptor, previewId);
|
||||
} catch (err) {
|
||||
onUploadError(err, previewId);
|
||||
}
|
||||
(file: File) => {
|
||||
startChannelUpload(channelKey, file);
|
||||
},
|
||||
[onUploaded, onUploadError, reserveUploadingPreview],
|
||||
[channelKey],
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -621,7 +507,14 @@ export function useMediaUpload() {
|
||||
[],
|
||||
);
|
||||
|
||||
const isUploading = uploadingCount > 0;
|
||||
// Local previews (annotation/paperclip) + background store jobs for this
|
||||
// channel. Store jobs carry ids ≥ UPLOAD_JOB_ID_BASE so they never collide.
|
||||
const allUploadingPreviews = React.useMemo(
|
||||
() => [...uploadingPreviews, ...storePreviews],
|
||||
[uploadingPreviews, storePreviews],
|
||||
);
|
||||
const totalUploadingCount = uploadingCount + storeJobs.length;
|
||||
const isUploading = totalUploadingCount > 0;
|
||||
|
||||
return React.useMemo(
|
||||
() => ({
|
||||
@@ -643,8 +536,8 @@ export function useMediaUpload() {
|
||||
setUploadState,
|
||||
uploadEditedAttachment,
|
||||
uploadFile,
|
||||
uploadingCount,
|
||||
uploadingPreviews,
|
||||
uploadingCount: totalUploadingCount,
|
||||
uploadingPreviews: allUploadingPreviews,
|
||||
uploadState,
|
||||
}),
|
||||
[
|
||||
@@ -664,8 +557,8 @@ export function useMediaUpload() {
|
||||
setPendingImeta,
|
||||
uploadEditedAttachment,
|
||||
uploadFile,
|
||||
uploadingCount,
|
||||
uploadingPreviews,
|
||||
totalUploadingCount,
|
||||
allUploadingPreviews,
|
||||
uploadState,
|
||||
],
|
||||
);
|
||||
|
||||
95
desktop/src/features/messages/lib/videoPoster.ts
Normal file
95
desktop/src/features/messages/lib/videoPoster.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Client-side video poster capture. Shared by the composer upload hook and the
|
||||
* background upload-jobs store so both can show a thumbnail while a video
|
||||
* uploads. Pure DOM helpers — no React, no Tauri.
|
||||
*/
|
||||
|
||||
function waitForMediaEvent(
|
||||
element: HTMLMediaElement,
|
||||
eventName: string,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error(`Timed out waiting for ${eventName}`));
|
||||
}, timeoutMs);
|
||||
|
||||
function cleanup() {
|
||||
window.clearTimeout(timeoutId);
|
||||
element.removeEventListener(eventName, onEvent);
|
||||
element.removeEventListener("error", onError);
|
||||
}
|
||||
|
||||
function onEvent() {
|
||||
cleanup();
|
||||
resolve();
|
||||
}
|
||||
|
||||
function onError() {
|
||||
cleanup();
|
||||
reject(new Error(`Could not load media for ${eventName}`));
|
||||
}
|
||||
|
||||
element.addEventListener(eventName, onEvent, { once: true });
|
||||
element.addEventListener("error", onError, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
export type CapturedVideoPoster = {
|
||||
dim: string;
|
||||
posterUrl: string;
|
||||
};
|
||||
|
||||
export async function captureVideoPosterFrame(
|
||||
file: File,
|
||||
): Promise<CapturedVideoPoster | null> {
|
||||
if (!file.type.startsWith("video/")) return null;
|
||||
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
const video = document.createElement("video");
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.preload = "metadata";
|
||||
|
||||
try {
|
||||
video.src = objectUrl;
|
||||
await waitForMediaEvent(video, "loadedmetadata", 3_000);
|
||||
|
||||
const duration = Number.isFinite(video.duration) ? video.duration : 0;
|
||||
const seekTime = duration > 0.2 ? 0.1 : 0;
|
||||
if (seekTime > 0) {
|
||||
const seeked = waitForMediaEvent(video, "seeked", 2_000);
|
||||
video.currentTime = seekTime;
|
||||
await seeked.catch(() => undefined);
|
||||
} else if (video.readyState < 2) {
|
||||
await waitForMediaEvent(video, "loadeddata", 2_000).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
|
||||
if (video.videoWidth === 0 || video.videoHeight === 0) return null;
|
||||
|
||||
const maxWidth = 640;
|
||||
const scale = Math.min(1, maxWidth / video.videoWidth);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
|
||||
canvas.height = Math.max(1, Math.round(video.videoHeight * scale));
|
||||
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return null;
|
||||
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
return {
|
||||
dim: `${video.videoWidth}x${video.videoHeight}`,
|
||||
posterUrl: canvas.toDataURL("image/jpeg", 0.82),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
video.removeAttribute("src");
|
||||
video.load();
|
||||
}
|
||||
}
|
||||
@@ -233,9 +233,9 @@ function MessageComposerImpl({
|
||||
typingRootEventId,
|
||||
);
|
||||
|
||||
// We pass a custom setter that both updates React state AND inserts
|
||||
// markdown into the Tiptap editor when media upload completes.
|
||||
const internalMedia = useMediaUpload();
|
||||
// When a parent supplies `mediaController`, its hook owns the channel jobs.
|
||||
// Keep this unconditional fallback off that channel to avoid double-draining.
|
||||
const internalMedia = useMediaUpload(mediaController ? null : channelId);
|
||||
const media = mediaController ?? internalMedia;
|
||||
const ownsDropZone = mediaController === undefined;
|
||||
|
||||
|
||||
48
desktop/src/features/messages/ui/UploadIndicator.tsx
Normal file
48
desktop/src/features/messages/ui/UploadIndicator.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { useActiveUploadJobs } from "@/features/messages/lib/uploadJobsStore";
|
||||
|
||||
type UploadIndicatorProps = {
|
||||
/** Jump to the channel an upload belongs to. */
|
||||
onOpenChannel: (channelId: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Channel-independent, always-mounted upload indicator.
|
||||
*
|
||||
* Uploads run in the workspace-scoped `uploadJobsStore`, not in any composer,
|
||||
* so this pill stays put while you navigate around. It shows aggregate
|
||||
* progress across every in-flight upload and, on click, opens the channel of
|
||||
* the oldest active one.
|
||||
*/
|
||||
export function UploadIndicator({ onOpenChannel }: UploadIndicatorProps) {
|
||||
const jobs = useActiveUploadJobs();
|
||||
if (jobs.length === 0) return null;
|
||||
|
||||
const pct = Math.round(
|
||||
jobs.reduce((sum, job) => sum + job.pct, 0) / jobs.length,
|
||||
);
|
||||
const label =
|
||||
jobs.length === 1
|
||||
? (jobs[0].filename ?? "Uploading…")
|
||||
: `Uploading ${jobs.length} files`;
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenChannel(jobs[0].channelId)}
|
||||
data-testid="global-upload-indicator"
|
||||
className={cn(
|
||||
"fixed bottom-4 right-4 z-50 flex items-center gap-2 rounded-full",
|
||||
"border border-border/60 bg-background/95 px-3 py-1.5 shadow-lg backdrop-blur",
|
||||
"text-sm text-foreground/90 transition-colors hover:bg-accent",
|
||||
)}
|
||||
title={`${label} — ${pct}%`}
|
||||
>
|
||||
<Loader2 className="size-4 animate-spin text-foreground/70" />
|
||||
<span className="max-w-40 truncate">{label}</span>
|
||||
<span className="tabular-nums text-foreground/60">{pct}%</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -559,17 +559,68 @@ export async function pickAndUploadMedia(): Promise<BlobDescriptor[]> {
|
||||
|
||||
const MEDIA_UPLOAD_CHUNK_BYTES = 1024 * 1024;
|
||||
|
||||
/** Open a staged upload slot in the OS temp dir; returns its id. */
|
||||
export async function beginStagedMediaUpload(): Promise<string> {
|
||||
return invokeTauri<string>("begin_staged_media_upload", {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Append one chunk of a staged upload as **raw bytes**.
|
||||
*
|
||||
* The chunk is sent over Tauri's binary IPC (an `ArrayBuffer` body) rather
|
||||
* than a JSON `number[]`. Serializing a ~1M-element array per megabyte on the
|
||||
* render thread was what janked typing during large uploads; raw bytes skip
|
||||
* that entirely. `uploadId` travels as a header so the body stays pure bytes.
|
||||
*/
|
||||
export async function appendStagedMediaChunk(
|
||||
uploadId: string,
|
||||
chunk: Uint8Array,
|
||||
): Promise<void> {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
// `.slice()` yields a tight copy backed by its own ArrayBuffer — a subarray
|
||||
// view would ship the entire underlying stream buffer.
|
||||
await invoke("append_staged_media_chunk", chunk.slice(), {
|
||||
headers: { "upload-id": uploadId },
|
||||
});
|
||||
}
|
||||
|
||||
/** Transcode + upload a completed staged file; returns its descriptor. */
|
||||
export async function finishStagedMediaUpload(
|
||||
uploadId: string,
|
||||
filename: string,
|
||||
progressId?: string,
|
||||
): Promise<BlobDescriptor> {
|
||||
return invokeTauri<BlobDescriptor>("finish_staged_media_upload", {
|
||||
uploadId,
|
||||
filename,
|
||||
progressId,
|
||||
});
|
||||
}
|
||||
|
||||
/** Delete a staged upload's temp file (cancel / cleanup). Best-effort. */
|
||||
export async function cancelStagedMediaUpload(uploadId: string): Promise<void> {
|
||||
await invokeTauri("cancel_staged_media_upload", { uploadId }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage a browser File in bounded chunks, then let Rust transcode and stream it.
|
||||
* This avoids materializing the entire file as a JS number array or Rust Vec.
|
||||
*
|
||||
* `onStaged` reports cumulative bytes handed to Rust so callers can render a
|
||||
* real "reading" phase before the HTTP upload (and its byte-level progress
|
||||
* events) begins.
|
||||
*/
|
||||
export async function uploadMediaFile(
|
||||
file: File,
|
||||
progressId?: string,
|
||||
onStaged?: (stagedBytes: number) => void,
|
||||
): Promise<BlobDescriptor> {
|
||||
const uploadId = await invokeTauri<string>("begin_staged_media_upload", {});
|
||||
const uploadId = await beginStagedMediaUpload();
|
||||
try {
|
||||
const reader = file.stream().getReader();
|
||||
let staged = 0;
|
||||
let pending = new Uint8Array(0);
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
@@ -584,31 +635,22 @@ export async function uploadMediaFile(
|
||||
}
|
||||
let offset = 0;
|
||||
while (bytes.length - offset >= MEDIA_UPLOAD_CHUNK_BYTES) {
|
||||
await invokeTauri("append_staged_media_chunk", {
|
||||
uploadId,
|
||||
data: Array.from(
|
||||
bytes.subarray(offset, offset + MEDIA_UPLOAD_CHUNK_BYTES),
|
||||
),
|
||||
});
|
||||
const chunk = bytes.subarray(offset, offset + MEDIA_UPLOAD_CHUNK_BYTES);
|
||||
await appendStagedMediaChunk(uploadId, chunk);
|
||||
staged += chunk.length;
|
||||
onStaged?.(staged);
|
||||
offset += MEDIA_UPLOAD_CHUNK_BYTES;
|
||||
}
|
||||
pending = bytes.slice(offset);
|
||||
}
|
||||
if (pending.length > 0) {
|
||||
await invokeTauri("append_staged_media_chunk", {
|
||||
uploadId,
|
||||
data: Array.from(pending),
|
||||
});
|
||||
await appendStagedMediaChunk(uploadId, pending);
|
||||
staged += pending.length;
|
||||
onStaged?.(staged);
|
||||
}
|
||||
return await invokeTauri<BlobDescriptor>("finish_staged_media_upload", {
|
||||
uploadId,
|
||||
filename: file.name,
|
||||
progressId,
|
||||
});
|
||||
return await finishStagedMediaUpload(uploadId, file.name, progressId);
|
||||
} catch (error) {
|
||||
await invokeTauri("cancel_staged_media_upload", { uploadId }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
await cancelStagedMediaUpload(uploadId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user