Compare commits

..
17 Commits
Author SHA1 Message Date
VallierDevandClaude Opus 5.5 25d8d0c915 Release v0.1.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:46:11 +08:00
VallierDevandClaude Opus 5.5 1a3348dfe9 Portal: keep the first valid frame on a fresh session (#2); CI builds wayland,portal
A new portal session started with was_locked=true, so the first unlocked
capture reset the cached frame. A static desktop delivers no new PipeWire
frame, so the viewer stayed black until something redrew. Only an observed
lock (or a closed stream) now discards the cached frame; an unknown lock
state shows a blank frame without clearing it.

CI now also builds and tests --features wayland,portal on ubuntu-24.04.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:45:47 +08:00
VallierDevandClaude Opus 5.5 bff7ad320e Release v0.1.2
GNOME fractional-scale pointer fix and portal clipboard recovery from the
VM workstream; known issues documented in the release notes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:13:27 +08:00
VallierDev 17978500e4 Add timed VM-only idle inhibition for active long-connection acceptance 2026-10-15 02:10:59 +08:00
VallierDev cc2df0fbd2 Count test-window key events without recording key values for active endurance 2026-10-15 02:10:59 +08:00
VallierDev 2ab33b88f0 Log only room-token remaining lifetime to diagnose cloud release timing 2026-10-15 02:10:59 +08:00
VallierDev 4e4062a4df Compare fixed clipboard markers in native UTF-8 and UTF-16 representations 2026-10-15 02:10:59 +08:00
VallierDev 73cc0a8cdd Audit receiver sequence progress and relay selection across the full endurance interval 2026-10-15 02:10:59 +08:00
VallierDev 6957d63671 Add native Mac marker-only clipboard acceptance fixture 2026-10-15 02:10:59 +08:00
VallierDev 66c8bb3249 Preserve granted clipboard capability across locked-session handshake and test closed state 2026-10-15 02:10:59 +08:00
VallierDev a18a69c19e Wait for GNOME portal recovery before deciding clipboard availability 2026-10-15 02:10:59 +08:00
VallierDev 050b8710a8 Fix GNOME fractional-scale absolute pointer coordinates and add precise GTK target probe 2026-10-15 02:10:59 +08:00
VallierDev 06946568b7 Record test-window pointer position to diagnose official coordinate mapping 2026-10-15 02:10:59 +08:00
VallierDev 4c2cd143f4 Use a denied GTK gesture to audit targets with supported introspection 2026-10-15 02:10:59 +08:00
VallierDev 2a295638d0 Observe GTK button targets without participating in gesture recognition 2026-10-15 02:10:59 +08:00
VallierDev 7e334bfe69 Separate portal input audit budgets and count native GTK button delivery 2026-10-15 02:10:59 +08:00
VallierDevandClaude Opus 5.5 ef697de387 Add bug report issue template with a diagnostics command
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 01:17:49 +08:00
21 changed files with 539 additions and 12 deletions

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
name: 问题反馈 / Bug report
description: 报告 bug 或使用问题 / Report a bug or problem
labels: [bug]
body:
- type: markdown
attributes:
value: |
感谢反馈!请尽量填写完整,否则我们很难定位问题。/ Thanks! Please fill in everything you can.
- type: textarea
id: problem
attributes:
label: 问题描述 / What happened
description: 做了什么操作、期望什么结果、实际发生了什么;能稳定复现吗?/ Steps, expected vs actual, reproducible?
validations:
required: true
- type: input
id: version
attributes:
label: 版本 / Version
description: Release 版本号(如 v0.1.1)或自己编译的提交号 / Release tag or commit
validations:
required: true
- type: dropdown
id: viewer
attributes:
label: 控制端 / Viewer
options: [Mac, Windows, iPhone / iPad, Android, 其他 / Other]
validations:
required: true
- type: textarea
id: diagnostics
attributes:
label: 诊断信息 / Diagnostics
description: |
先复现一次问题,然后在被控的 Linux 上运行下面的命令,把输出粘贴到这里(IP 会被自动抹掉,不包含密码、令牌或剪贴板内容)。
Reproduce the problem, then run this on the Linux host and paste the output (IPs are masked; no passwords, tokens or clipboard data).
```sh
{
echo "== 系统"; grep PRETTY_NAME /etc/os-release; uname -rm
echo "== 桌面"; echo "session=$XDG_SESSION_TYPE desktop=$XDG_CURRENT_DESKTOP"
echo "== 显示器"; xrandr --listmonitors 2>/dev/null
echo "== 缩放"; gsettings get org.gnome.desktop.interface scaling-factor 2>/dev/null; gsettings get org.gnome.mutter experimental-features 2>/dev/null
echo "== 显卡"; lspci 2>/dev/null | grep -iE 'vga|3d'
echo "== FFmpeg"; ffmpeg -hide_banner -encoders 2>/dev/null | grep -E 'h264_nvenc|libx264'
echo "== 日志"; journalctl --user -u uuremote-native.service --since "-30min" --no-pager -o cat \
| grep -E 'Starting|backend|Selected capture|Desktop encoder|Capture setting request|Desktop video settings|Offer for connection|WARN|ERROR' | tail -n 80
} 2>&1 | sed -E 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/x.x.x.x/g'
```
render: text
validations:
required: true
- type: textarea
id: extra
attributes:
label: 截图或补充说明 / Screenshots, notes
description: 显示缩放比例(如 125%)、多显示器、是否用 NVIDIA 显卡等 / Display scaling, multiple monitors, GPU, ...
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: true
+14
View File
@@ -18,3 +18,17 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --locked
test-wayland:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Install build dependencies (X11 + Wayland + portal)
run: |
sudo apt-get update
sudo apt-get install -y build-essential pkg-config \
libx11-dev libxext-dev libxtst-dev libxfixes-dev libgtk-3-dev \
libwayland-dev libxkbcommon-dev libglib2.0-dev libpipewire-0.3-dev
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --locked --features wayland,portal
Generated
+1 -1
View File
@@ -2487,7 +2487,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uu-remote-linux"
version = "0.1.1"
version = "0.1.3"
dependencies = [
"base64 0.22.1",
"bytes",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "uu-remote-linux"
version = "0.1.1"
version = "0.1.3"
edition = "2021"
authors = ["uu-remote-linux contributors"]
description = "Unofficial Linux host for NetEase UU Remote: control a Linux desktop from the official clients"
+1
View File
@@ -94,6 +94,7 @@ static void selection_transfer(GDBusConnection *bus,const gchar *sender,const gc
g_variant_new("(oub)",p->session,serial,success),NULL,G_DBUS_CALL_FLAGS_NONE,2000,NULL,NULL);
if (reply) g_variant_unref(reply);
}
int uu_portal_clipboard_supported(struct uu_portal *p) { return p && p->clipboard_enabled; }
int uu_portal_clipboard_ready(struct uu_portal *p) { return p && p->clipboard_enabled && uu_portal_alive(p); }
int uu_portal_clipboard_set(struct uu_portal *p,const uint8_t *text,size_t length) {
if (!uu_portal_clipboard_ready(p) || length>CLIP_LIMIT || !g_utf8_validate((const char *)text,(gssize)length,NULL)) return -1;
+13 -1
View File
@@ -46,6 +46,7 @@ struct uu_portal {
int error;
uint32_t node, width, height;
int logical_width, logical_height;
int absolute_stream_pixels;
enum spa_video_format format;
uint8_t *frame;
size_t frame_length;
@@ -271,6 +272,13 @@ struct uu_portal *uu_portal_open_persist(const char *restore, void (*save_token)
*error = 0; *width = *height = 0;
struct uu_portal *p = calloc(1, sizeof(*p));
if (!p) { *error = 8; return NULL; }
/* GNOME forwards NotifyPointerMotionAbsolute into Mutter's stream-to-stage
* transform. It expects stream pixels, unlike the compositor-sized KDE path.
* Do not apply the compositor scale twice on fractional-scale displays. */
gchar **desktops = g_strsplit(g_getenv("XDG_CURRENT_DESKTOP") ? g_getenv("XDG_CURRENT_DESKTOP") : "", ":", -1);
for (gchar **desktop = desktops; *desktop; desktop++)
if (!g_ascii_strcasecmp(*desktop, "GNOME")) p->absolute_stream_pixels = 1;
g_strfreev(desktops);
pthread_mutex_init(&p->lock, NULL); pthread_cond_init(&p->changed, NULL);
p->context = g_main_context_new(); g_main_context_push_thread_default(p->context);
p->bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
@@ -359,6 +367,9 @@ struct uu_portal *uu_portal_open_persist(const char *restore, void (*save_token)
p->dbus_started = 1;
*error = connect_pipewire(p);
if (*error) { uu_portal_close(p); return NULL; }
fprintf(stderr, "Portal pointer geometry: frame=%ux%u compositor=%dx%d absolute=%s\n",
p->width, p->height, p->logical_width, p->logical_height,
p->absolute_stream_pixels ? "stream-pixels" : "compositor-logical");
*width = p->width; *height = p->height;
return p;
done:
@@ -447,7 +458,8 @@ int uu_portal_move(struct uu_portal *p, double x, double y, int relative) {
x * p->logical_width / p->width, y * p->logical_height / p->height));
if (x < 0 || y < 0 || x >= p->width || y >= p->height) return 11;
return notify(p, "NotifyPointerMotionAbsolute", g_variant_new("(o@a{sv}udd)", p->session, empty_options(), p->node,
x * p->logical_width / p->width, y * p->logical_height / p->height));
p->absolute_stream_pixels ? x : x * p->logical_width / p->width,
p->absolute_stream_pixels ? y : y * p->logical_height / p->height));
}
int uu_portal_button(struct uu_portal *p, int button, int pressed) {
if (!p) return 11;
+22
View File
@@ -0,0 +1,22 @@
Wayland(GNOME / KDE portal)修复版本。X11 行为不变。
Wayland (GNOME / KDE portal) fix release. X11 behavior is unchanged.
### 修复 / Fixed
- **GNOME 开启分数缩放(如 125%、150%)时,鼠标点击偏到左上方**:portal 的绝对坐标被缩放了两次。现在 GNOME 直接使用画面坐标,
KDE 保持原有逻辑;虚拟机内按钮级点击误差 ≤ 2 像素。
GNOME with fractional scaling: absolute pointer positions were scaled twice, so clicks landed up-left of the target.
- **锁屏后重连时剪贴板失效**(portal):剪贴板现在会等待 portal 会话恢复,并在锁屏状态的握手中保留已授权的剪贴板能力。
Clipboard no longer gets disabled when a connection starts while GNOME is locked (portal).
- portal 键鼠注入失败时输出带数量上限的诊断日志(不记录按键内容)。/ Bounded diagnostics for portal input failures.
- 日志中记录房间令牌的剩余有效时间(只记录秒数)。/ Log the room token's remaining lifetime (seconds only).
### 已知问题 / Known issues
- Wayland(portal)下剪贴板目前只有「控制端 → Linux」方向可用,「Linux → 控制端」方向尚未通过验收。
On the portal backend, clipboard works viewer → Linux only; Linux → viewer is not working yet.
- 长时间连接(约 20 分钟)可能被云端释放,原因仍在排查。/ Long sessions may be released by the cloud after ~20 min; under investigation.
- Wayland 支持仍为实验性,需从源码以 `--features wayland,portal` 编译。/ Wayland remains experimental (build from source).
### 下载 / Download
`uu-remote-linux-v0.1.2-x86_64-linux.tar.gz`:X11 版可执行文件(x86_64,glibc ≥ 2.35)。
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
+21
View File
@@ -0,0 +1,21 @@
Wayland(GNOME / KDE portal)修复版本。X11 行为不变。
Wayland (GNOME / KDE portal) fix release. X11 behavior is unchanged.
### 修复 / Fixed
- **GNOME Wayland 首次连接黑屏,桌面重绘后才恢复**(#2):新建的 portal 会话会把第一帧有效画面当作锁屏残留清掉,
静止的桌面又不会产生新帧,所以画面一直是黑的。现在只有真正检测到锁屏(或 portal 被关闭)时才丢弃旧画面。
First connection on GNOME Wayland stayed black until the desktop redrew (#2): a fresh portal session discarded its
first valid frame as if it came from the lock screen.
### 其他 / Other
- CI 新增 `--features wayland,portal` 的编译和测试。/ CI now builds and tests `--features wayland,portal`.
### 已知问题 / Known issues
- Wayland(portal)下 Mac 控制端输入的下划线可能丢失(#3,正在排查,与键盘布局有关)。
- Wayland 下剪贴板只有「控制端 → Linux」方向可用;长连接约 20 分钟可能被云端释放(排查中)。
- Wayland 支持仍为实验性,需从源码以 `--features wayland,portal` 编译。
### 下载 / Download
`uu-remote-linux-v0.1.3-x86_64-linux.tar.gz`:X11 版可执行文件(x86_64,glibc ≥ 2.35)。
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
+29 -1
View File
@@ -196,10 +196,38 @@ impl UUAuthClient {
if code == TOKEN_INVALID { return Err(RoomError::LoginExpired); }
if status == 200 && code == 0 {
if let Some(data) = body.get("data") {
return serde_json::from_value(data.clone()).map_err(|e| RoomError::Other(format!("room data decode failed: {e}")));
let room: RoomData = serde_json::from_value(data.clone()).map_err(|e| RoomError::Other(format!("room data decode failed: {e}")))?;
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();
log::info!("Room token lifetime: remaining_s={:?}", room_token_lifetime(&room.token, now));
return Ok(room);
}
}
Err(RoomError::Other(format!("create_room error http {status} code {code}: {}",
body.get("msg").and_then(|m| m.as_str()).unwrap_or(""))))
}
}
// Report only the remaining lifetime; never return or log token/claim contents.
fn room_token_lifetime(token: &str, now: u64) -> Option<i64> {
use base64::Engine as _;
let payload = token.split('.').nth(1)?;
if payload.len() > 16384 { return None; }
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload)
.or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(payload)).ok()?;
let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
let remaining = claims.get("exp")?.as_i64()?.saturating_sub(i64::try_from(now).ok()?);
(remaining.unsigned_abs() <= 7 * 24 * 3600).then_some(remaining)
}
#[cfg(test)]
mod room_lifetime_tests {
use super::room_token_lifetime;
use base64::Engine as _;
#[test]
fn exposes_only_remaining_seconds_and_handles_opaque_tokens() {
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"exp":2200,"ignored":"test-only"}"#);
assert_eq!(room_token_lifetime(&format!("h.{payload}.s"),1000),Some(1200));
assert_eq!(room_token_lifetime("opaque",1000),None);
assert_eq!(room_token_lifetime("h.invalid.s",1000),None);
}
}
+9
View File
@@ -173,6 +173,15 @@ pub fn start_portal(session: std::sync::Arc<crate::portal::PortalSession>) -> Cl
let (output,outgoing)=watch::channel(None);
let (ready_tx,ready)=tokio::sync::oneshot::channel();
tokio::task::spawn_blocking(move || {
// GNOME closes the native portal while locked. A desktop connection
// starts its TEXT channel before CONTROL auto-unlock/capture recovery.
// Wait for that same Arc to recover instead of permanently disabling
// clipboard on an already authorized but temporarily closed session.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
while !session.is_alive() && std::time::Instant::now() < deadline {
if output.is_closed() || input.has_changed().is_err() { return; }
std::thread::sleep(std::time::Duration::from_millis(100));
}
let available=session.clipboard_ready(); let _=ready_tx.send(available);
if !available { return; }
let mut last=None; let mut pending=None;
+10 -3
View File
@@ -33,11 +33,11 @@ struct PendingPointer {
unsafe fn x11_pointer_state(_: *mut libc::c_int,_:*mut libc::c_int,_:*mut libc::c_uint)->libc::c_int {-1}
#[derive(Default)]
struct HeldInput { buttons: std::collections::BTreeSet<i32>, keys: std::collections::BTreeSet<u64> }
pub struct InputInjector { portal_failures: std::sync::atomic::AtomicUsize, portal_outcomes: std::sync::atomic::AtomicUsize, portal:std::sync::Mutex<Option<std::sync::Arc<crate::portal::PortalSession>>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex<PendingPointer>, held: std::sync::Mutex<HeldInput> }
pub struct InputInjector { portal_failures: std::sync::atomic::AtomicUsize, portal_outcomes: [std::sync::atomic::AtomicUsize; 3], portal:std::sync::Mutex<Option<std::sync::Arc<crate::portal::PortalSession>>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex<PendingPointer>, held: std::sync::Mutex<HeldInput> }
impl InputInjector {
pub fn new() -> Self {
Self { portal_failures: std::sync::atomic::AtomicUsize::new(0), portal_outcomes: std::sync::atomic::AtomicUsize::new(0), portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) }
Self { portal_failures: std::sync::atomic::AtomicUsize::new(0), portal_outcomes: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)), portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) }
}
pub fn bind_portal(&self,session:Option<std::sync::Arc<crate::portal::PortalSession>>) {
@@ -95,6 +95,12 @@ impl InputInjector {
}
pub fn wire_mouse_button(&self, button: i32, is_press: bool) {
if let Some(mapped) = crate::input_mapping::mouse_button_to_x11(button) { self.mouse_button(mapped,is_press); }
else {
static UNKNOWN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
if UNKNOWN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
log::warn!("Unsupported desktop wire mouse button: {}", button);
}
}
}
pub fn mouse_button(&self, button: i32, is_press: bool) {
self.flush_pointer();
@@ -136,7 +142,8 @@ impl InputInjector {
// and D-Bus errors. Never include keys, coordinates, text or portal tokens.
fn portal_result(&self, operation: &str, result: Result<(), String>) -> i32 {
use std::sync::atomic::Ordering::Relaxed;
if self.portal_outcomes.fetch_add(1, Relaxed) < 16 {
let slot = match operation { "motion" => 0, "button" => 1, _ => 2 };
if self.portal_outcomes[slot].fetch_add(1, Relaxed) < 16 {
log::info!("Portal input outcome: operation={} success={}", operation, result.is_ok());
}
match result {
+29
View File
@@ -71,6 +71,35 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
let input=InputInjector::new();
input.bind_portal(screen.portal.clone());
if std::env::args().nth(2).as_deref() == Some("--clipboard-targets") {
let read = || -> Result<serde_json::Value, Box<dyn std::error::Error>> {
Ok(serde_json::from_slice(&std::fs::read("/tmp/uuremote-clipboard-official.json")?)?)
};
let before = read()?;
if before["native_wayland"] != true || before["window_active"] != true { return Err("Native clipboard fixture must be focused".into()); }
for name in ["check", "copy"] {
let bounds = before[format!("{name}_bounds")].as_array().ok_or("Missing test button bounds")?;
let number = |index: usize| bounds[index].as_f64().ok_or("Invalid button bounds");
let x = number(0)? + number(2)? / 2.0;
let y = number(1)? + number(3)? / 2.0;
let width = before["window_size"][0].as_f64().ok_or("Missing test window width")?;
let height = before["window_size"][1].as_f64().ok_or("Missing test window height")?;
input.mouse_absolute_normalized(x / width, y / height, (screen.width,screen.height));
input.mouse_button(1,true); input.mouse_button(1,false);
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let after = read()?;
let key = format!("{name}_activations");
if after[&key].as_u64() != before[&key].as_u64().map(|n| n+1) {
return Err(format!("Portal small-target click missed: {name}").into());
}
let position = after["last_position"].as_array().ok_or("Missing native test pointer position")?;
if (position[0].as_f64().ok_or("Invalid pointer x")? - x).abs() > 2.0 || (position[1].as_f64().ok_or("Invalid pointer y")? - y).abs() > 2.0 {
return Err("Portal small-target pointer error exceeds two logical pixels".into());
}
println!("Portal native small-target click passed: {name}; pointer_error<=2px");
}
return Ok(());
}
input.mouse_absolute_normalized(0.25,0.25,(screen.width,screen.height));input.flush_pointer();
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
input.mouse_absolute_normalized(0.5,0.5,(screen.width,screen.height));input.flush_pointer();
+20 -4
View File
@@ -10,6 +10,7 @@ mod native {
use std::{ffi::c_void, ptr::NonNull, sync::Mutex};
extern "C" {
fn uu_portal_open_persist(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), data: *mut c_void, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void;
fn uu_portal_clipboard_supported(portal: *mut c_void) -> i32;
fn uu_portal_clipboard_ready(portal: *mut c_void) -> i32;
fn uu_portal_clipboard_set(portal: *mut c_void, text: *const u8, length: usize) -> i32;
fn uu_portal_clipboard_poll(portal: *mut c_void, text: *mut u8, capacity: usize) -> i32;
@@ -49,13 +50,24 @@ mod native {
}
let pointer = unsafe { uu_portal_open_persist(token.as_ref().map_or(std::ptr::null(), |v| v.as_ptr()), save_token, &mut cache as *mut _ as *mut c_void, &mut error, &mut width, &mut height) };
let handle = NonNull::new(pointer).ok_or_else(|| super::error(error))?;
Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(true), retry_at: Mutex::new(None), width, height })
// A freshly opened session holds no lock-screen frame: only an observed lock (or a
// closed stream) must discard the cached frame. Starting "locked" cleared the first
// valid frame, and a static desktop sends no new one, so the viewer stayed black (#2).
Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), retry_at: Mutex::new(None), width, height })
}
pub fn capture(&self, frame: &mut [u8]) -> Result<(), String> {
let mut handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
let locked = *self.locked.borrow() != Some(false);
if locked || self.was_locked.swap(locked, std::sync::atomic::Ordering::AcqRel) {
self.was_locked.store(locked, std::sync::atomic::Ordering::Release);
let state = *self.locked.borrow();
if state != Some(false) {
// Unknown state (watcher not reported yet): show nothing but keep the cached frame.
if state == Some(true) {
self.was_locked.store(true, std::sync::atomic::Ordering::Release);
unsafe { uu_portal_reset_frame(handle.0.as_ptr()) };
}
super::blank(frame); return Ok(());
}
if self.was_locked.swap(false, std::sync::atomic::Ordering::AcqRel) {
// First unlocked capture after a real lock: drop frames captured while locked.
unsafe { uu_portal_reset_frame(handle.0.as_ptr()) };
super::blank(frame); return Ok(());
}
@@ -89,6 +101,9 @@ mod native {
if code == 10 || code == 9 { super::blank(frame); Ok(()) } else { super::check(code) }
}
pub fn clipboard_supported(&self) -> bool {
self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_supported(handle.0.as_ptr()) != 0 })
}
pub fn clipboard_ready(&self) -> bool {
self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_ready(handle.0.as_ptr()) != 0 })
}
@@ -144,6 +159,7 @@ pub use native::Session as PortalSession;
pub struct PortalSession { pub width: u32, pub height: u32 }
#[cfg(not(all(target_os = "linux", feature = "portal")))]
impl PortalSession {
pub fn clipboard_supported(&self) -> bool { false }
pub fn clipboard_ready(&self) -> bool { false }
pub fn clipboard_set(&self, _: &str) -> Result<(), String> { Err(error(2)) }
pub fn clipboard_poll(&self) -> Option<String> { None }
+15 -1
View File
@@ -271,7 +271,11 @@ impl WebRtcSession {
let input_clone = input.clone();
let control_capture = capture.clone();
let control_sequence = Arc::new(std::sync::atomic::AtomicU64::new(1));
let text_clipboard_ready = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Capability belongs to the granted session, including while GNOME is
// locked. Echo can precede TEXT readiness and CONTROL auto-unlock;
// advertising false here would disable clipboard for the entire peer.
let portal_clipboard_supported = desktop && capture.portal.as_ref().is_some_and(|session| session.clipboard_supported());
let text_clipboard_ready = Arc::new(std::sync::atomic::AtomicBool::new(portal_clipboard_supported));
// One file-transfer session per peer. The viewer may send FileTransferFtp RPCs on CONTROL,
// but it receives file traffic only through streamerDidReceiveFileData, so every reply and
// host-initiated request goes out on FILE_DATA_CHANNEL.
@@ -714,6 +718,16 @@ impl WebRtcSession {
match crate::control_protocol::decode_control(&msg.data) {
Ok(crate::control_protocol::ControlMessage::Input(event)) => {
use crate::control_protocol::ControlInput;
// Separate receipt budgets keep motion floods from hiding clicks.
static RECEIPTS: [std::sync::atomic::AtomicUsize; 3] = [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
let (slot, kind) = match &event {
ControlInput::MouseButton {..} | ControlInput::MouseClick {..} => (0, "button"),
ControlInput::Keyboard {..} | ControlInput::KeyboardClick {..} => (1, "keyboard"),
_ => (2, "motion"),
};
if RECEIPTS[slot].fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
log::info!("CONTROL input received: kind={}", kind);
}
match &event {
ControlInput::MouseAbsolute {x,y} => input_worker.mouse_absolute_normalized(*x,*y,input_size),
ControlInput::MouseRelative {dx,dy} => input_worker.mouse_relative(*dx,*dy),
+55
View File
@@ -0,0 +1,55 @@
import AppKit
// Synthetic acceptance fixture: clipboard values are compared only, never shown or saved.
final class MarkerCheck: NSObject {
let gnome = NSTextField(labelWithString: "GNOME → Mac: not checked")
let kde = NSTextField(labelWithString: "KDE → Mac: not checked")
let copied = NSTextField(labelWithString: "Mac marker: not copied")
let formats = NSTextField(labelWithString: "Known text formats: not checked")
@objc func copyMarker() {
NSPasteboard.general.clearContents()
let ok = NSPasteboard.general.setString("UU-Mac-to-VM 中文🙂", forType: .string)
copied.stringValue = ok ? "Mac marker: copied" : "Mac marker: failed"
}
func matches() -> Bool {
let board = NSPasteboard.general
let utf16 = NSPasteboard.PasteboardType("public.utf16-plain-text")
let known = board.types ?? []
formats.stringValue = "Known text formats: UTF-8=\(known.contains(.string)), UTF-16=\(known.contains(utf16))"
let marker = "UU-VM-to-Mac 中文🚀"
if board.data(forType: .string) == Data(marker.utf8) { return true }
guard let actual = board.data(forType: utf16) else { return false }
for encoding in [String.Encoding.utf16, .utf16LittleEndian, .utf16BigEndian] {
guard let expected = marker.data(using: encoding) else { continue }
if actual == expected || actual == expected + Data([0, 0]) { return true }
}
return false
}
@objc func compareGnome() { gnome.stringValue = matches() ? "GNOME → Mac: PASS" : "GNOME → Mac: not matched" }
@objc func compareKde() { kde.stringValue = matches() ? "KDE → Mac: PASS" : "KDE → Mac: not matched" }
@objc func quit() { NSApp.terminate(nil) }
func button(_ title: String, _ action: Selector) -> NSButton {
NSButton(title: title, target: self, action: action)
}
func show() {
let window = NSWindow(contentRect: NSRect(x: 0,y: 0,width: 500,height: 360), styleMask: [.titled,.closable], backing: .buffered, defer: false)
window.title = "UU synthetic clipboard acceptance"
window.isReleasedWhenClosed = false
let stack = NSStackView(views: [
NSTextField(labelWithString: "Only fixed test-marker matches are displayed."),
button("Copy Mac test marker", #selector(copyMarker)), copied,
button("Compare GNOME VM marker", #selector(compareGnome)), gnome,
button("Compare KDE VM marker", #selector(compareKde)), kde, formats,
button("Quit test fixture", #selector(quit))])
stack.orientation = .vertical; stack.spacing = 14
stack.translatesAutoresizingMaskIntoConstraints = false
window.contentView!.addSubview(stack)
NSLayoutConstraint.activate([stack.centerXAnchor.constraint(equalTo: window.contentView!.centerXAnchor),stack.centerYAnchor.constraint(equalTo: window.contentView!.centerYAnchor)])
window.center(); window.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true)
}
}
let app = NSApplication.shared
app.setActivationPolicy(.regular)
let fixture = MarkerCheck()
fixture.show()
app.run()
+61
View File
@@ -0,0 +1,61 @@
"""Official viewer clipboard fixture; only synthetic-marker match booleans are recorded."""
import gi,json
from pathlib import Path
gi.require_version('Gtk','4.0'); gi.require_version('Gdk','4.0')
from gi.repository import Gtk,Gdk,GLib
assert Path('/proc/sys/kernel/hostname').read_text().strip()=='uu-hyprland-test'
state={'native_wayland':False,'mac_to_vm':False,'reverse_owned':False,'button_presses':0,'button_releases':0,'check_activations':0,'copy_activations':0,'window_active':False,'key_presses':0,'key_releases':0}
report=Path('/tmp/uuremote-clipboard-official.json')
app=Gtk.Application(application_id='dev.uuremote.ClipboardOfficial')
def activate(app):
window=Gtk.ApplicationWindow(application=app,title='UU clipboard official acceptance')
box=Gtk.Box(orientation=Gtk.Orientation.VERTICAL,spacing=24)
box.set_halign(Gtk.Align.CENTER);box.set_valign(Gtk.Align.CENTER)
label=Gtk.Label(label='UU Portal clipboard acceptance')
check=Gtk.Button(label='Check Mac → VM')
copy=Gtk.Button(label='Copy VM → Mac')
box.append(label);box.append(check);box.append(copy);window.set_child(box)
clipboard=window.get_clipboard()
def read(*_):
state['check_activations']+=1
def done(source,result):
try: state['mac_to_vm']=source.read_text_finish(result)=='UU-Mac-to-VM 中文🙂'
except GLib.Error: state['mac_to_vm']=False
label.set_label('Mac → VM: '+('PASS' if state['mac_to_vm'] else 'not matched'))
clipboard.read_text_async(None,done)
def write(*_):
state['copy_activations']+=1
clipboard.set('UU-VM-to-Mac 中文🚀');state['reverse_owned']=True
label.set_label('VM marker copied')
check.connect('clicked',read);copy.connect('clicked',write)
keys=Gtk.EventControllerKey();keys.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
def key_seen(*_):state['key_presses']+=1;return False
keys.connect('key-pressed',key_seen)
keys.connect('key-released',lambda *_:state.update(key_releases=state['key_releases']+1))
window.add_controller(keys)
window.connect('notify::is-active',lambda *_:state.update(window_active=window.is_active()))
gesture=Gtk.GestureClick();gesture.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
def pressed_seen(gesture,count,x,y):
state['button_presses']+=1
state['last_button']=gesture.get_current_button()
state['last_modifiers']=int(gesture.get_current_event_state())
state['last_position']=[round(x,1),round(y,1)]
widget=window.pick(x,y,Gtk.PickFlags.DEFAULT)
state['last_target']='other'
while widget:
if widget is check:state['last_target']='check';break
if widget is copy:state['last_target']='copy';break
widget=widget.get_parent()
# An observer must not compete with the button's own click gesture.
gesture.set_state(Gtk.EventSequenceState.DENIED)
gesture.connect('pressed',pressed_seen);window.add_controller(gesture)
window.present();window.fullscreen()
state['native_wayland']='wayland' in type(Gdk.Display.get_default()).__name__.lower()
def record():
state['window_size']=[window.get_width(),window.get_height()]
for name,button in [('check',check),('copy',copy)]:
ok,bounds=button.compute_bounds(window)
if ok:state[name+'_bounds']=[bounds.get_x(),bounds.get_y(),bounds.get_width(),bounds.get_height()]
report.write_text(json.dumps(state));return True
GLib.timeout_add(200,record)
app.connect('activate',activate);app.run([])
+37
View File
@@ -0,0 +1,37 @@
"""Audit receiver progress for a bounded VM service journal interval, not contents."""
import json,re,subprocess,sys,time,pathlib
class Audit:
def __init__(self,start,end):
self.start=start;self.end=end;self.reports=0;self.sequences={};self.last_progress=start;self.max_gap=0;self.peers=set();self.local_kinds=set();self.turn_errors=0;self.binding_errors=0;self.room_deferrals=0;self.interruptions=0
def accept(self,stamp,message):
if not self.start<=stamp<=self.end:return
if 'Video receiver report:' in message:
found=re.search(r'ssrc=(\d+) last_sequence=(\d+)',message)
if found:
ssrc,sequence=map(int,found.groups());self.reports+=1
if self.sequences.get(ssrc)!=sequence:
self.max_gap=max(self.max_gap,stamp-self.last_progress);self.last_progress=stamp
self.sequences[ssrc]=sequence
if 'ICE path:' in message:
found=re.search(r'session=(\d+).*local=\w+/(\w+)',message)
if found:self.peers.add(found[1]);self.local_kinds.add(found[2])
if 'fail to refresh permissions:' in message:self.turn_errors+=1
if 'bind() for refresh failed:' in message:self.binding_errors+=1
if 'Room renewal deferred while remote connection is active' in message:self.room_deferrals+=1
if any(text in message for text in ['Remote controller disconnected:','Live desktop stream stopped:','PeerConnection State changed: Failed','PeerConnection State changed: Disconnected','peer connection state changed: closed']):self.interruptions+=1
def result(self):
gap=max(self.max_gap,self.end-self.last_progress)
passed=self.end-self.start>=3600 and self.reports>0 and len(self.sequences)==1 and len(self.peers)==1 and self.local_kinds=={'relay'} and gap<=90 and self.interruptions==0 and self.room_deferrals>0
return dict(passed=passed,duration_s=round(self.end-self.start,3),video_reports=self.reports,video_ssrc_count=len(self.sequences),peer_count=len(self.peers),local_candidate_kinds=sorted(self.local_kinds),maximum_video_progress_gap_s=round(gap,3),interruptions=self.interruptions,turn_permission_refresh_errors=self.turn_errors,turn_channel_bind_refresh_errors=self.binding_errors,room_renewal_deferrals=self.room_deferrals)
def run(start,end):
assert pathlib.Path('/proc/sys/kernel/hostname').read_text().strip()=='uu-hyprland-test'
audit=Audit(start,end)
proc=subprocess.Popen(['journalctl','--user','-u','uuremote-test.service','--since',f'@{start}','--until',f'@{end}','--no-pager','-o','json'],stdout=subprocess.PIPE,text=True)
for line in proc.stdout:
row=json.loads(line);audit.accept(int(row['__REALTIME_TIMESTAMP'])/1e6,row.get('MESSAGE',''))
if proc.wait()!=0:raise RuntimeError('Journal read failed')
return audit.result()
if __name__=='__main__':print(json.dumps(run(float(sys.argv[1]),float(sys.argv[2]) if len(sys.argv)>2 else time.time())))
+21
View File
@@ -0,0 +1,21 @@
"""Hold an ephemeral idle inhibition only in the isolated QEMU acceptance VM."""
import pathlib,subprocess,signal,threading,sys
assert pathlib.Path('/proc/sys/kernel/hostname').read_text().strip()=='uu-hyprland-test'
assert subprocess.check_output(['systemd-detect-virt'],text=True).strip()=='qemu'
import gi
gi.require_version('Gio','2.0')
from gi.repository import Gio,GLib
seconds=min(4200,max(1,int(sys.argv[1]) if len(sys.argv)>1 else 3600))
bus=Gio.bus_get_sync(Gio.BusType.SESSION,None)
reply=bus.call_sync('org.freedesktop.ScreenSaver','/ScreenSaver','org.freedesktop.ScreenSaver','Inhibit',GLib.Variant('(ss)',('UU isolated acceptance','Timed live-connection acceptance')),GLib.VariantType.new('(u)'),Gio.DBusCallFlags.NONE,3000,None)
cookie=reply.unpack()[0]
stop=threading.Event()
signal.signal(signal.SIGTERM,lambda *_:stop.set())
signal.signal(signal.SIGINT,lambda *_:stop.set())
print('VM timed idle inhibition acquired',flush=True)
try:stop.wait(seconds)
finally:
try:
bus.call_sync('org.freedesktop.ScreenSaver','/ScreenSaver','org.freedesktop.ScreenSaver','UnInhibit',GLib.Variant('(u)',(cookie,)),None,Gio.DBusCallFlags.NONE,3000,None)
print('VM timed idle inhibition released',flush=True)
except GLib.Error:print('VM idle inhibition connection closed',flush=True)
+17
View File
@@ -0,0 +1,17 @@
import importlib.util,pathlib,unittest
spec=importlib.util.spec_from_file_location('audit',pathlib.Path(__file__).with_name('endurance-audit.py'));module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
class TestAudit(unittest.TestCase):
def make(self,progress=True):
audit=module.Audit(0,3600)
for stamp in range(0,3601,30):audit.accept(stamp,f'Video receiver report: ssrc=99 last_sequence={stamp if progress else 1}')
audit.accept(0,'ICE path: session=1 route=relay local=udp/relay remote=udp/host')
audit.accept(900,'Room renewal deferred while remote connection is active')
return audit
def test_receiver_heartbeats_without_new_video_fail(self):self.assertFalse(self.make(False).result()['passed'])
def test_local_relay_progress_and_deferrals_pass(self):self.assertTrue(self.make().result()['passed'])
def test_peer_replacement_and_remote_only_relay_do_not_pass(self):
audit=self.make();audit.accept(1000,'ICE path: session=2 route=relay local=udp/relay remote=udp/host');self.assertFalse(audit.result()['passed'])
audit=self.make();audit.local_kinds={'srflx'};self.assertFalse(audit.result()['passed'])
def test_turn_refresh_errors_alone_do_not_mean_video_failure(self):
audit=self.make();audit.accept(120,'fail to refresh permissions: error 400');self.assertTrue(audit.result()['passed']);self.assertEqual(audit.result()['turn_permission_refresh_errors'],1)
if __name__=='__main__':unittest.main()
+105
View File
@@ -0,0 +1,105 @@
#define _GNU_SOURCE
/* Protocol-independent C bounds/lifecycle checks; never requests consent. */
#include <assert.h>
#include "portal_engine.c"
static void clipboard_bounds(void) {
int fds[2]; uint8_t bytes[8]={0};
assert(pipe2(fds,O_NONBLOCK)==0);
assert(write(fds[1],"abc",3)==3); close(fds[1]);
assert(clipboard_io(fds[0],bytes,4,0)==3 && !memcmp(bytes,"abc",3)); close(fds[0]);
assert(pipe2(fds,O_NONBLOCK)==0);
assert(write(fds[1],"1234",4)==4); close(fds[1]);
assert(clipboard_io(fds[0],bytes,4,0)==-1); close(fds[0]);
assert(pipe2(fds,O_NONBLOCK)==0); close(fds[0]);
assert(clipboard_io(fds[1],bytes,1,1)==-1); close(fds[1]);
assert(clipboard_io(-1,bytes,0,1)==0);
}
int main(void) {
clipboard_bounds();
struct uu_portal *p = calloc(1, sizeof(*p));
assert(p);
pthread_mutex_init(&p->lock, NULL);
pthread_cond_init(&p->changed, NULL);
uint8_t storage[256];
struct spa_pod_builder builder = SPA_POD_BUILDER_INIT(storage, sizeof(storage));
const struct spa_pod *format = spa_format_video_raw_build(&builder, SPA_PARAM_Format,
&SPA_VIDEO_INFO_RAW_INIT(.format=SPA_VIDEO_FORMAT_BGRA, .size=SPA_RECTANGLE(2,2), .framerate=SPA_FRACTION(60,1)));
stream_format(p, SPA_PARAM_Format, format);
assert(p->width == 2 && p->height == 2 && p->frame_length == 16 && !p->error);
uint8_t pixels[16] = {0};
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 10);
p->sequence = 1;
assert(uu_portal_capture(p, pixels, sizeof(pixels)-1) == 11);
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 0);
p->logical_width = p->logical_height = 2;
assert(uu_portal_move(p, NAN, 1, 0) == 11);
assert(uu_portal_move(p, 2, 1, 0) == 11);
assert(uu_portal_alive(p));
/* Synthetic RGBA with row padding validates both channel order and stride. */
uint8_t source[24] = {255,0,0,255, 0,255,0,255, 99,99,99,99,
0,0,255,255, 255,255,255,255, 88,88,88,88};
struct spa_chunk chunk = {.offset=0, .size=20, .stride=12};
struct spa_data data = {.type=SPA_DATA_MemPtr, .data=source, .maxsize=24, .chunk=&chunk};
struct spa_buffer buffer = {.n_datas=1, .datas=&data};
p->format=SPA_VIDEO_FORMAT_RGBA;
copy_video_buffer(p, &buffer);
const uint8_t expected[16] = {0,0,255,255, 0,255,0,255, 255,0,0,255, 255,255,255,255};
assert(!memcmp(p->frame, expected, 16) && p->sequence == 2);
/* Capacity still contains old bytes, but zero/short chunks are not frames. */
for (unsigned size=0; size<20; size++) {
chunk.size=size; copy_video_buffer(p, &buffer);
assert(p->sequence == 2 && !memcmp(p->frame, expected, 16) && !p->error);
}
chunk.size=20; chunk.flags=SPA_CHUNK_FLAG_CORRUPTED;
copy_video_buffer(p, &buffer);
assert(p->sequence==2 && !p->error);
chunk.flags=0;
struct spa_meta_header header={.flags=SPA_META_HEADER_FLAG_CORRUPTED};
struct spa_meta metadata={.type=SPA_META_Header, .size=sizeof(header), .data=&header};
buffer.n_metas=1; buffer.metas=&metadata;
copy_video_buffer(p, &buffer); assert(p->sequence==2 && !p->error);
buffer.n_metas=0; buffer.metas=NULL;
/* Explicit EMPTY is opaque black rather than a stale desktop image. */
chunk.size=0; chunk.flags=SPA_CHUNK_FLAG_EMPTY;
copy_video_buffer(p, &buffer); assert(p->sequence==3);
for (unsigned pixel=0; pixel<4; pixel++) {
assert(p->frame[pixel*4]==0 && p->frame[pixel*4+1]==0 && p->frame[pixel*4+2]==0 && p->frame[pixel*4+3]==255);
}
/* A valid buffer after corruption remains usable; no permanent failure. */
chunk.size=20; chunk.flags=0; copy_video_buffer(p, &buffer);
assert(p->sequence==4 && !memcmp(p->frame, expected, 16));
uu_portal_reset_frame(p);
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 10);
copy_video_buffer(p, &buffer);
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 0);
p->session=g_strdup("/uu_test_session");
GVariantBuilder clip_options; g_variant_builder_init(&clip_options,G_VARIANT_TYPE_VARDICT);
const char *types[]={"image/png","text/plain",NULL};
g_variant_builder_add(&clip_options,"{sv}","mime_types",g_variant_new_strv(types,-1));
GVariant *event=g_variant_ref_sink(g_variant_new("(o@a{sv})",p->session,g_variant_builder_end(&clip_options)));
selection_owner(NULL,NULL,NULL,NULL,NULL,event,p); g_variant_unref(event);
assert(p->clipboard_changed && !strcmp(p->clipboard_mime,"text/plain"));
g_variant_builder_init(&clip_options,G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&clip_options,"{sv}","session_is_owner",g_variant_new_boolean(TRUE));
event=g_variant_ref_sink(g_variant_new("(o@a{sv})",p->session,g_variant_builder_end(&clip_options)));
selection_owner(NULL,NULL,NULL,NULL,NULL,event,p); g_variant_unref(event);
assert(!p->clipboard_changed && !p->clipboard_mime);
assert(uu_portal_clipboard_set(p,(const uint8_t *)"x",1)==-1);
assert(uu_portal_clipboard_poll(p,NULL,CLIP_LIMIT)==-1);
p->error=8;
assert(!uu_portal_alive(p));
assert(uu_portal_key(p, 'a', 1)==9); /* no input into an unusable stream */
p->error=0;
p->clipboard_enabled=1;
assert(uu_portal_clipboard_supported(p));
assert(uu_portal_clipboard_ready(p));
atomic_store(&p->closed, 1);
/* Closing a granted session temporarily removes readiness, not capability. */
assert(uu_portal_clipboard_supported(p));
assert(!uu_portal_clipboard_ready(p));
assert(!uu_portal_alive(p));
assert(uu_portal_capture(p, pixels, sizeof(pixels)) == 9);
uu_portal_close(p);
puts("Portal C bounds/lifecycle checks passed");
return 0;
}