Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(remote-desktop): 支持手机远程查看与操作电脑桌面

Dash2c26b914b976
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 0056e46dea..104f834d64 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1028,6 +1028,36 @@ function buildSwiftHelperForForgeArch(
}
}
+function buildRemoteDesktopInput(platform: ForgePlatform, arch: ForgeArch): void {
+ const destDir = path.join(__dirname, 'resources', 'tools', 'remote-desktop');
+ fs.mkdirSync(destDir, { recursive: true });
+ if (process.platform === 'darwin' && isMacForgePlatform(platform)) {
+ const dest = path.join(destDir, 'cindy-macos-desktop-input');
+ buildSwiftHelperForForgeArch(path.join(__dirname, 'native', 'remote-desktop', 'macos-input.swift'), dest, arch, '10.15', [], 'remote desktop input');
+ fs.chmodSync(dest, 0o755);
+ const capture = path.join(destDir, 'cindy-macos-desktop-capture');
+ const captureArch = arch === 'universal' ? ['-arch', 'arm64', '-arch', 'x86_64'] : ['-arch', arch === 'arm64' ? 'arm64' : 'x86_64'];
+ const result = spawnSync('xcrun', ['clang', path.join(__dirname, 'native', 'remote-desktop', 'macos-capture.m'),
+ ...captureArch, '-mmacosx-version-min=10.15', '-fobjc-arc', '-fblocks', '-O2',
+ '-framework', 'Foundation', '-framework', 'AppKit', '-framework', 'CoreGraphics', '-framework', 'CoreImage',
+ '-framework', 'IOSurface', '-framework', 'ImageIO', '-framework', 'IOKit', '-o', capture], { stdio: 'inherit' });
+ if (result.error || result.status !== 0) throw new Error('Remote desktop capture build failed');
+ fs.chmodSync(capture, 0o755);
+ } else if (process.platform === 'win32' && platform === 'win32') {
+ if (arch !== 'x64' && arch !== 'arm64') throw new Error('Unsupported Windows desktop architecture');
+ const target = arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';
+ for (const helper of ['windows-input', 'windows-host']) {
+ const root = path.join(__dirname, 'native', 'remote-desktop', helper);
+ const result = spawnSync('cargo', ['build', '--release', '--locked', '--target', target, '--manifest-path', path.join(root, 'Cargo.toml')], { stdio: 'inherit' });
+ if (result.error || result.status !== 0) throw new Error(`Remote desktop ${helper} build failed`);
+ const output = path.join(root, 'target', target, 'release');
+ const name = `cindy-windows-desktop-${helper === 'windows-input' ? 'input' : 'host'}`;
+ fs.copyFileSync(path.join(output, `${name}.exe`), path.join(destDir, `${name}.exe`));
+ if (helper === 'windows-host') fs.copyFileSync(path.join(output, 'cindy_windows_desktop_host.dll'), path.join(destDir, `${name}.node`));
+ }
+ }
+}
+
function buildMacXboxGamepadHelper(platform: ForgePlatform, arch: ForgeArch): void {
if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;
const src = path.join(__dirname, 'native', 'xbox-gamepad', 'macos-xbox-gamepad-helper.swift');
@@ -1416,6 +1446,7 @@ const config: ForgeConfig = {
// Windows / Linux 完全忽略此字段。
extendInfo: {
NSMicrophoneUsageDescription: 'This app needs access to the microphone for voice input.',
+ NSAudioCaptureUsageDescription: 'Share computer audio with your connected remote desktop.',
// agent 会话中访问受 TCC 保护的目录(桌面/文稿/下载)时,macOS 需要这些声明才能向
// 用户展示授权弹窗;缺失时系统直接静默拒绝,不弹窗。
NSDesktopFolderUsageDescription:
@@ -1484,6 +1515,7 @@ const config: ForgeConfig = {
// the packaged app correctly in Privacy & Security > Microphone.
extendHelperInfo: {
NSMicrophoneUsageDescription: 'This app needs access to the microphone for voice input.',
+ NSAudioCaptureUsageDescription: 'Share computer audio with your connected remote desktop.',
NSDesktopFolderUsageDescription:
"Cindy's AI agent needs access to read and write files on your Desktop.",
NSDocumentsFolderUsageDescription:
@@ -1554,6 +1586,7 @@ const config: ForgeConfig = {
buildMacAgentIslandHelper(platform, arch);
buildMacComputerPermissionGuideHelper(platform, arch);
buildMacSessionDragReleaseHelper(platform, arch);
+ buildRemoteDesktopInput(platform, arch);
},
// packaged dir 产出后、makers 跑之前签内部 .exe。这样 NSIS 包出来的
// Setup.exe 内嵌的、和 publish 阶段从同一 packagedDir 打的热更 ZIP 内嵌的,
diff --git a/apps/desktop/native/remote-desktop/macos-capture.m b/apps/desktop/native/remote-desktop/macos-capture.m
new file mode 100644
index 0000000000..5eb6924e8f
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/macos-capture.m
@@ -0,0 +1,168 @@
+#import <Foundation/Foundation.h>
+#import <AppKit/AppKit.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <CoreImage/CoreImage.h>
+#import <IOSurface/IOSurface.h>
+#import <IOKit/pwr_mgt/IOPMLib.h>
+#import <dlfcn.h>
+#import <signal.h>
+#import <unistd.h>
+#import <stdatomic.h>
+#import <time.h>
+
+static _Atomic(time_t) lastRequest;
+
+// Compatibility capture for an already logged-in macOS session. These public
+// legacy symbols are unavailable at compile time in SDK 15+, and may eventually
+// disappear at runtime. Resolve them explicitly and fail closed if unavailable.
+// No private WindowServer APIs, elevation, TCC changes, or network listener.
+typedef void (^FrameHandler)(int32_t, uint64_t, IOSurfaceRef, const void *);
+typedef CFTypeRef (*CreateStream)(CGDirectDisplayID, size_t, size_t, int32_t,
+ CFDictionaryRef, dispatch_queue_t, FrameHandler);
+typedef CGError (*StartStream)(CFTypeRef);
+
+static NSDictionary *readCursor(CGDirectDisplayID display) {
+ // Read on the main queue. currentSystemCursor returns the actual global shape,
+ // including cursors supplied by other applications (not this helper's cursor).
+ typedef boolean_t (*CursorVisible)(void);
+ CursorVisible visible = (CursorVisible)dlsym(RTLD_DEFAULT, "CGCursorIsVisible");
+ if (!visible) return nil;
+ NSCursor *cursor = [NSCursor currentSystemCursor];
+ if (!cursor) return nil;
+ NSImage *image = cursor.image;
+ NSSize size = image.size;
+ if (size.width <= 0 || size.height <= 0 || size.width > 256 || size.height > 256) return nil;
+ CGImageRef cg = [image CGImageForProposedRect:NULL context:nil hints:nil];
+ if (!cg || CGImageGetWidth(cg) > 512 || CGImageGetHeight(cg) > 512) return nil;
+ NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:cg];
+ NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
+ if (!png || png.length > 49152) return nil;
+ CGEventRef event = CGEventCreate(NULL);
+ if (!event) return nil;
+ CGPoint point = CGEventGetLocation(event);
+ CFRelease(event);
+ CGRect bounds = CGDisplayBounds(display);
+ if (bounds.size.width <= 0 || bounds.size.height <= 0) return nil;
+ NSPoint hot = cursor.hotSpot;
+ return @{
+ @"visible": visible() && CGRectContainsPoint(bounds, point) ? @YES : @NO,
+ @"x": @(fmax(0, fmin(1, (point.x - bounds.origin.x) / bounds.size.width))),
+ @"y": @(fmax(0, fmin(1, (point.y - bounds.origin.y) / bounds.size.height))),
+ @"width": @(size.width), @"height": @(size.height),
+ @"hotX": @(fmax(0, fmin(size.width, hot.x))),
+ @"hotY": @(fmax(0, fmin(size.height, hot.y))),
+ @"png": [png base64EncodedStringWithOptions:0]
+ };
+}
+
+int main(int argc, const char *argv[]) {
+ @autoreleasepool {
+ BOOL overlay = argc == 5 && strcmp(argv[2], "cursor-overlay") == 0;
+ if (argc != 2 && !overlay) return 2;
+ int fps = overlay && strcmp(argv[3], "60") == 0 ? 60 : (overlay ? 30 : 15);
+ double quality = overlay ? atof(argv[4]) : 0.55;
+ if (quality < 0.1 || quality > 1) return 2;
+ char *end = NULL;
+ unsigned long value = strtoul(argv[1], &end, 10);
+ if (!*argv[1] || *end || value > UINT32_MAX || !CGDisplayIsOnline((uint32_t)value)) return 2;
+ if (!CGPreflightScreenCaptureAccess()) return 3;
+ // A sleeping display can accept CGDisplayStreamStart yet deliver no frames.
+ // Wake its pixels without changing the lock/authentication state. Main holds
+ // prevent-display-sleep only for the authenticated viewer lease.
+ IOPMAssertionID activity = kIOPMNullAssertionID;
+ IOPMAssertionDeclareUserActivity(CFSTR("Cindy remote desktop viewer"), kIOPMUserActiveLocal, &activity);
+ CreateStream create = (CreateStream)dlsym(RTLD_DEFAULT, "CGDisplayStreamCreateWithDispatchQueue");
+ StartStream start = (StartStream)dlsym(RTLD_DEFAULT, "CGDisplayStreamStart");
+ const CFStringRef *intervalKey = dlsym(RTLD_DEFAULT, "kCGDisplayStreamMinimumFrameTime");
+ const CFStringRef *cursorKey = dlsym(RTLD_DEFAULT, "kCGDisplayStreamShowCursor");
+ if (!create || !start || !intervalKey || !cursorKey) return 4;
+ CGDirectDisplayID display = (uint32_t)value;
+ size_t width = CGDisplayPixelsWide(display), height = CGDisplayPixelsHigh(display);
+ if (!width || !height) return 2;
+ // This is a negotiated capture mode, not a snapshot of cursor availability.
+ // A temporarily hidden/unreadable cursor must not permanently bake the
+ // cursor into video or stop subsequent shape/visibility polling.
+ BOOL separateCursor = overlay;
+ // Preserve full selected display resolution for the cursor-overlay path.
+ // The legacy compatibility path retains its original inexpensive bounds.
+ double scale = MIN(1.0, (overlay ? 4096.0 : 1280.0) / MAX(width, height));
+ width = MAX(1, (size_t)(width * scale)); height = MAX(1, (size_t)(height * scale));
+ dispatch_queue_t queue = dispatch_queue_create("cindy.desktop.capture", DISPATCH_QUEUE_SERIAL);
+ CIContext *context = [CIContext contextWithOptions:@{ kCIContextCacheIntermediates: @NO }];
+ CGColorSpaceRef color = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ __block NSData *latest = nil;
+ __block BOOL requested = NO;
+ atomic_store(&lastRequest, time(NULL));
+ void (^reply)(void) = ^{
+ if (!requested || !latest) return;
+ requested = NO;
+ NSData *data;
+ if (overlay) {
+ __block NSDictionary *cursor = nil;
+ if (separateCursor) dispatch_sync(dispatch_get_main_queue(), ^{ cursor = readCursor(display); });
+ NSDictionary *frame = @{@"jpeg": [latest base64EncodedStringWithOptions:0], @"cursor": cursor ?: [NSNull null]};
+ NSMutableData *line = [[NSJSONSerialization dataWithJSONObject:frame options:0 error:NULL] mutableCopy];
+ [line appendBytes:"\n" length:1];
+ data = line;
+ } else {
+ NSString *line = [[latest base64EncodedStringWithOptions:0] stringByAppendingString:@"\n"];
+ data = [line dataUsingEncoding:NSUTF8StringEncoding];
+ }
+ const uint8_t *bytes = data.bytes;
+ size_t remaining = data.length;
+ while (remaining) {
+ ssize_t count = write(STDOUT_FILENO, bytes, remaining);
+ if (count <= 0) _exit(0);
+ bytes += count; remaining -= count;
+ }
+ };
+ CFTypeRef stream = create(display, width, height, 'BGRA',
+ (__bridge CFDictionaryRef)@{(__bridge NSString *)*intervalKey: @(1.0/fps), (__bridge NSString *)*cursorKey: separateCursor ? @NO : @YES}, queue,
+ ^(int32_t status, uint64_t timestamp, IOSurfaceRef surface, const void *update) {
+ @autoreleasepool {
+ if (status == 3) _exit(5); // stopped; never serve the previous session's frame
+ if (status == 2) { latest = nil; return; } // blank display
+ if (status != 0 || !surface) return;
+ CIImage *image = [CIImage imageWithIOSurface:surface];
+ NSData *jpeg = [context JPEGRepresentationOfImage:image colorSpace:color
+ options:@{(__bridge NSString *)kCGImageDestinationLossyCompressionQuality: @(quality)}];
+ NSUInteger limit = overlay ? 1000000 : 180000;
+ if (overlay) {
+ for (NSNumber *q in @[@0.45, @0.25, @0.1]) {
+ if (jpeg.length <= limit) break;
+ jpeg = [context JPEGRepresentationOfImage:image colorSpace:color
+ options:@{(__bridge NSString *)kCGImageDestinationLossyCompressionQuality: q}];
+ }
+ // Bound high-detail screens without turning them into disconnects.
+ for (int attempt = 0; jpeg.length > limit && attempt < 4; attempt++) {
+ image = [image imageByApplyingTransform:CGAffineTransformMakeScale(0.75, 0.75)];
+ jpeg = [context JPEGRepresentationOfImage:image colorSpace:color
+ options:@{(__bridge NSString *)kCGImageDestinationLossyCompressionQuality: @0.25}];
+ }
+ }
+ latest = jpeg.length <= limit ? jpeg : nil;
+ reply();
+ }
+ });
+ if (!stream || start(stream) != kCGErrorSuccess) return 5;
+ signal(SIGPIPE, SIG_IGN);
+ // stdin is a private parent pipe: one byte asks for one latest frame. EOF
+ // and a stalled parent both terminate capture without retaining any pixels.
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
+ char byte;
+ while (read(STDIN_FILENO, &byte, 1) == 1) {
+ if (byte != 'f') _exit(2);
+ atomic_store(&lastRequest, time(NULL));
+ dispatch_async(queue, ^{ requested = YES; reply(); });
+ }
+ _exit(0);
+ });
+ dispatch_source_t watchdog = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
+ dispatch_source_set_timer(watchdog, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0);
+ dispatch_source_set_event_handler(watchdog, ^{
+ if (time(NULL) - atomic_load(&lastRequest) > 5) _exit(0);
+ });
+ dispatch_resume(watchdog);
+ dispatch_main();
+ }
+}
diff --git a/apps/desktop/native/remote-desktop/macos-input.swift b/apps/desktop/native/remote-desktop/macos-input.swift
new file mode 100644
index 0000000000..48fe46ab4d
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/macos-input.swift
@@ -0,0 +1,211 @@
+import Foundation
+import ApplicationServices
+import AppKit
+import IOKit.graphics
+
+// Expose only the clipboard change counter, never clipboard content on stdout.
+if CommandLine.arguments.count == 2 && ["--clipboard-version", "--clipboard-content-version"].contains(CommandLine.arguments[1]) {
+ let session = CGSessionCopyCurrentDictionary() as? [String: Any]
+ guard let session = session, !(session["CGSSessionScreenIsLocked"] as? Bool ?? false) else { exit(2) }
+ if CommandLine.arguments[1] == "--clipboard-content-version",
+ (NSPasteboard.general.pasteboardItems?.count ?? 0) > 1 { exit(3) }
+ print(NSPasteboard.general.changeCount); exit(0)
+}
+
+// Read the actual accessibility selection instead of attributing arbitrary
+// background pasteboard changes to a copy shortcut.
+if CommandLine.arguments.count == 2 && ["--clipboard-selection", "--clipboard-content-selection"].contains(CommandLine.arguments[1]) {
+ let session = CGSessionCopyCurrentDictionary() as? [String: Any]
+ guard let session = session, !(session["CGSSessionScreenIsLocked"] as? Bool ?? false),
+ AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication else { exit(2) }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ var focused: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(root, kAXFocusedUIElementAttribute as CFString, &focused) == .success,
+ let focused = focused, CFGetTypeID(focused) == AXUIElementGetTypeID() else { exit(2) }
+ let element = focused as! AXUIElement
+ var subrole: CFTypeRef?
+ _ = AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &subrole)
+ guard subrole as? String != "AXSecureTextField" else { exit(2) }
+ var raw: CFTypeRef?
+ let selectionResult = AXUIElementCopyAttributeValue(element, kAXSelectedTextAttribute as CFString, &raw)
+ var role: CFTypeRef?
+ _ = AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &role)
+ let nonText = CommandLine.arguments[1] == "--clipboard-content-selection"
+ && selectionResult == .attributeUnsupported
+ && ["AXImage", "AXButton", "AXGroup", "AXScrollArea", "AXList", "AXTable", "AXOutline", "AXRow", "AXCell"].contains(role as? String ?? "")
+ // A confirmed empty selection is different from a failed accessibility read.
+ guard selectionResult == .success || selectionResult == .noValue || nonText else { exit(2) }
+ let selectionText: String? = (selectionResult == .noValue || nonText) ? "" : raw as? String
+ guard let text = selectionText, text.utf16.count <= 16384,
+ NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier,
+ let data = try? JSONSerialization.data(withJSONObject: ["text": text]),
+ let json = String(data: data, encoding: .utf8) else { exit(2) }
+ var current: CFTypeRef?
+ guard let latest = CGSessionCopyCurrentDictionary() as? [String: Any],
+ !(latest["CGSSessionScreenIsLocked"] as? Bool ?? false),
+ AXUIElementCopyAttributeValue(root, kAXFocusedUIElementAttribute as CFString, &current) == .success,
+ let current = current, CFEqual(current, element) else { exit(2) }
+ print(json); exit(0)
+}
+
+// Display configuration is a separate one-shot command; it does not acquire
+// input ownership or require Accessibility permission. Only enumerated modes
+// can be applied, and changes last for the login session (not permanently).
+if CommandLine.arguments.count >= 3 && ["--display-modes", "--display-mode"].contains(CommandLine.arguments[1]) {
+ guard let display = UInt32(CommandLine.arguments[2]), CGDisplayIsOnline(display) != 0,
+ let modes = CGDisplayCopyAllDisplayModes(display, [kCGDisplayShowDuplicateLowResolutionModes: true] as CFDictionary) as? [CGDisplayMode],
+ let current = CGDisplayCopyDisplayMode(display) else { exit(2) }
+ if CommandLine.arguments[1] == "--display-modes" {
+ var preferred: [String: CGDisplayMode] = [:]
+ for mode in modes where mode.isUsableForDesktopGUI() {
+ let key = "\(mode.width)x\(mode.height)"
+ if let prior = preferred[key], prior.ioDisplayModeID == current.ioDisplayModeID ||
+ (mode.ioDisplayModeID != current.ioDisplayModeID && prior.pixelWidth >= mode.pixelWidth && prior.refreshRate >= mode.refreshRate) { continue }
+ preferred[key] = mode
+ }
+ let result = preferred.values.sorted { $0.width == $1.width ? $0.height < $1.height : $0.width < $1.width }.map {
+ ["id": String($0.ioDisplayModeID), "width": $0.width, "height": $0.height,
+ "current": $0.ioDisplayModeID == current.ioDisplayModeID,
+ "native": ($0.ioFlags & UInt32(kDisplayModeNativeFlag)) != 0] as [String: Any]
+ }
+ guard let data = try? JSONSerialization.data(withJSONObject: result), let json = String(data: data, encoding: .utf8) else { exit(2) }
+ print(json); exit(0)
+ }
+ guard CommandLine.arguments.count == 4, let modeID = UInt32(CommandLine.arguments[3]),
+ let mode = modes.first(where: { $0.ioDisplayModeID == modeID && $0.isUsableForDesktopGUI() }) else { exit(2) }
+ var config: CGDisplayConfigRef?
+ guard CGBeginDisplayConfiguration(&config) == .success, let config = config else { exit(3) }
+ guard CGConfigureDisplayWithDisplayMode(config, display, mode, nil) == .success else {
+ CGCancelDisplayConfiguration(config); exit(3)
+ }
+ guard CGCompleteDisplayConfiguration(config, .forSession) == .success else { exit(3) }
+ print("ready"); exit(0)
+}
+
+// A private event source keeps remote modifiers separate from physical keyboard state.
+let source = CGEventSource(stateID: .privateState)
+// Never post events from this source: posted F11/arrow flags accumulate in
+// a source's state table and must not become defaults for the next letter.
+let keyMetadataSource = CGEventSource(stateID: .privateState)
+var keys = Set<CGKeyCode>()
+var buttons = Set<Int>()
+var location = CGPoint.zero
+var lastSeen = Date()
+var lastClickAt = Date.distantPast
+var lastClickLocation = CGPoint.zero
+var lastClickButton = -1
+var clickCount: Int64 = 0
+let lock = NSLock()
+let keyCodes: [String: CGKeyCode] = [
+ "KeyA":0,"KeyS":1,"KeyD":2,"KeyF":3,"KeyH":4,"KeyG":5,"KeyZ":6,"KeyX":7,"KeyC":8,"KeyV":9,
+ "KeyB":11,"KeyQ":12,"KeyW":13,"KeyE":14,"KeyR":15,"KeyY":16,"KeyT":17,
+ "Digit1":18,"Digit2":19,"Digit3":20,"Digit4":21,"Digit6":22,"Digit5":23,"Equal":24,"Digit9":25,"Digit7":26,"Minus":27,"Digit8":28,"Digit0":29,
+ "BracketRight":30,"KeyO":31,"KeyU":32,"BracketLeft":33,"KeyI":34,"KeyP":35,"Enter":36,"KeyL":37,"KeyJ":38,"Quote":39,"KeyK":40,"Semicolon":41,"Backslash":42,"Comma":43,"Slash":44,"KeyN":45,"KeyM":46,"Period":47,
+ "Tab":48,"Space":49,"Backquote":50,"Backspace":51,"Escape":53,"MetaLeft":55,"ShiftLeft":56,"AltLeft":58,"ControlLeft":59,
+ "F1":122,"F2":120,"F3":99,"F4":118,"F5":96,"F6":97,"F7":98,"F8":100,"F9":101,"F10":109,"F11":103,"F12":111,
+ "Insert":114,"Home":115,"PageUp":116,"Delete":117,"End":119,"PageDown":121,"ArrowLeft":123,"ArrowRight":124,"ArrowDown":125,"ArrowUp":126,
+]
+func flags() -> CGEventFlags {
+ var result: CGEventFlags = []
+ for (key, flag) in [(55, CGEventFlags.maskCommand), (56,.maskShift), (58,.maskAlternate), (59,.maskControl)] {
+ if keys.contains(CGKeyCode(key)) { result.insert(flag) }
+ }
+ return result
+}
+func configureKeyFlags(_ event: CGEvent, _ code: CGKeyCode, _ down: Bool) {
+ // Quartz adds intrinsic flags for function keys, arrows and modifier sides.
+ // Replace only our managed modifiers; dropping the intrinsic flags prevents
+ // system shortcuts such as F11 and Control-Up from matching.
+ let metadata = CGEvent(keyboardEventSource: keyMetadataSource, virtualKey: code, keyDown: down)
+ var nativeFlags = metadata?.flags ?? []
+ nativeFlags.subtract([.maskCommand, .maskShift, .maskAlternate, .maskControl, .maskAlphaShift])
+ event.flags = nativeFlags.union(flags())
+}
+func makeKeyEvent(_ code: CGKeyCode, _ down: Bool) -> CGEvent? {
+ let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down)
+ if let event = event { configureKeyFlags(event, code, down) }
+ return event
+}
+func key(_ code: CGKeyCode, _ down: Bool) {
+ if down { keys.insert(code) } else { keys.remove(code) }
+ makeKeyEvent(code, down)?.post(tap: .cghidEventTap)
+ // Give WindowServer time to observe modifier transitions before the next key.
+ usleep(8000)
+}
+func mouse(_ button: Int, _ down: Bool) {
+ let b: CGMouseButton = button == 2 ? .right : button == 1 ? .center : .left
+ let type: CGEventType = button == 2 ? (down ? .rightMouseDown : .rightMouseUp) : button == 1 ? (down ? .otherMouseDown : .otherMouseUp) : (down ? .leftMouseDown : .leftMouseUp)
+ if down { buttons.insert(button) } else { buttons.remove(button) }
+ if down {
+ let nearby = hypot(location.x-lastClickLocation.x, location.y-lastClickLocation.y) < 5
+ clickCount = button == lastClickButton && nearby && Date().timeIntervalSince(lastClickAt) < 0.5 ? min(3, clickCount + 1) : 1
+ lastClickAt = Date(); lastClickLocation = location; lastClickButton = button
+ }
+ let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: location, mouseButton: b)
+ event?.setIntegerValueField(.mouseEventClickState, value: clickCount)
+ event?.flags = flags()
+ event?.post(tap: .cghidEventTap)
+}
+func releaseAll() {
+ for b in Array(buttons) { mouse(b, false) }
+ for k in Array(keys) { key(k, false) }
+}
+func apply(_ event: [String: Any]) {
+ guard let kind = event["kind"] as? String else { return }
+ if kind == "release" { releaseAll(); return }
+ if kind == "move" || kind == "button" {
+ guard let x = event["x"] as? Double, let y = event["y"] as? Double, x.isFinite, y.isFinite else { return }
+ location = CGPoint(x:x,y:y)
+ if kind == "button", let button = event["button"] as? Int, let down = event["down"] as? Bool { mouse(button, down) }
+ else {
+ let b = buttons.contains(0) ? 0 : buttons.contains(2) ? 2 : buttons.contains(1) ? 1 : -1
+ let type: CGEventType = b == 0 ? .leftMouseDragged : b == 2 ? .rightMouseDragged : b == 1 ? .otherMouseDragged : .mouseMoved
+ let e = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: location, mouseButton: b == 2 ? .right : b == 1 ? .center : .left)
+ e?.flags = flags(); e?.post(tap: .cghidEventTap)
+ }
+ } else if kind == "key", let code = event["code"] as? String, let native = keyCodes[code], let down = event["down"] as? Bool {
+ key(native, down)
+ } else if kind == "scroll", let dy = event["dy"] as? Double, let dx = event["dx"] as? Double {
+ CGEvent(scrollWheelEvent2Source: source, units: .pixel, wheelCount: 2, wheel1: -Int32(dy), wheel2: -Int32(dx), wheel3: 0)?.post(tap: .cghidEventTap)
+ } else if kind == "text", let text = event["text"] as? String {
+ // Character boundaries prevent splitting a UTF-16 surrogate pair.
+ for character in text.prefix(4096) {
+ var units = Array(String(character).utf16)
+ for down in [true, false] {
+ let e = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: down)
+ e?.keyboardSetUnicodeString(stringLength: units.count, unicodeString: &units)
+ e?.post(tap: .cghidEventTap)
+ }
+ }
+ }
+}
+#if !DESKTOP_INPUT_TEST
+if CommandLine.arguments.contains("--check") {
+ print(AXIsProcessTrusted() ? "ready" : "permission"); exit(0)
+}
+if CommandLine.arguments.contains("--request-permission") {
+ let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
+ print(AXIsProcessTrustedWithOptions(options) ? "ready" : "permission"); exit(0)
+}
+guard AXIsProcessTrusted() else { print("permission"); fflush(stdout); exit(2) }
+print("ready"); fflush(stdout)
+let watchdog = DispatchSource.makeTimerSource(queue: .global())
+watchdog.schedule(deadline: .now() + 1, repeating: 1)
+watchdog.setEventHandler {
+ lock.lock(); defer { lock.unlock() }
+ if !AXIsProcessTrusted() { releaseAll(); print("error"); fflush(stdout); exit(2) }
+ if Date().timeIntervalSince(lastSeen) > 5 { releaseAll() }
+}
+watchdog.resume()
+signal(SIGTERM, SIG_IGN)
+let termination = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .global())
+termination.setEventHandler { lock.lock(); releaseAll(); lock.unlock(); exit(0) }
+termination.resume()
+while let line = readLine() {
+ guard line.utf8.count <= 65536, let data = line.data(using: .utf8), let events = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { continue }
+ lock.lock(); lastSeen = Date()
+ for event in events { apply(event) }
+ lock.unlock()
+}
+lock.lock(); releaseAll(); lock.unlock()
+#endif
diff --git a/apps/desktop/native/remote-desktop/macos-input.test.swift b/apps/desktop/native/remote-desktop/macos-input.test.swift
new file mode 100644
index 0000000000..1bf745ebf4
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/macos-input.test.swift
@@ -0,0 +1,29 @@
+// Compiled with the real helper and DESKTOP_INPUT_TEST. Never posts OS events
+// or requests permissions: these assertions inspect constructed CGEvents only.
+for down in [true, false] {
+ keys = []
+ let desktop = makeKeyEvent(103, down)!
+ precondition(desktop.flags.contains(.maskSecondaryFn), "F11 must match the system shortcut")
+ precondition(!desktop.flags.contains(.maskControl))
+
+ keys = [59]
+ let windows = makeKeyEvent(126, down)!
+ precondition(windows.flags.contains([.maskControl, .maskSecondaryFn, .maskNumericPad]),
+ "Control-Up must retain both the remote modifier and intrinsic arrow flags")
+
+ keys = [55, 56]
+ let letter = makeKeyEvent(0, down)!
+ precondition(letter.flags.contains([.maskCommand, .maskShift]))
+ precondition(!letter.flags.contains(.maskSecondaryFn), "Letters must not become function keys")
+
+ keys = []
+ precondition(!makeKeyEvent(0, down)!.flags.contains(.maskCommand), "Released modifiers must clear")
+ // Simulate flags left in the sending source by earlier F11 / arrow events.
+ letter.flags.formUnion([.maskSecondaryFn, .maskNumericPad, .maskControl])
+ configureKeyFlags(letter, 0, down)
+ precondition(letter.flags.intersection([.maskSecondaryFn, .maskNumericPad, .maskControl, .maskCommand, .maskShift]).isEmpty,
+ "Previous shortcut flags must not leak into ordinary typing")
+ let control = makeKeyEvent(59, down)!
+ precondition(!control.flags.contains(.maskSecondaryFn), "Control must not inherit F11's Fn state")
+}
+print("native keyboard flags passed")
diff --git a/apps/desktop/native/remote-desktop/windows-host/.gitignore b/apps/desktop/native/remote-desktop/windows-host/.gitignore
new file mode 100644
index 0000000000..b83d22266a
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/apps/desktop/native/remote-desktop/windows-host/Cargo.lock b/apps/desktop/native/remote-desktop/windows-host/Cargo.lock
new file mode 100644
index 0000000000..c224ffc489
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/Cargo.lock
@@ -0,0 +1,462 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "bitflags"
+version = "2.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cindy-windows-desktop-host"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "jpeg-encoder",
+ "napi",
+ "napi-build",
+ "napi-derive",
+ "serde_json",
+ "sha2",
+ "tokio",
+ "windows-sys",
+]
+
+[[package]]
+name = "convert_case"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "ctor"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "jpeg-encoder"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "napi"
+version = "2.16.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"
+dependencies = [
+ "bitflags",
+ "ctor",
+ "napi-derive",
+ "napi-sys",
+ "once_cell",
+ "tokio",
+]
+
+[[package]]
+name = "napi-build"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1c0f5d67ee408a4685b61f5ab7e58605c8ae3f2b4189f0127d804ff13d5560a"
+
+[[package]]
+name = "napi-derive"
+version = "2.16.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"
+dependencies = [
+ "cfg-if",
+ "convert_case",
+ "napi-derive-backend",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "napi-derive-backend"
+version = "1.0.75"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"
+dependencies = [
+ "convert_case",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "semver",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "napi-sys"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"
+dependencies = [
+ "libloading",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.5",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tokio"
+version = "1.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+dependencies = [
+ "pin-project-lite",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/apps/desktop/native/remote-desktop/windows-host/Cargo.toml b/apps/desktop/native/remote-desktop/windows-host/Cargo.toml
new file mode 100644
index 0000000000..78928ec1d5
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "cindy-windows-desktop-host"
+version = "0.1.0"
+edition = "2021"
+license = "Apache-2.0"
+
+[lib]
+crate-type = ["cdylib"]
+
+[build-dependencies]
+napi-build = "=2.1.3"
+
+[dependencies]
+serde_json = "1"
+sha2 = "0.10"
+base64 = "0.22"
+jpeg-encoder = "0.6"
+napi = { version = "2", features = ["napi6", "tokio_rt"] }
+napi-derive = "2"
+tokio = { version = "1", features = ["rt"] }
+windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authentication_Identity", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_System_RemoteDesktop", "Win32_System_StationsAndDesktops", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Memory", "Win32_System_Environment", "Win32_System_Com", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_UI_HiDpi", "Win32_Graphics_Gdi"] }
+
+[features]
+default = ["windows-sys/Win32_System_JobObjects", "windows-sys/Win32_System_Registry", "windows-sys/Win32_System_SystemServices"]
+
+[profile.release]
+panic = "abort"
+lto = true
+opt-level = "s"
+strip = true
diff --git a/apps/desktop/native/remote-desktop/windows-host/build.rs b/apps/desktop/native/remote-desktop/windows-host/build.rs
new file mode 100644
index 0000000000..0f1b01002b
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ napi_build::setup();
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/capture.rs b/apps/desktop/native/remote-desktop/windows-host/src/capture.rs
new file mode 100644
index 0000000000..d8a8acc0a7
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/capture.rs
@@ -0,0 +1,164 @@
+use crate::win::*;
+use base64::Engine;
+use std::{mem, ptr};
+use windows_sys::Win32::{
+ Foundation::*,
+ Graphics::Gdi::*,
+ UI::{HiDpi::*, WindowsAndMessaging::*},
+};
+#[path = "../../windows-input/src/desktop.rs"]
+mod desktop;
+pub struct Capture {
+ desktop: desktop::InputDesktop,
+ rect: [i32; 4],
+}
+impl Capture {
+ pub fn new(rect: &serde_json::Value) -> Result<Self> {
+ let rect = rect.as_array().filter(|r| r.len() == 4).ok_or_else(error)?;
+ let mut values = [0; 4];
+ for (i, v) in rect.iter().enumerate() {
+ values[i] = v
+ .as_i64()
+ .and_then(|n| i32::try_from(n).ok())
+ .ok_or_else(error)?;
+ }
+ if !(1..=16384).contains(&values[2])
+ || !(1..=16384).contains(&values[3])
+ || values[0].unsigned_abs() > 65536
+ || values[1].unsigned_abs() > 65536
+ {
+ return denied();
+ }
+ unsafe {
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ }
+ Ok(Self {
+ desktop: desktop::InputDesktop::new(),
+ rect: values,
+ })
+ }
+ pub fn frame(&mut self) -> Result<Vec<u8>> {
+ self.desktop
+ .bind()
+ .map_err(|_| std::io::Error::from(std::io::ErrorKind::PermissionDenied))?;
+ let [x, y, width, height] = self.rect;
+ unsafe {
+ // Verify the requested region remains exactly one physical monitor.
+ // A geometry change invalidates capture instead of sampling another screen.
+ let monitor = MonitorFromPoint(POINT { x, y }, MONITOR_DEFAULTTONULL);
+ let mut info: MONITORINFO = mem::zeroed();
+ info.cbSize = mem::size_of::<MONITORINFO>() as u32;
+ if monitor.is_null()
+ || GetMonitorInfoW(monitor, &mut info) == 0
+ || info.rcMonitor.left != x
+ || info.rcMonitor.top != y
+ || info.rcMonitor.right - x != width
+ || info.rcMonitor.bottom - y != height
+ {
+ return denied();
+ }
+ let scale = 1280.0 / (width.max(height) as f64);
+ let scale = scale.min(1.0);
+ let w = (width as f64 * scale).round().max(1.0) as i32;
+ let h = (height as f64 * scale).round().max(1.0) as i32;
+ let source = GetDC(ptr::null_mut());
+ if source.is_null() {
+ return Err(error());
+ }
+ let target = CreateCompatibleDC(source);
+ if target.is_null() {
+ ReleaseDC(ptr::null_mut(), source);
+ return Err(error());
+ }
+ let mut bitmap: BITMAPINFO = mem::zeroed();
+ bitmap.bmiHeader = BITMAPINFOHEADER {
+ biSize: mem::size_of::<BITMAPINFOHEADER>() as u32,
+ biWidth: w,
+ biHeight: -h,
+ biPlanes: 1,
+ biBitCount: 32,
+ biCompression: BI_RGB,
+ ..mem::zeroed()
+ };
+ let mut pixels = ptr::null_mut();
+ let dib = CreateDIBSection(
+ source,
+ &bitmap,
+ DIB_RGB_COLORS,
+ &mut pixels,
+ ptr::null_mut(),
+ 0,
+ );
+ if dib.is_null() {
+ DeleteDC(target);
+ ReleaseDC(ptr::null_mut(), source);
+ return Err(error());
+ }
+ let old = SelectObject(target, dib);
+ SetStretchBltMode(target, HALFTONE);
+ let ok = StretchBlt(
+ target,
+ 0,
+ 0,
+ w,
+ h,
+ source,
+ x,
+ y,
+ width,
+ height,
+ SRCCOPY | CAPTUREBLT,
+ );
+ // The cursor is not necessarily included in the screen DC.
+ let mut cursor: CURSORINFO = mem::zeroed();
+ cursor.cbSize = mem::size_of::<CURSORINFO>() as u32;
+ if ok != 0 && GetCursorInfo(&mut cursor) != 0 && cursor.flags == CURSOR_SHOWING {
+ let mut icon: ICONINFO = mem::zeroed();
+ if GetIconInfo(cursor.hCursor, &mut icon) != 0 {
+ DrawIconEx(
+ target,
+ ((cursor.ptScreenPos.x - x - icon.xHotspot as i32) as f64 * scale) as i32,
+ ((cursor.ptScreenPos.y - y - icon.yHotspot as i32) as f64 * scale) as i32,
+ cursor.hCursor,
+ (GetSystemMetrics(SM_CXCURSOR) as f64 * scale) as i32,
+ (GetSystemMetrics(SM_CYCURSOR) as f64 * scale) as i32,
+ 0,
+ ptr::null_mut(),
+ DI_NORMAL,
+ );
+ if !icon.hbmMask.is_null() {
+ DeleteObject(icon.hbmMask);
+ }
+ if !icon.hbmColor.is_null() {
+ DeleteObject(icon.hbmColor);
+ }
+ }
+ }
+ GdiFlush();
+ let data = if ok != 0 {
+ Some(std::slice::from_raw_parts(pixels.cast::<u8>(), (w * h * 4) as usize).to_vec())
+ } else {
+ None
+ };
+ SelectObject(target, old);
+ DeleteObject(dib);
+ DeleteDC(target);
+ ReleaseDC(ptr::null_mut(), source);
+ let data = data.ok_or_else(error)?;
+ for quality in [65, 45, 25, 10] {
+ let mut jpeg = Vec::new();
+ jpeg_encoder::Encoder::new(&mut jpeg, quality)
+ .encode(&data, w as u16, h as u16, jpeg_encoder::ColorType::Bgra)
+ .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidData))?;
+ if jpeg.len() <= 180000 {
+ let mut line = base64::engine::general_purpose::STANDARD
+ .encode(jpeg)
+ .into_bytes();
+ line.push(b'\n');
+ return Ok(line);
+ }
+ }
+ Err(std::io::Error::from(std::io::ErrorKind::InvalidData))
+ }
+ }
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/lib.rs b/apps/desktop/native/remote-desktop/windows-host/src/lib.rs
new file mode 100644
index 0000000000..0506598b05
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/lib.rs
@@ -0,0 +1,126 @@
+//! Main-only Node-API transport: the OS sees the actual Cindy PID opening the
+//! pipe. A child process or a self-reported parent PID is never authorization.
+mod pipe;
+mod win;
+use napi_derive::napi;
+use sha2::{Digest, Sha256};
+use std::{
+ path::PathBuf,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+};
+use windows_sys::Win32::System::Services::*;
+fn failure(_: impl std::fmt::Debug) -> napi::Error {
+ napi::Error::from_reason("DESKTOP_SYSTEM_SERVICE_UNAVAILABLE")
+}
+#[napi]
+pub struct DesktopConnection {
+ pipe: Arc<Mutex<Option<pipe::Pipe>>>,
+ cancel: Arc<AtomicBool>,
+}
+#[napi]
+impl DesktopConnection {
+ #[napi(factory)]
+ pub async fn open(binary: String, init: String) -> napi::Result<Self> {
+ tokio::task::spawn_blocking(move || {
+ let path = PathBuf::from(binary).canonicalize().map_err(failure)?;
+ let name = format!(
+ "CindyRemoteDesktop-{:x}",
+ Sha256::digest(path.to_string_lossy().to_lowercase().as_bytes())
+ )[..35]
+ .to_string();
+ let mut pipe = pipe::Pipe::client(&format!(r"\\.\pipe\{}", name)).map_err(failure)?;
+ let pid = pipe.server_pid().map_err(failure)?;
+ let server = win::process(pid).map_err(failure)?;
+ if !win::system(win::token(server.0).map_err(failure)?.0).map_err(failure)?
+ || win::image(server.0)
+ .map_err(failure)?
+ .canonicalize()
+ .map_err(failure)?
+ != path
+ {
+ return Err(failure("identity"));
+ }
+ unsafe {
+ let manager =
+ OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT);
+ if manager.is_null() {
+ return Err(failure("scm"));
+ }
+ let service =
+ OpenServiceW(manager, win::wide(&name).as_ptr(), SERVICE_QUERY_STATUS);
+ CloseServiceHandle(manager);
+ if service.is_null() {
+ return Err(failure("service"));
+ }
+ let mut status: SERVICE_STATUS_PROCESS = std::mem::zeroed();
+ let mut needed = 0;
+ let ok = QueryServiceStatusEx(
+ service,
+ SC_STATUS_PROCESS_INFO,
+ (&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
+ std::mem::size_of_val(&status) as u32,
+ &mut needed,
+ );
+ CloseServiceHandle(service);
+ if ok == 0 || status.dwCurrentState != SERVICE_RUNNING || status.dwProcessId != pid
+ {
+ return Err(failure("service identity"));
+ }
+ }
+ if init.len() > 1023 || init.contains('\n') {
+ return Err(failure("init"));
+ }
+ pipe.write(format!("{init}\n").as_bytes())
+ .map_err(failure)?;
+ if pipe.line(1024).map_err(failure)? != b"ready\n" {
+ return Err(failure("ready"));
+ }
+ let cancel = pipe.cancel.clone();
+ Ok(Self {
+ pipe: Arc::new(Mutex::new(Some(pipe))),
+ cancel,
+ })
+ })
+ .await
+ .map_err(failure)?
+ }
+ #[napi]
+ pub async fn request(&self, line: String) -> napi::Result<String> {
+ if line.len() > 32767 || line.contains('\n') || self.cancel.load(Ordering::SeqCst) {
+ return Err(failure("request"));
+ }
+ let pipe = self.pipe.clone();
+ let cancel = self.cancel.clone();
+ tokio::task::spawn_blocking(move || {
+ let mut guard = pipe.lock().map_err(failure)?;
+ let result = (|| {
+ let pipe = guard.as_mut().ok_or_else(|| failure("closed"))?;
+ pipe.write(format!("{line}\n").as_bytes())
+ .map_err(failure)?;
+ let bytes = pipe.line(240001).map_err(failure)?;
+ String::from_utf8(bytes).map_err(failure)
+ })();
+ if result.is_err() || cancel.load(Ordering::SeqCst) {
+ guard.take();
+ }
+ result
+ })
+ .await
+ .map_err(failure)?
+ }
+ #[napi]
+ pub fn close(&self) {
+ self.cancel.store(true, Ordering::SeqCst);
+ if let Ok(mut guard) = self.pipe.try_lock() {
+ guard.take();
+ }
+ }
+}
+impl Drop for DesktopConnection {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/main.rs b/apps/desktop/native/remote-desktop/windows-host/src/main.rs
new file mode 100644
index 0000000000..944a45f944
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/main.rs
@@ -0,0 +1,57 @@
+mod capture;
+mod pipe;
+mod security;
+mod service;
+mod win;
+use sha2::{Digest, Sha256};
+use win::*;
+
+fn service_name() -> Result<String> {
+ let path = std::env::current_exe()?
+ .canonicalize()?
+ .to_string_lossy()
+ .to_lowercase();
+ Ok(format!("CindyRemoteDesktop-{:x}", Sha256::digest(path.as_bytes()))[..35].to_string())
+}
+fn pipe_name() -> Result<String> {
+ Ok(format!(r"\\.\pipe\{}", service_name()?))
+}
+fn run() -> Result<()> {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ match args.first().map(String::as_str) {
+ Some("--service") => service::run(),
+ Some("--worker") if args.len() == 2 => service::worker(&args[1]),
+ Some("--install") if args.len() == 2 => {
+ let pid = args[1].parse::<u32>().map_err(|_| error())?;
+ service::install()?;
+ service::authorize(pid)
+ }
+ Some("--uninstall") => service::uninstall(),
+ Some("--elevate-install") if args.len() == 2 => {
+ let pid = args[1].parse::<u32>().map_err(|_| error())?;
+ let (_main, _) = security::authorize_client(pid)?;
+ service::elevate(&format!("--install {pid}"))
+ }
+ Some("--elevate-uninstall") => service::elevate("--uninstall"),
+ Some("--status") => {
+ println!(
+ "{}",
+ if service::pid().is_ok() {
+ "ready"
+ } else if security::protected_install().is_err() {
+ "installRequired"
+ } else {
+ "missing"
+ }
+ );
+ Ok(())
+ }
+ _ => denied(),
+ }
+}
+fn main() {
+ if run().is_err() {
+ println!("error");
+ std::process::exit(1);
+ }
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/pipe.rs b/apps/desktop/native/remote-desktop/windows-host/src/pipe.rs
new file mode 100644
index 0000000000..492f074665
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/pipe.rs
@@ -0,0 +1,238 @@
+//! Local-only, overlapped, bounded byte streams. Cancellation is completed before
+//! dropping OVERLAPPED or its buffer. No raw input/pixels are written to logs.
+use crate::win::*;
+use std::{
+ io, mem, ptr,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ time::{Duration, Instant},
+};
+use windows_sys::Win32::{
+ Foundation::*,
+ Security::Authorization::*,
+ Security::*,
+ Storage::FileSystem::*,
+ System::{Pipes::*, Threading::*, IO::*},
+};
+pub struct Pipe {
+ handle: Handle,
+ buffered: Vec<u8>,
+ pub cancel: Arc<AtomicBool>,
+ pub shutdown: Option<&'static AtomicBool>,
+}
+unsafe impl Send for Pipe {}
+impl Pipe {
+ fn cancelled(&self) -> bool {
+ self.cancel.load(Ordering::SeqCst)
+ || self
+ .shutdown
+ .is_some_and(|stop| stop.load(Ordering::SeqCst))
+ }
+ pub fn server(name: &str, system_only: bool) -> Result<Self> {
+ // GR/GW would include FILE_CREATE_PIPE_INSTANCE. Explicit data rights only.
+ let sddl = wide(if system_only {
+ "D:P(A;;GA;;;SY)"
+ } else {
+ "D:P(A;;GA;;;SY)(A;;0x00100003;;;IU)"
+ });
+ let mut descriptor = ptr::null_mut();
+ if unsafe {
+ ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ sddl.as_ptr(),
+ 1,
+ &mut descriptor,
+ ptr::null_mut(),
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let attributes = SECURITY_ATTRIBUTES {
+ nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
+ lpSecurityDescriptor: descriptor,
+ bInheritHandle: 0,
+ };
+ let raw = unsafe {
+ CreateNamedPipeW(
+ wide(name).as_ptr(),
+ PIPE_ACCESS_DUPLEX
+ | FILE_FLAG_OVERLAPPED
+ | if system_only {
+ FILE_FLAG_FIRST_PIPE_INSTANCE
+ } else {
+ 0
+ },
+ PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
+ 4,
+ 262144,
+ 32768,
+ 0,
+ &attributes,
+ )
+ };
+ unsafe {
+ LocalFree(descriptor);
+ }
+ Ok(Self {
+ handle: Handle::new(raw)?,
+ buffered: Vec::new(),
+ cancel: Arc::new(AtomicBool::new(false)),
+ shutdown: None,
+ })
+ }
+ pub fn client(name: &str) -> Result<Self> {
+ let name = wide(name);
+ unsafe {
+ WaitNamedPipeW(name.as_ptr(), 3000);
+ }
+ let handle = Handle::new(unsafe {
+ CreateFileW(
+ name.as_ptr(),
+ FILE_READ_DATA | FILE_WRITE_DATA | SYNCHRONIZE,
+ 0,
+ ptr::null(),
+ OPEN_EXISTING,
+ FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
+ ptr::null_mut(),
+ )
+ })?;
+ Ok(Self {
+ handle,
+ buffered: Vec::new(),
+ cancel: Arc::new(AtomicBool::new(false)),
+ shutdown: None,
+ })
+ }
+ fn operation(
+ &self,
+ run: impl FnOnce(*mut OVERLAPPED) -> BOOL,
+ timeout: u32,
+ connect: bool,
+ ) -> Result<u32> {
+ if self.cancelled() {
+ return Err(io::Error::from(io::ErrorKind::Interrupted));
+ }
+ let event = Handle::new(unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) })?;
+ let mut operation: OVERLAPPED = unsafe { mem::zeroed() };
+ operation.hEvent = event.0;
+ let ok = run(&mut operation);
+ let code = unsafe { GetLastError() };
+ if ok == 0 && connect && code == ERROR_PIPE_CONNECTED {
+ return Ok(0);
+ }
+ if ok == 0 && code != ERROR_IO_PENDING {
+ return Err(io::Error::from_raw_os_error(code as i32));
+ }
+ let deadline = Instant::now() + Duration::from_millis(timeout as u64);
+ let mut completed = ok != 0;
+ while !completed && !self.cancelled() && Instant::now() < deadline {
+ completed = unsafe { WaitForSingleObject(event.0, 100) } == WAIT_OBJECT_0;
+ }
+ if !completed {
+ unsafe {
+ CancelIoEx(self.handle.0, &operation);
+ let mut bytes = 0;
+ GetOverlappedResult(self.handle.0, &operation, &mut bytes, 1);
+ }
+ return Err(io::Error::from(io::ErrorKind::TimedOut));
+ }
+ let mut bytes = 0;
+ if unsafe { GetOverlappedResult(self.handle.0, &operation, &mut bytes, 1) } == 0 {
+ return Err(error());
+ }
+ Ok(bytes)
+ }
+ pub fn accept(&self, timeout: u32) -> Result<()> {
+ self.operation(
+ |op| unsafe { ConnectNamedPipe(self.handle.0, op) },
+ timeout,
+ true,
+ )
+ .map(|_| ())
+ }
+ pub fn client_pid(&self) -> Result<u32> {
+ let mut pid = 0;
+ if unsafe { GetNamedPipeClientProcessId(self.handle.0, &mut pid) } == 0 {
+ Err(error())
+ } else {
+ Ok(pid)
+ }
+ }
+ pub fn server_pid(&self) -> Result<u32> {
+ let mut pid = 0;
+ if unsafe { GetNamedPipeServerProcessId(self.handle.0, &mut pid) } == 0 {
+ Err(error())
+ } else {
+ Ok(pid)
+ }
+ }
+ pub fn write(&self, data: &[u8]) -> Result<()> {
+ if data.len() > 240001 {
+ return denied();
+ }
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let mut offset = 0;
+ while offset < data.len() {
+ let remaining = deadline
+ .saturating_duration_since(Instant::now())
+ .as_millis()
+ .min(5000) as u32;
+ let count = self.operation(
+ |op| unsafe {
+ WriteFile(
+ self.handle.0,
+ data[offset..].as_ptr(),
+ (data.len() - offset) as u32,
+ ptr::null_mut(),
+ op,
+ )
+ },
+ remaining,
+ false,
+ )? as usize;
+ if count == 0 {
+ return Err(io::Error::from(io::ErrorKind::WriteZero));
+ }
+ offset += count;
+ }
+ Ok(())
+ }
+ pub fn line(&mut self, limit: usize) -> Result<Vec<u8>> {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ if let Some(end) = self.buffered.iter().position(|b| *b == b'\n') {
+ if end + 1 > limit {
+ return denied();
+ }
+ return Ok(self.buffered.drain(..=end).collect());
+ }
+ if self.buffered.len() >= limit {
+ return denied();
+ }
+ let mut chunk = [0u8; 8192];
+ let remaining = deadline
+ .saturating_duration_since(Instant::now())
+ .as_millis()
+ .min(5000) as u32;
+ let count = self.operation(
+ |op| unsafe {
+ ReadFile(
+ self.handle.0,
+ chunk.as_mut_ptr(),
+ chunk.len() as u32,
+ ptr::null_mut(),
+ op,
+ )
+ },
+ remaining,
+ false,
+ )? as usize;
+ if count == 0 {
+ return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
+ }
+ self.buffered.extend_from_slice(&chunk[..count]);
+ }
+ }
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/security.rs b/apps/desktop/native/remote-desktop/windows-host/src/security.rs
new file mode 100644
index 0000000000..6a0b98193b
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/security.rs
@@ -0,0 +1,239 @@
+use crate::win::*;
+use std::os::windows::fs::MetadataExt;
+use std::{
+ mem,
+ path::{Path, PathBuf},
+ ptr,
+};
+use windows_sys::Win32::{
+ Foundation::*,
+ Security::Authorization::*,
+ Security::*,
+ Storage::FileSystem::*,
+ System::{Com::*, SystemServices::*},
+ UI::Shell::*,
+};
+
+pub fn same_file(a: &Path, b: &Path) -> bool {
+ match (a.canonicalize(), b.canonicalize()) {
+ (Ok(a), Ok(b)) => a
+ .as_os_str()
+ .to_string_lossy()
+ .eq_ignore_ascii_case(&b.as_os_str().to_string_lossy()),
+ _ => false,
+ }
+}
+
+// Retain non-delete-sharing handles through caller authorization / worker spawn.
+// Reject ACLs that we cannot prove safe rather than interpreting a path prefix as
+// an integrity boundary. Installation does not silently repair administrator ACLs.
+pub fn protected_install() -> Result<Vec<Handle>> {
+ let mut raw = ptr::null_mut();
+ if unsafe { SHGetKnownFolderPath(&FOLDERID_ProgramFiles, 0, ptr::null_mut(), &mut raw) } < 0 {
+ return denied();
+ }
+ let root = unsafe {
+ let mut len = 0;
+ while *raw.add(len) != 0 {
+ len += 1;
+ }
+ let result = PathBuf::from(String::from_utf16_lossy(std::slice::from_raw_parts(
+ raw, len,
+ )));
+ CoTaskMemFree(raw.cast());
+ result
+ };
+ let executable = std::env::current_exe()?;
+ let install = executable
+ .parent()
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .ok_or_else(error)?;
+ if !install.starts_with(&root) || install == root {
+ return denied();
+ }
+ let mut trusted_installer = ptr::null_mut();
+ // Exact Windows servicing identity, not all service SIDs.
+ if unsafe {
+ ConvertStringSidToSidW(
+ wide("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464").as_ptr(),
+ &mut trusted_installer,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ struct LocalSid(PSID);
+ impl Drop for LocalSid {
+ fn drop(&mut self) {
+ unsafe {
+ LocalFree(self.0);
+ }
+ }
+ }
+ let trusted_installer = LocalSid(trusted_installer);
+ let mut paths = vec![
+ install.join("resources/app.asar"),
+ executable.clone(),
+ executable.with_file_name("cindy-windows-desktop-host.node"),
+ executable.with_file_name("cindy-windows-desktop-input.exe"),
+ ];
+ // Packaged exe identity is discovered only from the protected app directory.
+ // No caller-selected executable or command line is accepted by the broker.
+ for item in std::fs::read_dir(install)? {
+ let path = item?.path();
+ if path
+ .extension()
+ .is_some_and(|e| e.eq_ignore_ascii_case("exe") || e.eq_ignore_ascii_case("dll"))
+ {
+ paths.push(path);
+ }
+ }
+ // Unpacked native code is part of the executable trust boundary too.
+ let unpacked = install.join("resources/app.asar.unpacked");
+ if unpacked.exists() {
+ let mut pending = vec![unpacked];
+ while let Some(path) = pending.pop() {
+ let metadata = std::fs::symlink_metadata(&path)?;
+ if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ return denied();
+ }
+ if metadata.is_dir() {
+ for item in std::fs::read_dir(&path)? {
+ pending.push(item?.path());
+ }
+ }
+ paths.push(path);
+ if paths.len() + pending.len() > 100_000 {
+ return denied();
+ }
+ }
+ }
+ let mut directory = executable.parent();
+ while let Some(path) = directory {
+ paths.push(path.to_owned());
+ if path == root {
+ break;
+ }
+ directory = path.parent();
+ }
+ let mut handles = Vec::new();
+ for path in paths {
+ let handle = Handle::new(unsafe {
+ CreateFileW(
+ wide(&path.to_string_lossy()).as_ptr(),
+ READ_CONTROL | FILE_READ_ATTRIBUTES,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ ptr::null(),
+ OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
+ ptr::null_mut(),
+ )
+ })?;
+ let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { mem::zeroed() };
+ if unsafe { GetFileInformationByHandle(handle.0, &mut info) } == 0
+ || info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
+ {
+ return denied();
+ }
+ let mut owner = ptr::null_mut();
+ let mut acl = ptr::null_mut();
+ let mut descriptor = ptr::null_mut();
+ let code = unsafe {
+ GetSecurityInfo(
+ handle.0,
+ SE_FILE_OBJECT,
+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
+ &mut owner,
+ ptr::null_mut(),
+ &mut acl,
+ ptr::null_mut(),
+ &mut descriptor,
+ )
+ };
+ if code != ERROR_SUCCESS {
+ return denied();
+ }
+ let trusted = |sid| unsafe {
+ IsWellKnownSid(sid, WinLocalSystemSid) != 0
+ || IsWellKnownSid(sid, WinBuiltinAdministratorsSid) != 0
+ || EqualSid(sid, trusted_installer.0) != 0
+ };
+ let mut safe = !acl.is_null() && trusted(owner);
+ if safe {
+ unsafe {
+ for i in 0..(*acl).AceCount as u32 {
+ let mut ace = ptr::null_mut();
+ if GetAce(acl, i, &mut ace) == 0 {
+ safe = false;
+ break;
+ }
+ let header = &*ace.cast::<ACE_HEADER>();
+ if header.AceFlags as u32 & INHERIT_ONLY_ACE != 0 {
+ continue;
+ }
+ if header.AceType as u32 == ACCESS_DENIED_ACE_TYPE {
+ continue;
+ }
+ if header.AceType as u32 != ACCESS_ALLOWED_ACE_TYPE {
+ safe = false;
+ break;
+ }
+ let allow = &*ace.cast::<ACCESS_ALLOWED_ACE>();
+ let mutations = GENERIC_ALL
+ | GENERIC_WRITE
+ | WRITE_DAC
+ | WRITE_OWNER
+ | DELETE
+ | FILE_WRITE_DATA
+ | FILE_APPEND_DATA
+ | FILE_WRITE_EA
+ | FILE_WRITE_ATTRIBUTES
+ | FILE_DELETE_CHILD;
+ if allow.Mask & mutations != 0
+ && !trusted((&allow.SidStart as *const u32).cast_mut().cast())
+ {
+ safe = false;
+ break;
+ }
+ }
+ }
+ }
+ unsafe {
+ LocalFree(descriptor);
+ }
+ if !safe {
+ return denied();
+ }
+ handles.push(handle);
+ }
+ Ok(handles)
+}
+
+pub fn authorize_client(pid: u32) -> Result<(Handle, u32)> {
+ let client = process(pid)?;
+ let session = session(token(client.0)?.0)?;
+ if session == 0
+ || session
+ != unsafe { windows_sys::Win32::System::RemoteDesktop::WTSGetActiveConsoleSessionId() }
+ {
+ return denied();
+ }
+ let client_image = image(client.0)?;
+ let executable = std::env::current_exe()?;
+ let install = executable
+ .parent()
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .ok_or_else(error)?;
+ if !client_image.parent().is_some_and(|p| same_file(p, install))
+ || !client_image.file_name().is_some_and(|n| {
+ n.eq_ignore_ascii_case("Cindy.exe") || n.eq_ignore_ascii_case("CindyDev.exe")
+ })
+ {
+ return denied();
+ }
+ Ok((client, session))
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/service.rs b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
new file mode 100644
index 0000000000..9d9f88dedd
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
@@ -0,0 +1,712 @@
+use crate::{pipe::Pipe, win::*};
+use std::{
+ io::{self, BufRead, Write},
+ mem, ptr,
+ sync::{
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+ Mutex,
+ },
+ time::{Duration, Instant},
+};
+use windows_sys::Win32::{
+ Foundation::*,
+ Security::*,
+ Storage::FileSystem::DELETE,
+ System::{Com::*, JobObjects::*, RemoteDesktop::*, Services::*, Threading::*},
+ UI::{Shell::*, WindowsAndMessaging::*},
+};
+static AUTHORIZED: Mutex<Option<Handle>> = Mutex::new(None);
+static STOP: AtomicBool = AtomicBool::new(false);
+static CLIENTS: AtomicUsize = AtomicUsize::new(0);
+static STATUS: Mutex<usize> = Mutex::new(0);
+struct ServiceHandle(SC_HANDLE);
+impl Drop for ServiceHandle {
+ fn drop(&mut self) {
+ unsafe {
+ CloseServiceHandle(self.0);
+ }
+ }
+}
+fn manager(access: u32) -> Result<ServiceHandle> {
+ let value = unsafe { OpenSCManagerW(ptr::null(), ptr::null(), access) };
+ if value.is_null() {
+ Err(error())
+ } else {
+ Ok(ServiceHandle(value))
+ }
+}
+fn service(manager: &ServiceHandle, access: u32) -> Result<ServiceHandle> {
+ let value = unsafe { OpenServiceW(manager.0, wide(&crate::service_name()?).as_ptr(), access) };
+ if value.is_null() {
+ Err(error())
+ } else {
+ Ok(ServiceHandle(value))
+ }
+}
+pub fn pid() -> Result<u32> {
+ let manager = manager(SC_MANAGER_CONNECT)?;
+ let service = service(&manager, SERVICE_QUERY_STATUS)?;
+ let mut status: SERVICE_STATUS_PROCESS = unsafe { mem::zeroed() };
+ let mut size = 0;
+ if unsafe {
+ QueryServiceStatusEx(
+ service.0,
+ SC_STATUS_PROCESS_INFO,
+ (&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
+ mem::size_of_val(&status) as u32,
+ &mut size,
+ )
+ } == 0
+ || status.dwCurrentState != SERVICE_RUNNING
+ || status.dwProcessId == 0
+ {
+ return denied();
+ }
+ Ok(status.dwProcessId)
+}
+pub fn install() -> Result<()> {
+ let _guard = crate::security::protected_install()?;
+ let manager = manager(SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT)?;
+ let name = wide(&crate::service_name()?);
+ let executable = std::env::current_exe()?;
+ let command = wide(&format!("\"{}\" --service", executable.display()));
+ let raw = unsafe {
+ CreateServiceW(
+ manager.0,
+ name.as_ptr(),
+ wide("Cindy Remote Desktop").as_ptr(),
+ SERVICE_START | SERVICE_QUERY_STATUS,
+ SERVICE_WIN32_OWN_PROCESS,
+ SERVICE_DEMAND_START,
+ SERVICE_ERROR_NORMAL,
+ command.as_ptr(),
+ ptr::null(),
+ ptr::null_mut(),
+ ptr::null(),
+ ptr::null(),
+ ptr::null(),
+ )
+ };
+ let installed = if raw.is_null() {
+ if unsafe { GetLastError() } != ERROR_SERVICE_EXISTS {
+ return Err(error());
+ }
+ service(&manager, SERVICE_START | SERVICE_QUERY_STATUS)?
+ } else {
+ ServiceHandle(raw)
+ };
+ if unsafe { StartServiceW(installed.0, 0, ptr::null()) } == 0
+ && unsafe { GetLastError() } != ERROR_SERVICE_ALREADY_RUNNING
+ {
+ return Err(error());
+ }
+ let deadline = Instant::now() + Duration::from_secs(8);
+ while Instant::now() < deadline {
+ if pid().is_ok() {
+ return Ok(());
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ Err(io::Error::from(io::ErrorKind::TimedOut))
+}
+pub fn uninstall() -> Result<()> {
+ let manager = manager(SC_MANAGER_CONNECT)?;
+ let service = match service(&manager, SERVICE_STOP | DELETE | SERVICE_QUERY_STATUS) {
+ Ok(s) => s,
+ Err(e) if e.raw_os_error() == Some(ERROR_SERVICE_DOES_NOT_EXIST as i32) => return Ok(()),
+ Err(e) => return Err(e),
+ };
+ let mut status: SERVICE_STATUS = unsafe { mem::zeroed() };
+ if unsafe { ControlService(service.0, SERVICE_CONTROL_STOP, &mut status) } == 0
+ && unsafe { GetLastError() } != ERROR_SERVICE_NOT_ACTIVE
+ {
+ return Err(error());
+ }
+ let deadline = Instant::now() + Duration::from_secs(20);
+ loop {
+ if unsafe { QueryServiceStatus(service.0, &mut status) } == 0 {
+ return Err(error());
+ }
+ if status.dwCurrentState == SERVICE_STOPPED {
+ break;
+ }
+ if Instant::now() >= deadline {
+ return Err(io::Error::from(io::ErrorKind::TimedOut));
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ if unsafe { DeleteService(service.0) } == 0 {
+ return Err(error());
+ }
+ Ok(())
+}
+pub fn elevate(command: &str) -> Result<()> {
+ let _guard = crate::security::protected_install()?;
+ let executable = wide(&std::env::current_exe()?.to_string_lossy());
+ let verb = wide("runas");
+ let parameters = wide(command);
+ let mut info: SHELLEXECUTEINFOW = unsafe { mem::zeroed() };
+ info.cbSize = mem::size_of_val(&info) as u32;
+ info.fMask = SEE_MASK_NOCLOSEPROCESS;
+ info.lpVerb = verb.as_ptr();
+ info.lpFile = executable.as_ptr();
+ info.lpParameters = parameters.as_ptr();
+ info.nShow = SW_HIDE;
+ if unsafe { ShellExecuteExW(&mut info) } == 0 {
+ return Err(error());
+ }
+ let process = Handle::new(info.hProcess)?;
+ if unsafe { WaitForSingleObject(process.0, 120000) } != WAIT_OBJECT_0 {
+ return Err(io::Error::from(io::ErrorKind::TimedOut));
+ }
+ let mut code = 1;
+ if unsafe { GetExitCodeProcess(process.0, &mut code) } == 0 || code != 0 {
+ return denied();
+ }
+ Ok(())
+}
+fn status(state: u32) {
+ let handle = *STATUS.lock().unwrap() as SERVICE_STATUS_HANDLE;
+ if handle.is_null() {
+ return;
+ }
+ let value = SERVICE_STATUS {
+ dwServiceType: SERVICE_WIN32_OWN_PROCESS,
+ dwCurrentState: state,
+ dwControlsAccepted: if state == SERVICE_RUNNING {
+ SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN
+ } else {
+ 0
+ },
+ dwWin32ExitCode: 0,
+ dwServiceSpecificExitCode: 0,
+ dwCheckPoint: 0,
+ dwWaitHint: if state == SERVICE_STOP_PENDING {
+ 15000
+ } else {
+ 0
+ },
+ };
+ unsafe {
+ SetServiceStatus(handle, &value);
+ }
+}
+unsafe extern "system" fn control(
+ code: u32,
+ _event: u32,
+ _data: *mut core::ffi::c_void,
+ _context: *mut core::ffi::c_void,
+) -> u32 {
+ if code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN {
+ STOP.store(true, Ordering::SeqCst);
+ status(SERVICE_STOP_PENDING);
+ }
+ 0
+}
+unsafe extern "system" fn entry(_argc: u32, _argv: *mut *mut u16) {
+ let Ok(name) = crate::service_name() else {
+ return;
+ };
+ let handle =
+ RegisterServiceCtrlHandlerExW(wide(&name).as_ptr(), Some(control), ptr::null_mut());
+ if handle.is_null() {
+ return;
+ }
+ *STATUS.lock().unwrap() = handle as usize;
+ let Ok(_installation) = crate::security::protected_install() else {
+ status(SERVICE_STOPPED);
+ return;
+ };
+ status(SERVICE_RUNNING);
+ let registration_deadline = Instant::now() + Duration::from_secs(30);
+ while !STOP.load(Ordering::SeqCst) {
+ let should_stop = match AUTHORIZED.lock() {
+ Ok(authorized) => match authorized.as_ref() {
+ Some(main) => unsafe { WaitForSingleObject(main.0, 0) != WAIT_TIMEOUT },
+ None => Instant::now() >= registration_deadline,
+ },
+ Err(_) => true,
+ };
+ if should_stop {
+ STOP.store(true, Ordering::SeqCst);
+ status(SERVICE_STOP_PENDING);
+ break;
+ }
+
+ if CLIENTS.load(Ordering::SeqCst) >= 3 {
+ std::thread::sleep(Duration::from_millis(100));
+ continue;
+ }
+ let Ok(mut pipe) = Pipe::server(&crate::pipe_name().unwrap(), false) else {
+ std::thread::sleep(Duration::from_millis(500));
+ continue;
+ };
+ pipe.shutdown = Some(&STOP);
+ if pipe.accept(500).is_err() {
+ continue;
+ }
+ if CLIENTS.fetch_add(1, Ordering::SeqCst) >= 4 {
+ CLIENTS.fetch_sub(1, Ordering::SeqCst);
+ continue;
+ }
+ std::thread::spawn(move || {
+ let _ = serve(pipe);
+ CLIENTS.fetch_sub(1, Ordering::SeqCst);
+ });
+ }
+ // Existing clients have finite I/O deadlines; service process exit is also
+ // a kernel-enforced job-close boundary for every worker and input child.
+ let until = Instant::now() + Duration::from_secs(12);
+ while CLIENTS.load(Ordering::SeqCst) > 0 && Instant::now() < until {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ status(SERVICE_STOPPED);
+}
+pub fn run() -> Result<()> {
+ let name = wide(&crate::service_name()?);
+ let table = [
+ SERVICE_TABLE_ENTRYW {
+ lpServiceName: name.as_ptr().cast_mut(),
+ lpServiceProc: Some(entry),
+ },
+ SERVICE_TABLE_ENTRYW {
+ lpServiceName: ptr::null_mut(),
+ lpServiceProc: None,
+ },
+ ];
+ if unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } == 0 {
+ Err(error())
+ } else {
+ Ok(())
+ }
+}
+
+fn enable_session_privilege() -> Result<()> {
+ let mut raw = ptr::null_mut();
+ if unsafe {
+ OpenProcessToken(
+ GetCurrentProcess(),
+ TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
+ &mut raw,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let token = Handle::new(raw)?;
+ let mut luid = unsafe { mem::zeroed() };
+ if unsafe { LookupPrivilegeValueW(ptr::null(), wide("SeTcbPrivilege").as_ptr(), &mut luid) }
+ == 0
+ {
+ return Err(error());
+ }
+ let privileges = TOKEN_PRIVILEGES {
+ PrivilegeCount: 1,
+ Privileges: [LUID_AND_ATTRIBUTES {
+ Luid: luid,
+ Attributes: SE_PRIVILEGE_ENABLED,
+ }],
+ };
+ if unsafe {
+ AdjustTokenPrivileges(token.0, 0, &privileges, 0, ptr::null_mut(), ptr::null_mut())
+ } == 0
+ || unsafe { GetLastError() } == ERROR_NOT_ALL_ASSIGNED
+ {
+ return Err(error());
+ }
+ Ok(())
+}
+fn spawn_worker(name: &str, session: u32) -> Result<(Handle, Handle, u32)> {
+ enable_session_privilege()?;
+ let mut original = ptr::null_mut();
+ if unsafe {
+ OpenProcessToken(
+ GetCurrentProcess(),
+ TOKEN_DUPLICATE | TOKEN_QUERY,
+ &mut original,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let original = Handle::new(original)?;
+ let mut raw = ptr::null_mut();
+ if unsafe {
+ DuplicateTokenEx(
+ original.0,
+ TOKEN_ALL_ACCESS,
+ ptr::null(),
+ SecurityImpersonation,
+ TokenPrimary,
+ &mut raw,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let token = Handle::new(raw)?;
+ if unsafe { SetTokenInformation(token.0, TokenSessionId, (&session as *const u32).cast(), 4) }
+ == 0
+ {
+ return Err(error());
+ }
+ let job = Handle::new(unsafe { CreateJobObjectW(ptr::null(), ptr::null()) })?;
+ let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { mem::zeroed() };
+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+ if unsafe {
+ SetInformationJobObject(
+ job.0,
+ JobObjectExtendedLimitInformation,
+ (&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
+ mem::size_of_val(&limits) as u32,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let executable = std::env::current_exe()?;
+ let path = wide(&executable.to_string_lossy());
+ let mut command = wide(&format!("\"{}\" --worker {}", executable.display(), name));
+ let desktop = wide("winsta0\\default");
+ let mut startup: STARTUPINFOW = unsafe { mem::zeroed() };
+ startup.cb = mem::size_of_val(&startup) as u32;
+ startup.lpDesktop = desktop.as_ptr().cast_mut();
+ let mut process: PROCESS_INFORMATION = unsafe { mem::zeroed() };
+ if unsafe {
+ CreateProcessAsUserW(
+ token.0,
+ path.as_ptr(),
+ command.as_mut_ptr(),
+ ptr::null(),
+ ptr::null(),
+ 0,
+ CREATE_SUSPENDED | CREATE_NO_WINDOW,
+ ptr::null(),
+ wide(&executable.parent().unwrap().to_string_lossy()).as_ptr(),
+ &startup,
+ &mut process,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let thread = Handle::new(process.hThread)?;
+ let child = Handle::new(process.hProcess)?;
+ if unsafe { AssignProcessToJobObject(job.0, child.0) } == 0 {
+ unsafe {
+ TerminateProcess(child.0, 1);
+ }
+ return Err(error());
+ }
+ if unsafe { ResumeThread(thread.0) } == u32::MAX {
+ return Err(error());
+ }
+ Ok((job, child, process.dwProcessId))
+}
+fn serve(mut client: Pipe) -> Result<()> {
+ let caller = process(client.client_pid()?)?;
+ let init = client.line(1024)?;
+ let parsed: serde_json::Value = serde_json::from_slice(&init)?;
+ if parsed["mode"] == "authorize" {
+ // Only the fixed UAC-elevated setup executable may register a process.
+ let caller_token = token(caller.0)?;
+ let mut elevation: TOKEN_ELEVATION = unsafe { mem::zeroed() };
+ let mut needed = 0;
+ if !crate::security::same_file(&image(caller.0)?, &std::env::current_exe()?)
+ || unsafe {
+ GetTokenInformation(
+ caller_token.0,
+ TokenElevation,
+ (&mut elevation as *mut TOKEN_ELEVATION).cast(),
+ mem::size_of_val(&elevation) as u32,
+ &mut needed,
+ )
+ } == 0
+ || elevation.TokenIsElevated == 0
+ {
+ return denied();
+ }
+ let main_pid = parsed["pid"]
+ .as_u64()
+ .filter(|p| *p <= u32::MAX as u64)
+ .ok_or_else(error)? as u32;
+ let (main, _) = crate::security::authorize_client(main_pid)?;
+ *AUTHORIZED.lock().map_err(|_| error())? = Some(main);
+ return client.write(b"ready\n");
+ }
+ {
+ let authorized = AUTHORIZED.lock().map_err(|_| error())?;
+ let main = authorized.as_ref().ok_or_else(error)?;
+ if unsafe { WaitForSingleObject(main.0, 0) } != WAIT_TIMEOUT
+ || unsafe { GetProcessId(main.0) } != client.client_pid()?
+ {
+ return denied();
+ }
+ }
+ let (owner, session) = crate::security::authorize_client(client.client_pid()?)?;
+ if parsed["mode"] == "probe" {
+ return client.write(b"ready\n");
+ }
+ if parsed["mode"] != "input" && parsed["mode"] != "capture" {
+ return denied();
+ }
+ let mut guid = unsafe { mem::zeroed() };
+ if unsafe { CoCreateGuid(&mut guid) } < 0 {
+ return denied();
+ }
+ let name = format!(
+ r"\\.\pipe\{}-{:08x}{:04x}{:04x}{:02x?}",
+ crate::service_name()?,
+ guid.data1,
+ guid.data2,
+ guid.data3,
+ guid.data4
+ )
+ .replace([',', ' ', '[', ']'], "");
+ let mut worker = Pipe::server(&name, true)?;
+ worker.shutdown = Some(&STOP);
+ let (job, child, pid) = spawn_worker(&name, session)?;
+ let mut worker = Worker {
+ pipe: Some(worker),
+ child,
+ job,
+ };
+ worker.accept(5000)?;
+ if worker.client_pid()? != pid {
+ return denied();
+ }
+ worker.write(&init)?;
+ client.write(&worker.line(1024)?)?;
+ let mut held = std::collections::HashSet::<String>::new();
+ loop {
+ let request = client.line(32768)?;
+ if STOP.load(Ordering::SeqCst)
+ || unsafe { WaitForSingleObject(owner.0, 0) } != WAIT_TIMEOUT
+ || session != unsafe { WTSGetActiveConsoleSessionId() }
+ {
+ return denied();
+ }
+ {
+ let authorized = AUTHORIZED.lock().map_err(|_| error())?;
+ if !authorized.as_ref().is_some_and(|main| unsafe {
+ WaitForSingleObject(main.0, 0) == WAIT_TIMEOUT
+ && GetProcessId(main.0) == GetProcessId(owner.0)
+ }) {
+ return denied();
+ }
+ }
+ if parsed["mode"] == "input" {
+ let events: Vec<serde_json::Value> = serde_json::from_slice(&request)?;
+ if events.len() > 64 {
+ return denied();
+ }
+ for event in events {
+ if event["kind"] == "release" {
+ held.clear();
+ }
+ if event["kind"] == "key" {
+ if let (Some(code), Some(down)) =
+ (event["code"].as_str(), event["down"].as_bool())
+ {
+ if down
+ && code == "Delete"
+ && (held.contains("ControlLeft") || held.contains("ControlRight"))
+ && (held.contains("AltLeft") || held.contains("AltRight"))
+ {
+ worker.write(b"[{\"kind\":\"release\"}]\n")?;
+ worker.line(1024)?;
+ send_sas(&owner)?;
+ client.write(b"ok\n")?;
+ // Drop this input generation, including all pending batches.
+ return Ok(());
+ }
+ if down {
+ held.insert(code.to_owned());
+ } else {
+ held.remove(code);
+ }
+ if held.len() > 256 {
+ return denied();
+ }
+ }
+ }
+ }
+ }
+ worker.write(&request)?;
+ let response = worker.line(240001)?;
+ if session != unsafe { WTSGetActiveConsoleSessionId() } || STOP.load(Ordering::SeqCst) {
+ return denied();
+ }
+ {
+ let authorized = AUTHORIZED.lock().map_err(|_| error())?;
+ if !authorized.as_ref().is_some_and(|main| unsafe {
+ WaitForSingleObject(main.0, 0) == WAIT_TIMEOUT
+ && GetProcessId(main.0) == GetProcessId(owner.0)
+ }) {
+ return denied();
+ }
+ }
+ client.write(&response)?;
+ }
+}
+struct Worker {
+ pipe: Option<Pipe>,
+ child: Handle,
+ job: Handle,
+}
+impl std::ops::Deref for Worker {
+ type Target = Pipe;
+ fn deref(&self) -> &Pipe {
+ self.pipe.as_ref().unwrap()
+ }
+}
+impl std::ops::DerefMut for Worker {
+ fn deref_mut(&mut self) -> &mut Pipe {
+ self.pipe.as_mut().unwrap()
+ }
+}
+impl Drop for Worker {
+ fn drop(&mut self) {
+ drop(self.pipe.take());
+ unsafe {
+ if WaitForSingleObject(self.child.0, 1200) != WAIT_OBJECT_0 {
+ TerminateJobObject(self.job.0, 1);
+ }
+ }
+ }
+}
+struct InputChild(std::process::Child);
+impl Drop for InputChild {
+ fn drop(&mut self) {
+ if let Some(mut input) = self.0.stdin.take() {
+ let _ = input.write_all(b"[{\"kind\":\"release\"}]\n");
+ }
+ let until = Instant::now() + Duration::from_millis(500);
+ while Instant::now() < until {
+ if self.0.try_wait().ok().flatten().is_some() {
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+}
+pub fn worker(name: &str) -> Result<()> {
+ if !system(token(unsafe { GetCurrentProcess() })?.0)?
+ || !name.starts_with(&format!(r"\\.\pipe\{}-", crate::service_name()?))
+ {
+ return denied();
+ }
+ let mut pipe = Pipe::client(name)?;
+ if pipe.server_pid()? != pid()? {
+ return denied();
+ }
+ let init: serde_json::Value = serde_json::from_slice(&pipe.line(1024)?)?;
+ if init["mode"] == "capture" {
+ let mut capture = crate::capture::Capture::new(&init["rect"])?;
+ pipe.write(b"ready\n")?;
+ loop {
+ if pipe.line(16)? != b"f\n" {
+ return denied();
+ }
+ pipe.write(&capture.frame()?)?;
+ }
+ }
+ if init["mode"] != "input" {
+ return denied();
+ }
+ let binary = std::env::current_exe()?.with_file_name("cindy-windows-desktop-input.exe");
+ use std::os::windows::process::CommandExt;
+ let mut child = InputChild(
+ std::process::Command::new(binary)
+ .creation_flags(CREATE_NO_WINDOW)
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .spawn()?,
+ );
+ let mut reader = io::BufReader::new(child.0.stdout.take().ok_or_else(error)?);
+ let mut line = String::new();
+ reader.read_line(&mut line)?;
+ if line != "ready\n" {
+ return denied();
+ }
+ pipe.write(b"ready\n")?;
+ // Observe input failure without blocking normal per-batch replies.
+ let failed = std::sync::Arc::new(AtomicBool::new(false));
+ let output = failed.clone();
+ std::thread::spawn(move || {
+ let mut line = String::new();
+ let _ = reader.read_line(&mut line);
+ output.store(true, Ordering::SeqCst);
+ });
+ loop {
+ let line = pipe.line(32768)?;
+ if failed.load(Ordering::SeqCst) {
+ return denied();
+ }
+ let events: Vec<serde_json::Value> = serde_json::from_slice(&line)?;
+ if events.len() > 64 {
+ return denied();
+ }
+ child.0.stdin.as_mut().ok_or_else(error)?.write_all(&line)?;
+ pipe.write(b"ok\n")?;
+ }
+}
+
+pub fn authorize(main_pid: u32) -> Result<()> {
+ let mut pipe = Pipe::client(&crate::pipe_name()?)?;
+ let server = process(pipe.server_pid()?)?;
+ if !system(token(server.0)?.0)?
+ || !crate::security::same_file(&image(server.0)?, &std::env::current_exe()?)
+ || pipe.server_pid()? != pid()?
+ {
+ return denied();
+ }
+ pipe.write(format!("{{\"mode\":\"authorize\",\"pid\":{main_pid}}}\n").as_bytes())?;
+ if pipe.line(1024)? != b"ready\n" {
+ return denied();
+ }
+ Ok(())
+}
+
+fn send_sas(owner: &Handle) -> Result<()> {
+ let mut raw = ptr::null_mut();
+ if unsafe { OpenProcessToken(owner.0, TOKEN_QUERY | TOKEN_DUPLICATE, &mut raw) } == 0 {
+ return Err(error());
+ }
+ let original = Handle::new(raw)?;
+ let mut raw = ptr::null_mut();
+ if unsafe {
+ DuplicateTokenEx(
+ original.0,
+ TOKEN_QUERY | TOKEN_IMPERSONATE,
+ ptr::null(),
+ SecurityImpersonation,
+ TokenImpersonation,
+ &mut raw,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ let impersonation = Handle::new(raw)?;
+ if unsafe { SetThreadToken(ptr::null(), impersonation.0) } == 0 {
+ return Err(error());
+ }
+ struct Revert;
+ impl Drop for Revert {
+ fn drop(&mut self) {
+ unsafe {
+ RevertToSelf();
+ }
+ }
+ }
+ let _revert = Revert;
+ // Windows policy decides whether software SAS is permitted. Never change it.
+ unsafe {
+ windows_sys::Win32::Security::Authentication::Identity::SendSAS(0);
+ }
+ Ok(())
+}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/win.rs b/apps/desktop/native/remote-desktop/windows-host/src/win.rs
new file mode 100644
index 0000000000..25085a4e10
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-host/src/win.rs
@@ -0,0 +1,91 @@
+use std::{io, ptr};
+use windows_sys::Win32::{
+ Foundation::*, Security::*, Storage::FileSystem::SYNCHRONIZE, System::Threading::*,
+};
+pub type Result<T> = io::Result<T>;
+pub fn error() -> io::Error {
+ io::Error::last_os_error()
+}
+pub fn denied<T>() -> Result<T> {
+ Err(io::Error::from(io::ErrorKind::PermissionDenied))
+}
+pub fn wide(value: &str) -> Vec<u16> {
+ value.encode_utf16().chain(Some(0)).collect()
+}
+pub struct Handle(pub HANDLE);
+unsafe impl Send for Handle {}
+impl Handle {
+ pub fn new(value: HANDLE) -> Result<Self> {
+ if value.is_null() || value == INVALID_HANDLE_VALUE {
+ Err(error())
+ } else {
+ Ok(Self(value))
+ }
+ }
+}
+impl Drop for Handle {
+ fn drop(&mut self) {
+ unsafe {
+ CloseHandle(self.0);
+ }
+ }
+}
+pub fn process(pid: u32) -> Result<Handle> {
+ Handle::new(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid) })
+}
+pub fn token(process: HANDLE) -> Result<Handle> {
+ let mut token = ptr::null_mut();
+ if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 {
+ return Err(error());
+ }
+ Handle::new(token)
+}
+pub fn session(token: HANDLE) -> Result<u32> {
+ let mut value = 0u32;
+ let mut size = 0;
+ if unsafe {
+ GetTokenInformation(
+ token,
+ TokenSessionId,
+ (&mut value as *mut u32).cast(),
+ 4,
+ &mut size,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ Ok(value)
+}
+pub fn system(token: HANDLE) -> Result<bool> {
+ let mut data = [0usize; 128];
+ let mut size = 0;
+ if unsafe {
+ GetTokenInformation(
+ token,
+ TokenUser,
+ data.as_mut_ptr().cast(),
+ std::mem::size_of_val(&data) as u32,
+ &mut size,
+ )
+ } == 0
+ {
+ return Err(error());
+ }
+ Ok(unsafe {
+ IsWellKnownSid(
+ (*(data.as_ptr().cast::<TOKEN_USER>())).User.Sid,
+ WinLocalSystemSid,
+ ) != 0
+ })
+}
+pub fn image(process: HANDLE) -> Result<std::path::PathBuf> {
+ let mut value = vec![0u16; 32768];
+ let mut size = value.len() as u32;
+ if unsafe { QueryFullProcessImageNameW(process, 0, value.as_mut_ptr(), &mut size) } == 0 {
+ return Err(error());
+ }
+ Ok(std::path::PathBuf::from(String::from_utf16_lossy(
+ &value[..size as usize],
+ )))
+}
diff --git a/apps/desktop/native/remote-desktop/windows-input/.gitignore b/apps/desktop/native/remote-desktop/windows-input/.gitignore
new file mode 100644
index 0000000000..b83d22266a
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-input/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/apps/desktop/native/remote-desktop/windows-input/Cargo.lock b/apps/desktop/native/remote-desktop/windows-input/Cargo.lock
new file mode 100644
index 0000000000..0b087914e8
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-input/Cargo.lock
@@ -0,0 +1,255 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "cindy-windows-desktop-input"
+version = "0.1.0"
+dependencies = [
+ "serde_json",
+ "windows",
+ "windows-sys",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.5",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "windows"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
+dependencies = [
+ "windows-core",
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-result",
+ "windows-strings",
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
+dependencies = [
+ "windows-result",
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/apps/desktop/native/remote-desktop/windows-input/Cargo.toml b/apps/desktop/native/remote-desktop/windows-input/Cargo.toml
new file mode 100644
index 0000000000..5a42982db1
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-input/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "cindy-windows-desktop-input"
+version = "0.1.0"
+edition = "2021"
+license = "Apache-2.0"
+
+[dependencies]
+windows = { version = "0.58", features = ["Win32_System_Com", "Win32_UI_Accessibility"] }
+serde_json = "1"
+windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_System_DataExchange", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging", "Win32_UI_HiDpi", "Win32_System_StationsAndDesktops", "Win32_System_Threading"] }
+
+[profile.release]
+panic = "abort"
+lto = true
+opt-level = "s"
+strip = true
diff --git a/apps/desktop/native/remote-desktop/windows-input/src/desktop.rs b/apps/desktop/native/remote-desktop/windows-input/src/desktop.rs
new file mode 100644
index 0000000000..c381db77bf
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-input/src/desktop.rs
@@ -0,0 +1,79 @@
+//! Input belongs to the active Windows desktop, not permanently to Default.
+//! This does not grant access: the OS still checks the process token. Secure
+//! desktops require the session worker to be launched by the SYSTEM broker.
+use windows_sys::Win32::System::StationsAndDesktops::*;
+
+pub struct InputDesktop {
+ handle: HDESK,
+ original: HDESK,
+ name: Vec<u16>,
+}
+
+impl InputDesktop {
+ pub fn new() -> Self {
+ Self {
+ handle: std::ptr::null_mut(),
+ original: unsafe {
+ GetThreadDesktop(windows_sys::Win32::System::Threading::GetCurrentThreadId())
+ },
+ name: Vec::new(),
+ }
+ }
+
+ /// Call only on the input thread, which must never own windows or hooks.
+ /// Returns true after a transition; callers discard the transition batch
+ /// so characters intended for the previous screen cannot reach a password
+ /// prompt or another user's desktop.
+ pub fn bind(&mut self) -> Result<bool, ()> {
+ unsafe {
+ let next = OpenInputDesktop(
+ 0,
+ 0,
+ DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP,
+ );
+ if next.is_null() {
+ return Err(());
+ }
+ let mut name = vec![0u16; 256];
+ let mut needed = 0;
+ if GetUserObjectInformationW(
+ next,
+ UOI_NAME,
+ name.as_mut_ptr().cast(),
+ (name.len() * 2) as u32,
+ &mut needed,
+ ) == 0
+ {
+ CloseDesktop(next);
+ return Err(());
+ }
+ name.truncate((needed as usize / 2).min(name.len()));
+ if !self.handle.is_null() && name == self.name {
+ CloseDesktop(next);
+ return Ok(false);
+ }
+ if SetThreadDesktop(next) == 0 {
+ CloseDesktop(next);
+ return Err(());
+ }
+ let changed = !self.handle.is_null();
+ if changed {
+ CloseDesktop(self.handle);
+ }
+ self.handle = next;
+ self.name = name;
+ Ok(changed)
+ }
+ }
+}
+
+impl Drop for InputDesktop {
+ fn drop(&mut self) {
+ unsafe {
+ // A desktop cannot be closed while still assigned to this thread.
+ if !self.handle.is_null() && SetThreadDesktop(self.original) != 0 {
+ CloseDesktop(self.handle);
+ }
+ }
+ }
+}
diff --git a/apps/desktop/native/remote-desktop/windows-input/src/main.rs b/apps/desktop/native/remote-desktop/windows-input/src/main.rs
new file mode 100644
index 0000000000..0db8e9f77d
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-input/src/main.rs
@@ -0,0 +1,302 @@
+use serde_json::Value;
+use std::{
+ collections::HashSet,
+ io::{self, BufRead, Read, Write},
+ sync::mpsc,
+ time::Duration,
+};
+use windows_sys::Win32::UI::{HiDpi::*, Input::KeyboardAndMouse::*, WindowsAndMessaging::*};
+mod desktop;
+mod selection;
+
+static FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+fn send(input: INPUT) -> bool {
+ let ok = unsafe { SendInput(1, &input, std::mem::size_of::<INPUT>() as i32) == 1 };
+ if !ok && !FAILED.swap(true, std::sync::atomic::Ordering::SeqCst) {
+ println!("error");
+ io::stdout().flush().ok();
+ }
+ ok
+}
+fn key(code: u16, down: bool, unicode: bool) -> bool {
+ let extended = [0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x2d, 0x2e].contains(&code);
+ send(INPUT {
+ r#type: INPUT_KEYBOARD,
+ Anonymous: INPUT_0 {
+ ki: KEYBDINPUT {
+ wVk: if unicode { 0 } else { code },
+ wScan: if unicode { code } else { 0 },
+ dwFlags: (if down { 0 } else { KEYEVENTF_KEYUP })
+ | (if unicode {
+ KEYEVENTF_UNICODE
+ } else if extended {
+ KEYEVENTF_EXTENDEDKEY
+ } else {
+ 0
+ }),
+ time: 0,
+ dwExtraInfo: 0,
+ },
+ },
+ })
+}
+fn mouse(flags: u32, dx: i32, dy: i32, data: u32) -> bool {
+ send(INPUT {
+ r#type: INPUT_MOUSE,
+ Anonymous: INPUT_0 {
+ mi: MOUSEINPUT {
+ dx,
+ dy,
+ mouseData: data,
+ dwFlags: flags,
+ time: 0,
+ dwExtraInfo: 0,
+ },
+ },
+ })
+}
+fn button(b: u64, down: bool) -> bool {
+ mouse(
+ match (b, down) {
+ (0, true) => MOUSEEVENTF_LEFTDOWN,
+ (0, false) => MOUSEEVENTF_LEFTUP,
+ (1, true) => MOUSEEVENTF_MIDDLEDOWN,
+ (1, false) => MOUSEEVENTF_MIDDLEUP,
+ (2, true) => MOUSEEVENTF_RIGHTDOWN,
+ _ => MOUSEEVENTF_RIGHTUP,
+ },
+ 0,
+ 0,
+ 0,
+ )
+}
+fn code(s: &str) -> Option<u16> {
+ if s.len() == 4 && s.starts_with("Key") && s.as_bytes()[3].is_ascii_uppercase() {
+ return Some(s.as_bytes()[3] as u16);
+ }
+ if s.len() == 6 && s.starts_with("Digit") && s.as_bytes()[5].is_ascii_digit() {
+ return Some(s.as_bytes()[5] as u16);
+ }
+ if let Some(n) = s.strip_prefix('F').and_then(|v| v.parse::<u16>().ok()) {
+ if (1..=12).contains(&n) {
+ return Some(0x6f + n);
+ }
+ }
+ Some(match s {
+ "Enter" => 13,
+ "Escape" => 27,
+ "Tab" => 9,
+ "Space" => 32,
+ "Backspace" => 8,
+ "Delete" => 46,
+ "Insert" => 45,
+ "Home" => 36,
+ "End" => 35,
+ "PageUp" => 33,
+ "PageDown" => 34,
+ "ArrowUp" => 38,
+ "ArrowDown" => 40,
+ "ArrowLeft" => 37,
+ "ArrowRight" => 39,
+ "ShiftLeft" => 0xa0,
+ "ControlLeft" => 0xa2,
+ "AltLeft" => 0xa4,
+ "MetaLeft" => 0x5b,
+ "Minus" => 0xbd,
+ "Equal" => 0xbb,
+ "BracketLeft" => 0xdb,
+ "BracketRight" => 0xdd,
+ "Backslash" => 0xdc,
+ "Semicolon" => 0xba,
+ "Quote" => 0xde,
+ "Backquote" => 0xc0,
+ "Comma" => 0xbc,
+ "Period" => 0xbe,
+ "Slash" => 0xbf,
+ _ => return None,
+ })
+}
+fn release(keys: &mut HashSet<u16>, buttons: &mut HashSet<u64>) {
+ for k in keys.clone() {
+ if key(k, false, false) {
+ keys.remove(&k);
+ }
+ }
+ for b in buttons.clone() {
+ if button(b, false) {
+ buttons.remove(&b);
+ }
+ }
+}
+fn main() {
+ if matches!(std::env::args().nth(1).as_deref(), Some("--clipboard-selection" | "--clipboard-content-selection")) {
+ match selection::read(std::env::args().nth(1).as_deref() == Some("--clipboard-content-selection")) {
+ Ok(text) => println!("{}", serde_json::json!({"text":text})),
+ Err(_) => std::process::exit(2),
+ }
+ return;
+ }
+ if std::env::args().nth(1).as_deref() == Some("--clipboard-version") {
+ // The user-session clipboard must never masquerade as secure-desktop data.
+ use windows_sys::Win32::System::{DataExchange::*, StationsAndDesktops::*};
+ unsafe {
+ let desktop = OpenInputDesktop(0, 0, DESKTOP_READOBJECTS);
+ if desktop.is_null() {
+ std::process::exit(2);
+ }
+ let mut name = [0u16; 256];
+ let mut needed = 0;
+ let ok = GetUserObjectInformationW(
+ desktop,
+ UOI_NAME,
+ name.as_mut_ptr().cast(),
+ 512,
+ &mut needed,
+ );
+ CloseDesktop(desktop);
+ let length = name.iter().position(|c| *c == 0).unwrap_or(name.len());
+ if ok == 0 || String::from_utf16_lossy(&name[..length]) != "Default" {
+ std::process::exit(2);
+ }
+ println!("{}", GetClipboardSequenceNumber());
+ }
+ return;
+ }
+
+ unsafe {
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ }
+ let (tx, rx) = mpsc::sync_channel(64);
+ std::thread::spawn(move || {
+ let mut input = io::stdin().lock();
+ loop {
+ // Bound allocation before reading, not after lines() has allocated
+ // an arbitrarily large attacker-controlled string.
+ let mut line = Vec::new();
+ match input.by_ref().take(32_769).read_until(b'\n', &mut line) {
+ Ok(0) | Err(_) => break,
+ Ok(_) if line.len() > 32_768 || line.last() != Some(&b'\n') => break,
+ Ok(_) => {
+ if tx.send(line).is_err() {
+ break;
+ }
+ }
+ }
+ }
+ });
+ let mut keys = HashSet::new();
+ let mut buttons = HashSet::new();
+ let mut desktop = desktop::InputDesktop::new();
+ if desktop.bind().is_err() {
+ println!("error");
+ return;
+ }
+ println!("ready");
+ io::stdout().flush().ok();
+ 'input: loop {
+ let line = match rx.recv_timeout(Duration::from_secs(5)) {
+ Ok(line) => line,
+ Err(mpsc::RecvTimeoutError::Timeout) => break,
+ Err(_) => break,
+ };
+ match desktop.bind() {
+ Ok(true) => {
+ release(&mut keys, &mut buttons);
+ break;
+ }
+ Ok(false) => (),
+ Err(_) => {
+ println!("error");
+ io::stdout().flush().ok();
+ break;
+ }
+ }
+ let events: Vec<Value> = match serde_json::from_slice(&line) {
+ Ok(v) => v,
+ Err(_) => break,
+ };
+ if events.len() > 64 {
+ break;
+ }
+ for e in events {
+ // Never replay a queued batch on a newly active secure desktop.
+ if desktop.bind() != Ok(false) {
+ break 'input;
+ }
+ if FAILED.load(std::sync::atomic::Ordering::SeqCst) {
+ release(&mut keys, &mut buttons);
+ break;
+ }
+ let kind = e["kind"].as_str().unwrap_or("");
+ match kind {
+ "release" => release(&mut keys, &mut buttons),
+ "move" | "button" => {
+ if let (Some(x), Some(y)) = (e["x"].as_f64(), e["y"].as_f64()) {
+ unsafe {
+ let left = GetSystemMetrics(SM_XVIRTUALSCREEN);
+ let top = GetSystemMetrics(SM_YVIRTUALSCREEN);
+ let w = GetSystemMetrics(SM_CXVIRTUALSCREEN).max(2);
+ let h = GetSystemMetrics(SM_CYVIRTUALSCREEN).max(2);
+ mouse(
+ MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
+ (((x - left as f64) * 65535.0) / (w - 1) as f64) as i32,
+ (((y - top as f64) * 65535.0) / (h - 1) as f64) as i32,
+ 0,
+ );
+ }
+ }
+ if kind == "button" {
+ if let (Some(b), Some(down)) = (e["button"].as_u64(), e["down"].as_bool()) {
+ if b <= 2 {
+ if down {
+ buttons.insert(b);
+ }
+ if button(b, down) && !down {
+ buttons.remove(&b);
+ }
+ }
+ }
+ }
+ }
+ "key" => {
+ if let (Some(c), Some(down)) =
+ (e["code"].as_str().and_then(code), e["down"].as_bool())
+ {
+ if down {
+ keys.insert(c);
+ }
+ if key(c, down, false) && !down {
+ keys.remove(&c);
+ }
+ }
+ }
+ "text" => {
+ if let Some(text) = e["text"].as_str() {
+ for c in text.encode_utf16().take(4096) {
+ if desktop.bind() != Ok(false) {
+ break 'input;
+ }
+ key(c, true, true);
+ key(c, false, true);
+ }
+ }
+ }
+ "scroll" => {
+ let dy = e["dy"].as_f64().unwrap_or(0.0).clamp(-2000.0, 2000.0) as i32;
+ let dx = e["dx"].as_f64().unwrap_or(0.0).clamp(-2000.0, 2000.0) as i32;
+ if dy != 0 {
+ mouse(MOUSEEVENTF_WHEEL, 0, 0, (-dy) as u32);
+ }
+ if dx != 0 {
+ mouse(MOUSEEVENTF_HWHEEL, 0, 0, dx as u32);
+ }
+ }
+ _ => (),
+ }
+ }
+ if FAILED.load(std::sync::atomic::Ordering::SeqCst) {
+ break;
+ }
+ }
+ release(&mut keys, &mut buttons);
+}
diff --git a/apps/desktop/native/remote-desktop/windows-input/src/selection.rs b/apps/desktop/native/remote-desktop/windows-input/src/selection.rs
new file mode 100644
index 0000000000..7c8391fb9d
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/windows-input/src/selection.rs
@@ -0,0 +1,79 @@
+use windows::{
+ core::Interface,
+ Win32::{System::Com::*, UI::Accessibility::*},
+};
+
+pub fn read(portable: bool) -> windows::core::Result<String> {
+ unsafe {
+ require_normal_desktop()?;
+ CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
+ struct Com;
+ impl Drop for Com {
+ fn drop(&mut self) {
+ unsafe {
+ CoUninitialize();
+ }
+ }
+ }
+ let _com = Com;
+ let automation: IUIAutomation =
+ CoCreateInstance(&CUIAutomation, None, CLSCTX_INPROC_SERVER)?;
+ let element = automation.GetFocusedElement()?;
+ if element.CurrentIsPassword()?.as_bool() {
+ return Err(windows::core::Error::from_win32());
+ }
+ let text = match element.GetCurrentPattern(UIA_TextPatternId) {
+ Ok(pattern) => {
+ let pattern: IUIAutomationTextPattern = pattern.cast()?;
+ let selection = pattern.GetSelection()?;
+ // Disjoint selections have application-specific ordering.
+ let count = selection.Length()?;
+ if count < 0 || count > 1 {
+ return Err(windows::core::Error::from_win32());
+ }
+ if count == 0 { String::new() }
+ else { selection.GetElement(0)?.GetText(16385)?.to_string() }
+ }
+ Err(error) if portable && error.code().0 as u32 == UIA_E_NOTSUPPORTED => String::new(),
+ Err(error) => return Err(error),
+ };
+ if text.encode_utf16().count() > 16384
+ || !automation
+ .CompareElements(&element, &automation.GetFocusedElement()?)?
+ .as_bool()
+ {
+ return Err(windows::core::Error::from_win32());
+ }
+ require_normal_desktop()?;
+ if element.CurrentIsPassword()?.as_bool() {
+ return Err(windows::core::Error::from_win32());
+ }
+ Ok(text)
+ }
+}
+
+fn require_normal_desktop() -> windows::core::Result<()> {
+ unsafe {
+ // Never expose the ordinary user's selection while a secure desktop is active.
+ use windows_sys::Win32::System::StationsAndDesktops::*;
+ let desktop = OpenInputDesktop(0, 0, DESKTOP_READOBJECTS);
+ if desktop.is_null() {
+ return Err(windows::core::Error::from_win32());
+ }
+ let mut name = [0u16; 256];
+ let mut needed = 0;
+ let ok = GetUserObjectInformationW(
+ desktop,
+ UOI_NAME,
+ name.as_mut_ptr().cast(),
+ 512,
+ &mut needed,
+ );
+ CloseDesktop(desktop);
+ let length = name.iter().position(|c| *c == 0).unwrap_or(name.len());
+ if ok == 0 || String::from_utf16_lossy(&name[..length]) != "Default" {
+ return Err(windows::core::Error::from_win32());
+ }
+ Ok(())
+ }
+}
diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nsh
index aa013f55b2..ab6a42ff46 100644
--- a/apps/desktop/resources/installer.nsh
+++ b/apps/desktop/resources/installer.nsh
@@ -79,3 +79,17 @@
DeleteRegKey HKCU "Software\Classes\SystemFileAssociations\.xdtshare\shell\${PRODUCT_FILENAME}"
System::Call 'shell32::SHChangeNotify(i 0x08000000, i 0, i 0, i 0)'
!macroend
+
+; Runs before removing files, including the old-version uninstall during upgrade.
+; Never leave a SYSTEM service referring to a removed or partially updated image.
+!macro customUnInit
+ IfFileExists "$INSTDIR\resources\tools\remote-desktop\cindy-windows-desktop-host.exe" 0 cindy_remote_service_done
+ nsExec::ExecToStack '"$INSTDIR\resources\tools\remote-desktop\cindy-windows-desktop-host.exe" --uninstall'
+ Pop $R0
+ Pop $R1
+ ${If} $R0 != 0
+ MessageBox MB_OK|MB_ICONSTOP "Could not stop the Cindy remote desktop service. Run the uninstaller as administrator and try again."
+ Abort
+ ${EndIf}
+ cindy_remote_service_done:
+!macroend
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
index 9c75204af3..960333fc4b 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
@@ -1170,6 +1170,7 @@ describe('device-link revoke / restore handlers', () => {
describe('device-link settings normalize', () => {
it('非法输入回落默认值,布尔严格校验', () => {
expect(settingsTesting.normalize(null)).toEqual({
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
@@ -1177,6 +1178,7 @@ describe('device-link settings normalize', () => {
lastKnownDeviceNames: {},
});
expect(settingsTesting.normalize({})).toEqual({
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
@@ -1184,6 +1186,7 @@ describe('device-link settings normalize', () => {
lastKnownDeviceNames: {},
});
expect(settingsTesting.normalize({ remoteControlEnabled: 'true' })).toEqual({
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
@@ -1191,6 +1194,7 @@ describe('device-link settings normalize', () => {
lastKnownDeviceNames: {},
});
expect(settingsTesting.normalize({ remoteControlEnabled: true })).toEqual({
+ remoteDesktopEnabled: false,
remoteControlEnabled: true,
keepAwake: false,
revokedControllers: [],
@@ -1205,6 +1209,7 @@ describe('device-link settings normalize', () => {
disabledControlDeviceIds: [' dev-1 ', 'dev-1', '', 42, 'dev-2'],
}),
).toEqual({
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
@@ -1224,6 +1229,7 @@ describe('device-link settings normalize', () => {
},
}),
).toEqual({
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
diff --git a/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts b/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts
index bad6337fc2..d263665bc7 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts
@@ -62,6 +62,7 @@ const h = vi.hoisted(() => {
const SETTINGS_PATH = path.join('/tmp/userdata', 'device-link-settings.json');
const DEFAULT_SETTINGS = {
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
@@ -128,6 +129,7 @@ describe('readDeviceLinkSettings', () => {
const { readDeviceLinkSettings } = await load();
expect(readDeviceLinkSettings()).toEqual({
remoteControlEnabled: true,
+ remoteDesktopEnabled: false,
keepAwake: false,
revokedControllers: ['dev-1', 'dev-2'],
disabledControlDeviceIds: [],
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 382681a98b..c639ec6d73 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -461,6 +461,7 @@ import { sanitizeGhostNoticeText } from './cindy-brain/notifySlot.js';
import { isIpcError } from '../shared/ipc-errors';
import { readFileBytesForPreview } from './fileReadBytes.js';
import { initHeartbeatService } from './heartbeatService';
+import { registerRemoteDesktopIpc } from './remote-desktop';
import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';
import { initLogUploadService, scheduleStartupBackfill } from './log-upload';
import { WindowManualDragController } from './windowManualDrag';
@@ -8825,6 +8826,7 @@ app.on('ready', async () => {
// owning modules above; future collections/actions do not add tunnel channels.
registerRemoteResourcesIpc();
registerDeviceLinkIpc();
+ registerRemoteDesktopIpc();
void startupPurgeDrain
.then(({ purged, pending }) => {
if (purged > 0 || pending > 0) {
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 3370cfb660..81495146de 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -66,6 +66,8 @@ import {
type ProviderLogoRouting,
} from '@cindy/model-providers/branding';
import { app } from 'electron';
+import { remoteDesktop } from '../remote-desktop';
+import { REMOTE_DESKTOP_CHANNEL } from '@cindy/device-link';
import type { DeviceLinkClient } from '@cindy/device-link';
import { createLogger } from '../logger';
import { projectMobileMessagePage, projectMobileToolPush } from './mobileToolProjection';
@@ -1805,6 +1807,7 @@ export function dropAllControllers(
client: DeviceLinkClient,
reason: 'user' | 'toggle-off' | 'shutdown',
): void {
+ remoteDesktop.stop();
const controllerIds = new Set([
...subscriptions.getControllerIds(),
...topicSubscriptionControllers,
@@ -1863,6 +1866,7 @@ function deactivateControllerState(
}
let changed = false;
changed = acceptedLinkControllers.delete(deviceId) || changed;
+ remoteDesktop.stop(deviceId);
changed = controllerConnectionEpochByDevice.delete(deviceId) || changed;
changed = controllerLinkGenerationByDevice.delete(deviceId) || changed;
changed = reportedControllerNameByDevice.has(deviceId) || changed;
@@ -1902,6 +1906,7 @@ export function deactivateController(
/** Relay 连接离开 online:清本连接代所有 active controller,但保留恢复意图。 */
export function deactivateAllControllers(reason: string): void {
+ remoteDesktop.stop();
const controllerIds = new Set([
...subscriptions.getControllerIds(),
...topicSubscriptionControllers,
@@ -1940,6 +1945,7 @@ export function forgetControllerInvokeState(deviceId: string): void {
/** 显式撤销时清理短时离线队列与 remembered topic,避免恢复后重放撤权期间数据。 */
export function purgeRevokedController(deviceId: string): void {
+ remoteDesktop.stop(deviceId);
const changed = deactivateControllerState(deviceId);
topicSubscriptionControllers.delete(deviceId);
offlinePushQueue.clear(deviceId);
@@ -1988,6 +1994,7 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi
return;
}
clearRemoteInvokeStateFor(src);
+ remoteDesktop.stop(src);
offlinePushQueue.clear(src);
const deactivated = deactivateControllerState(src);
// Keep the protocol-capability marker, but discard all remembered routing.
@@ -3195,6 +3202,11 @@ export async function runInvoke(
};
}
+ if (payload.channel === REMOTE_DESKTOP_CHANNEL) {
+ try { return { ok: true, result: await remoteDesktop.request(src, payload.args?.[0]) }; }
+ catch (error) { return { ok: false, error: { code: 'IPC_ERROR', message: error instanceof Error ? error.message : 'DESKTOP_UNAVAILABLE' } }; }
+ }
+
// Review sessions may be mirrored to controllers for visibility, but their
// only input is the host's direct reviewer.send() call. Reject before the
// synthetic ipcMain event is dispatched, then let the handler repeat the
diff --git a/apps/desktop/src/main/device-link/settings-store.ts b/apps/desktop/src/main/device-link/settings-store.ts
index 6b15e100a3..1f7ec624c6 100644
--- a/apps/desktop/src/main/device-link/settings-store.ts
+++ b/apps/desktop/src/main/device-link/settings-store.ts
@@ -30,6 +30,8 @@ import { createLogger } from '../logger';
const log = createLogger('device-link-settings');
export interface DeviceLinkSettings {
+ /** Full desktop viewing/input is a separate, local opt-in. */
+ remoteDesktopEnabled: boolean;
remoteControlEnabled: boolean;
/**
* 「保持电脑唤醒」:开启后 main 用 powerSaveBlocker('prevent-app-suspension')
@@ -46,6 +48,7 @@ export interface DeviceLinkSettings {
}
const DEFAULTS: DeviceLinkSettings = {
+ remoteDesktopEnabled: false,
remoteControlEnabled: false,
keepAwake: false,
revokedControllers: [],
@@ -61,6 +64,7 @@ function normalize(raw: unknown): DeviceLinkSettings {
if (!raw || typeof raw !== 'object') return { ...DEFAULTS };
const r = raw as Record<string, unknown>;
return {
+ remoteDesktopEnabled: r.remoteDesktopEnabled === true,
remoteControlEnabled: r.remoteControlEnabled === true,
keepAwake: r.keepAwake === true,
revokedControllers: Array.isArray(r.revokedControllers)
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index 86f22e332c..fc06f351c9 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -1,4 +1,5 @@
import path from 'node:path';
+import { withAgentDesktopInput } from '../remote-desktop/inputOwnership';
import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { spawn, type ChildProcess } from 'node:child_process';
@@ -3356,6 +3357,16 @@ export async function callComputerDriverTool(
name: ComputerMcpToolName,
args: Record<string, unknown>,
context?: ComputerMcpCallContext,
+): Promise<unknown> {
+ return getComputerTool(name)?.readOnly === true
+ ? callComputerDriverToolImpl(name, args, context)
+ : withAgentDesktopInput(() => callComputerDriverToolImpl(name, args, context));
+}
+
+async function callComputerDriverToolImpl(
+ name: ComputerMcpToolName,
+ args: Record<string, unknown>,
+ context?: ComputerMcpCallContext,
): Promise<unknown> {
const signal = context?.signal;
signal?.throwIfAborted();
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts
new file mode 100644
index 0000000000..2d74f5a937
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { desktopCaptureSource } from '../captureSource';
+
+describe('desktop capture availability', () => {
+ it('waits for the same attached display when capture temporarily omits it', () => {
+ const displays = [{ id: 1 }, { id: 2 }];
+ const other = { display_id: '2', id: 'screen:2:0' };
+ const selected = { display_id: '1', id: 'screen:1:0' };
+ expect(desktopCaptureSource([], '1', displays)).toBeNull();
+ expect(desktopCaptureSource([other], '1', displays)).toBeNull();
+ expect(desktopCaptureSource([other, selected], '1', displays)).toBe(selected);
+ });
+ it('still rejects a detached display and does not infer undocumented IDs', () => {
+ expect(() => desktopCaptureSource([{ display_id: '1' }], '1', [])).toThrow('DESKTOP_DISPLAY_MISSING');
+ expect(desktopCaptureSource([{ display_id: '', id: 'screen:1:0' }], '1', [{ id: 1 }])).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
new file mode 100644
index 0000000000..892781dbf4
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
@@ -0,0 +1,259 @@
+import { describe, expect, it, vi } from 'vitest';
+import { RemoteDesktopController, type DesktopControllerDeps } from '../controller';
+import { acquireHumanDesktopInput, withAgentDesktopInput } from '../inputOwnership';
+import type { RemoteDesktopLease } from '@cindy/device-link';
+
+function harness() {
+ let now = 1000;
+ let allowed = true;
+ const deps: DesktopControllerDeps = {
+ authorized: () => allowed,
+ now: () => now,
+ capabilities: async () => ({
+ version: 1,
+ enabled: allowed,
+ canControl: true,
+ platform: 'darwin',
+ displays: [{ id: '1', name: 'Main', width: 1920, height: 1080 }],
+ }),
+ frame: vi.fn(async () => 'jpeg'),
+ startInput: vi.fn(async () => {}),
+ input: vi.fn(),
+ stopInput: vi.fn(),
+ stopVideo: vi.fn(),
+ offer: vi.fn(async () => 'answer'),
+ changed: vi.fn(),
+ };
+ const controller = new RemoteDesktopController(deps);
+ return {
+ controller,
+ deps,
+ advance: (ms: number) => {
+ now += ms;
+ },
+ revoke: () => {
+ allowed = false;
+ },
+ start: async () =>
+ controller.request('phone', { op: 'start', displayId: '1' }) as Promise<RemoteDesktopLease>,
+ };
+}
+describe('remote desktop authority and lifecycle', () => {
+ it('takes over only explicitly and prevents the evicted device from automatically returning', async () => {
+ const h = harness();
+ const first = await h.start();
+ await expect(h.controller.request('other', { op: 'start', displayId: '1' })).rejects.toThrow('DESKTOP_BUSY');
+ await expect(h.controller.request('other', { op: 'start', displayId: 'missing', takeover: true })).rejects.toThrow('DESKTOP_DISPLAY_MISSING');
+ expect(h.controller.hasLease(first.lease)).toBe(true);
+ await expect(h.controller.request('other', { op: 'start', displayId: '1', takeover: true, resume: true })).rejects.toThrow('INVALID_REQUEST');
+ const second = await h.controller.request('other', { op: 'start', displayId: '1', takeover: true }) as RemoteDesktopLease;
+ expect(h.controller.hasLease(first.lease)).toBe(false);
+ expect(h.controller.hasLease(second.lease)).toBe(true);
+ await expect(h.controller.request('phone', { op: 'stop', lease: first.lease })).rejects.toThrow('DESKTOP_STOPPED');
+ expect(h.controller.hasLease(second.lease)).toBe(true);
+ h.controller.stop('other');
+ await expect(h.controller.request('phone', { op: 'start', displayId: '1', resume: true })).rejects.toThrow('DESKTOP_STOPPED');
+ });
+ it('keeps the same lease and video negotiation through an empty fallback frame', async () => {
+ const h = harness();
+ h.deps.frame = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce('jpeg');
+ const { lease } = await h.start();
+ await expect(h.controller.request('phone', { op: 'frame', lease })).resolves.toEqual({ jpeg: null });
+ h.advance(350);
+ await expect(h.controller.request('phone', { op: 'frame', lease })).resolves.toEqual({ jpeg: 'jpeg' });
+ expect(h.controller.hasLease(lease)).toBe(true);
+ expect(h.deps.stopVideo).not.toHaveBeenCalled();
+ });
+ it('remembers a stop after the peer went offline and isolates each peer recovery decision', async () => {
+ const h = harness();
+ const first = await h.start();
+ h.controller.stop('phone');
+ h.controller.stopByUser();
+ const other = (await h.controller.request('other', {
+ op: 'start',
+ displayId: '1',
+ })) as RemoteDesktopLease;
+ h.controller.stopByUser();
+ await expect(
+ h.controller.request('phone', { op: 'start', displayId: '1', resume: true }),
+ ).rejects.toThrow('STOPPED');
+ await expect(
+ h.controller.request('other', { op: 'start', displayId: '1', resume: true }),
+ ).rejects.toThrow('STOPPED');
+ const explicit = await h.start();
+ expect(explicit.lease).not.toBe(first.lease);
+ h.controller.stop('phone');
+ await expect(
+ h.controller.request('phone', { op: 'start', displayId: '1', resume: true }),
+ ).resolves.toHaveProperty('lease');
+ });
+ it('distinguishes explicit host disconnect from an expired connection for recovery', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ h.controller.stopByUser();
+ await expect(
+ h.controller.request('phone', { op: 'start', displayId: '1', resume: true }),
+ ).rejects.toThrow('STOPPED');
+ await expect(h.controller.request('phone', { op: 'heartbeat', lease })).rejects.toThrow(
+ 'DESKTOP_STOPPED',
+ );
+ expect(() => h.controller.input(lease, 1, [{ kind: 'release' }])).toThrow('DESKTOP_STOPPED');
+ await expect(h.controller.request('other', { op: 'heartbeat', lease })).rejects.toThrow(
+ 'EXPIRED',
+ );
+ const next = (await h.controller.request('other', {
+ op: 'start',
+ displayId: '1',
+ })) as RemoteDesktopLease;
+ await expect(h.controller.request('phone', { op: 'stop', lease })).rejects.toThrow('STOPPED');
+ await expect(
+ h.controller.request('other', { op: 'heartbeat', lease: next.lease }),
+ ).resolves.toEqual({ controlling: false });
+ h.controller.stop();
+ await expect(
+ h.controller.request('other', { op: 'heartbeat', lease: next.lease }),
+ ).rejects.toThrow('EXPIRED');
+ });
+ it('keeps the host disconnect reason when an input grant completes late', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ let finish!: () => void;
+ h.deps.startInput = () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const control = h.controller.request('phone', { op: 'control', lease, enabled: true });
+ h.controller.stopByUser();
+ finish();
+ await expect(control).rejects.toThrow('STOPPED');
+ expect(h.controller.state).toBeNull();
+ });
+ it('requires local opt-in for the dedicated guide and never starts a lease while guiding', async () => {
+ const h = harness();
+ h.deps.permissions = vi.fn(async () => ({
+ screenRecording: 'missing' as const,
+ accessibility: 'granted' as const,
+ }));
+ await h.controller.request('phone', { op: 'permissions', action: 'guide' });
+ expect(h.deps.permissions).toHaveBeenCalledExactlyOnceWith('guide');
+ expect(h.controller.state).toBeNull();
+ h.revoke();
+ await expect(
+ h.controller.request('phone', { op: 'permissions', action: 'guide' }),
+ ).rejects.toThrow('DISABLED');
+ expect(h.deps.permissions).toHaveBeenCalledTimes(1);
+ });
+ it('requires screen permission to view, while missing accessibility still allows view-only', async () => {
+ const h = harness();
+ const caps = await h.deps.capabilities();
+ h.deps.capabilities = async () => ({
+ ...caps,
+ permissions: { screenRecording: 'missing', accessibility: 'granted' },
+ });
+ await expect(h.start()).rejects.toThrow('SCREEN_PERMISSION');
+ expect(h.controller.state).toBeNull();
+ h.deps.capabilities = async () => ({
+ ...caps,
+ permissions: { screenRecording: 'granted', accessibility: 'missing' },
+ });
+ expect((await h.start()).controlling).toBe(false);
+ });
+ it('starts view-only and binds every action to the actual peer and lease', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ expect(h.controller.state?.controlling).toBe(false);
+ await expect(
+ h.controller.request('other', { op: 'control', lease, enabled: true }),
+ ).rejects.toThrow('EXPIRED');
+ await expect(
+ h.controller.request('phone', {
+ op: 'input',
+ lease,
+ sequence: 1,
+ events: [{ kind: 'release' }],
+ }),
+ ).rejects.toThrow('VIEW_ONLY');
+ expect(h.deps.input).not.toHaveBeenCalled();
+ });
+ it('expires a lost phone and releases input/video; a different peer cannot stop it', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ await h.controller.request('phone', { op: 'control', lease, enabled: true });
+ h.controller.stop('other');
+ expect(h.controller.state).not.toBeNull();
+ h.advance(12001);
+ h.controller.tick();
+ expect(h.controller.state).toBeNull();
+ expect(h.deps.stopInput).toHaveBeenCalled();
+ expect(h.deps.stopVideo).toHaveBeenCalled();
+ });
+ it('never replays input and rechecks revoked authorization on the RTC path', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ await h.controller.request('phone', { op: 'control', lease, enabled: true });
+ h.controller.input(lease, 2, [{ kind: 'key', code: 'KeyA', down: true }]);
+ h.controller.input(lease, 2, [{ kind: 'key', code: 'KeyA', down: true }]);
+ expect(h.deps.input).toHaveBeenCalledTimes(1);
+ h.revoke();
+ expect(() => h.controller.input(lease, 3, [{ kind: 'release' }])).toThrow('EXPIRED');
+ expect(h.deps.input).toHaveBeenCalledTimes(1);
+ });
+ it('discards capture completed after local stop and bounds concurrent frame capture', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ let finish!: (value: string) => void;
+ h.deps.frame = () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ });
+ const first = h.controller.request('phone', { op: 'frame', lease });
+ expect(await h.controller.request('phone', { op: 'frame', lease })).toEqual({ jpeg: null });
+ h.controller.stop();
+ finish('private-screen');
+ await expect(first).rejects.toThrow('EXPIRED');
+ });
+ it('cannot resurrect control when the native helper becomes ready after stop', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ let finish!: () => void;
+ h.deps.startInput = () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ });
+ const start = h.controller.request('phone', { op: 'control', lease, enabled: true });
+ await expect(
+ h.controller.request('phone', { op: 'control', lease, enabled: true }),
+ ).rejects.toThrow('BUSY');
+ h.controller.stop();
+ finish();
+ await expect(start).rejects.toThrow('EXPIRED');
+ expect(h.controller.state).toBeNull();
+ });
+ it('arbitrates pending starts instead of allocating two leases', async () => {
+ const h = harness();
+ const first = h.start();
+ await expect(h.start()).rejects.toThrow('BUSY');
+ await first;
+ });
+ it('cancels a pending start when that peer disconnects', async () => {
+ const h = harness();
+ const first = h.start();
+ h.controller.stop('phone');
+ await expect(first).rejects.toThrow('DISABLED');
+ expect(h.controller.state).toBeNull();
+ });
+});
+describe('human / Agent input ownership', () => {
+ it('excludes simultaneous input in both directions and releases on error', async () => {
+ const release = acquireHumanDesktopInput();
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('person');
+ release();
+ await expect(
+ withAgentDesktopInput(async () => {
+ expect(() => acquireHumanDesktopInput()).toThrow('BUSY');
+ throw new Error('action');
+ }),
+ ).rejects.toThrow('action');
+ acquireHumanDesktopInput()();
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/frame.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/frame.test.ts
new file mode 100644
index 0000000000..68ec5ded6a
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/frame.test.ts
@@ -0,0 +1,28 @@
+import type { NativeImage } from 'electron';
+import { describe, expect, it, vi } from 'vitest';
+import { encodeDesktopFrame } from '../frame';
+import { REMOTE_DESKTOP_MAX_FRAME_BYTES } from '@cindy/device-link';
+
+function image(empty: boolean, bytes = Buffer.from('jpeg')) {
+ const thumbnail = {
+ isEmpty: () => empty,
+ toJPEG: vi.fn(() => bytes),
+ getSize: () => ({ width: 1280, height: 720 }),
+ resize: vi.fn(() => thumbnail),
+ };
+ return thumbnail as unknown as NativeImage;
+}
+
+describe('desktop fallback frames', () => {
+ it('treats an empty thumbnail as no frame, not a permission denial', () => {
+ const thumbnail = image(true);
+ expect(encodeDesktopFrame(thumbnail)).toBeNull();
+ expect(thumbnail.toJPEG).not.toHaveBeenCalled();
+ expect(encodeDesktopFrame(image(false))).toBe(Buffer.from('jpeg').toString('base64'));
+ });
+ it('keeps the encoded frame size bounded', () => {
+ const thumbnail = image(false, Buffer.alloc(REMOTE_DESKTOP_MAX_FRAME_BYTES + 1));
+ expect(() => encodeDesktopFrame(thumbnail)).toThrow('DESKTOP_FRAME_TOO_LARGE');
+ expect(thumbnail.toJPEG).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts
new file mode 100644
index 0000000000..ff6448af91
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts
@@ -0,0 +1,91 @@
+import { EventEmitter } from 'node:events';
+import type { ChildProcessWithoutNullStreams } from 'node:child_process';
+import { describe, expect, it, vi } from 'vitest';
+import { DesktopInputHost } from '../inputHost';
+import { withAgentDesktopInput } from '../inputOwnership';
+
+vi.mock('electron', () => ({
+ app: {},
+ screen: { getAllDisplays: () => [{ id: 1, bounds: { x: 0, y: 0, width: 100, height: 100 } }] },
+}));
+function childProcess() {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 1,
+ stdout: new EventEmitter(),
+ stderr: { resume() {} },
+ stdin: Object.assign(new EventEmitter(), {
+ destroyed: false,
+ writableLength: 0,
+ write: vi.fn(),
+ end: vi.fn(),
+ }),
+ exitCode: null as number | null,
+ signalCode: null,
+ kill: vi.fn(),
+ });
+ return {
+ child,
+ typed: child as unknown as ChildProcessWithoutNullStreams,
+ exit: () => {
+ child.exitCode = 0;
+ child.emit('exit', 0);
+ child.emit('close', 0);
+ },
+ };
+}
+describe('native input lifecycle', () => {
+ it('keeps Agent input excluded until the old helper has actually exited', async () => {
+ const c = childProcess();
+ const host = new DesktopInputHost(vi.fn(), {
+ platform: 'darwin',
+ resolveBinary: async () => '/test/helper',
+ spawn: () => {
+ queueMicrotask(() => c.child.stdout.emit('data', Buffer.from('ready\n')));
+ return c.typed;
+ },
+ });
+ await host.start('1');
+ host.stop();
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('person');
+ expect(c.child.stdin.end).toHaveBeenCalledWith('[{"kind":"release"}]\n');
+ c.exit();
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ });
+ it('does not spawn a helper if the lease was stopped during compilation', async () => {
+ let resolve!: (value: string) => void;
+ const spawn = vi.fn();
+ const host = new DesktopInputHost(vi.fn(), {
+ platform: 'darwin',
+ resolveBinary: () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ spawn,
+ });
+ const start = host.start('1');
+ await Promise.resolve();
+ host.stop();
+ resolve('/test/helper');
+ await expect(start).rejects.toThrow('EXPIRED');
+ expect(spawn).not.toHaveBeenCalled();
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ });
+ it('fails closed rather than writing an oversized native command', async () => {
+ const c = childProcess();
+ let host: DesktopInputHost;
+ const failure = vi.fn(() => host.stop());
+ host = new DesktopInputHost(failure, {
+ platform: 'darwin',
+ resolveBinary: async () => '/test/helper',
+ spawn: () => {
+ queueMicrotask(() => c.child.stdout.emit('data', Buffer.from('ready\n')));
+ return c.typed;
+ },
+ });
+ await host.start('1');
+ host.input(Array(3).fill({ kind: 'text', text: '中'.repeat(4096) }));
+ expect(failure).toHaveBeenCalledOnce();
+ expect(c.child.stdin.write).not.toHaveBeenCalled();
+ c.exit();
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts
new file mode 100644
index 0000000000..2ae4a1850d
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts
@@ -0,0 +1,29 @@
+import { execFile } from 'node:child_process';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { expect, it } from 'vitest';
+
+const exec = promisify(execFile);
+
+it.skipIf(process.platform !== 'darwin')(
+ 'preserves native system shortcut flags without posting input',
+ async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'cindy-keyboard-flags-'));
+ try {
+ const native = path.resolve(import.meta.dirname, '../../../../native/remote-desktop');
+ const source = await readFile(path.join(native, 'macos-input.swift'), 'utf8');
+ const tests = await readFile(path.join(native, 'macos-input.test.swift'), 'utf8');
+ const main = path.join(directory, 'main.swift');
+ const binary = path.join(directory, 'keyboard-test');
+ await writeFile(main, `${source}\n${tests}`);
+ await exec('swiftc', ['-D', 'DESKTOP_INPUT_TEST', main, '-o', binary], { timeout: 120_000 });
+ const { stdout } = await exec(binary, [], { timeout: 5000 });
+ expect(stdout.trim()).toBe('native keyboard flags passed');
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ },
+ 130_000,
+);
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/permissions.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/permissions.test.ts
new file mode 100644
index 0000000000..f1213926df
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/permissions.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it, vi } from 'vitest';
+import { RemoteDesktopPermissionsService } from '../permissions';
+function harness() {
+ const deps = {
+ required: true,
+ screen: vi.fn(() => 'missing' as const),
+ accessibility: vi.fn(async () => 'granted' as const),
+ request: vi.fn(
+ async (_permission: string, _isCurrent: () => boolean, _signal: AbortSignal) => {},
+ ),
+ openSettings: vi.fn(async () => {}),
+ showGuide: vi.fn(),
+ };
+ return { deps, service: new RemoteDesktopPermissionsService(deps) };
+}
+describe('remote desktop OS permissions', () => {
+ it('reads the two real permissions independently without requesting or opening anything', async () => {
+ const { service, deps } = harness();
+ expect(await service.read()).toEqual({ screenRecording: 'missing', accessibility: 'granted' });
+ expect(deps.request).not.toHaveBeenCalled();
+ expect(deps.openSettings).not.toHaveBeenCalled();
+ expect(deps.showGuide).not.toHaveBeenCalled();
+ });
+ it('does not claim a failed probe is granted', async () => {
+ const { service, deps } = harness();
+ deps.accessibility.mockRejectedValue(new Error('helper unavailable'));
+ expect((await service.read()).accessibility).toBe('unknown');
+ });
+ it('coalesces simultaneous checks but reads fresh permission state afterwards', async () => {
+ const { service, deps } = harness();
+ await Promise.all([service.read(), service.read()]);
+ expect(deps.accessibility).toHaveBeenCalledTimes(1);
+ await service.read();
+ expect(deps.accessibility).toHaveBeenCalledTimes(2);
+ });
+ it('only displays the in-app guide once, without triggering an OS prompt', () => {
+ const { service, deps } = harness();
+ service.show();
+ service.show();
+ expect(deps.showGuide).toHaveBeenCalledOnce();
+ expect(deps.request).not.toHaveBeenCalled();
+ service.dismiss();
+ expect(service.guideOpen).toBe(false);
+ });
+ it('cancels a pending OS follow-up after the guide closes', async () => {
+ const { service, deps } = harness();
+ let finish!: () => void;
+ let isCurrent!: () => boolean;
+ let signal!: AbortSignal;
+ deps.request.mockImplementation((_permission, current, abortSignal) => {
+ isCurrent = current;
+ signal = abortSignal;
+ return new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ });
+ const open = service.open('accessibility');
+ service.dismiss();
+ expect(isCurrent()).toBe(false);
+ expect(signal.aborted).toBe(true);
+ finish();
+ await open;
+ expect(deps.openSettings).not.toHaveBeenCalled();
+ });
+ it('still opens settings when the native request fails, without marking permissions granted', async () => {
+ const { service, deps } = harness();
+ deps.request.mockRejectedValue(new Error('request failed'));
+ await service.open('screenRecording');
+ expect(deps.openSettings).toHaveBeenCalledWith('screenRecording');
+ expect((await service.read()).screenRecording).toBe('missing');
+ });
+ it('does not reopen a dismissed guide when an old enable preflight resolves', async () => {
+ const { service, deps } = harness();
+ let finish!: () => void;
+ deps.accessibility.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = () => resolve('granted');
+ }),
+ );
+ const enable = service.showIfNeeded(() => true);
+ service.dismiss();
+ finish();
+ await enable;
+ expect(deps.showGuide).not.toHaveBeenCalled();
+ });
+ it('does not probe or open macOS permissions on other platforms', async () => {
+ const { service, deps } = harness();
+ deps.required = false;
+ expect(await service.read()).toEqual({
+ screenRecording: 'notRequired',
+ accessibility: 'notRequired',
+ });
+ service.show();
+ await service.open('accessibility');
+ expect(deps.accessibility).not.toHaveBeenCalled();
+ expect(deps.request).not.toHaveBeenCalled();
+ expect(deps.showGuide).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/captureSource.ts b/apps/desktop/src/main/remote-desktop/captureSource.ts
new file mode 100644
index 0000000000..45c8b2bc96
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/captureSource.ts
@@ -0,0 +1,11 @@
+/** A display can remain attached while its capture source is temporarily unavailable. */
+export function desktopCaptureSource<T extends { display_id: string }>(
+ sources: readonly T[],
+ displayId: string,
+ displays: readonly { id: number }[],
+): T | null {
+ if (!displays.some(display => String(display.id) === displayId))
+ throw new Error('DESKTOP_DISPLAY_MISSING');
+ // Never substitute another monitor or guess a mapping from source ordering.
+ return sources.find(source => source.display_id === displayId) ?? null;
+}
diff --git a/apps/desktop/src/main/remote-desktop/clipboard.ts b/apps/desktop/src/main/remote-desktop/clipboard.ts
new file mode 100644
index 0000000000..02c70c1365
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/clipboard.ts
@@ -0,0 +1,125 @@
+import { clipboard, nativeImage } from 'electron';
+import { REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS, type DesktopInput, type RemoteClipboardContent, parseClipboardContent, CLIPBOARD_MAX_CHARS } from '@cindy/device-link';
+import { readDesktopClipboardVersion, readDesktopSelection } from './inputHost';
+
+/** Explicit selection/text transfer. No background sync, logging or persistence. */
+export async function transferDesktopClipboard(
+ action: 'copy' | 'paste',
+ text: string | undefined,
+ isCurrent: () => boolean,
+ input: (events: DesktopInput[]) => void,
+): Promise<string | void> {
+ const check = () => {
+ if (!isCurrent()) throw new Error('DESKTOP_LEASE_EXPIRED');
+ };
+ check();
+ input([{ kind: 'release' }]);
+ if (action === 'copy') {
+ const selected = await readDesktopSelection();
+ check();
+ if (selected) {
+ clipboard.writeText(selected);
+ return selected;
+ }
+ // Only a confirmed empty selection opts into the computer clipboard.
+ // Permission errors, unsupported selection APIs and oversized selections
+ // remain errors rather than silently returning unrelated clipboard text.
+ const before = await readDesktopClipboardVersion();
+ check();
+ const existing = clipboard.readText();
+ if (!existing || existing.length > REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS)
+ throw new Error('DESKTOP_CLIPBOARD_INVALID');
+ const after = await readDesktopClipboardVersion();
+ check();
+ if (before !== after) throw new Error('DESKTOP_CLIPBOARD_CHANGED');
+ return existing;
+ }
+ await readDesktopClipboardVersion(); // Refuse secure/locked desktop clipboard access.
+ check();
+ if (!text || text.length > REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS)
+ throw new Error('DESKTOP_CLIPBOARD_INVALID');
+ clipboard.writeText(text);
+ if (clipboard.readText() !== text) throw new Error('DESKTOP_CLIPBOARD_WRITE_FAILED');
+ const modifier = process.platform === 'darwin' ? 'MetaLeft' : 'ControlLeft';
+ input([
+ { kind: 'release' },
+ { kind: 'key', code: modifier, down: true },
+ { kind: 'key', code: 'KeyV', down: true },
+ { kind: 'key', code: 'KeyV', down: false },
+ { kind: 'key', code: modifier, down: false },
+ ]);
+}
+
+/** Portable formats are written together so HTML/image alternatives survive. */
+export async function transferDesktopClipboardContent(
+ action: 'copy' | 'paste',
+ content: RemoteClipboardContent | undefined,
+ isCurrent: () => boolean,
+ input: (events: DesktopInput[]) => void,
+): Promise<RemoteClipboardContent | void> {
+ const check = () => { if (!isCurrent()) throw new Error('DESKTOP_LEASE_EXPIRED'); };
+ check();
+ input([{ kind: 'release' }]);
+ if (action === 'copy') {
+ const selected = await readDesktopSelection(true);
+ check();
+ if (selected) return { text: selected };
+ const before = await readDesktopClipboardVersion(true);
+ check();
+ const formats = clipboard.availableFormats();
+ // Paths represent files on this computer, not transferable content.
+ if (formats.some((format) => /file-url|filenames|hdrop|filecontents|filegroupdescriptor|uri-list/i.test(format)))
+ throw new Error('CLIPBOARD_UNSUPPORTED');
+ const snapshot: RemoteClipboardContent = {};
+ const text = clipboard.readText();
+ const html = clipboard.readHTML();
+ const rtf = clipboard.readRTF();
+ if (text) snapshot.text = text;
+ if (html) snapshot.html = html;
+ if (rtf) snapshot.rtf = rtf;
+ const image = clipboard.readImage();
+ if (!image.isEmpty()) {
+ const size = image.getSize();
+ if (size.width * size.height > 64_000_000) throw new Error('CLIPBOARD_TOO_LONG');
+ snapshot.png = image.toPNG().toString('base64');
+ }
+ const after = await readDesktopClipboardVersion(true);
+ check();
+ if (before !== after) throw new Error('DESKTOP_CLIPBOARD_CHANGED');
+ if (!Object.keys(snapshot).length) throw new Error(formats.length ? 'CLIPBOARD_UNSUPPORTED' : 'CLIPBOARD_EMPTY');
+ const json = JSON.stringify(snapshot);
+ if (json.length > CLIPBOARD_MAX_CHARS) throw new Error('CLIPBOARD_TOO_LONG');
+ return parseClipboardContent(json);
+ }
+ if (!content) throw new Error('CLIPBOARD_EMPTY');
+ const value = parseClipboardContent(JSON.stringify(content));
+ let image: Electron.NativeImage | undefined;
+ if (value.png) {
+ const bytes = Buffer.from(value.png, 'base64');
+ // Bound decompression before passing untrusted image bytes to nativeImage.
+ if (bytes.length < 24 || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 64_000_000)
+ throw new Error('CLIPBOARD_TOO_LONG');
+ image = nativeImage.createFromBuffer(bytes);
+ if (image.isEmpty()) throw new Error('CLIPBOARD_UNSUPPORTED');
+ }
+ await readDesktopClipboardVersion();
+ check();
+ clipboard.write({
+ ...(value.text || value.url ? { text: value.text || value.url } : {}),
+ ...(value.html ? { html: value.html } : {}),
+ ...(value.rtf ? { rtf: value.rtf } : {}),
+ ...(image ? { image } : {}),
+ });
+ if ((image && clipboard.readImage().isEmpty()) ||
+ (value.text && clipboard.readText() !== value.text))
+ throw new Error('DESKTOP_CLIPBOARD_WRITE_FAILED');
+ check();
+ const modifier = process.platform === 'darwin' ? 'MetaLeft' : 'ControlLeft';
+ input([
+ { kind: 'release' },
+ { kind: 'key', code: modifier, down: true },
+ { kind: 'key', code: 'KeyV', down: true },
+ { kind: 'key', code: 'KeyV', down: false },
+ { kind: 'key', code: modifier, down: false },
+ ]);
+}
diff --git a/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts b/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts
new file mode 100644
index 0000000000..d6d2cbdab5
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts
@@ -0,0 +1,56 @@
+import { randomUUID } from 'node:crypto';
+import {
+ CLIPBOARD_CHUNK_CHARS, CLIPBOARD_MAX_CHARS, parseClipboardContent,
+ type ClipboardContentRequest, type RemoteClipboardContent,
+} from '@cindy/device-link';
+
+/** One bounded, short-lived transfer per controller. Payloads never reach disk/logs. */
+export class ClipboardTransfer {
+ private value: { id: string; lease: string; length: number; data: string; direction: 'copy' | 'paste' } | null = null;
+ private timer: ReturnType<typeof setTimeout> | undefined;
+ reset(): void {
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ this.value = null;
+ }
+ async handle(
+ request: ClipboardContentRequest,
+ isCurrent: () => boolean,
+ transfer: (action: 'copy' | 'paste', content: RemoteClipboardContent | undefined, isCurrent: () => boolean) => Promise<RemoteClipboardContent | void>,
+ ): Promise<unknown> {
+ if (!isCurrent()) throw new Error('DESKTOP_LEASE_EXPIRED');
+ if (request.action === 'copy' || request.action === 'begin') {
+ this.reset();
+ const data = request.action === 'copy' ? JSON.stringify(await transfer('copy', undefined, isCurrent)) : '';
+ if (!isCurrent()) throw new Error('DESKTOP_LEASE_EXPIRED');
+ if (typeof data !== 'string') throw new Error('CLIPBOARD_EMPTY');
+ const length = request.action === 'begin' ? request.length : data.length;
+ if (length > CLIPBOARD_MAX_CHARS) throw new Error('CLIPBOARD_TOO_LONG');
+ const id = randomUUID();
+ this.value = { id, lease: request.lease, length, data, direction: request.action === 'copy' ? 'copy' : 'paste' };
+ this.timer = setTimeout(() => this.reset(), 60_000);
+ this.timer.unref();
+ return { id, length };
+ }
+ const value = this.value;
+ if (!value || value.id !== request.id || value.lease !== request.lease) throw new Error('CLIPBOARD_EXPIRED');
+ if (request.action === 'cancel') { this.reset(); return { ok: true }; }
+ if (request.action === 'read' && value.direction === 'copy') {
+ if (request.offset >= value.length) throw new Error('INVALID_REQUEST');
+ return { data: value.data.slice(request.offset, request.offset + CLIPBOARD_CHUNK_CHARS) };
+ }
+ if (request.action === 'write' && value.direction === 'paste') {
+ if (request.offset !== value.data.length || value.data.length + request.data.length > value.length)
+ throw new Error('INVALID_REQUEST');
+ value.data += request.data;
+ return { ok: true };
+ }
+ if (request.action === 'commit' && value.direction === 'paste') {
+ this.reset(); // Consume before any side effect: a repeated commit cannot paste twice.
+ if (value.data.length !== value.length) throw new Error('INVALID_REQUEST');
+ await transfer('paste', parseClipboardContent(value.data), isCurrent);
+ return { ok: true };
+ }
+ throw new Error('INVALID_REQUEST');
+ }
+}
diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.ts
new file mode 100644
index 0000000000..670c346214
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/controller.ts
@@ -0,0 +1,297 @@
+import { ClipboardTransfer } from './clipboardTransfer';
+import { randomUUID } from 'node:crypto';
+import {
+ parseRemoteDesktopRequest,
+ REMOTE_DESKTOP_LEASE_MS,
+ type DesktopInput,
+ type RemoteDesktopCursorFrame,
+ type RemoteClipboardContent,
+ type RemoteDesktopVideoSettings,
+ type RemoteDesktopDisplayMode,
+ type RemoteDesktopCapabilities,
+ type RemoteDesktopLease,
+ type RemoteDesktopPermissions,
+ desktopPermissionReady,
+} from '@cindy/device-link';
+
+export interface DesktopControllerDeps {
+ authorized(peer: string): boolean;
+ capabilities(): Promise<RemoteDesktopCapabilities>;
+ permissions?(action: 'check' | 'guide'): Promise<RemoteDesktopPermissions>;
+ frame(displayId: string, cursorOverlay?: boolean): Promise<string | RemoteDesktopCursorFrame | null>;
+ startInput(displayId: string): Promise<void>;
+ input(events: DesktopInput[]): void;
+ stopInput(): void;
+ stopVideo(): void;
+ offer(
+ lease: RemoteDesktopLease,
+ sdp: string,
+ settings?: RemoteDesktopVideoSettings,
+ cursorOverlay?: boolean,
+ ): Promise<string>;
+ displayModes?(displayId: string): Promise<RemoteDesktopDisplayMode[]>;
+ resolution?(displayId: string, modeId: string, isCurrent: () => boolean): Promise<void>;
+ clipboard?(
+ action: 'copy' | 'paste',
+ text: string | undefined,
+ isCurrent: () => boolean,
+ ): Promise<string | void>;
+ clipboardContent?(action: 'copy' | 'paste', content: RemoteClipboardContent | undefined, isCurrent: () => boolean): Promise<RemoteClipboardContent | void>;
+ changed(): void;
+ now?: () => number;
+}
+
+/** One human lease, peer-bound, with finite lifetime even if the relay disappears. */
+export class RemoteDesktopController {
+ private active:
+ | (RemoteDesktopLease & {
+ peer: string;
+ expires: number;
+ sequence: number;
+ backgroundViewing?: boolean;
+ })
+ | null = null;
+ private starting = false;
+ private startingPeer: string | null = null;
+ private framePending = false;
+ private clipboardPending = false;
+ private clipboardTransfer = new ClipboardTransfer();
+ private lastFrame = -Infinity;
+ private controlGeneration = 0;
+ private inputStarting = false;
+ private userStopped = new Map<string, string>();
+ private lastEnded: { peer: string; lease: string } | null = null;
+ constructor(private readonly deps: DesktopControllerDeps) {}
+ get state(): { peer: string; controlling: boolean } | null {
+ return this.active ? { peer: this.active.peer, controlling: this.active.controlling } : null;
+ }
+ get displayId(): string | null {
+ return this.active?.display.id ?? null;
+ }
+ hasLease(lease: string): boolean {
+ this.tick();
+ return this.active?.lease === lease;
+ }
+ private now(): number {
+ return this.deps.now?.() ?? Date.now();
+ }
+ tick(): void {
+ if (
+ this.active &&
+ (this.active.expires <= this.now() || !this.deps.authorized(this.active.peer))
+ )
+ this.stop();
+ }
+ stop(peer?: string): void {
+ if (peer && this.active?.peer !== peer && this.startingPeer !== peer) return;
+ if (this.active) this.lastEnded = { peer: this.active.peer, lease: this.active.lease };
+ this.clipboardTransfer.reset();
+ this.controlGeneration++;
+ this.active = null;
+ this.deps.stopInput();
+ this.deps.stopVideo();
+ this.deps.changed();
+ }
+ /** Explicit local disconnect must not be undone by the phone's recovery. */
+ stopByUser(): void {
+ const target = this.active ?? this.lastEnded;
+ if (target) this.userStopped.set(target.peer, target.lease);
+ this.stop();
+ }
+ private require(peer: string, lease: string) {
+ this.tick();
+ if (this.userStopped.get(peer) === lease) throw new Error('DESKTOP_STOPPED');
+ const active = this.active;
+ if (!active || active.peer !== peer || active.lease !== lease)
+ throw new Error('DESKTOP_LEASE_EXPIRED');
+ return active;
+ }
+ /** Only the trusted capture renderer may forward live DataChannel pongs. */
+ viewHeartbeat(lease: string): void {
+ this.tick();
+ if (this.active?.lease === lease && this.active.backgroundViewing && !this.active.controlling)
+ this.active.expires = this.now() + REMOTE_DESKTOP_LEASE_MS;
+ }
+ /** Also used by the exact capture renderer's DataChannel bridge. */
+ input(lease: string, sequence: number, events: unknown): void {
+ const active = this.active;
+ if (!active)
+ throw new Error(
+ [...this.userStopped.values()].includes(lease)
+ ? 'DESKTOP_STOPPED'
+ : 'DESKTOP_LEASE_EXPIRED',
+ );
+ const request = parseRemoteDesktopRequest({ op: 'input', lease, sequence, events });
+ if (request.op !== 'input') return;
+ this.require(active.peer, lease);
+ if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');
+ if (sequence <= active.sequence) return; // never replay a click after retries/reconnect
+ active.sequence = sequence;
+ this.deps.input(request.events);
+ }
+ async request(peer: string, raw: unknown): Promise<unknown> {
+ const request = parseRemoteDesktopRequest(raw);
+ this.tick();
+ if (request.op === 'capabilities')
+ return { ...(await this.deps.capabilities()), automaticReconnect: true, connectionTakeover: true };
+ if (!this.deps.authorized(peer)) throw new Error('DESKTOP_DISABLED');
+ if (request.op === 'permissions') {
+ if (!this.deps.permissions) throw new Error('DESKTOP_PERMISSIONS_UNAVAILABLE');
+ return this.deps.permissions(request.action);
+ }
+ if (request.op === 'start') {
+ if (request.resume && this.userStopped.has(peer)) throw new Error('DESKTOP_STOPPED');
+ if (this.starting || (this.active && !request.takeover)) throw new Error('DESKTOP_BUSY');
+ this.starting = true;
+ this.startingPeer = peer;
+ const generation = this.controlGeneration;
+ try {
+ const caps = await this.deps.capabilities();
+ const display = caps.displays.find((d) => d.id === request.displayId);
+ if (!display) throw new Error('DESKTOP_DISPLAY_MISSING');
+ if (generation !== this.controlGeneration || !this.deps.authorized(peer))
+ throw new Error('DESKTOP_DISABLED');
+ if (caps.permissions && !desktopPermissionReady(caps.permissions.screenRecording))
+ throw new Error('DESKTOP_SCREEN_PERMISSION_REQUIRED');
+ if (request.resume && this.userStopped.has(peer)) throw new Error('DESKTOP_STOPPED');
+ if (request.takeover && this.active) this.stopByUser();
+ if (!request.resume) this.userStopped.delete(peer);
+ const lease: RemoteDesktopLease = { lease: randomUUID(), display, controlling: false };
+ this.active = {
+ ...lease,
+ peer,
+ expires: this.now() + REMOTE_DESKTOP_LEASE_MS,
+ sequence: -1,
+ };
+ this.deps.changed();
+ return lease;
+ } finally {
+ this.starting = false;
+ this.startingPeer = null;
+ }
+ }
+ const active = this.require(peer, request.lease);
+ switch (request.op) {
+ case 'stop':
+ this.stop(peer);
+ return { ok: true };
+ case 'heartbeat':
+ active.expires = this.now() + REMOTE_DESKTOP_LEASE_MS;
+ return { controlling: active.controlling };
+ case 'presentation': {
+ active.backgroundViewing = request.enabled;
+ if (request.enabled) {
+ active.controlling = false;
+ this.clipboardTransfer.reset();
+ this.controlGeneration++;
+ this.deps.stopInput();
+ }
+ this.deps.changed();
+ return { controlling: active.controlling };
+ }
+ case 'control': {
+ if (request.enabled) active.backgroundViewing = false;
+ if (request.enabled && this.inputStarting) throw new Error('DESKTOP_INPUT_BUSY');
+ this.clipboardTransfer.reset();
+ const generation = ++this.controlGeneration;
+ if (!request.enabled) {
+ active.controlling = false;
+ this.deps.stopInput();
+ } else if (!active.controlling) {
+ this.inputStarting = true;
+ try {
+ await this.deps.startInput(active.display.id);
+ if (
+ generation !== this.controlGeneration ||
+ this.active !== active ||
+ !this.deps.authorized(peer)
+ ) {
+ this.deps.stopInput();
+ throw new Error(
+ this.userStopped.get(peer) === request.lease
+ ? 'DESKTOP_STOPPED'
+ : 'DESKTOP_LEASE_EXPIRED',
+ );
+ }
+ this.require(peer, request.lease);
+ active.controlling = true;
+ } finally {
+ this.inputStarting = false;
+ }
+ }
+ this.deps.changed();
+ return { controlling: active.controlling };
+ }
+ case 'clipboardContent':
+ case 'clipboard': {
+ if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');
+ if (request.op === 'clipboard' ? !this.deps.clipboard : !this.deps.clipboardContent) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
+ if (this.clipboardPending) throw new Error('DESKTOP_CLIPBOARD_BUSY');
+ const generation = this.controlGeneration;
+ const isCurrent = () => {
+ this.tick();
+ return (
+ this.active === active && active.controlling && generation === this.controlGeneration
+ );
+ };
+ this.clipboardPending = true;
+ try {
+ if (request.op === 'clipboardContent') {
+ const result = await this.clipboardTransfer.handle(request, isCurrent, this.deps.clipboardContent!);
+ if (!isCurrent()) { this.clipboardTransfer.reset(); throw new Error('DESKTOP_LEASE_EXPIRED'); }
+ return result;
+ }
+ const text = await this.deps.clipboard!(
+ request.action,
+ request.action === 'paste' ? request.text : undefined,
+ isCurrent,
+ );
+ this.require(peer, request.lease);
+ if (!isCurrent()) throw new Error('DESKTOP_VIEW_ONLY');
+ return request.action === 'copy' ? { text } : { ok: true };
+ } finally {
+ this.clipboardPending = false;
+ }
+ }
+ case 'input':
+ this.input(request.lease, request.sequence, request.events);
+ return { ok: true };
+ case 'frame': {
+ // Compatibility transport: one small frame in flight, no replaying frame queue.
+ if (this.framePending || this.now() - this.lastFrame < 250) return { jpeg: null };
+ this.framePending = true;
+ this.lastFrame = this.now();
+ try {
+ const jpeg = await this.deps.frame(active.display.id, request.cursorOverlay);
+ this.require(peer, request.lease); // revoke during capture must not leak the result
+ return typeof jpeg === 'object' && jpeg !== null ? jpeg : { jpeg };
+ } finally {
+ this.framePending = false;
+ }
+ }
+ case 'displayModes': {
+ if (!this.deps.displayModes) throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');
+ const modes = await this.deps.displayModes(active.display.id);
+ this.require(peer, request.lease);
+ return modes;
+ }
+ case 'resolution': {
+ if (!active.controlling) throw new Error('DESKTOP_VIEW_ONLY');
+ if (!this.deps.resolution) throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');
+ await this.deps.resolution(active.display.id, request.modeId, () => {
+ this.tick();
+ return this.active === active && active.controlling;
+ });
+ // The OS geometry change ends capture/input; the viewer reconnects using
+ // fresh capabilities. This never tears down the shared device link.
+ if (this.active === active) this.stop(peer);
+ return { ok: true };
+ }
+ case 'offer': {
+ const sdp = await this.deps.offer(active, request.sdp, request.settings, request.cursorOverlay);
+ this.require(peer, request.lease);
+ return { sdp };
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/main/remote-desktop/frame.ts b/apps/desktop/src/main/remote-desktop/frame.ts
new file mode 100644
index 0000000000..c1db07b54a
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/frame.ts
@@ -0,0 +1,14 @@
+import type { NativeImage } from 'electron';
+import { REMOTE_DESKTOP_MAX_FRAME_BYTES } from '@cindy/device-link';
+
+/** Capture can briefly produce an empty thumbnail even with permission granted. */
+export function encodeDesktopFrame(thumbnail: NativeImage): string | null {
+ if (thumbnail.isEmpty()) return null;
+ let image = thumbnail;
+ for (let attempt = 0; attempt < 4; attempt++) {
+ const jpeg = image.toJPEG(55);
+ if (jpeg.length <= REMOTE_DESKTOP_MAX_FRAME_BYTES) return jpeg.toString('base64');
+ image = image.resize({ width: Math.floor(image.getSize().width * 0.75) });
+ }
+ throw new Error('DESKTOP_FRAME_TOO_LARGE');
+}
diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.ts
new file mode 100644
index 0000000000..5cbba16629
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/index.ts
@@ -0,0 +1,483 @@
+import {
+ app,
+ BrowserWindow,
+ desktopCapturer,
+ ipcMain,
+ powerMonitor,
+ powerSaveBlocker,
+ screen,
+ shell,
+ systemPreferences,
+ type WebContents,
+ type DesktopCapturerSource,
+} from 'electron';
+import { randomUUID } from 'node:crypto';
+import {
+ isDesktopPermission,
+ type RemoteDesktopLease,
+ type RemoteDesktopVideoSettings,
+} from '@cindy/device-link';
+import { DESKTOP_LOCAL, type DesktopHostCommand } from '../../shared/remoteDesktop';
+import {
+ assertTrustedAppRendererEvent,
+ isTrustedAppRendererWindow,
+} from '../security/trustedAppRenderer';
+import { readDeviceLinkSettings, writeDeviceLinkSetting } from '../device-link/settings-store';
+import { throwIpcError } from '../utils/ipcValidate';
+import { RemoteDesktopController } from './controller';
+import { desktopCaptureSource } from './captureSource';
+import { encodeDesktopFrame } from './frame';
+import { transferDesktopClipboard, transferDesktopClipboardContent } from './clipboard';
+import { NativeDesktopCapture } from './nativeCapture';
+import { readWindowsDesktopSupport, configureWindowsDesktopSupport } from './windowsHost';
+import {
+ DesktopInputHost,
+ readDesktopDisplayModes,
+ setDesktopDisplayMode,
+ readDesktopInputPermission,
+ requestDesktopInputPermission,
+} from './inputHost';
+import { getDeepLinkMainWindow } from '../deepLink';
+import { RemoteDesktopPermissionsService } from './permissions';
+import {
+ MAC_ACCESSIBILITY_SETTINGS_URL,
+ MAC_SCREEN_RECORDING_SETTINGS_URL,
+} from '../computer-permission-guide/request';
+
+const permissions = new RemoteDesktopPermissionsService({
+ required: process.platform === 'darwin',
+ screen: () => {
+ const status = systemPreferences.getMediaAccessStatus('screen');
+ return status === 'granted' ? 'granted' : status === 'unknown' ? 'unknown' : 'missing';
+ },
+ accessibility: readDesktopInputPermission,
+ request: async (permission, isCurrent, signal) => {
+ if (permission === 'accessibility') await requestDesktopInputPermission(isCurrent, signal);
+ else
+ await desktopCapturer.getSources({
+ types: ['screen'],
+ thumbnailSize: { width: 0, height: 0 },
+ });
+ },
+ openSettings: (permission) =>
+ shell.openExternal(
+ permission === 'screenRecording'
+ ? MAC_SCREEN_RECORDING_SETTINGS_URL
+ : MAC_ACCESSIBILITY_SETTINGS_URL,
+ ),
+ showGuide: () => {
+ const window = getDeepLinkMainWindow();
+ if (window && !window.isDestroyed()) {
+ if (window.isMinimized()) window.restore();
+ window.show();
+ window.focus();
+ }
+ },
+});
+
+let host: WebContents | null = null;
+const nativeCapture = new NativeDesktopCapture();
+let displayAwake: number | null = null;
+let nativeDisplay: string | null = null;
+let windowsAvailable = false;
+let captureGrant: { source: DesktopCapturerSource; lease: string; audio: boolean } | null = null;
+const supportsSystemAudio =
+ process.platform === 'win32' ||
+ (process.platform === 'darwin' && typeof process.getSystemVersion === 'function' &&
+ (() => {
+ const [major, minor] = process.getSystemVersion().split('.').map(Number);
+ return major > 14 || (major === 14 && minor >= 2);
+ })());
+let videoLease: string | null = null;
+let offerGeneration = 0;
+let nativeOverlay = false;
+let nativeSettings: RemoteDesktopVideoSettings | undefined;
+let preparingOffer = false;
+let pending: {
+ id: string;
+ resolve(sdp: string): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+} | null = null;
+const input = new DesktopInputHost(() => remoteDesktop.stop());
+function stopVideo(): void {
+ offerGeneration++;
+ nativeOverlay = false;
+ nativeSettings = undefined;
+ nativeCapture.stop();
+ nativeDisplay = null;
+ captureGrant = null;
+ videoLease = null;
+ if (host && !host.isDestroyed()) {
+ host.setBackgroundThrottling(true);
+ if (isTrustedAppRendererWindow(BrowserWindow.fromWebContents(host)))
+ host.send(DESKTOP_LOCAL.COMMAND, {
+ id: randomUUID(),
+ op: 'stop',
+ } satisfies DesktopHostCommand);
+ }
+ if (pending) {
+ clearTimeout(pending.timer);
+ pending.reject(new Error('DESKTOP_VIDEO_STOPPED'));
+ pending = null;
+ }
+}
+async function sources(thumbnail = false) {
+ if (
+ process.platform === 'darwin' &&
+ systemPreferences.getMediaAccessStatus('screen') !== 'granted'
+ )
+ throw new Error('DESKTOP_SCREEN_PERMISSION_REQUIRED');
+ return desktopCapturer.getSources({
+ types: ['screen'],
+ thumbnailSize: thumbnail ? { width: 1280, height: 1280 } : { width: 0, height: 0 },
+ fetchWindowIcons: false,
+ });
+}
+async function offer(
+ lease: RemoteDesktopLease,
+ sdp: string,
+ settings?: RemoteDesktopVideoSettings,
+ cursorOverlay?: boolean,
+): Promise<string> {
+ if (
+ !host ||
+ host.isDestroyed() ||
+ !isTrustedAppRendererWindow(BrowserWindow.fromWebContents(host))
+ )
+ throw new Error('DESKTOP_VIDEO_UNAVAILABLE');
+ if (pending || preparingOffer) throw new Error('DESKTOP_VIDEO_BUSY');
+ preparingOffer = true;
+ const generation = ++offerGeneration;
+ nativeCapture.stop();
+ nativeDisplay = null;
+ videoLease = null;
+ captureGrant = null;
+ const currentHost = host;
+ let source: DesktopCapturerSource | null = null;
+ let enumerationTimer: ReturnType<typeof setTimeout> | undefined;
+ let nativeAvailable = process.platform === 'darwin';
+ try {
+ nativeAvailable ||=
+ process.platform === 'win32' && (await readWindowsDesktopSupport()) === 'ready';
+ try {
+ const available = nativeAvailable
+ ? await Promise.race([
+ sources(),
+ new Promise<never>((_, reject) => {
+ enumerationTimer = setTimeout(() => reject(new Error('DESKTOP_VIDEO_TIMEOUT')), 2000);
+ }),
+ ])
+ : await sources();
+ source = desktopCaptureSource(available, lease.display.id, screen.getAllDisplays());
+ } catch (error) {
+ // A locked macOS session can reject Chromium's source enumeration even
+ // though the user has granted capture. Only the native adapter may recover.
+ if (
+ !nativeAvailable ||
+ (process.platform === 'darwin' &&
+ systemPreferences.getMediaAccessStatus('screen') !== 'granted')
+ )
+ throw error;
+ }
+ } finally {
+ if (enumerationTimer) clearTimeout(enumerationTimer);
+ preparingOffer = false;
+ }
+ if (!source && !nativeAvailable) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');
+ if (
+ generation !== offerGeneration ||
+ !remoteDesktop.hasLease(lease.lease) ||
+ host !== currentHost ||
+ currentHost.isDestroyed()
+ )
+ throw new Error('DESKTOP_LEASE_EXPIRED');
+ if (settings?.audio && !supportsSystemAudio) throw new Error('DESKTOP_AUDIO_UNAVAILABLE');
+ captureGrant = source ? { source, lease: lease.lease, audio: settings?.audio === true } : null;
+ nativeDisplay = nativeAvailable ? lease.display.id : null;
+ nativeOverlay = cursorOverlay === true && process.platform === 'darwin';
+ nativeSettings = settings;
+ videoLease = lease.lease;
+ currentHost.setBackgroundThrottling(false);
+ return new Promise<string>((resolve, reject) => {
+ const id = randomUUID();
+ const timer = setTimeout(() => {
+ if (pending?.id === id) {
+ pending = null;
+ stopVideo();
+ reject(new Error('DESKTOP_VIDEO_TIMEOUT'));
+ }
+ }, 10_000);
+ pending = { id, resolve, reject, timer };
+ currentHost.send(DESKTOP_LOCAL.COMMAND, {
+ id,
+ op: 'offer',
+ sourceId: source?.id,
+ nativeCapture: nativeAvailable,
+ cursorOverlay: nativeOverlay,
+ lease: lease.lease,
+ sdp,
+ settings,
+ } satisfies DesktopHostCommand);
+ });
+}
+
+export const remoteDesktop = new RemoteDesktopController({
+ authorized: (peer) => {
+ const settings = readDeviceLinkSettings();
+ return (
+ settings.remoteControlEnabled &&
+ settings.remoteDesktopEnabled &&
+ !settings.revokedControllers.includes(peer)
+ );
+ },
+ capabilities: async () => {
+ windowsAvailable = (await readWindowsDesktopSupport()) === 'ready';
+ const settings = readDeviceLinkSettings();
+ const enabled = settings.remoteDesktopEnabled && settings.remoteControlEnabled;
+ return {
+ version: 1,
+ cursorOverlay: process.platform === 'darwin',
+ clipboardContent: process.platform === 'darwin' || process.platform === 'win32',
+ clipboardText: process.platform === 'darwin' || process.platform === 'win32',
+ videoSettings: true,
+ backgroundViewing: true,
+ systemAudio: supportsSystemAudio,
+ displayModes: process.platform === 'darwin',
+ enabled,
+ canControl: process.platform === 'darwin' || process.platform === 'win32',
+ platform: process.platform,
+ ...(enabled ? { permissions: await permissions.read() } : {}),
+ displays: enabled
+ ? screen.getAllDisplays().map((d, i) => ({
+ id: String(d.id),
+ name: d.label || `Display ${i + 1}`,
+ width: d.size.width,
+ height: d.size.height,
+ }))
+ : [],
+ };
+ },
+ permissions: async (action) => {
+ // Dedicated remote-desktop guide only. No remote OS settings URL or opt-in write.
+ if (action === 'guide') permissions.show();
+ return permissions.read();
+ },
+ frame: async (displayId, cursorOverlay) => {
+ // Compatibility viewers must also wake/capture without waiting for
+ // Chromium's thumbnail enumeration, which may hang on a sleeping display.
+ if (process.platform === 'darwin' || windowsAvailable) return nativeCapture.frame(displayId, cursorOverlay === true && process.platform === 'darwin', nativeSettings);
+ const source = desktopCaptureSource(await sources(true), displayId, screen.getAllDisplays());
+ return source ? encodeDesktopFrame(source.thumbnail) : null;
+ },
+ clipboard: (action, text, isCurrent) =>
+ transferDesktopClipboard(action, text, isCurrent, (events) => input.input(events)),
+ clipboardContent: (action, content, isCurrent) =>
+ transferDesktopClipboardContent(action, content, isCurrent, (events) => input.input(events)),
+ displayModes: readDesktopDisplayModes,
+ resolution: setDesktopDisplayMode,
+ startInput: (displayId) => input.start(displayId),
+ input: (events) => input.input(events),
+ stopInput: () => input.stop(),
+ offer,
+ stopVideo,
+ changed: () => {
+ // Applies to the viewer lease, not the global remote-control preference.
+ // All supported Electron platforms release this assertion on disconnect.
+ if (remoteDesktop.state && displayAwake === null)
+ displayAwake = powerSaveBlocker.start('prevent-display-sleep');
+ else if (!remoteDesktop.state && displayAwake !== null) {
+ powerSaveBlocker.stop(displayAwake);
+ displayAwake = null;
+ }
+ },
+});
+
+export function registerRemoteDesktopIpc(): void {
+ const timer = setInterval(() => remoteDesktop.tick(), 1000);
+ timer.unref();
+ app.on('before-quit', () => {
+ clearInterval(timer);
+ permissions.dismiss();
+ remoteDesktop.stop();
+ });
+ screen.on('display-removed', (_event, display) => {
+ if (String(display.id) === remoteDesktop.displayId) remoteDesktop.stop();
+ });
+ screen.on('display-metrics-changed', (_event, display, metrics) => {
+ // Work-area changes (lock screen, Dock/menu bar, display wake) do not
+ // change whole-screen input coordinates and must not terminate the lease.
+ if (
+ String(display.id) === remoteDesktop.displayId &&
+ metrics.some(
+ (metric) => metric === 'bounds' || metric === 'scaleFactor' || metric === 'rotation',
+ )
+ )
+ remoteDesktop.stop();
+ });
+ const sessionChanged = () => {
+ nativeCapture.stop(); // do not retain pixels from the previous OS session state
+ if (remoteDesktop.state?.controlling) {
+ try {
+ input.input([{ kind: 'release' }]);
+ } catch {
+ remoteDesktop.stop();
+ }
+ }
+ if (videoLease && nativeDisplay && host && !host.isDestroyed())
+ host.send(DESKTOP_LOCAL.COMMAND, {
+ id: randomUUID(),
+ op: 'capture-reset',
+ lease: videoLease,
+ } satisfies DesktopHostCommand);
+ };
+ powerMonitor.on('lock-screen', sessionChanged);
+ powerMonitor.on('unlock-screen', sessionChanged);
+ ipcMain.handle(DESKTOP_LOCAL.NATIVE_FRAME, async (event, lease: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (
+ event.sender !== host ||
+ typeof lease !== 'string' ||
+ lease !== videoLease ||
+ !nativeDisplay ||
+ !remoteDesktop.hasLease(lease)
+ )
+ throwIpcError('PERMISSION_DENIED', 'Invalid desktop capture lease');
+ const generation = offerGeneration;
+ const jpeg = await nativeCapture.frame(nativeDisplay, nativeOverlay, nativeSettings).catch(() => null);
+ if (generation !== offerGeneration || !remoteDesktop.hasLease(lease)) return null;
+ return jpeg;
+ });
+ ipcMain.handle(DESKTOP_LOCAL.VIEW_HEARTBEAT, (event, lease: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (event.sender !== host || typeof lease !== 'string' || lease !== videoLease)
+ throwIpcError('PERMISSION_DENIED', 'Invalid desktop viewer heartbeat');
+ remoteDesktop.viewHeartbeat(lease);
+ });
+ ipcMain.handle(DESKTOP_LOCAL.STATE, async (event) => {
+ assertTrustedAppRendererEvent(event);
+ return {
+ enabled: readDeviceLinkSettings().remoteDesktopEnabled,
+ active: remoteDesktop.state,
+ permissionGuide: permissions.guideOpen,
+ windowsSupport: await readWindowsDesktopSupport(),
+ };
+ });
+ let windowsSetupBusy = false;
+ ipcMain.handle(DESKTOP_LOCAL.WINDOWS_SUPPORT, async (event, enabled: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (process.platform !== 'win32' || typeof enabled !== 'boolean')
+ throwIpcError('INVALID_PARAMS', 'Invalid Windows desktop support request');
+ if (event.sender !== getDeepLinkMainWindow()?.webContents || windowsSetupBusy)
+ throwIpcError('PERMISSION_DENIED', 'Windows desktop setup unavailable');
+ windowsSetupBusy = true;
+ remoteDesktop.stop();
+ try {
+ await configureWindowsDesktopSupport(enabled);
+ } catch {
+ throwIpcError('PERMISSION_DENIED', 'Windows desktop support setup failed');
+ } finally {
+ windowsSetupBusy = false;
+ }
+ windowsAvailable = enabled;
+ });
+ ipcMain.handle(DESKTOP_LOCAL.ENABLE, async (event, enabled: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid desktop setting');
+ await writeDeviceLinkSetting('remoteDesktopEnabled', enabled);
+ if (!enabled) {
+ remoteDesktop.stop();
+ permissions.dismiss();
+ } else {
+ await permissions.showIfNeeded(() => readDeviceLinkSettings().remoteDesktopEnabled);
+ }
+ });
+ ipcMain.handle(DESKTOP_LOCAL.PERMISSIONS, (event) => {
+ assertTrustedAppRendererEvent(event);
+ return permissions.read();
+ });
+ ipcMain.handle(DESKTOP_LOCAL.OPEN_PERMISSION, (event, permission: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (!isDesktopPermission(permission))
+ throwIpcError('INVALID_PARAMS', 'Invalid desktop permission');
+ return permissions.open(permission);
+ });
+ ipcMain.handle(DESKTOP_LOCAL.DISMISS_GUIDE, (event) => {
+ assertTrustedAppRendererEvent(event);
+ permissions.dismiss();
+ });
+ ipcMain.handle(DESKTOP_LOCAL.STOP, (event) => {
+ assertTrustedAppRendererEvent(event);
+ remoteDesktop.stopByUser();
+ });
+ ipcMain.handle(DESKTOP_LOCAL.REGISTER, (event) => {
+ assertTrustedAppRendererEvent(event);
+ if (getDeepLinkMainWindow()?.webContents !== event.sender)
+ throwIpcError('PERMISSION_DENIED', 'Only the main window can host desktop capture');
+ if (host && !host.isDestroyed() && host !== event.sender)
+ throwIpcError('PERMISSION_DENIED', 'Desktop host already registered');
+ if (host === event.sender) return;
+ host = event.sender;
+ const owner = host;
+ owner.session.setDisplayMediaRequestHandler((request, callback) => {
+ const grant = captureGrant;
+ if (
+ !grant ||
+ host !== owner ||
+ request.frame !== owner.mainFrame ||
+ !isTrustedAppRendererWindow(BrowserWindow.fromWebContents(owner)) ||
+ !remoteDesktop.hasLease(grant.lease) ||
+ !pending ||
+ !request.videoRequested
+ ) {
+ callback({});
+ return;
+ }
+ captureGrant = null; // single-use and bound to the exact active offer
+ callback({
+ video: grant.source,
+ ...(grant.audio && request.audioRequested ? { audio: 'loopback' as const } : {}),
+ });
+ });
+ const stop = () => {
+ if (host === owner) {
+ remoteDesktop.stop();
+ host = null;
+ }
+ };
+ owner.once('destroyed', stop);
+ owner.on('render-process-gone', stop);
+ owner.on('will-navigate', stop);
+ });
+ ipcMain.handle(DESKTOP_LOCAL.REPLY, (event, id: unknown, sdp: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (event.sender !== host || !pending || id !== pending.id)
+ throwIpcError('PERMISSION_DENIED', 'Invalid desktop host reply');
+ const request = pending;
+ pending = null;
+ clearTimeout(request.timer);
+ if (typeof sdp === 'string' && sdp.length <= 64_000) request.resolve(sdp);
+ else {
+ stopVideo();
+ request.reject(new Error('DESKTOP_VIDEO_UNAVAILABLE'));
+ }
+ });
+ ipcMain.handle(
+ DESKTOP_LOCAL.INPUT,
+ (event, lease: unknown, sequence: unknown, events: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (
+ event.sender !== host ||
+ lease !== videoLease ||
+ typeof lease !== 'string' ||
+ typeof sequence !== 'number'
+ )
+ throwIpcError('PERMISSION_DENIED', 'Invalid desktop host input');
+ try {
+ remoteDesktop.input(lease, sequence, events);
+ } catch {
+ throwIpcError('PERMISSION_DENIED', 'Desktop input rejected');
+ }
+ },
+ );
+}
diff --git a/apps/desktop/src/main/remote-desktop/inputHost.ts b/apps/desktop/src/main/remote-desktop/inputHost.ts
new file mode 100644
index 0000000000..b8d366ee5e
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/inputHost.ts
@@ -0,0 +1,384 @@
+import { app, screen } from 'electron';
+import { spawn, execFile, type ChildProcessWithoutNullStreams } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import type {
+ DesktopInput,
+ DesktopPermissionStatus,
+ RemoteDesktopDisplayMode,
+} from '@cindy/device-link';
+import { acquireHumanDesktopInput } from './inputOwnership';
+import {
+ openWindowsDesktopConnection,
+ readWindowsDesktopSupport,
+ type WindowsDesktopConnection,
+} from './windowsHost';
+
+const exec = promisify(execFile);
+const binaryName =
+ process.platform === 'darwin' ? 'cindy-macos-desktop-input' : 'cindy-windows-desktop-input.exe';
+let build: Promise<string> | null = null;
+async function resolveBinary(prepare = true): Promise<string> {
+ if (app.isPackaged)
+ return path.join(process.resourcesPath, 'tools', 'remote-desktop', binaryName);
+ if (build && prepare) return build;
+ const resolve = async () => {
+ const sourceRoot = path.join(app.getAppPath(), 'native', 'remote-desktop');
+ const source =
+ process.platform === 'darwin'
+ ? path.join(sourceRoot, 'macos-input.swift')
+ : path.join(sourceRoot, 'windows-input', 'src', 'main.rs');
+ const digest = createHash('sha256')
+ .update(await fs.readFile(source))
+ .update(process.arch)
+ .update('v1-O');
+ if (process.platform === 'win32') {
+ digest.update(await fs.readFile(path.join(sourceRoot, 'windows-input', 'src', 'desktop.rs')));
+ digest.update(
+ await fs.readFile(path.join(sourceRoot, 'windows-input', 'src', 'selection.rs')),
+ );
+ digest.update(await fs.readFile(path.join(sourceRoot, 'windows-input', 'Cargo.toml')));
+ digest.update(await fs.readFile(path.join(sourceRoot, 'windows-input', 'Cargo.lock')));
+ }
+ const hash = digest.digest('hex');
+ const directory = path.join(app.getPath('userData'), 'remote-desktop', 'native', hash);
+ const binary = path.join(directory, binaryName);
+ try {
+ await fs.access(binary);
+ return binary;
+ } catch {
+ /* build this source version */
+ }
+ if (!prepare) throw new Error('DESKTOP_INPUT_NOT_PREPARED');
+ await fs.mkdir(directory, { recursive: true });
+ const temporary = `${binary}.${process.pid}.tmp`;
+ if (process.platform === 'darwin') {
+ await exec('swiftc', [source, '-O', '-o', temporary], { timeout: 120_000 });
+ } else {
+ const manifest = path.join(sourceRoot, 'windows-input', 'Cargo.toml');
+ await exec(
+ 'cargo',
+ [
+ 'build',
+ '--release',
+ '--locked',
+ '--manifest-path',
+ manifest,
+ '--target-dir',
+ path.join(directory, 'build'),
+ ],
+ { timeout: 180_000 },
+ );
+ await fs.copyFile(path.join(directory, 'build', 'release', binaryName), temporary);
+ }
+ await fs.rename(temporary, binary);
+ return binary;
+ };
+ if (!prepare) return resolve();
+ build = resolve().finally(() => {
+ build = null;
+ });
+ return build;
+}
+
+/** Probe the actual input process, never CuaDriver's or Electron's AX grant. */
+export async function readDesktopInputPermission(): Promise<DesktopPermissionStatus> {
+ if (process.platform !== 'darwin') return 'notRequired';
+ try {
+ const { stdout } = await exec(await resolveBinary(false), ['--check'], {
+ timeout: 5000,
+ maxBuffer: 1024,
+ });
+ return stdout.trim() === 'ready'
+ ? 'granted'
+ : stdout.trim() === 'permission'
+ ? 'missing'
+ : 'unknown';
+ } catch {
+ return 'unknown';
+ }
+}
+
+export async function requestDesktopInputPermission(
+ isCurrent: () => boolean,
+ signal: AbortSignal,
+): Promise<void> {
+ if (process.platform !== 'darwin') return;
+ const binary = await resolveBinary();
+ if (isCurrent())
+ await exec(binary, ['--request-permission'], { timeout: 5000, maxBuffer: 1024, signal });
+}
+
+export class DesktopInputHost {
+ private windows: WindowsDesktopConnection | null = null;
+ private queuedBytes = 0;
+ private writing = Promise.resolve();
+ private child: ChildProcessWithoutNullStreams | null = null;
+ private releaseOwnership: (() => void) | null = null;
+ private displayId = '';
+ private generation = 0;
+ private heartbeat: ReturnType<typeof setInterval> | null = null;
+ private stopping: Promise<void> = Promise.resolve();
+ constructor(
+ private readonly onFailure: () => void,
+ private readonly runtime: {
+ platform?: NodeJS.Platform;
+ resolveBinary(): Promise<string>;
+ spawn(binary: string): ChildProcessWithoutNullStreams;
+ } = {
+ resolveBinary,
+ spawn: (binary: string) => spawn(binary, [], { stdio: 'pipe', windowsHide: true }),
+ },
+ ) {}
+ async start(displayId: string): Promise<void> {
+ this.stop();
+ const platform = this.runtime.platform ?? process.platform;
+ if (platform !== 'darwin' && platform !== 'win32') throw new Error('DESKTOP_INPUT_UNSUPPORTED');
+ const generation = this.generation;
+ await this.stopping;
+ if (generation !== this.generation) throw new Error('DESKTOP_LEASE_EXPIRED');
+ const release = acquireHumanDesktopInput();
+ this.releaseOwnership = release;
+ try {
+ if (
+ platform === 'win32' &&
+ !this.runtime.platform &&
+ (await readWindowsDesktopSupport()) === 'ready'
+ ) {
+ if (generation !== this.generation) throw new Error('DESKTOP_LEASE_EXPIRED');
+ const connection = await openWindowsDesktopConnection({ mode: 'input' });
+ if (generation !== this.generation) {
+ connection.close();
+ throw new Error('DESKTOP_LEASE_EXPIRED');
+ }
+ this.windows = connection;
+ this.displayId = displayId;
+ this.heartbeat = setInterval(() => this.write([]), 2000);
+ return;
+ }
+ const binary = await this.runtime.resolveBinary();
+ if (generation !== this.generation) throw new Error('DESKTOP_LEASE_EXPIRED');
+ const child = this.runtime.spawn(binary);
+ this.child = child;
+ this.displayId = displayId;
+ child.stderr.resume(); // never log typed text or protocol payloads
+ child.stdin.on('error', () => {
+ if (this.child === child) this.onFailure();
+ });
+ child.on('exit', () => {
+ if (this.child === child) this.onFailure();
+ });
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('DESKTOP_INPUT_UNAVAILABLE')), 8000);
+ let text = '';
+ const finish = (error?: Error) => {
+ clearTimeout(timer);
+ child.stdout.off('data', receive);
+ error ? reject(error) : resolve();
+ };
+ const receive = (data: Buffer) => {
+ text += data.toString();
+ if (text.includes('\n'))
+ finish(
+ text.startsWith('ready') ? undefined : new Error('DESKTOP_ACCESSIBILITY_REQUIRED'),
+ );
+ };
+ child.stdout.on('data', receive);
+ child.once('error', () => finish(new Error('DESKTOP_INPUT_UNAVAILABLE')));
+ child.once('exit', () => finish(new Error('DESKTOP_INPUT_UNAVAILABLE')));
+ });
+ if (generation !== this.generation) throw new Error('DESKTOP_LEASE_EXPIRED');
+ child.stdout.on('data', (data: Buffer) => {
+ if (data.toString().includes('error') && this.child === child) this.onFailure();
+ });
+ this.heartbeat = setInterval(() => this.write([]), 2000);
+ } catch (error) {
+ if (generation === this.generation) this.stop();
+ throw error;
+ }
+ }
+ input(events: DesktopInput[]): void {
+ const display = screen.getAllDisplays().find((item) => String(item.id) === this.displayId);
+ if (!display || (!this.child && !this.windows)) throw new Error('DESKTOP_INPUT_UNAVAILABLE');
+ this.write(
+ events.map((event) => {
+ if (event.kind !== 'move' && event.kind !== 'button') return event;
+ const point = {
+ x: Math.round(display.bounds.x + event.x * (display.bounds.width - 1)),
+ y: Math.round(display.bounds.y + event.y * (display.bounds.height - 1)),
+ };
+ const native = process.platform === 'win32' ? screen.dipToScreenPoint(point) : point;
+ return { ...event, ...native };
+ }),
+ );
+ }
+ private write(events: unknown[]): void {
+ const child = this.child;
+ const line = `${JSON.stringify(events)}\n`;
+ const connection = this.windows;
+ if (connection) {
+ const bytes = Buffer.byteLength(line);
+ if (this.queuedBytes + bytes > 32_768) {
+ this.onFailure();
+ return;
+ }
+ this.queuedBytes += bytes;
+ const generation = this.generation;
+ this.writing = this.writing
+ .then(async () => {
+ if (this.windows !== connection) return;
+ if ((await connection.request(line.slice(0, -1))) !== 'ok\n')
+ throw new Error('DESKTOP_INPUT_UNAVAILABLE');
+ })
+ .catch(() => {
+ if (this.windows === connection) this.onFailure();
+ })
+ .finally(() => {
+ if (generation === this.generation) this.queuedBytes -= bytes;
+ });
+ return;
+ }
+ if (
+ !child ||
+ child.stdin.destroyed ||
+ child.stdin.writableLength + Buffer.byteLength(line) > 32_768
+ ) {
+ this.onFailure();
+ return;
+ }
+ child.stdin.write(line);
+ }
+ stop(): void {
+ this.generation++;
+ const windows = this.windows;
+ windows?.close();
+ this.windows = null;
+ this.queuedBytes = 0;
+ this.writing = Promise.resolve();
+ if (this.heartbeat) clearInterval(this.heartbeat);
+ this.heartbeat = null;
+ const child = this.child;
+ this.child = null;
+ const release = this.releaseOwnership;
+ this.releaseOwnership = null;
+ if (child) {
+ this.stopping = new Promise<void>((resolve) => {
+ const finish = () => {
+ release?.();
+ resolve();
+ };
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) finish();
+ else {
+ child.once('close', finish);
+ }
+ });
+ // EOF runs native releaseAll; its watchdog also releases on a stalled parent.
+ child.stdin.end('[{"kind":"release"}]\n');
+ const timer = setTimeout(() => child.kill(), 1500);
+ timer.unref();
+ child.once('exit', () => clearTimeout(timer));
+ } else if (windows) {
+ // The service closes its worker gracefully before the job-kill deadline.
+ this.stopping = new Promise<void>((resolve) =>
+ setTimeout(() => {
+ release?.();
+ resolve();
+ }, 1500),
+ );
+ } else release?.();
+ }
+}
+
+/** Native mode IDs come only from this computer's current display enumeration. */
+export async function readDesktopDisplayModes(
+ displayId: string,
+): Promise<RemoteDesktopDisplayMode[]> {
+ if (process.platform !== 'darwin' || !/^[0-9]{1,10}$/.test(displayId))
+ throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');
+ const { stdout } = await exec(await resolveBinary(), ['--display-modes', displayId], {
+ timeout: 5000,
+ maxBuffer: 64_000,
+ });
+ const modes = JSON.parse(stdout) as RemoteDesktopDisplayMode[];
+ if (
+ !Array.isArray(modes) ||
+ modes.length > 256 ||
+ !modes.every(
+ (mode) =>
+ typeof mode.id === 'string' &&
+ /^[0-9]{1,10}$/.test(mode.id) &&
+ Number.isInteger(mode.width) &&
+ mode.width > 0 &&
+ Number.isInteger(mode.height) &&
+ mode.height > 0 &&
+ typeof mode.current === 'boolean' &&
+ (mode.native === undefined || typeof mode.native === 'boolean'),
+ )
+ )
+ throw new Error('DESKTOP_DISPLAY_MODES_UNAVAILABLE');
+ return modes;
+}
+let changingResolution = false;
+export async function setDesktopDisplayMode(
+ displayId: string,
+ modeId: string,
+ isCurrent: () => boolean,
+): Promise<void> {
+ if (changingResolution) throw new Error('DESKTOP_DISPLAY_BUSY');
+ changingResolution = true;
+ try {
+ const modes = await readDesktopDisplayModes(displayId);
+ if (!modes.some((mode) => mode.id === modeId)) throw new Error('DESKTOP_DISPLAY_MODE_MISSING');
+ const binary = await resolveBinary();
+ // Build/enumeration can finish after disconnect, revocation or view-only.
+ if (!isCurrent()) throw new Error('DESKTOP_LEASE_EXPIRED');
+ await exec(binary, ['--display-mode', displayId, modeId], { timeout: 5000, maxBuffer: 1024 });
+ } finally {
+ changingResolution = false;
+ }
+}
+
+/** Counter only: clipboard text never crosses a helper's stdout/log boundary. */
+export async function readDesktopClipboardVersion(portable = false): Promise<string> {
+ if (process.platform !== 'darwin' && process.platform !== 'win32')
+ throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
+ try {
+ const { stdout } = await exec(await resolveBinary(), [portable && process.platform === 'darwin' ? '--clipboard-content-version' : '--clipboard-version'], {
+ timeout: 2000,
+ maxBuffer: 128,
+ windowsHide: true,
+ });
+ const version = stdout.trim();
+ if (!/^[0-9]+$/.test(version)) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
+ return version;
+ } catch (error) {
+ if (portable && process.platform === 'darwin' && error && typeof error === 'object' && 'code' in error && error.code === 3)
+ throw new Error('CLIPBOARD_UNSUPPORTED');
+ throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
+ }
+}
+
+export async function readDesktopSelection(portable = false): Promise<string> {
+ try {
+ const { stdout } = await exec(await resolveBinary(), [portable ? '--clipboard-content-selection' : '--clipboard-selection'], {
+ timeout: 3000,
+ maxBuffer: 128_000,
+ windowsHide: true,
+ });
+ const value: unknown = JSON.parse(stdout);
+ if (
+ !value ||
+ typeof value !== 'object' ||
+ !('text' in value) ||
+ typeof value.text !== 'string' ||
+ value.text.length > 16_384
+ )
+ throw new Error('INVALID_SELECTION');
+ return value.text;
+ } catch {
+ // execFile/JSON errors can contain stdout. Never propagate selected text in errors.
+ throw new Error('DESKTOP_CLIPBOARD_COPY_FAILED');
+ }
+}
diff --git a/apps/desktop/src/main/remote-desktop/inputOwnership.ts b/apps/desktop/src/main/remote-desktop/inputOwnership.ts
new file mode 100644
index 0000000000..dc3250d670
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/inputOwnership.ts
@@ -0,0 +1,24 @@
+// Process-local arbitration: a human and an Agent cannot inject simultaneously.
+let human = false;
+let actions = 0;
+export function acquireHumanDesktopInput(): () => void {
+ if (human || actions > 0) throw new Error('DESKTOP_INPUT_BUSY');
+ human = true;
+ let released = false;
+ return () => {
+ if (!released) {
+ released = true;
+ human = false;
+ }
+ };
+}
+export async function withAgentDesktopInput<T>(run: () => Promise<T>): Promise<T> {
+ if (human)
+ throw new Error('Desktop input is in use by a person. Retry after they release control.');
+ actions++;
+ try {
+ return await run();
+ } finally {
+ actions--;
+ }
+}
diff --git a/apps/desktop/src/main/remote-desktop/nativeCapture.ts b/apps/desktop/src/main/remote-desktop/nativeCapture.ts
new file mode 100644
index 0000000000..ce3178574d
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/nativeCapture.ts
@@ -0,0 +1,210 @@
+import { isRemoteDesktopCursor, type RemoteDesktopCursorFrame, type RemoteDesktopVideoSettings } from '@cindy/device-link';
+import { app, screen } from 'electron';
+import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { openWindowsDesktopConnection, type WindowsDesktopConnection } from './windowsHost';
+
+const exec = promisify(execFile);
+const name = 'cindy-macos-desktop-capture';
+let building: Promise<string> | null = null;
+async function binary(): Promise<string> {
+ if (app.isPackaged) return path.join(process.resourcesPath, 'tools', 'remote-desktop', name);
+ if (building) return building;
+ building = (async () => {
+ const source = path.join(app.getAppPath(), 'native', 'remote-desktop', 'macos-capture.m');
+ const hash = createHash('sha256')
+ .update(await fs.readFile(source))
+ .update(process.arch)
+ .digest('hex');
+ const directory = path.join(app.getPath('userData'), 'remote-desktop', 'native', hash);
+ const output = path.join(directory, name);
+ try {
+ await fs.access(output);
+ return output;
+ } catch {
+ /* compile this source */
+ }
+ await fs.mkdir(directory, { recursive: true });
+ const temporary = `${output}.${process.pid}.tmp`;
+ try {
+ await exec(
+ 'xcrun',
+ [
+ 'clang',
+ source,
+ '-fobjc-arc',
+ '-fblocks',
+ '-O2',
+ '-framework',
+ 'Foundation',
+ '-framework',
+ 'AppKit',
+ '-framework',
+ 'CoreGraphics',
+ '-framework',
+ 'CoreImage',
+ '-framework',
+ 'IOSurface',
+ '-framework',
+ 'ImageIO',
+ '-framework',
+ 'IOKit',
+ '-o',
+ temporary,
+ ],
+ { timeout: 120_000 },
+ );
+ await fs.rename(temporary, output);
+ } finally {
+ await fs.rm(temporary, { force: true });
+ }
+ return output;
+ })().finally(() => {
+ building = null;
+ });
+ return building;
+}
+
+/** One capture child for the current lease. No sockets, files, or frame history.
+ * macOS uses a user-session child; Windows uses the authorized SYSTEM broker.
+ * Neither adapter keeps frame history on disk.
+ */
+export class NativeDesktopCapture {
+ private windows: WindowsDesktopConnection | null = null;
+ private child: ChildProcessWithoutNullStreams | null = null;
+ private display = '';
+ private config = '';
+ private generation = 0;
+ private busy = false;
+ private cancel: ((error?: Error) => void) | null = null;
+
+ async frame(display: string, overlay = false, settings?: RemoteDesktopVideoSettings): Promise<string | RemoteDesktopCursorFrame | null> {
+ if (process.platform === 'win32') {
+ if (this.busy) return null;
+ if (this.display && this.display !== display) this.stop();
+ const selected = screen.getAllDisplays().find((item) => String(item.id) === display);
+ if (!selected) return null;
+ this.busy = true;
+ const generation = this.generation;
+ try {
+ if (!this.windows) {
+ const bounds = screen.dipToScreenRect(null, selected.bounds);
+ const connection = await openWindowsDesktopConnection({
+ mode: 'capture',
+ rect: [bounds.x, bounds.y, bounds.width, bounds.height],
+ });
+ if (generation !== this.generation) {
+ connection.close();
+ return null;
+ }
+ this.windows = connection;
+ this.display = display;
+ }
+ const jpeg = (await this.windows.request('f')).trim();
+ return generation === this.generation &&
+ jpeg.length <= 240000 &&
+ /^[A-Za-z0-9+/]+={0,2}$/.test(jpeg)
+ ? jpeg
+ : null;
+ } catch {
+ if (generation === this.generation) this.stop();
+ return null;
+ } finally {
+ if (generation === this.generation) this.busy = false;
+ }
+ }
+ const config = overlay ? [settings?.fps ?? 30, settings?.bitrate ?? 0].join(':') : '';
+ if (this.child && this.config !== config) this.stop();
+ if (process.platform !== 'darwin' || !/^[0-9]{1,10}$/.test(display)) return null;
+ if (this.busy) return null;
+ if (this.display && this.display !== display) this.stop();
+ this.busy = true;
+ const generation = this.generation;
+ try {
+ if (!this.child) {
+ const executable = await binary();
+ if (generation !== this.generation) return null;
+ const quality = settings?.bitrate === 20_000_000 ? 0.95 : settings?.bitrate === 8_000_000 ? 0.8 : 0.65;
+ const child = spawn(executable, overlay ? [display, 'cursor-overlay', String(settings?.fps ?? 30), String(quality)] : [display], { stdio: 'pipe' });
+ this.child = child;
+ this.display = display;
+ this.config = config;
+ child.stderr.resume();
+ child.stdin.on('error', () => {
+ if (this.child === child) this.stop();
+ });
+ child.on('error', () => {
+ if (this.child === child) this.stop();
+ });
+ child.on('exit', (code) => {
+ if (this.child !== child) return;
+ this.cancel?.(new Error(code === 3
+ ? 'DESKTOP_SCREEN_PERMISSION_REQUIRED'
+ : 'DESKTOP_VIDEO_UNAVAILABLE'));
+ this.stop();
+ });
+ }
+ const child = this.child;
+ return await new Promise<string | RemoteDesktopCursorFrame | null>((resolve, reject) => {
+ let text = '';
+ const finish = (frame: string | RemoteDesktopCursorFrame | null, error?: Error) => {
+ clearTimeout(timer);
+ child.stdout.off('data', receive);
+ this.cancel = null;
+ if (error) reject(error);
+ else resolve(frame);
+ };
+ const receive = (chunk: Buffer) => {
+ text += chunk.toString('ascii');
+ if (text.length > (overlay ? 1_500_000 : 240_001)) {
+ this.stop();
+ return;
+ }
+ if (!text.endsWith('\n')) return;
+ if (overlay) {
+ try {
+ const value = JSON.parse(text) as RemoteDesktopCursorFrame;
+ if (typeof value.jpeg !== 'string' || value.jpeg.length > 1_333_336 ||
+ !/^[A-Za-z0-9+/]+={0,2}$/.test(value.jpeg) || (value.cursor !== null && !isRemoteDesktopCursor(value.cursor)))
+ throw new Error('INVALID_CURSOR_FRAME');
+ finish(generation === this.generation ? value : null);
+ } catch { this.stop(); }
+ return;
+ }
+ const jpeg = text.slice(0, -1);
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(jpeg)) {
+ this.stop();
+ return;
+ }
+ finish(generation === this.generation ? jpeg : null);
+ };
+ const timer = setTimeout(() => this.stop(), 3000);
+ this.cancel = (error) => finish(null, error);
+ child.stdout.on('data', receive);
+ child.stdin.write('f');
+ });
+ } finally {
+ // A cancelled old request must not reset a newer reader's backpressure.
+ if (generation === this.generation) this.busy = false;
+ }
+ }
+
+ stop(): void {
+ this.generation++;
+ this.windows?.close();
+ this.windows = null;
+ this.cancel?.();
+ this.cancel = null;
+ const child = this.child;
+ this.child = null;
+ this.display = '';
+ this.busy = false;
+ if (child) {
+ child.stdin.destroy();
+ child.kill();
+ }
+ }
+}
diff --git a/apps/desktop/src/main/remote-desktop/permissions.ts b/apps/desktop/src/main/remote-desktop/permissions.ts
new file mode 100644
index 0000000000..7d8382f286
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/permissions.ts
@@ -0,0 +1,85 @@
+import type {
+ DesktopPermission,
+ RemoteDesktopPermissions,
+ DesktopPermissionStatus,
+} from '@cindy/device-link';
+import { desktopPermissionReady } from '@cindy/device-link';
+
+/** Readiness is independent of the persisted opt-in. Reads never open OS UI. */
+export class RemoteDesktopPermissionsService {
+ private reading: Promise<RemoteDesktopPermissions> | null = null;
+ private generation = 0;
+ private opening = false;
+ private requestAbort: AbortController | null = null;
+ guideOpen = false;
+ constructor(
+ private readonly deps: {
+ required: boolean;
+ screen(): DesktopPermissionStatus;
+ accessibility(): Promise<DesktopPermissionStatus>;
+ request(
+ permission: DesktopPermission,
+ isCurrent: () => boolean,
+ signal: AbortSignal,
+ ): Promise<void>;
+ openSettings(permission: DesktopPermission): Promise<void>;
+ showGuide(): void;
+ },
+ ) {}
+ read(): Promise<RemoteDesktopPermissions> {
+ if (!this.deps.required)
+ return Promise.resolve({ screenRecording: 'notRequired', accessibility: 'notRequired' });
+ if (this.reading) return this.reading;
+ this.reading = (async () => {
+ const accessibility = await this.deps.accessibility().catch(() => 'unknown' as const);
+ let screenRecording: DesktopPermissionStatus = 'unknown';
+ try {
+ screenRecording = this.deps.screen();
+ } catch {
+ /* unknown is not granted */
+ }
+ return { screenRecording, accessibility };
+ })().finally(() => {
+ this.reading = null;
+ });
+ return this.reading;
+ }
+ show(): void {
+ if (!this.deps.required || this.guideOpen) return;
+ this.guideOpen = true;
+ this.deps.showGuide();
+ }
+ async showIfNeeded(stillEnabled: () => boolean): Promise<void> {
+ const generation = this.generation;
+ const status = await this.read();
+ if (
+ generation === this.generation &&
+ stillEnabled() &&
+ (!desktopPermissionReady(status.screenRecording) ||
+ !desktopPermissionReady(status.accessibility))
+ )
+ this.show();
+ }
+ dismiss(): void {
+ this.generation++;
+ this.requestAbort?.abort();
+ this.guideOpen = false;
+ }
+ async open(permission: DesktopPermission): Promise<void> {
+ if (!this.deps.required || this.opening) return;
+ const generation = this.generation;
+ const abort = new AbortController();
+ this.requestAbort = abort;
+ this.opening = true;
+ try {
+ // A failed prompt must still offer the exact System Settings pane.
+ await this.deps
+ .request(permission, () => generation === this.generation, abort.signal)
+ .catch(() => {});
+ if (generation === this.generation) await this.deps.openSettings(permission);
+ } finally {
+ if (this.requestAbort === abort) this.requestAbort = null;
+ this.opening = false;
+ }
+ }
+}
diff --git a/apps/desktop/src/main/remote-desktop/windowsHost.ts b/apps/desktop/src/main/remote-desktop/windowsHost.ts
new file mode 100644
index 0000000000..fe8fe95336
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/windowsHost.ts
@@ -0,0 +1,65 @@
+import { app } from 'electron';
+import { execFile } from 'node:child_process';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import type { WindowsDesktopSupport } from '../../shared/remoteDesktop';
+
+const exec = promisify(execFile);
+const requireNative = createRequire(import.meta.url);
+const binary = () =>
+ path.join(process.resourcesPath, 'tools', 'remote-desktop', 'cindy-windows-desktop-host.exe');
+export interface WindowsDesktopConnection {
+ request(line: string): Promise<string>;
+ close(): void;
+}
+export async function readWindowsDesktopSupport(): Promise<WindowsDesktopSupport | undefined> {
+ if (process.platform !== 'win32') return undefined;
+ if (!app.isPackaged) return 'installRequired';
+ try {
+ const { stdout } = await exec(binary(), ['--status'], {
+ timeout: 8000,
+ maxBuffer: 1024,
+ windowsHide: true,
+ });
+ const status = stdout.trim();
+ if (status === 'ready') {
+ try {
+ const connection = await openWindowsDesktopConnection({ mode: 'probe' });
+ connection.close();
+ } catch {
+ return 'missing';
+ }
+ }
+ return status === 'ready' || status === 'missing' || status === 'installRequired'
+ ? status
+ : 'unavailable';
+ } catch {
+ return 'unavailable';
+ }
+}
+export async function configureWindowsDesktopSupport(enabled: boolean): Promise<void> {
+ if (process.platform !== 'win32' || !app.isPackaged)
+ throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');
+ await exec(
+ binary(),
+ enabled ? ['--elevate-install', String(process.pid)] : ['--elevate-uninstall'],
+ { timeout: 130_000, maxBuffer: 1024, windowsHide: true },
+ );
+ if (enabled && (await readWindowsDesktopSupport()) !== 'ready')
+ throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');
+}
+export async function openWindowsDesktopConnection(
+ init: { mode: 'input' | 'probe' } | { mode: 'capture'; rect: number[] },
+): Promise<WindowsDesktopConnection> {
+ if (process.platform !== 'win32' || !app.isPackaged)
+ throw new Error('DESKTOP_SYSTEM_SERVICE_UNAVAILABLE');
+ // Fixed packaged Node-API addon, loaded only by Main. It opens the pipe in
+ // this process and authenticates SCM/SYSTEM identity before sending anything.
+ const native = requireNative(
+ path.join(process.resourcesPath, 'tools', 'remote-desktop', 'cindy-windows-desktop-host.node'),
+ ) as {
+ DesktopConnection: { open(binary: string, init: string): Promise<WindowsDesktopConnection> };
+ };
+ return native.DesktopConnection.open(binary(), JSON.stringify(init));
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index c7fbb2406b..13f6e5a5f4 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,4 +1,5 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
+import { DESKTOP_LOCAL, type RemoteDesktopApi, type DesktopHostCommand } from '../shared/remoteDesktop';
import { DEVICE_LINK_PUSH } from '../shared/deviceLinkIpc';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import type { AppearanceSettings } from '../shared/appearanceSettings';
@@ -4176,6 +4177,25 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── Device Link (设备互联/跨设备远程控制) ─────────────────────────────
// 同账号设备经 server relay 互联;此处只暴露开关 + 设备列表管理面,
// 隧道(远程会话控制)在 M3 接入。
+ remoteDesktop: {
+ state: () => ipcRenderer.invoke(DESKTOP_LOCAL.STATE),
+ permissions: () => ipcRenderer.invoke(DESKTOP_LOCAL.PERMISSIONS),
+ openPermission: (permission) => ipcRenderer.invoke(DESKTOP_LOCAL.OPEN_PERMISSION, permission),
+ dismissPermissionGuide: () => ipcRenderer.invoke(DESKTOP_LOCAL.DISMISS_GUIDE),
+ enable: (enabled) => ipcRenderer.invoke(DESKTOP_LOCAL.ENABLE, enabled),
+ windowsSupport: (enabled) => ipcRenderer.invoke(DESKTOP_LOCAL.WINDOWS_SUPPORT, enabled),
+ stop: () => ipcRenderer.invoke(DESKTOP_LOCAL.STOP),
+ registerHost: () => ipcRenderer.invoke(DESKTOP_LOCAL.REGISTER),
+ onCommand: (listener) => {
+ const wrapped = (_event: Electron.IpcRendererEvent, command: DesktopHostCommand) => listener(command);
+ ipcRenderer.on(DESKTOP_LOCAL.COMMAND, wrapped);
+ return () => { ipcRenderer.removeListener(DESKTOP_LOCAL.COMMAND, wrapped); };
+ },
+ reply: (id, sdp) => ipcRenderer.invoke(DESKTOP_LOCAL.REPLY, id, sdp),
+ input: (lease, sequence, events) => ipcRenderer.invoke(DESKTOP_LOCAL.INPUT, lease, sequence, events),
+ viewHeartbeat: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.VIEW_HEARTBEAT, lease),
+ nativeFrame: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.NATIVE_FRAME, lease),
+ } satisfies RemoteDesktopApi,
deviceLink: {
getState: (): Promise<{
remoteControlEnabled: boolean;
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 7ad7f19e8a..e413a78b70 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -1,6 +1,7 @@
import { RouterProvider } from 'react-router-dom';
import { useEffect } from 'react';
+import { RemoteDesktopHost } from '@/features/remote-desktop/RemoteDesktopHost';
import { useCloseWindowFallbackShortcut } from '@/hooks/useCloseWindowShortcut';
import { useDisableContextMenu } from '@/hooks/useDisableContextMenu';
@@ -368,6 +369,7 @@ export function App() {
)}
<EnvCheckGuard>
<MakerBootstrap />
+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <RemoteDesktopHost />}
<ProjectAutomationNotifyBridge />
{/* confirm 槽:插件请主机弹确认框。必须在 ConfirmDialogProvider
内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口
diff --git a/apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx b/apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx
new file mode 100644
index 0000000000..52feb47c00
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx
@@ -0,0 +1,68 @@
+import { Check } from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { Spinner } from '@/components/ui/spinner';
+
+export function ComputerPermissionRow({
+ label,
+ iconSrc,
+ granted,
+ pending,
+ actionLabel,
+ onAction,
+ compact = false,
+}: {
+ compact?: boolean;
+ label: string;
+ iconSrc: string;
+ granted: boolean;
+ pending: boolean;
+ actionLabel: string;
+ onAction: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onAction}
+ disabled={pending}
+ className={cn(
+ 'flex w-full min-w-0 items-center text-left',
+ compact
+ ? 'min-h-8 gap-2 rounded-md py-1'
+ : 'min-h-[64px] gap-3 rounded-xl border border-solid border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3.5 py-3',
+ 'transition-colors hover:bg-[var(--settings-menu-bg-hover)]',
+ 'disabled:cursor-default disabled:hover:bg-[var(--settings-input-bg)]',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <img
+ className={cn(
+ 'shrink-0 object-contain grayscale opacity-70',
+ compact ? 'size-4' : 'size-8',
+ )}
+ src={iconSrc}
+ alt=""
+ aria-hidden="true"
+ />
+ <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--settings-section-title)]">
+ {label}
+ </span>
+ <span
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1.5 rounded-full font-medium',
+ compact ? 'h-6 px-2 text-11' : 'h-8 px-3 text-12',
+ compact && !pending && granted
+ ? 'border border-transparent bg-transparent text-[var(--settings-section-sublabel)]'
+ : pending
+ ? 'border border-dashed border-[var(--settings-input-border)] bg-[var(--surface-chip)] text-[var(--settings-section-desc)]'
+ : granted
+ ? 'border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] text-[var(--settings-section-title)]'
+ : 'border border-[var(--surface-chip)] bg-[var(--surface-chip)] text-[var(--settings-section-title)]',
+ )}
+ >
+ {pending ? <Spinner size={12} /> : null}
+ <span>{actionLabel}</span>
+ {granted && !pending ? <Check size={13} strokeWidth={2.3} aria-hidden="true" /> : null}
+ </span>
+ </button>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
index d1844517b8..195b6205d9 100644
--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
@@ -44,6 +44,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { createLogger } from '@/lib/logger';
import { BrowserBackendSubsection } from './BrowserBackendSubsection';
+import { ComputerPermissionRow } from './ComputerPermissionRow';
import { BrowserRealProfileSubsection } from './BrowserRealProfileSubsection';
import {
REAL_PROFILE_READ_DENIED,
@@ -156,55 +157,6 @@ interface ComputerUseSectionProps {
workingDir?: string;
}
-function ComputerPermissionRow({
- label,
- iconSrc,
- granted,
- pending,
- actionLabel,
- onAction,
-}: {
- label: string;
- iconSrc: string;
- granted: boolean;
- pending: boolean;
- actionLabel: string;
- onAction: () => void;
-}) {
- return (
- <button
- type="button"
- onClick={onAction}
- disabled={pending}
- className={cn(
- 'flex min-h-[64px] w-full min-w-0 items-center gap-3 rounded-xl px-3.5 py-3 text-left',
- 'border border-solid border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',
- 'transition-colors hover:bg-[var(--settings-menu-bg-hover)]',
- 'disabled:cursor-default disabled:hover:bg-[var(--settings-input-bg)]',
- 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- )}
- >
- <img className="size-8 shrink-0 object-contain grayscale opacity-70" src={iconSrc} alt="" aria-hidden="true" />
- <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--settings-section-title)]">
- {label}
- </span>
- <span
- className={cn(
- 'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-12 font-medium',
- pending
- ? 'border border-dashed border-[var(--settings-input-border)] bg-[var(--surface-chip)] text-[var(--settings-section-desc)]'
- : granted
- ? 'border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] text-[var(--settings-section-title)]'
- : 'border border-[var(--surface-chip)] bg-[var(--surface-chip)] text-[var(--settings-section-title)]',
- )}
- >
- {pending ? <Spinner size={12} /> : null}
- <span>{actionLabel}</span>
- {granted && !pending ? <Check size={13} strokeWidth={2.3} aria-hidden="true" /> : null}
- </span>
- </button>
- );
-}
export function ComputerUseSection({
workingDir,
diff --git a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
index 0c0888a895..9c29955f82 100644
--- a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
+++ b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
@@ -132,9 +132,11 @@ function ControlRow({
export function MyDevicesPanel({
s,
variant = 'all',
+ selfSettings,
}: {
s: DeviceLinkSettings;
variant?: 'all' | 'self' | 'others';
+ selfSettings?: ReactNode;
}) {
const { t } = useTranslation();
const [editingId, setEditingId] = useState<string | null>(null);
@@ -303,6 +305,7 @@ export function MyDevicesPanel({
/>
</ControlRow>
</div>
+ {s.enabled && selfSettings && <div className="mt-3">{selfSettings}</div>}
</li>
)}
diff --git a/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
index 64ef2bdf6f..358b136f03 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
@@ -24,6 +24,7 @@ import { ChevronDown, ChevronRight } from 'lucide-react';
import { useDeviceLinkSettings, type DeviceLinkSettings } from '@/hooks/useDeviceLinkSettings';
import { MyDevicesPanel } from './MyDevicesPanel';
+import { RemoteDesktopSetting } from './RemoteDesktopSetting';
import { RemoteSection } from './RemoteSection';
import { useAuth } from '@/contexts/AuthContext';
@@ -244,7 +245,9 @@ export function RemoteControlSection() {
dotColor={null}
open={devicesOpen}
onToggle={toggleDevices}
- pinned={<MyDevicesPanel s={s} variant="self" />}
+ pinned={
+ <MyDevicesPanel s={s} variant="self" selfSettings={<RemoteDesktopSetting />} />
+ }
>
<MyDevicesPanel s={s} variant="others" />
</CollapsibleSubSection>
diff --git a/apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx b/apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx
new file mode 100644
index 0000000000..f0290e37ad
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx
@@ -0,0 +1,123 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ desktopPermissionReady,
+ type DesktopPermission,
+ type RemoteDesktopPermissions as Permissions,
+} from '@cindy/device-link';
+import accessibilityIcon from '@/assets/system-settings/accessibility-icon.png';
+import screenRecordingIcon from '@/assets/system-settings/screen-recording-icon.png';
+import { ComputerPermissionRow } from './ComputerPermissionRow';
+
+/** Compact permission rows backed by the actual remote host. */
+export function RemoteDesktopPermissions() {
+ const { t } = useTranslation();
+ const [status, setStatus] = useState<Permissions | null>(null);
+ const [pending, setPending] = useState<DesktopPermission | null>(null);
+ const [error, setError] = useState<'check' | 'action' | null>(null);
+ const mounted = useRef(false);
+ const reading = useRef(false);
+ const refresh = useCallback(async () => {
+ if (reading.current) return;
+ reading.current = true;
+ try {
+ const next = await window.electronAPI.remoteDesktop.permissions();
+ if (mounted.current) {
+ setStatus(next);
+ setError((previous) => (previous === 'check' ? null : previous));
+ }
+ } catch {
+ if (mounted.current) setError((previous) => (previous === 'action' ? previous : 'check'));
+ } finally {
+ reading.current = false;
+ }
+ }, []);
+ useEffect(() => {
+ mounted.current = true;
+ void refresh();
+ const timer = setInterval(() => {
+ if (!document.hidden) void refresh();
+ }, 1500);
+ window.addEventListener('focus', refresh);
+ return () => {
+ mounted.current = false;
+ clearInterval(timer);
+ window.removeEventListener('focus', refresh);
+ };
+ }, [refresh]);
+ if (status?.screenRecording === 'notRequired' && status.accessibility === 'notRequired')
+ return null;
+ const ready =
+ status &&
+ desktopPermissionReady(status.screenRecording) &&
+ desktopPermissionReady(status.accessibility);
+ const open = async (permission: DesktopPermission) => {
+ if (pending) return;
+ setPending(permission);
+ setError(null);
+ try {
+ await window.electronAPI.remoteDesktop.openPermission(permission);
+ if (mounted.current) await refresh();
+ } catch {
+ if (mounted.current) setError('action');
+ } finally {
+ if (mounted.current) setPending(null);
+ }
+ };
+ return (
+ <div className="flex flex-col gap-1.5 border-t border-[var(--border-default)] pt-3">
+ <p role="status" className="text-12 text-[var(--settings-section-desc)]">
+ {t(ready ? 'remoteDesktop.permissionsReady' : 'remoteDesktop.permissionsIntro')}
+ </p>
+ {(['screenRecording', 'accessibility'] as const).map((permission) => {
+ const value = status?.[permission];
+ return (
+ <div key={permission} className="flex flex-col gap-1">
+ <ComputerPermissionRow
+ compact
+ label={t(`remoteDesktop.${permission}`)}
+ iconSrc={permission === 'screenRecording' ? screenRecordingIcon : accessibilityIcon}
+ granted={value === 'granted'}
+ pending={!status || pending !== null}
+ actionLabel={t(
+ !status
+ ? 'remoteDesktop.permissionChecking'
+ : value === 'granted'
+ ? 'remoteDesktop.permissionGranted'
+ : 'remoteDesktop.openPermissionSettings',
+ )}
+ onAction={() => {
+ void open(permission);
+ }}
+ />
+ {value !== 'granted' && (
+ <p className="text-12 text-[var(--settings-section-desc)]">
+ {value === 'unknown' ? `${t('remoteDesktop.permissionUnknown')} · ` : ''}
+ {t(`remoteDesktop.${permission}Help`)}
+ </p>
+ )}
+ </div>
+ );
+ })}
+ <button
+ type="button"
+ className="self-start rounded-full px-2 py-1 text-11 text-[var(--settings-section-title)] hover:bg-[var(--surface-chip)]"
+ onClick={() => {
+ setError(null);
+ void refresh();
+ }}
+ >
+ {t('remoteDesktop.recheckPermissions')}
+ </button>
+ {error && (
+ <p role="alert" className="text-12 text-[var(--settings-section-desc)]">
+ {t(
+ error === 'check'
+ ? 'remoteDesktop.permissionCheckFailed'
+ : 'remoteDesktop.permissionActionFailed',
+ )}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx b/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx
new file mode 100644
index 0000000000..6b97455d0d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx
@@ -0,0 +1,132 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import type { WindowsDesktopSupport } from '../../../shared/remoteDesktop';
+import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
+import { RemoteDesktopPermissions } from './RemoteDesktopPermissions';
+
+export function RemoteDesktopSetting() {
+ const { t } = useTranslation();
+ const [windowsSupport, setWindowsSupport] = useState<WindowsDesktopSupport>();
+ const [serviceError, setServiceError] = useState(false);
+ const [enabled, setEnabled] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(false);
+ const revision = useRef(0);
+ const changing = useRef(false);
+ useEffect(() => {
+ const api = window.electronAPI?.remoteDesktop;
+ if (!api) return;
+ let active = true;
+ let reading = false;
+ const refresh = () => {
+ if (reading || changing.current) return;
+ reading = true;
+ const current = revision.current;
+ void api
+ .state()
+ .then((state) => {
+ if (active && current === revision.current) {
+ setEnabled(state.enabled);
+ setWindowsSupport(state.windowsSupport);
+ }
+ })
+ .catch(() => {
+ if (active) setError(true);
+ })
+ .finally(() => {
+ reading = false;
+ });
+ };
+ refresh();
+ const timer = setInterval(refresh, 2000);
+ return () => {
+ active = false;
+ clearInterval(timer);
+ };
+ }, []);
+ if (!window.electronAPI?.remoteDesktop) return null;
+ return (
+ <section
+ aria-label={t('remoteDesktop.allow')}
+ className="flex flex-col gap-3 rounded-lg bg-[var(--settings-input-bg)] p-3"
+ >
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex flex-col gap-1">
+ <p className="text-13 font-medium text-[var(--text-primary)]">
+ {t('remoteDesktop.allow')}
+ </p>
+ <p className="text-12 text-[var(--text-tertiary)]">{t('remoteDesktop.allowHint')}</p>
+ {error && (
+ <p role="alert" className="text-12 text-[var(--text-primary)]">
+ {t('remoteDesktop.permissionHint')}
+ </p>
+ )}
+ </div>
+ <Switch
+ aria-label={t('remoteDesktop.allow')}
+ disabled={busy}
+ checked={enabled}
+ onCheckedChange={(next) => {
+ revision.current++;
+ changing.current = true;
+ setBusy(true);
+ setError(false);
+ void window.electronAPI.remoteDesktop
+ .enable(next)
+ .then(() => setEnabled(next))
+ .catch(() => setError(true))
+ .finally(() => {
+ changing.current = false;
+ setBusy(false);
+ });
+ }}
+ />
+ </div>
+ {enabled && windowsSupport && (
+ <div className="flex items-center justify-between gap-4 border-t border-[var(--border-default)] pt-3">
+ <div className="flex flex-col gap-1">
+ <p className="text-13 font-medium text-[var(--text-primary)]">
+ {t('remoteDesktop.windowsTitle')}
+ </p>
+ <p className="text-12 text-[var(--text-tertiary)]">
+ {t(`remoteDesktop.windows${windowsSupport}`)}
+ </p>
+ {serviceError && (
+ <p role="alert" className="text-12 text-[var(--text-primary)]">
+ {t('remoteDesktop.windowsError')}
+ </p>
+ )}
+ </div>
+ <Button
+ disabled={
+ busy || windowsSupport === 'installRequired' || windowsSupport === 'unavailable'
+ }
+ onClick={() => {
+ revision.current++;
+ changing.current = true;
+ setBusy(true);
+ setServiceError(false);
+ void window.electronAPI.remoteDesktop
+ .windowsSupport(windowsSupport !== 'ready')
+ .then(() => window.electronAPI.remoteDesktop.state())
+ .then((state) => setWindowsSupport(state.windowsSupport))
+ .catch(() => setServiceError(true))
+ .finally(() => {
+ changing.current = false;
+ setBusy(false);
+ });
+ }}
+ >
+ {t(
+ windowsSupport === 'ready'
+ ? 'remoteDesktop.windowsDisable'
+ : 'remoteDesktop.windowsEnable',
+ )}
+ </Button>
+ </div>
+ )}
+ {enabled && !windowsSupport && <RemoteDesktopPermissions />}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/remoteDesktopPermissions.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/remoteDesktopPermissions.test.tsx
new file mode 100644
index 0000000000..a01a661ebe
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/remoteDesktopPermissions.test.tsx
@@ -0,0 +1,34 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { RemoteDesktopPermissions } from '../RemoteDesktopPermissions';
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+it('shows independent permission rows, opens only the selected permission, and refreshes automatically', async () => {
+ vi.useFakeTimers();
+ const permissions = vi.fn(async () => ({ screenRecording: 'missing', accessibility: 'granted' }));
+ const openPermission = vi.fn(async () => {});
+ Object.assign(window, { electronAPI: { remoteDesktop: { permissions, openPermission } } });
+ render(<RemoteDesktopPermissions />);
+ await act(async () => {});
+ expect(openPermission).not.toHaveBeenCalled();
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: /remoteDesktop.screenRecording\s*remoteDesktop.openPermissionSettings/,
+ }),
+ );
+ await act(async () => {});
+ expect(openPermission).toHaveBeenCalledExactlyOnceWith('screenRecording');
+ permissions.mockResolvedValue({ screenRecording: 'granted', accessibility: 'granted' });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(screen.getByRole('status').textContent).toBe('remoteDesktop.permissionsReady');
+ cleanup();
+ const count = permissions.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(permissions).toHaveBeenCalledTimes(count);
+});
diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx
new file mode 100644
index 0000000000..12cd56d37d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx
@@ -0,0 +1,358 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { isDesktopInput, type DesktopInput, type RemoteDesktopCursor } from '@cindy/device-link';
+import type { DesktopLocalState } from '../../../shared/remoteDesktop';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { RemoteDesktopPermissions } from '@/components/settings/RemoteDesktopPermissions';
+import { nativeCaptureStream } from './nativeCaptureStream';
+
+/** Lives only in the existing trusted main renderer; no remote document gets this bridge. */
+export function RemoteDesktopHost() {
+ const { t } = useTranslation();
+ const [state, setState] = useState<DesktopLocalState | null>(null);
+ const stateRevision = useRef(0);
+ const dismissing = useRef(false);
+ useEffect(() => {
+ const api = window.electronAPI?.remoteDesktop;
+ if (!api) return;
+ let peer: RTCPeerConnection | null = null;
+ let stream: MediaStream | null = null;
+ let generation = 0;
+ let disposed = false;
+ let heartbeat: ReturnType<typeof setInterval> | null = null;
+ let latestCursor: RemoteDesktopCursor | null | undefined;
+ let cursorTimer: ReturnType<typeof setInterval> | null = null;
+ let native: Awaited<ReturnType<typeof nativeCaptureStream>> | null = null;
+ let recoverCapture: (() => void) | null = null;
+ let activeLease: string | null = null;
+ const stop = () => {
+ generation++;
+ latestCursor = undefined;
+ if (cursorTimer) clearInterval(cursorTimer);
+ cursorTimer = null;
+ native?.stop();
+ native = null;
+ recoverCapture = null;
+ activeLease = null;
+ if (heartbeat) clearInterval(heartbeat);
+ heartbeat = null;
+ peer?.close();
+ peer = null;
+ stream?.getTracks().forEach((track) => track.stop());
+ stream = null;
+ };
+ const unsubscribe = api.onCommand((command) => {
+ if (command.op === 'capture-reset') {
+ if (command.lease === activeLease) {
+ native?.clear();
+ recoverCapture?.();
+ }
+ return;
+ }
+ stop();
+ if (
+ command.op !== 'offer' ||
+ !command.lease ||
+ !command.sdp ||
+ (!command.sourceId && !command.nativeCapture)
+ )
+ return;
+ const current = generation;
+ const lease = command.lease;
+ activeLease = lease;
+ void (async () => {
+ try {
+ const capture = async () =>
+ command.settings?.audio
+ ? await navigator.mediaDevices.getDisplayMedia({
+ audio: true,
+ video: { frameRate: { ideal: command.settings.fps, max: command.settings.fps } },
+ })
+ : await navigator.mediaDevices.getUserMedia({
+ audio: false,
+ video: {
+ mandatory: {
+ chromeMediaSource: 'desktop',
+ chromeMediaSourceId: command.sourceId,
+ maxFrameRate: command.settings?.fps ?? 30,
+ ...(!command.settings ? { maxWidth: 1920, maxHeight: 1920 } : {}),
+ },
+ } as MediaTrackConstraints,
+ });
+ const boundedCapture = async () => {
+ if (!command.sourceId) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');
+ let abandoned = false;
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ capture().then((value) => {
+ if (abandoned || current !== generation) {
+ value.getTracks().forEach((track) => track.stop());
+ throw new Error('DESKTOP_VIDEO_STOPPED');
+ }
+ return value;
+ }),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(() => {
+ abandoned = true;
+ reject(new Error('DESKTOP_VIDEO_TIMEOUT'));
+ }, command.nativeCapture ? 2000 : 10000);
+ }),
+ ]);
+ } finally {
+ if (timeout) clearTimeout(timeout);
+ }
+ };
+ const nativeStream = async () => {
+ const result = await nativeCaptureStream(
+ () => api.nativeFrame(lease),
+ () => current === generation,
+ () => stop(),
+ (value) => { if (current === generation) latestCursor = value; },
+ command.cursorOverlay ? (command.settings?.fps ?? 30) : 15,
+ );
+ if (current !== generation) {
+ result.stop();
+ throw new Error('DESKTOP_VIDEO_STOPPED');
+ }
+ native = result;
+ return result.stream;
+ };
+ let captured: MediaStream;
+ if (command.cursorOverlay) {
+ // Chromium in our runtime exposes no cursor constraint. Use the
+ // cursor-free native video while retaining the normal audio track.
+ let audioSource: MediaStream | null = null;
+ try {
+ if (command.settings?.audio && command.sourceId) {
+ try {
+ audioSource = await boundedCapture();
+ } catch (error) {
+ if (current !== generation) throw error;
+ // Native video remains usable when system audio is unavailable.
+ }
+ }
+ captured = await nativeStream();
+ if (current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');
+ for (const track of audioSource?.getAudioTracks() ?? []) captured.addTrack(track);
+ audioSource?.getVideoTracks().forEach((track) => track.stop());
+ } catch (error) {
+ audioSource?.getTracks().forEach((track) => track.stop());
+ throw error;
+ }
+ } else try {
+ captured = await boundedCapture();
+ } catch (error) {
+ if (!command.nativeCapture || current !== generation) throw error;
+ captured = await nativeStream();
+ }
+ if (current !== generation) {
+ captured.getTracks().forEach((track) => track.stop());
+ return;
+ }
+ if (command.settings?.audio && !command.nativeCapture && !captured.getAudioTracks().length) {
+ captured.getTracks().forEach((track) => track.stop());
+ throw new Error('DESKTOP_AUDIO_UNAVAILABLE');
+ }
+ stream = captured;
+ const rtc = new RTCPeerConnection({
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
+ });
+ peer = rtc;
+ let recovering = false;
+ recoverCapture = () => {
+ if (!command.nativeCapture || native || recovering || current !== generation) return;
+ recovering = true;
+ void (async () => {
+ const replacement = await nativeStream();
+ const sender = rtc.getSenders().find((item) => item.track?.kind === 'video');
+ if (!sender || current !== generation) throw new Error('DESKTOP_VIDEO_STOPPED');
+ await sender.replaceTrack(replacement.getVideoTracks()[0]);
+ captured.getVideoTracks().forEach((track) => {
+ track.onended = null;
+ track.onmute = null;
+ track.stop();
+ });
+ })().catch(() => {
+ if (current === generation) stop();
+ });
+ };
+ captured.getVideoTracks().forEach((track) => {
+ track.onended = () => recoverCapture?.();
+ track.onmute = () => recoverCapture?.();
+ });
+ rtc.onconnectionstatechange = () => {
+ if (
+ current === generation &&
+ ['failed', 'closed', 'disconnected'].includes(rtc.connectionState)
+ )
+ stop();
+ };
+ rtc.ondatachannel = ({ channel }) => {
+ if (channel.label !== 'input-v1') {
+ channel.close();
+ return;
+ }
+ if (command.cursorOverlay) {
+ let lastCursor = '';
+ cursorTimer = setInterval(() => {
+ if (latestCursor === undefined || channel.readyState !== 'open' ||
+ current !== generation || channel.bufferedAmount > 65536) return;
+ const data = JSON.stringify({ type: 'cursor', cursor: latestCursor });
+ if (data !== lastCursor) { channel.send(data); lastCursor = data; }
+ }, 50);
+ }
+ let pending = 0;
+ let challenge = '';
+ heartbeat = setInterval(() => {
+ if (channel.readyState !== 'open' || current !== generation) return;
+ challenge = crypto.randomUUID();
+ channel.send(JSON.stringify({ type: 'viewPing', challenge }));
+ }, 2000);
+ channel.onmessage = ({ data }) => {
+ if (current !== generation) return;
+ if (typeof data === 'string' && challenge && data === challenge) {
+ challenge = '';
+ void api.viewHeartbeat(lease).catch(() => {});
+ return;
+ }
+ if (typeof data !== 'string' || data.length > 32_768 || pending >= 8) {
+ stop();
+ void api.stop().catch(() => {});
+ return;
+ }
+ try {
+ const message = JSON.parse(data) as { sequence: number; events: DesktopInput[] };
+ if (
+ !Number.isSafeInteger(message.sequence) ||
+ !Array.isArray(message.events) ||
+ message.events.length > 64 ||
+ !message.events.every(isDesktopInput)
+ ) {
+ stop();
+ void api.stop().catch(() => {});
+ return;
+ }
+ pending++;
+ void api
+ .input(lease, message.sequence, message.events)
+ .catch(() => channel.close())
+ .finally(() => {
+ pending--;
+ });
+ } catch {
+ stop();
+ void api.stop().catch(() => {});
+ }
+ };
+ };
+ stream.getTracks().forEach((track) => rtc.addTrack(track, captured));
+ await rtc.setRemoteDescription({ type: 'offer', sdp: command.sdp });
+ await rtc.setLocalDescription(await rtc.createAnswer());
+ for (const sender of rtc.getSenders()) {
+ if (sender.track?.kind !== 'video' || !command.settings) continue;
+ const parameters = sender.getParameters();
+ if (!parameters.encodings?.length) continue;
+ for (const encoding of parameters.encodings) {
+ encoding.maxFramerate = command.settings.fps;
+ if (command.settings.bitrate) encoding.maxBitrate = command.settings.bitrate;
+ }
+ await sender.setParameters(parameters);
+ }
+ await new Promise<void>((resolve) => {
+ if (rtc.iceGatheringState === 'complete') {
+ resolve();
+ return;
+ }
+ const timer = setTimeout(resolve, 3500);
+ rtc.onicegatheringstatechange = () => {
+ if (rtc.iceGatheringState === 'complete') {
+ clearTimeout(timer);
+ resolve();
+ }
+ };
+ });
+ if (current === generation)
+ await api.reply(command.id, rtc.localDescription?.sdp ?? null);
+ } catch {
+ if (current === generation) {
+ stop();
+ await api.reply(command.id, null).catch(() => {});
+ }
+ }
+ })();
+ });
+ void api.registerHost().catch(() => {});
+ let readingState = false;
+ const refresh = () => {
+ if (readingState || dismissing.current) return;
+ readingState = true;
+ const revision = stateRevision.current;
+ void api
+ .state()
+ .then((next) => {
+ if (!disposed && revision === stateRevision.current) setState(next);
+ })
+ .catch(() => {})
+ .finally(() => {
+ readingState = false;
+ });
+ };
+ refresh();
+ const timer = setInterval(refresh, 1000);
+ return () => {
+ disposed = true;
+ clearInterval(timer);
+ unsubscribe();
+ stop();
+ void api.stop().catch(() => {});
+ };
+ }, []);
+ if (!state) return null;
+ return (
+ <>
+ <ConfirmDialog
+ open={Boolean(state.permissionGuide)}
+ onOpenChange={(open) => {
+ if (!open) {
+ stateRevision.current++;
+ dismissing.current = true;
+ setState((previous) => (previous ? { ...previous, permissionGuide: false } : previous));
+ void window.electronAPI.remoteDesktop
+ .dismissPermissionGuide()
+ .catch(() => {})
+ .finally(() => {
+ dismissing.current = false;
+ });
+ }
+ }}
+ title={t('remoteDesktop.permissionsTitle')}
+ describeContent
+ content={state.permissionGuide ? <RemoteDesktopPermissions /> : null}
+ confirmText={t('remoteDesktop.closePermissionGuide')}
+ showCancel={false}
+ maxWidth={460}
+ />
+ {state.active && (
+ <div
+ role="status"
+ className="fixed bottom-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-3 rounded-full border border-[var(--border-default)] bg-[var(--settings-theme-card-bg)] px-4 py-2 text-13 text-[var(--text-primary)]"
+ >
+ <span>
+ {t(
+ state.active.controlling
+ ? 'remoteDesktop.beingControlled'
+ : 'remoteDesktop.beingViewed',
+ )}
+ </span>
+ <button
+ className="min-h-11 rounded-full px-3 font-medium hover:bg-sidebar-item-hover"
+ onClick={() => void window.electronAPI.remoteDesktop.stop()}
+ >
+ {t('remoteDesktop.disconnect')}
+ </button>
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.ts b/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.ts
new file mode 100644
index 0000000000..9c31c94941
--- /dev/null
+++ b/apps/desktop/src/renderer/features/remote-desktop/nativeCaptureStream.ts
@@ -0,0 +1,72 @@
+import type { RemoteDesktopCursor, RemoteDesktopCursorFrame } from '@cindy/device-link';
+/** Converts the bounded native fallback frames into the existing WebRTC video
+ * transport. Serial pulls/decode keep both IPC and image memory bounded.
+ */
+export async function nativeCaptureStream(
+ read: () => Promise<string | RemoteDesktopCursorFrame | null>,
+ alive: () => boolean,
+ failed: () => void,
+ cursor: (value: RemoteDesktopCursor | null) => void = () => {},
+ fps = 15,
+): Promise<{ stream: MediaStream; stop(): void; clear(): void }> {
+ const canvas = document.createElement('canvas');
+ const context = canvas.getContext('2d');
+ if (!context) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');
+ let stopped = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let epoch = 0;
+ let lastFrame = performance.now();
+ const draw = async () => {
+ const current = epoch;
+ const frame = await read();
+ const jpeg = typeof frame === 'string' ? frame : frame?.jpeg;
+ if (!jpeg || stopped || !alive() || current !== epoch) return false;
+ const bytes = Uint8Array.from(atob(jpeg), (value) => value.charCodeAt(0));
+ const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/jpeg' }));
+ try {
+ if (stopped || !alive() || current !== epoch) return false;
+ if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ }
+ context.drawImage(bitmap, 0, 0);
+ if (frame && typeof frame !== 'string') cursor(frame.cursor);
+ lastFrame = performance.now();
+ return true;
+ } finally {
+ bitmap.close();
+ }
+ };
+ if (!(await draw())) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');
+ const stream = canvas.captureStream(fps);
+ const stop = () => {
+ stopped = true;
+ if (timer) clearTimeout(timer);
+ stream.getTracks().forEach((track) => track.stop());
+ canvas.width = canvas.height = 1;
+ };
+ const pull = async () => {
+ if (stopped || !alive()) {
+ stop();
+ return;
+ }
+ try {
+ await draw();
+ if (performance.now() - lastFrame > 5000) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');
+ if (!stopped && alive()) timer = setTimeout(() => void pull(), Math.round(1000 / fps));
+ else stop();
+ } catch {
+ stop();
+ if (alive()) failed();
+ }
+ };
+ timer = setTimeout(() => void pull(), Math.round(1000 / fps));
+ return {
+ stream,
+ stop,
+ clear: () => {
+ epoch++;
+ context.clearRect(0, 0, canvas.width, canvas.height);
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts
index e488acb2e7..146b837d41 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts
@@ -98,6 +98,25 @@ describe('useAvailableAgents roster cache', () => {
await waitFor(() => expect(remounted.result.current.availableVendors.has('pi')).toBe(true));
});
+ it('does not probe an unrelated phone while a desktop roster is in use', async () => {
+ const { api, presenceListeners } = installDeviceLinkApi();
+ api.invoke.mockResolvedValue(['claude-code']);
+ const { useAvailableAgents } = await import('../useAvailableAgents');
+ const { prefetchDeviceCapabilities } = await import('../useAgentCapabilities');
+ const { result } = renderHook(() => useAvailableAgents('desktop'));
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ await act(async () => {
+ for (const listener of presenceListeners) listener({ deviceId: 'phone', online: true });
+ });
+ expect(api.invoke).toHaveBeenCalledTimes(1);
+ expect(prefetchDeviceCapabilities).not.toHaveBeenCalled();
+ await act(async () => {
+ for (const listener of presenceListeners) listener({ deviceId: 'desktop', online: true });
+ });
+ expect(prefetchDeviceCapabilities).toHaveBeenCalledWith('desktop');
+ expect(api.invoke).toHaveBeenCalledTimes(2);
+ });
+
it('refetches a remote roster after the selected device reconnects', async () => {
const first = deferred<RuntimeAgentKind[]>();
const second = deferred<RuntimeAgentKind[]>();
diff --git a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
index 84886d0653..4ca105468b 100644
--- a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
+++ b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
@@ -145,9 +145,9 @@ function remoteRosterKeys(): Set<string> {
}
function notifyRosterChanged(deviceId?: string): void {
- // Presence includes controller-only phones. Only refresh devices whose roster
- // was actually requested; reverse capability invokes to an iPhone are rejected
- // and can tear down the peer link currently serving that phone's requests.
+ // Presence includes controller-only phones. Query only devices whose agent
+ // roster has actually been used; probing phones can reject the reverse link
+ // and interrupt their incoming remote-control connection.
if (deviceId && !remoteRosterKeys().has(deviceId)) return;
const key = cacheKeyOf(deviceId);
if (!invalidateAgentsCache(key)) return;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 69ef0d612e..5d49b66e15 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1,4 +1,67 @@
{
+ "remoteDesktop": {
+ "windowsTitle": "Lock screen control",
+ "windowsready": "Enabled for this Cindy process. Restarting Cindy requires administrator authorization again.",
+ "windowsmissing": "Allow control of the lock screen and administrator prompts. Administrator authorization is required.",
+ "windowsinstallRequired": "Install Cindy for all users in Program Files to enable this feature.",
+ "windowsunavailable": "The system service is unavailable. Reinstall Cindy and try again.",
+ "windowsEnable": "Authorize",
+ "windowsDisable": "Remove service",
+ "windowsError": "Authorization was not completed. Try again on this computer.",
+ "permissionsTitle": "Remote desktop permissions",
+ "permissionsIntro": "Screen recording lets you view the desktop. Accessibility also enables control. Complete authorization on the computer; status updates automatically.",
+ "permissionsReady": "System permissions are ready. You can reconnect.",
+ "screenRecording": "Screen recording",
+ "accessibility": "Accessibility",
+ "screenRecordingHelp": "Open System Settings and enable screen recording for this Cindy app. If macOS asks you to restart, reopen Cindy before connecting.",
+ "accessibilityHelp": "Open settings and enable accessibility for the app identified by the system prompt. The actual input permission is checked automatically when you return.",
+ "permissionChecking": "Checking…",
+ "permissionGranted": "Granted",
+ "permissionUnknown": "Unconfirmed",
+ "permissionMissing": "Not granted",
+ "openPermissionSettings": "Grant permission",
+ "recheckPermissions": "Check again",
+ "permissionActionFailed": "Could not open the permission guide. Try again in Remote control settings on the computer.",
+ "permissionCheckFailed": "Could not check permissions. Make sure the computer is online and try again.",
+ "openGuideOnComputer": "Open guide on computer",
+ "permissionGuideOpened": "The permission guide is open on the computer. Continue there.",
+ "reconnectAfterPermissions": "Check and reconnect",
+ "closePermissionGuide": "Close",
+ "title": "Remote desktop",
+ "allow": "Allow remote desktop",
+ "allowHint": "Allow your signed-in devices to view and operate all apps on this computer. Also enable device control above.",
+ "permissionHint": "On the computer, allow screen recording and accessibility in system settings, then reconnect.",
+ "beingControlled": "Your desktop is being controlled",
+ "beingViewed": "Your desktop is being viewed",
+ "disconnect": "Disconnect",
+ "back": "Back",
+ "connect": "Connect",
+ "connecting": "Connecting…",
+ "disconnected": "Disconnected",
+ "compatibility": "Compatibility mode · lower frame rate",
+ "live": "Live",
+ "controlling": "Controlling",
+ "viewOnly": "View only",
+ "upgrade": "Update Cindy on the computer to use remote desktop.",
+ "disabled": "On the computer, enable remote desktop in Settings → Remote control.",
+ "busy": "Desktop input is busy. Release control on the other device or wait for the Agent action to finish.",
+ "connectionError": "Connection ended. Check that the computer is online, then reconnect.",
+ "releaseControl": "Release control",
+ "takeControl": "Take control",
+ "pointer": "Trackpad",
+ "touch": "Touch",
+ "pan": "Move view",
+ "keyboard": "Keyboard",
+ "rightClick": "Right click",
+ "fit": "Fit",
+ "display": "Display",
+ "gestureHint": "Pinch to zoom. Two fingers scroll; Move view pans. Hold, then move to drag.",
+ "textPlaceholder": "Type on the computer",
+ "sendText": "Send text",
+ "keys": "Keys",
+ "showDesktop": "Desktop",
+ "allWindows": "All windows"
+ },
"ipcError": {
"INVALID_PARAMS": "Invalid input. Please check and try again.",
"PRECONDITION_FAILED": "This action is unavailable in the current state. Please try again.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1a300664be..a6715f9d87 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1,4 +1,67 @@
{
+ "remoteDesktop": {
+ "windowsTitle": "ロック画面の操作",
+ "windowsready": "現在の Cindy で有効です。Cindy を再起動すると管理者の再承認が必要です。",
+ "windowsmissing": "ロック画面と管理者の確認画面を操作するには管理者の承認が必要です。",
+ "windowsinstallRequired": "Cindy を Program Files に全ユーザー向けにインストールしてください。",
+ "windowsunavailable": "システムサービスを利用できません。Cindy を再インストールしてください。",
+ "windowsEnable": "承認して有効化",
+ "windowsDisable": "サービスを削除",
+ "windowsError": "承認が完了していません。このコンピューターで再試行してください。",
+ "permissionsTitle": "リモートデスクトップの権限",
+ "permissionsIntro": "画面の表示には画面収録、操作にはアクセシビリティの権限も必要です。コンピューターで許可すると、状態が自動更新されます。",
+ "permissionsReady": "システム権限の準備ができました。再接続できます。",
+ "screenRecording": "画面収録",
+ "accessibility": "アクセシビリティ",
+ "screenRecordingHelp": "システム設定を開き、この Cindy の画面収録を許可してください。再起動を求められた場合は、Cindy を開き直してから接続してください。",
+ "accessibilityHelp": "設定を開き、システムの許可ダイアログに表示されたアプリのアクセシビリティを有効にしてください。戻ると実際の入力権限を自動確認します。",
+ "permissionChecking": "確認中…",
+ "permissionGranted": "許可済み",
+ "permissionUnknown": "未確認",
+ "permissionMissing": "未許可",
+ "openPermissionSettings": "権限を許可",
+ "recheckPermissions": "再確認",
+ "permissionActionFailed": "権限ガイドを開けませんでした。コンピューターのリモート操作設定で再試行してください。",
+ "permissionCheckFailed": "権限を確認できません。コンピューターがオンラインか確認して再試行してください。",
+ "openGuideOnComputer": "コンピューターでガイドを開く",
+ "permissionGuideOpened": "コンピューターに権限ガイドを表示しました。そちらで続けてください。",
+ "reconnectAfterPermissions": "確認して再接続",
+ "closePermissionGuide": "閉じる",
+ "title": "リモートデスクトップ",
+ "allow": "リモートデスクトップを許可",
+ "allowHint": "同じアカウントのデバイスから、このコンピューターの全アプリの表示と操作を許可します。上のデバイス操作も有効にしてください。",
+ "permissionHint": "コンピューターのシステム設定で画面収録とアクセシビリティを許可し、再接続してください。",
+ "beingControlled": "デスクトップが操作されています",
+ "beingViewed": "デスクトップが表示されています",
+ "disconnect": "切断",
+ "back": "戻る",
+ "connect": "接続",
+ "connecting": "接続中…",
+ "disconnected": "切断済み",
+ "compatibility": "互換モード · 低フレームレート",
+ "live": "ライブ映像",
+ "controlling": "操作中",
+ "viewOnly": "表示のみ",
+ "upgrade": "コンピューター側の Cindy を更新してください。",
+ "disabled": "コンピューターの設定 → リモート操作でリモートデスクトップを有効にしてください。",
+ "busy": "デスクトップ操作中です。他のデバイスの操作を解除するか、Agent の操作終了を待ってください。",
+ "connectionError": "接続が終了しました。コンピューターがオンラインか確認し、再接続してください。",
+ "releaseControl": "操作を解除",
+ "takeControl": "操作を開始",
+ "pointer": "トラックパッド",
+ "touch": "タッチ",
+ "pan": "画面を移動",
+ "keyboard": "キーボード",
+ "rightClick": "右クリック",
+ "fit": "全体表示",
+ "display": "ディスプレイ",
+ "gestureHint": "ピンチで拡大縮小。2本指でスクロール、画面移動モードではパン。長押しして移動するとドラッグします。",
+ "textPlaceholder": "コンピューターに文字を入力",
+ "sendText": "文字を送信",
+ "keys": "キー",
+ "showDesktop": "デスクトップ",
+ "allWindows": "すべてのウィンドウ"
+ },
"ipcError": {
"INVALID_PARAMS": "パラメータが無効です。確認して再試行してください。",
"PRECONDITION_FAILED": "現在の状態ではこの操作を実行できません。しばらくしてから再試行してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1588a647d3..49f58780bf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1,4 +1,67 @@
{
+ "remoteDesktop": {
+ "windowsTitle": "잠금 화면 제어",
+ "windowsready": "현재 Cindy 실행에 허용되었습니다. Cindy를 다시 시작하면 관리자 승인이 다시 필요합니다.",
+ "windowsmissing": "잠금 화면과 관리자 확인 창을 제어하려면 관리자 승인이 필요합니다.",
+ "windowsinstallRequired": "Cindy를 Program Files에 모든 사용자용으로 설치하세요.",
+ "windowsunavailable": "시스템 서비스를 사용할 수 없습니다. Cindy를 다시 설치하세요.",
+ "windowsEnable": "승인 후 활성화",
+ "windowsDisable": "서비스 제거",
+ "windowsError": "승인이 완료되지 않았습니다. 이 컴퓨터에서 다시 시도하세요.",
+ "permissionsTitle": "원격 데스크톱 권한",
+ "permissionsIntro": "데스크톱을 보려면 화면 기록 권한이, 조작하려면 손쉬운 사용 권한도 필요합니다. 컴퓨터에서 허용하면 상태가 자동으로 갱신됩니다.",
+ "permissionsReady": "시스템 권한이 준비되었습니다. 다시 연결할 수 있습니다.",
+ "screenRecording": "화면 기록",
+ "accessibility": "손쉬운 사용",
+ "screenRecordingHelp": "시스템 설정을 열고 현재 Cindy 앱의 화면 기록을 허용하세요. 재시작을 요청하면 Cindy를 다시 연 후 연결하세요.",
+ "accessibilityHelp": "설정을 열고 시스템 권한 안내에 표시된 앱의 손쉬운 사용을 허용하세요. 돌아오면 실제 입력 권한을 자동 확인합니다.",
+ "permissionChecking": "확인 중…",
+ "permissionGranted": "허용됨",
+ "permissionUnknown": "확인되지 않음",
+ "permissionMissing": "허용되지 않음",
+ "openPermissionSettings": "권한 허용",
+ "recheckPermissions": "다시 확인",
+ "permissionActionFailed": "권한 안내를 열지 못했습니다. 컴퓨터의 원격 제어 설정에서 다시 시도하세요.",
+ "permissionCheckFailed": "권한을 확인하지 못했습니다. 컴퓨터가 온라인인지 확인하고 다시 시도하세요.",
+ "openGuideOnComputer": "컴퓨터에서 권한 안내 열기",
+ "permissionGuideOpened": "컴퓨터에 권한 안내를 표시했습니다. 컴퓨터에서 계속하세요.",
+ "reconnectAfterPermissions": "확인 후 다시 연결",
+ "closePermissionGuide": "닫기",
+ "title": "원격 데스크톱",
+ "allow": "원격 데스크톱 허용",
+ "allowHint": "같은 계정의 기기에서 이 컴퓨터의 모든 앱을 보고 조작하도록 허용합니다. 위의 기기 제어도 켜주세요.",
+ "permissionHint": "컴퓨터 시스템 설정에서 화면 기록과 손쉬운 사용을 허용한 후 다시 연결하세요.",
+ "beingControlled": "데스크톱을 원격으로 제어 중",
+ "beingViewed": "데스크톱을 원격으로 보는 중",
+ "disconnect": "연결 끊기",
+ "back": "뒤로",
+ "connect": "연결",
+ "connecting": "연결 중…",
+ "disconnected": "연결 끊김",
+ "compatibility": "호환 모드 · 낮은 프레임 속도",
+ "live": "실시간 화면",
+ "controlling": "제어 중",
+ "viewOnly": "보기 전용",
+ "upgrade": "컴퓨터의 Cindy를 업데이트하세요.",
+ "disabled": "컴퓨터의 설정 → 원격 제어에서 원격 데스크톱을 켜주세요.",
+ "busy": "데스크톱 입력을 사용 중입니다. 다른 기기의 제어를 해제하거나 Agent 작업이 끝날 때까지 기다리세요.",
+ "connectionError": "연결이 종료되었습니다. 컴퓨터가 온라인인지 확인하고 다시 연결하세요.",
+ "releaseControl": "제어 해제",
+ "takeControl": "제어 시작",
+ "pointer": "트랙패드",
+ "touch": "터치",
+ "pan": "화면 이동",
+ "keyboard": "키보드",
+ "rightClick": "오른쪽 클릭",
+ "fit": "화면 맞춤",
+ "display": "디스플레이",
+ "gestureHint": "두 손가락으로 확대/축소 및 스크롤합니다. 화면 이동 모드에서는 이동합니다. 길게 누른 후 움직이면 드래그합니다.",
+ "textPlaceholder": "컴퓨터에 텍스트 입력",
+ "sendText": "텍스트 전송",
+ "keys": "키",
+ "showDesktop": "데스크톱",
+ "allWindows": "모든 창"
+ },
"ipcError": {
"INVALID_PARAMS": "매개변수가 잘못되었습니다. 확인 후 다시 시도하세요.",
"PRECONDITION_FAILED": "현재 상태에서는 이 작업을 수행할 수 없습니다. 잠시 후 다시 시도하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index ecdf3cfb99..67ca8e53c2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1,4 +1,67 @@
{
+ "remoteDesktop": {
+ "windowsTitle": "锁屏控制",
+ "windowsready": "已为本次运行的 Cindy 开启。重新启动 Cindy 后需要再次由管理员授权。",
+ "windowsmissing": "允许操作锁屏界面和管理员提示,需要管理员授权。",
+ "windowsinstallRequired": "请将 Cindy 安装到 Program Files 并选择为所有用户安装,再启用此功能。",
+ "windowsunavailable": "系统服务不可用,请重新安装 Cindy 后重试。",
+ "windowsEnable": "授权开启",
+ "windowsDisable": "移除服务",
+ "windowsError": "未完成授权,请在这台电脑上重试。",
+ "permissionsTitle": "远程桌面权限",
+ "permissionsIntro": "查看桌面需要屏幕录制权限;操作桌面还需要辅助功能权限。请在电脑上完成授权,结果会自动更新。",
+ "permissionsReady": "系统权限已就绪,可以重新连接。",
+ "screenRecording": "屏幕录制",
+ "accessibility": "辅助功能",
+ "screenRecordingHelp": "打开系统设置,为当前 Cindy 开启屏幕录制。若系统要求重新启动,请重新打开 Cindy 后连接。",
+ "accessibilityHelp": "点击打开设置后,为系统授权提示中的应用开启辅助功能。返回后会自动检测实际输入权限。",
+ "permissionChecking": "检测中…",
+ "permissionGranted": "已授权",
+ "permissionUnknown": "未确认",
+ "permissionMissing": "未授权",
+ "openPermissionSettings": "去授权",
+ "recheckPermissions": "重新检测",
+ "permissionActionFailed": "未能打开授权引导。请在电脑端的远程控制设置中重试。",
+ "permissionCheckFailed": "暂时无法检测权限,请确认电脑在线后重试。",
+ "openGuideOnComputer": "在电脑上打开授权引导",
+ "permissionGuideOpened": "已在电脑上显示授权引导,请在电脑上继续。",
+ "reconnectAfterPermissions": "重新检测并连接",
+ "closePermissionGuide": "关闭",
+ "title": "远程桌面",
+ "allow": "允许远程桌面",
+ "allowHint": "允许已登录的同账号设备查看和操作这台电脑的所有应用。需同时开启上方的设备控制。",
+ "permissionHint": "请在电脑的系统设置中允许屏幕录制和辅助功能,然后重新连接。",
+ "beingControlled": "手机正在控制桌面",
+ "beingViewed": "手机正在查看桌面",
+ "disconnect": "断开连接",
+ "back": "返回",
+ "connect": "连接",
+ "connecting": "连接中…",
+ "disconnected": "已断开",
+ "compatibility": "兼容模式 · 帧率较低",
+ "live": "实时画面",
+ "controlling": "正在控制",
+ "viewOnly": "仅查看",
+ "upgrade": "请升级电脑端 Cindy 后使用远程桌面。",
+ "disabled": "请在电脑端的设置 → 远程控制中开启远程桌面。",
+ "busy": "桌面输入正在使用中。请让其他设备释放控制,或等待 Agent 操作结束。",
+ "connectionError": "连接已结束。请检查电脑是否在线,然后重新连接。",
+ "releaseControl": "释放控制",
+ "takeControl": "接管操作",
+ "pointer": "触控板",
+ "touch": "触屏",
+ "pan": "移动画面",
+ "keyboard": "键盘",
+ "rightClick": "右键",
+ "fit": "适应屏幕",
+ "display": "显示器",
+ "gestureHint": "双指缩放;双指移动可滚动,移动画面模式下可平移。长按后移动可拖拽。",
+ "textPlaceholder": "在电脑上输入文字",
+ "sendText": "发送文字",
+ "keys": "按键",
+ "showDesktop": "桌面",
+ "allWindows": "所有窗口"
+ },
"ipcError": {
"INVALID_PARAMS": "参数无效,请检查后重试。",
"PRECONDITION_FAILED": "当前状态下无法执行此操作,请稍后重试。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 17e0a594ec..f55a85fa4a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1,4 +1,67 @@
{
+ "remoteDesktop": {
+ "windowsTitle": "鎖定畫面控制",
+ "windowsready": "已為本次執行的 Cindy 啟用。重新啟動 Cindy 後需要再次由管理員授權。",
+ "windowsmissing": "允許操作鎖定畫面和管理員提示,需要管理員授權。",
+ "windowsinstallRequired": "請將 Cindy 安裝到 Program Files 並選擇為所有使用者安裝,再啟用此功能。",
+ "windowsunavailable": "系統服務無法使用,請重新安裝 Cindy 後重試。",
+ "windowsEnable": "授權啟用",
+ "windowsDisable": "移除服務",
+ "windowsError": "尚未完成授權,請在這台電腦上重試。",
+ "permissionsTitle": "遠端桌面權限",
+ "permissionsIntro": "檢視桌面需要螢幕錄製權限;操作桌面還需要輔助使用權限。請在電腦上完成授權,結果會自動更新。",
+ "permissionsReady": "系統權限已就緒,可以重新連線。",
+ "screenRecording": "螢幕錄製",
+ "accessibility": "輔助使用",
+ "screenRecordingHelp": "開啟系統設定,為目前的 Cindy 啟用螢幕錄製。若系統要求重新啟動,請重新開啟 Cindy 後連線。",
+ "accessibilityHelp": "點擊開啟設定後,為系統授權提示中的應用程式啟用輔助使用。返回後會自動檢測實際輸入權限。",
+ "permissionChecking": "檢測中…",
+ "permissionGranted": "已授權",
+ "permissionUnknown": "未確認",
+ "permissionMissing": "未授權",
+ "openPermissionSettings": "去授權",
+ "recheckPermissions": "重新檢測",
+ "permissionActionFailed": "無法開啟授權引導。請在電腦端的遠端控制設定中重試。",
+ "permissionCheckFailed": "暫時無法檢測權限,請確認電腦在線後重試。",
+ "openGuideOnComputer": "在電腦上開啟授權引導",
+ "permissionGuideOpened": "已在電腦上顯示授權引導,請在電腦上繼續。",
+ "reconnectAfterPermissions": "重新檢測並連線",
+ "closePermissionGuide": "關閉",
+ "title": "遠端桌面",
+ "allow": "允許遠端桌面",
+ "allowHint": "允許已登入的同帳號裝置檢視和操作這台電腦的所有應用程式。需同時開啟上方的裝置控制。",
+ "permissionHint": "請在電腦的系統設定中允許螢幕錄製和輔助使用,然後重新連線。",
+ "beingControlled": "手機正在控制桌面",
+ "beingViewed": "手機正在檢視桌面",
+ "disconnect": "中斷連線",
+ "back": "返回",
+ "connect": "連線",
+ "connecting": "連線中…",
+ "disconnected": "已中斷",
+ "compatibility": "相容模式 · 畫格率較低",
+ "live": "即時畫面",
+ "controlling": "正在控制",
+ "viewOnly": "僅檢視",
+ "upgrade": "請升級電腦端 Cindy 後使用遠端桌面。",
+ "disabled": "請在電腦端的設定 → 遠端控制中開啟遠端桌面。",
+ "busy": "桌面輸入正在使用中。請讓其他裝置釋放控制,或等待 Agent 操作結束。",
+ "connectionError": "連線已結束。請檢查電腦是否在線,然後重新連線。",
+ "releaseControl": "釋放控制",
+ "takeControl": "接管操作",
+ "pointer": "觸控板",
+ "touch": "觸控",
+ "pan": "移動畫面",
+ "keyboard": "鍵盤",
+ "rightClick": "右鍵",
+ "fit": "符合螢幕",
+ "display": "顯示器",
+ "gestureHint": "雙指縮放;雙指移動可捲動,移動畫面模式下可平移。長按後移動可拖曳。",
+ "textPlaceholder": "在電腦上輸入文字",
+ "sendText": "傳送文字",
+ "keys": "按鍵",
+ "showDesktop": "桌面",
+ "allWindows": "所有視窗"
+ },
"ipcError": {
"INVALID_PARAMS": "引數無效,請檢查後重試。",
"PRECONDITION_FAILED": "目前狀態下無法執行此操作,請稍後再試。",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 3b7c53c8dd..e50eb218b9 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3753,6 +3753,7 @@ interface ElectronAPI {
fetchReleaseNotesIndex: () => Promise<string[] | null>;
// ── Device Link (设备互联/跨设备远程控制) ─────────────────────────────
+ remoteDesktop: import('../shared/remoteDesktop').RemoteDesktopApi;
deviceLink: {
getState: () => Promise<{
remoteControlEnabled: boolean;
diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.ts
new file mode 100644
index 0000000000..bd7d1b0867
--- /dev/null
+++ b/apps/desktop/src/shared/remoteDesktop.ts
@@ -0,0 +1,54 @@
+import type {
+ DesktopInput,
+ RemoteDesktopCursorFrame,
+ DesktopPermission,
+ RemoteDesktopVideoSettings,
+ RemoteDesktopPermissions,
+} from '@cindy/device-link';
+export const DESKTOP_LOCAL = {
+ STATE: 'remote-desktop:state',
+ ENABLE: 'remote-desktop:enable',
+ STOP: 'remote-desktop:stop',
+ REGISTER: 'remote-desktop:register-host',
+ COMMAND: 'remote-desktop:host-command',
+ REPLY: 'remote-desktop:host-reply',
+ INPUT: 'remote-desktop:host-input',
+ VIEW_HEARTBEAT: 'remote-desktop:view-heartbeat',
+ NATIVE_FRAME: 'remote-desktop:native-frame',
+ WINDOWS_SUPPORT: 'remote-desktop:windows-support',
+ PERMISSIONS: 'remote-desktop:permissions',
+ OPEN_PERMISSION: 'remote-desktop:open-permission',
+ DISMISS_GUIDE: 'remote-desktop:dismiss-permission-guide',
+} as const;
+export interface DesktopHostCommand {
+ id: string;
+ op: 'offer' | 'stop' | 'capture-reset';
+ nativeCapture?: boolean;
+ cursorOverlay?: boolean;
+ lease?: string;
+ sourceId?: string;
+ sdp?: string;
+ settings?: RemoteDesktopVideoSettings;
+}
+export interface DesktopLocalState {
+ enabled: boolean;
+ active: { peer: string; controlling: boolean } | null;
+ permissionGuide?: boolean;
+ windowsSupport?: WindowsDesktopSupport;
+}
+export type WindowsDesktopSupport = 'ready' | 'missing' | 'installRequired' | 'unavailable';
+export interface RemoteDesktopApi {
+ state(): Promise<DesktopLocalState>;
+ enable(enabled: boolean): Promise<void>;
+ windowsSupport(enabled: boolean): Promise<void>;
+ stop(): Promise<void>;
+ permissions(): Promise<RemoteDesktopPermissions>;
+ openPermission(permission: DesktopPermission): Promise<void>;
+ dismissPermissionGuide(): Promise<void>;
+ registerHost(): Promise<void>;
+ onCommand(listener: (command: DesktopHostCommand) => void): () => void;
+ reply(id: string, sdp: string | null): Promise<void>;
+ viewHeartbeat(lease: string): Promise<void>;
+ nativeFrame(lease: string): Promise<string | RemoteDesktopCursorFrame | null>;
+ input(lease: string, sequence: number, events: DesktopInput[]): Promise<void>;
+}
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index 203308d5b1..f3be0c3996 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -119,6 +119,7 @@
}
}
],
+ "./plugins/with-remote-desktop-presentation",
"./plugins/with-foreground-only-audio",
[
"expo-audio",
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 892d3bfafc..7cf9221fa7 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -891,6 +891,11 @@ function DeviceDetailScreenContent() {
}}
testID="deviceDetail.summary"
>
+ <MainWindowActionButton action={{
+ label: t('remoteDesktop.title'),
+ onPress: () => guardedPush({ pathname: '/devices/desktop/[deviceId]', params: { deviceId, deviceName } }),
+ testID: 'deviceDetail.remoteDesktop',
+ }} />
<View style={[styles.summaryTopRow, { gap: windowLayout.metricGap }]}>
<MainWindowMetric
accessibilityLabel={t('devices.detail.metric.activeA11y')}
diff --git a/apps/mobile/app/devices/desktop/[deviceId].tsx b/apps/mobile/app/devices/desktop/[deviceId].tsx
new file mode 100644
index 0000000000..4a9cee553b
--- /dev/null
+++ b/apps/mobile/app/devices/desktop/[deviceId].tsx
@@ -0,0 +1 @@
+export { default } from "@/remote-desktop/RemoteDesktopScreen";
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index aaec681d4e..4606b5ba56 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -33,6 +33,7 @@ import {
FolderOpen,
LoaderCircle,
Menu,
+ Monitor,
MessagesSquare,
Lock,
Pencil,
@@ -2414,6 +2415,14 @@ function HomeScreenContent() {
}),
[displayedProjectOrder, groupByProject, groupDialogue, sortBy, statusFilter, t],
);
+ const openSelectedRemoteDesktop = useCallback(() => {
+ if (!selectedDeviceId) return;
+ const device = home.deviceFilters.find((item) => item.deviceId === selectedDeviceId);
+ guardedPush({
+ pathname: '/devices/desktop/[deviceId]',
+ params: { deviceId: selectedDeviceId, deviceName: device?.label ?? selectedDeviceLabel },
+ });
+ }, [guardedPush, home.deviceFilters, selectedDeviceId, selectedDeviceLabel]);
const nativeHomeHeader = usesNativeStackHeader();
const chromeHeight = nativeHomeHeader
@@ -2439,6 +2448,8 @@ function HomeScreenContent() {
onOpenDeviceMenu={openDeviceMenu}
onOpenDisplaySettings={openDisplaySettings}
onOpenMenu={openChromeMenu}
+ onOpenRemoteDesktop={selectedDeviceId ? openSelectedRemoteDesktop : undefined}
+ remoteDesktopA11y={t('remoteDesktop.title')}
onSelectScope={handleHomeScopeAction}
scopeActions={homeScopePullDownActions}
showRemoteGuide={showRemoteGuide}
@@ -2489,23 +2500,21 @@ function HomeScreenContent() {
{showRemoteGuide ? (
<View style={styles.headerIconButton} />
) : (
- <NativePullDownMenu
- actions={homeDisplayPullDownActions}
- onAction={(id) => {
- applyDisplayView(homeDisplayMenuPatch(id as HomeDisplayMenuKey, {
- groupByProject,
- groupDialogue,
- }));
- }}
- >
- <HomeHeaderGlassButton
- accessibilityLabel={t('devices.list.a11y.openDisplaySettings')}
- onPress={nativeHomeMenus ? () => undefined : openDisplaySettings}
- testID="home.displaySettingsButton"
+ <View style={styles.headerActions}>
+ {selectedDeviceId ? (
+ <HomeHeaderGlassButton accessibilityLabel={t('remoteDesktop.title')} onPress={openSelectedRemoteDesktop} testID="home.remoteDesktopButton">
+ <Monitor color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ ) : null}
+ <NativePullDownMenu
+ actions={homeDisplayPullDownActions}
+ onAction={(id) => applyDisplayView(homeDisplayMenuPatch(id as HomeDisplayMenuKey, { groupByProject, groupDialogue }))}
>
- <Ellipsis color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
- </HomeHeaderGlassButton>
- </NativePullDownMenu>
+ <HomeHeaderGlassButton accessibilityLabel={t('devices.list.a11y.openDisplaySettings')} onPress={nativeHomeMenus ? () => undefined : openDisplaySettings} testID="home.displaySettingsButton">
+ <Ellipsis color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ </NativePullDownMenu>
+ </View>
)}
</View>
)}
@@ -4382,6 +4391,11 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
justifyContent: 'center',
width: 44,
},
+ headerActions: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.xs,
+ },
headerTitleWrap: {
alignItems: 'center',
flex: 1,
diff --git a/apps/mobile/app/devices/manage/[deviceId].tsx b/apps/mobile/app/devices/manage/[deviceId].tsx
index fe06b698d9..8d3b80c1f6 100644
--- a/apps/mobile/app/devices/manage/[deviceId].tsx
+++ b/apps/mobile/app/devices/manage/[deviceId].tsx
@@ -1,7 +1,9 @@
import { Host, List, ListItem, Text as NativeText } from '@expo/ui';
+import { List as SwiftUIList } from '@expo/ui/swift-ui';
+import { scrollContentBackground } from '@expo/ui/swift-ui/modifiers';
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback } from 'react';
-import { ActivityIndicator, Button, View } from 'react-native';
+import { ActivityIndicator, Button, Platform, Pressable, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@/auth/AuthContext';
@@ -17,9 +19,12 @@ import {
} from '@/platform/chrome';
import { goBackGuarded } from '@/utils/backGuard';
import { useGuardedPush } from '@/utils/useGuardedPush';
-import { useTheme } from '@/theme';
+import { useTheme, iconSize, iconStroke } from '@/theme';
+import { Monitor } from 'lucide-react-native';
import { spacing } from '@/theme/tokens';
+const DeviceInformationList = Platform.OS === 'ios' ? SwiftUIList : List;
+
export default function DeviceInformationScreen() {
const { accountGeneration } = useAuth();
const { deviceId } = useLocalSearchParams<{ deviceId: string }>();
@@ -83,6 +88,17 @@ function DeviceInformationContent({ deviceId }: { deviceId: string }) {
testID="deviceInformation.screen"
>
<SimpleStackHeader
+ right={device && presentation?.canOpen ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t('remoteDesktop.title')}
+ onPress={() => push({ pathname: '/devices/desktop/[deviceId]', params: { deviceId, deviceName: device.name } })}
+ testID="deviceInformation.remoteDesktop"
+ style={({ pressed }) => ({ width: 44, height: 44, alignItems: 'center', justifyContent: 'center', opacity: pressed ? 0.72 : 1 })}
+ >
+ <Monitor color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ ) : undefined}
title={device?.name ?? t('devices.management.details')}
backTestID="deviceInformation.back"
onBack={back}
@@ -107,8 +123,12 @@ function DeviceInformationContent({ deviceId }: { deviceId: string }) {
</Text>
) : null}
{device ? (
- <Host style={{ flex: 1 }} colorScheme={mode}>
- <List>
+ <Host style={{ flex: 1, backgroundColor: colors.surface }} colorScheme={mode}>
+ <DeviceInformationList
+ {...(Platform.OS === 'ios'
+ ? { modifiers: [scrollContentBackground('hidden')] }
+ : {})}
+ >
<DeviceInformationFields fields={fields} />
<ListItem
onPress={() => {
@@ -141,7 +161,15 @@ function DeviceInformationContent({ deviceId }: { deviceId: string }) {
{t('devices.list.menu.showDeviceTasks')}
</ListItem>
) : null}
- </List>
+ {presentation?.canOpen ? (
+ <ListItem
+ onPress={() => push({ pathname: '/devices/desktop/[deviceId]', params: { deviceId, deviceName: device.name } })}
+ testID="deviceInformation.remoteDesktopRow"
+ >
+ {t('remoteDesktop.title')}
+ </ListItem>
+ ) : null}
+ </DeviceInformationList>
</Host>
) : null}
<DeviceManagementDialogs manager={manager} onDeleted={back} />
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 83dd046d48..2830264662 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -15,6 +15,7 @@ import {
List,
ListTodo,
Menu,
+ Monitor,
Mic,
Pencil,
Pin,
@@ -8730,6 +8731,13 @@ export default function SessionScreen() {
}}
onOpenSettings={() => openSessionMenu('menu')}
onOpenUsage={() => openSessionMenu('info')}
+ onOpenRemoteDesktop={() => {
+ if (!deviceId) return;
+ router.push({
+ pathname: '/devices/desktop/[deviceId]',
+ params: { deviceId, deviceName },
+ });
+ }}
onToggleSearch={() => {
if (searchOpen) closeSearch();
else setSearchOpen(true);
@@ -9497,6 +9505,7 @@ function SessionHeaderBar({
onOpenSessionList,
onOpenSettings,
onOpenUsage,
+ onOpenRemoteDesktop,
onToggleSearch,
pendingCount,
queueCount,
@@ -9526,6 +9535,7 @@ function SessionHeaderBar({
onOpenFiles(): void;
onOpenSettings(): void;
onOpenUsage(): void;
+ onOpenRemoteDesktop(): void;
onToggleSearch(): void;
pendingCount: number;
queueCount: number;
@@ -9631,6 +9641,14 @@ function SessionHeaderBar({
</View>
<View style={styles.sessionHeaderActions}>
+ <SessionHeaderIconButton
+ accessibilityLabel={t('remoteDesktop.title')}
+ active={false}
+ disabled={!currentSession}
+ icon={Monitor}
+ onPress={currentSession ? onOpenRemoteDesktop : undefined}
+ testID="session.remoteDesktop"
+ />
{headerActions.map((action) => (
<SessionHeaderIconButton
accessibilityHint={action.disabledReason ?? undefined}
diff --git a/apps/mobile/modules/cindy-remote-presentation/expo-module.config.json b/apps/mobile/modules/cindy-remote-presentation/expo-module.config.json
new file mode 100644
index 0000000000..98dfc33574
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/expo-module.config.json
@@ -0,0 +1,11 @@
+{
+ "platforms": [
+ "apple"
+ ],
+ "apple": {
+ "podspecPath": "./ios/CindyRemotePresentation.podspec",
+ "modules": [
+ "CindyRemotePresentationModule"
+ ]
+ }
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec
new file mode 100644
index 0000000000..df30a2dbc6
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec
@@ -0,0 +1,28 @@
+require 'json'
+
+package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
+
+Pod::Spec.new do |s|
+ s.name = 'CindyRemotePresentation'
+ s.version = package['version']
+ s.summary = 'Remote desktop presentation for Cindy mobile.'
+ s.description = 'Rotation and playback audio session for remote desktop picture in picture.'
+ s.license = { :type => 'Apache-2.0', :file => '../../../../../LICENSE' }
+ s.author = 'Cindy'
+ s.homepage = 'https://github.com/makecindy/cindy'
+ s.platforms = {
+ :ios => '16.4'
+ }
+ s.swift_version = '5.9'
+ s.source = { git: 'https://github.com/makecindy/cindy.git' }
+ s.static_framework = true
+
+ s.dependency 'ExpoModulesCore'
+
+ s.pod_target_xcconfig = {
+ 'DEFINES_MODULE' => 'YES',
+ 'SWIFT_COMPILATION_MODE' => 'wholemodule'
+ }
+
+ s.source_files = '**/*.{h,m,swift}'
+end
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift
new file mode 100644
index 0000000000..9e78befb9a
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift
@@ -0,0 +1,144 @@
+import ExpoModulesCore
+import UIKit
+import AVFoundation
+import UniformTypeIdentifiers
+
+public class CindyRemotePresentationModule: Module {
+ private var previousAudio: (AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)?
+ public func definition() -> ModuleDefinition {
+ Name("CindyRemotePresentation")
+ AsyncFunction("readClipboard") { () -> String in
+ try RemoteClipboard.read()
+ }.runOnQueue(.main)
+ AsyncFunction("writeClipboard") { (json: String) in
+ try RemoteClipboard.write(json)
+ }.runOnQueue(.main)
+ AsyncFunction("rotate") { (landscape: Bool, promise: Promise) in
+ guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene })
+ .first(where: { $0.activationState == .foregroundActive }) else {
+ promise.reject("NO_SCENE", "No active screen"); return
+ }
+ scene.windows.first(where: { $0.isKeyWindow })?.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
+ var settled = false
+ scene.requestGeometryUpdate(.iOS(interfaceOrientations: landscape ? .landscapeRight : .portrait)) { error in
+ if !settled { settled = true; promise.reject("ROTATION_FAILED", error.localizedDescription) }
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
+ if !settled {
+ settled = true
+ if scene.interfaceOrientation.isLandscape == landscape { promise.resolve(nil) }
+ else { promise.reject("ROTATION_FAILED", "Screen orientation did not change") }
+ }
+ }
+ }.runOnQueue(.main)
+ AsyncFunction("playback") { (enabled: Bool) in
+ let session = AVAudioSession.sharedInstance()
+ if enabled {
+ if self.previousAudio == nil { self.previousAudio = (session.category, session.mode, session.categoryOptions) }
+ try session.setCategory(.playback, mode: .moviePlayback, options: [.mixWithOthers])
+ try session.setActive(true)
+ } else if let previous = self.previousAudio {
+ self.previousAudio = nil
+ // Do not overwrite a newer voice/audio owner's category.
+ if session.category == .playback && session.mode == .moviePlayback {
+ try session.setCategory(previous.0, mode: previous.1, options: previous.2)
+ }
+ }
+ }.runOnQueue(.main)
+ }
+}
+
+/** One atomic portable item; never dereference clipboard file URLs. */
+enum RemoteClipboard {
+ static let limit = 32 * 1024 * 1024
+ static func failure(_ code: String) -> NSError {
+ NSError(domain: "CindyClipboard", code: 1, userInfo: [NSLocalizedDescriptionKey: code])
+ }
+ static func foreground() throws {
+ guard UIApplication.shared.applicationState == .active else { throw failure("DESKTOP_LEASE_EXPIRED") }
+ }
+ static func read() throws -> String {
+ try foreground()
+ let board = UIPasteboard.general
+ let version = board.changeCount
+ let items = board.items
+ guard !items.isEmpty else { throw failure("CLIPBOARD_EMPTY") }
+ guard items.count == 1 else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ let item = items[0]
+ // UIKit resolves the source app's alternative image representations. Do not
+ // guess an encoding by sorting UTIs, or reject a real image merely because
+ // the same item includes its source URL. Never dereference those URLs here.
+ let image = board.image
+ if image == nil && item.keys.contains(where: { UTType($0)?.conforms(to: .fileURL) == true }) {
+ throw failure("CLIPBOARD_UNSUPPORTED")
+ }
+ var result: [String: String] = [:]
+ func string(_ type: String) throws -> String? {
+ if let string = item[type] as? String { return string.isEmpty ? nil : string }
+ if let data = item[type] as? Data {
+ guard data.count <= limit else { throw failure("CLIPBOARD_TOO_LONG") }
+ guard let string = String(data: data, encoding: .utf8) else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ return string.isEmpty ? nil : string
+ }
+ return nil
+ }
+ for type in ["public.utf8-plain-text", "public.text", "public.plain-text"] {
+ if let text = try string(type) { result["text"] = text; break }
+ }
+ result["html"] = try string("public.html")
+ result["rtf"] = try string("public.rtf")
+ if let raw = item["public.url"] {
+ let url = (raw as? URL) ?? (raw as? String).flatMap(URL.init(string:))
+ if let url = url, ["http", "https"].contains(url.scheme?.lowercased() ?? "") {
+ result["url"] = url.absoluteString
+ } else if image == nil {
+ throw failure("CLIPBOARD_UNSUPPORTED")
+ }
+ }
+ if let image = image {
+ guard (image.images?.count ?? 1) <= 1 else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ guard image.size.width * image.scale * image.size.height * image.scale <= 64_000_000 else {
+ throw failure("CLIPBOARD_TOO_LONG")
+ }
+ guard let png = image.pngData() else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ guard png.count <= limit * 3 / 4 else { throw failure("CLIPBOARD_TOO_LONG") }
+ result["png"] = png.base64EncodedString()
+ }
+ guard !result.isEmpty else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ try foreground()
+ guard version == board.changeCount else { throw failure("CLIPBOARD_CHANGED") }
+ let data = try JSONSerialization.data(withJSONObject: result)
+ guard data.count <= limit else { throw failure("CLIPBOARD_TOO_LONG") }
+ return String(data: data, encoding: .utf8)!
+ }
+
+ static func write(_ json: String) throws {
+ try foreground()
+ guard json.utf8.count <= limit, let data = json.data(using: .utf8),
+ let content = try JSONSerialization.jsonObject(with: data) as? [String: String],
+ !content.isEmpty,
+ content.keys.allSatisfy({ ["text", "html", "rtf", "url", "png"].contains($0) })
+ else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ var item: [String: Any] = [:]
+ if let text = content["text"] { item["public.utf8-plain-text"] = text }
+ if let html = content["html"] { item["public.html"] = Data(html.utf8) }
+ if let rtf = content["rtf"] { item["public.rtf"] = Data(rtf.utf8) }
+ if let string = content["url"] {
+ guard let url = URL(string: string), ["http", "https"].contains(url.scheme?.lowercased() ?? "") else {
+ throw failure("CLIPBOARD_UNSUPPORTED")
+ }
+ item["public.url"] = url
+ }
+ if let encoded = content["png"] {
+ guard let png = Data(base64Encoded: encoded), png.count >= 24,
+ Array(png.prefix(8)) == [137, 80, 78, 71, 13, 10, 26, 10] else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ let width = png[16..<20].reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }
+ let height = png[20..<24].reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }
+ guard width > 0, height > 0, width * height <= 64_000_000,
+ UIImage(data: png) != nil else { throw failure("CLIPBOARD_UNSUPPORTED") }
+ item["public.png"] = png
+ }
+ try foreground()
+ UIPasteboard.general.setItems([item], options: [:])
+ }
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/package.json b/apps/mobile/modules/cindy-remote-presentation/package.json
new file mode 100644
index 0000000000..3b640b4f90
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "cindy-remote-presentation",
+ "version": "0.1.0",
+ "main": "src/index.ts",
+ "private": true,
+ "license": "Apache-2.0"
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/src/index.ts b/apps/mobile/modules/cindy-remote-presentation/src/index.ts
new file mode 100644
index 0000000000..7266a36342
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/src/index.ts
@@ -0,0 +1,7 @@
+import { requireOptionalNativeModule } from "expo-modules-core";
+export const remotePresentation = requireOptionalNativeModule<{
+ readClipboard?(): Promise<string>;
+ writeClipboard?(json: string): Promise<void>;
+ rotate(landscape: boolean): Promise<void>;
+ playback(enabled: boolean): Promise<void>;
+}>("CindyRemotePresentation");
diff --git a/apps/mobile/plugins/with-remote-desktop-presentation.js b/apps/mobile/plugins/with-remote-desktop-presentation.js
new file mode 100644
index 0000000000..918fe36ce0
--- /dev/null
+++ b/apps/mobile/plugins/with-remote-desktop-presentation.js
@@ -0,0 +1,7 @@
+const { withInfoPlist } = require('@expo/config-plugins');
+// Runs after foreground-only cleanup. This entitlement enables AVKit PiP;
+// voice recording and ordinary audio retain their foreground-only runtime policy.
+module.exports = config => withInfoPlist(config, result => {
+ result.modResults.UIBackgroundModes = [...new Set([...(result.modResults.UIBackgroundModes || []), 'audio'])];
+ return result;
+});
diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjs
index 200e19a87e..edd9f66581 100644
--- a/apps/mobile/scripts/lib/sim-whoami.mjs
+++ b/apps/mobile/scripts/lib/sim-whoami.mjs
@@ -1,10 +1,15 @@
-import { execFileSync } from 'node:child_process';
-import { dirname, normalize, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';
-import { withLocalMobileRegionConfig } from './mobile-dev-region.mjs';
+import { execFileSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import {
+ resolvePnpmInvocation,
+ usablePnpmExecPath,
+} from "../../../../scripts/shared/pnpm-invocation.mjs";
+import { dirname, normalize, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { mobileClientBundleEnv } from "../../../../scripts/shared/client-endpoint-build-env.mjs";
+import { withLocalMobileRegionConfig } from "./mobile-dev-region.mjs";
-const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
+const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
const SIMULATOR_UDID_PATTERN = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;
/** Parse one optional exact Simulator target without changing sim:start arguments. */
@@ -15,19 +20,21 @@ export function extractSimWhoamiUdidArgs(args) {
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
let value = null;
- if (arg === '--udid') {
+ if (arg === "--udid") {
value = args[++index];
- } else if (arg.startsWith('--udid=')) {
- value = arg.slice('--udid='.length);
+ } else if (arg.startsWith("--udid=")) {
+ value = arg.slice("--udid=".length);
} else {
passthrough.push(arg);
continue;
}
- if (simulatorUdid !== null) throw new Error('Simulator UDID 只能传一次');
- const normalized = String(value ?? '').trim().toUpperCase();
+ if (simulatorUdid !== null) throw new Error("Simulator UDID 只能传一次");
+ const normalized = String(value ?? "")
+ .trim()
+ .toUpperCase();
if (!SIMULATOR_UDID_PATTERN.test(normalized)) {
- throw new Error(`Simulator UDID 无效: ${value ?? '(缺失)'}`);
+ throw new Error(`Simulator UDID 无效: ${value ?? "(缺失)"}`);
}
simulatorUdid = normalized;
}
@@ -45,12 +52,12 @@ export function bootedSimulatorLinesForTarget(lines, simulatorUdid) {
/** Probe app installation on the exact Host-owned Simulator without fallback. */
export function getSimulatorAppContainer(run, simulatorUdid, bundleId) {
- return run('xcrun', [
- 'simctl',
- 'get_app_container',
- simulatorUdid ?? 'booted',
+ return run("xcrun", [
+ "simctl",
+ "get_app_container",
+ simulatorUdid ?? "booted",
bundleId,
- 'app',
+ "app",
]);
}
@@ -63,20 +70,20 @@ export function extractSimMetroPortArgs(args, defaultPort = 8081) {
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
let value = null;
- if (arg === '--port' || arg === '-p') {
+ if (arg === "--port" || arg === "-p") {
value = args[++index];
- } else if (arg.startsWith('--port=')) {
- value = arg.slice('--port='.length);
+ } else if (arg.startsWith("--port=")) {
+ value = arg.slice("--port=".length);
} else {
passthrough.push(arg);
continue;
}
- if (seen) throw new Error('Metro 端口只能传一次');
+ if (seen) throw new Error("Metro 端口只能传一次");
seen = true;
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
- throw new Error(`Metro 端口无效: ${value ?? '(缺失)'}`);
+ throw new Error(`Metro 端口无效: ${value ?? "(缺失)"}`);
}
port = parsed;
}
@@ -90,8 +97,8 @@ export function extractSimTakeoverArgs(args) {
const passthrough = [];
for (const arg of args) {
- if (arg === '--takeover') {
- if (takeover) throw new Error('--takeover 只能传一次');
+ if (arg === "--takeover") {
+ if (takeover) throw new Error("--takeover 只能传一次");
takeover = true;
} else {
passthrough.push(arg);
@@ -105,9 +112,13 @@ export function extractSimTakeoverArgs(args) {
export function classifySimMetroListener({ cwd, source, targetWorktree }) {
if (!cwd) return { confirmed: false, worktree: null };
- const normalizedCwd = normalize(cwd).replaceAll('\\', '/').replace(/\/+$/, '');
- const normalizedTarget = normalize(targetWorktree).replaceAll('\\', '/').replace(/\/+$/, '');
- const suffix = '/apps/mobile';
+ const normalizedCwd = normalize(cwd)
+ .replaceAll("\\", "/")
+ .replace(/\/+$/, "");
+ const normalizedTarget = normalize(targetWorktree)
+ .replaceAll("\\", "/")
+ .replace(/\/+$/, "");
+ const suffix = "/apps/mobile";
if (!normalizedCwd.endsWith(suffix) || !source) {
return { confirmed: false, worktree: null };
}
@@ -139,16 +150,16 @@ export function resolveSimMetroHandoff({
listener,
listenerWorktreeExists = false,
} = {}) {
- const occupant = cwd || '(未知进程)';
+ const occupant = cwd || "(未知进程)";
if (!listener?.confirmed) {
return {
- action: 'refuse',
- code: 'occupied-unknown',
+ action: "refuse",
+ code: "occupied-unknown",
lines: [
`✗ 端口 ${port} 被其他进程占用:${occupant}`,
- ' 不是可确认的 Cindy Metro(需要 .../apps/mobile 工作目录 + 注入的源码指纹)。',
- ' 未知进程即使传 `--takeover` 也不会停。',
+ " 不是可确认的 Cindy Metro(需要 .../apps/mobile 工作目录 + 注入的源码指纹)。",
+ " 未知进程即使传 `--takeover` 也不会停。",
],
};
}
@@ -157,20 +168,20 @@ export function resolveSimMetroHandoff({
if (runningSource === currentSource) {
if (envChanged && !takeover) {
return {
- action: 'refuse',
- code: 'target-env-stale',
+ action: "refuse",
+ code: "target-env-stale",
lines: [
`✗ 已补/改 apps/mobile/.env,但 ${port} 上的 Metro 是用旧 env 启动的(env 在 bundle 时注入)。`,
- ' 需要刷新 env 时传 `--takeover` 重起,新 env 才会生效。',
+ " 需要刷新 env 时传 `--takeover` 重起,新 env 才会生效。",
],
};
}
if (envChanged && takeover) {
- return { action: 'restart', code: 'target-env', lines: [] };
+ return { action: "restart", code: "target-env", lines: [] };
}
return {
- action: 'reuse',
- code: 'target-fresh',
+ action: "reuse",
+ code: "target-fresh",
lines: [
`✓ Metro 已在 ${port} 运行(本 worktree,源码指纹 ${currentSource})。改 JS 直接 Fast Refresh,无需重开。`,
],
@@ -178,42 +189,42 @@ export function resolveSimMetroHandoff({
}
if (!takeover) {
return {
- action: 'refuse',
- code: 'target-stale',
+ action: "refuse",
+ code: "target-stale",
lines: [
- `✗ ${port} 上是本 worktree 的 Metro,但源码指纹已过期(运行中=${runningSource || '(无)'} ≠ 当前=${currentSource})。`,
- ' 这通常表示 Metro 启动后又 amend/rebase/reset/改过文件。需要接管时传 `--takeover` 重起。',
+ `✗ ${port} 上是本 worktree 的 Metro,但源码指纹已过期(运行中=${runningSource || "(无)"} ≠ 当前=${currentSource})。`,
+ " 这通常表示 Metro 启动后又 amend/rebase/reset/改过文件。需要接管时传 `--takeover` 重起。",
],
};
}
- return { action: 'restart', code: 'target-stale', lines: [] };
+ return { action: "restart", code: "target-stale", lines: [] };
}
if (!listenerWorktreeExists) {
if (!takeover) {
return {
- action: 'refuse',
- code: 'occupied-orphan',
+ action: "refuse",
+ code: "occupied-orphan",
lines: [
`✗ 端口 ${port} 被已删除 worktree 的孤儿 Metro 占用:${occupant}`,
- ' 该目录已不存在,进程还占着端口。确认可以清掉时传 `--takeover`。',
+ " 该目录已不存在,进程还占着端口。确认可以清掉时传 `--takeover`。",
],
};
}
- return { action: 'restart', code: 'occupied-orphan', lines: [] };
+ return { action: "restart", code: "occupied-orphan", lines: [] };
}
if (!takeover) {
return {
- action: 'refuse',
- code: 'occupied-foreign',
+ action: "refuse",
+ code: "occupied-foreign",
lines: [
`✗ 端口 ${port} 被其他 Cindy worktree 的 Metro 占用:${occupant}`,
- ' 当前版本需要这块端口。确认可以切换时传 `--takeover`。',
+ " 当前版本需要这块端口。确认可以切换时传 `--takeover`。",
],
};
}
- return { action: 'restart', code: 'occupied-foreign', lines: [] };
+ return { action: "restart", code: "occupied-foreign", lines: [] };
}
/** Parse the machine-readable output switch for mobile:sim:whoami. */
@@ -222,8 +233,8 @@ export function extractSimJsonArgs(args) {
const passthrough = [];
for (const arg of args) {
- if (arg === '--json') {
- if (json) throw new Error('--json 只能传一次');
+ if (arg === "--json") {
+ if (json) throw new Error("--json 只能传一次");
json = true;
} else {
passthrough.push(arg);
@@ -238,22 +249,40 @@ export function extractSimJsonArgs(args) {
* 测试可注入 execFile,避免真的启动 Expo CLI。
*/
export function resolveMobileSimulatorBundleId(region, options = {}) {
- const run = options.execFile ?? execFileSync;
+ const run =
+ options.execFile ??
+ ((command, args, opts) => {
+ if (command !== "pnpm") return execFileSync(command, args, opts);
+ const invocation = resolvePnpmInvocation(
+ ["exec", "expo", "config", "--type", "public", "--json"],
+ {
+ npmExecPath: usablePnpmExecPath(process.env.npm_execpath, existsSync),
+ },
+ );
+ return execFileSync(invocation.command, invocation.args, {
+ ...opts,
+ env: { ...opts.env, ...(invocation.env ?? {}) },
+ });
+ });
const buildEnv = withLocalMobileRegionConfig(
mobileClientBundleEnv({ authRegion: region }),
);
let raw;
try {
- raw = run('pnpm', ['exec', 'expo', 'config', '--type', 'public', '--json'], {
- cwd: options.mobileDir ?? mobileDir,
- env: { ...(options.env ?? process.env), ...buildEnv },
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'pipe'],
- });
+ raw = run(
+ "pnpm",
+ ["exec", "expo", "config", "--type", "public", "--json"],
+ {
+ cwd: options.mobileDir ?? mobileDir,
+ env: { ...(options.env ?? process.env), ...buildEnv },
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
} catch (error) {
const detail = String(error?.stderr ?? error?.message ?? error).trim();
throw new Error(
- `无法解析 ${region} Simulator bundle id${detail ? `: ${detail}` : ''}`,
+ `无法解析 ${region} Simulator bundle id${detail ? `: ${detail}` : ""}`,
{ cause: error },
);
}
@@ -262,10 +291,12 @@ export function resolveMobileSimulatorBundleId(region, options = {}) {
try {
config = JSON.parse(String(raw));
} catch (error) {
- throw new Error(`Expo config 未返回合法 JSON(region=${region})`, { cause: error });
+ throw new Error(`Expo config 未返回合法 JSON(region=${region})`, {
+ cause: error,
+ });
}
const bundleId = config?.ios?.bundleIdentifier;
- if (typeof bundleId !== 'string' || !bundleId.trim()) {
+ if (typeof bundleId !== "string" || !bundleId.trim()) {
throw new Error(`Expo config 缺少 ios.bundleIdentifier(region=${region})`);
}
return bundleId.trim();
diff --git a/apps/mobile/src/device-link/DeviceManagementList.ios.tsx b/apps/mobile/src/device-link/DeviceManagementList.ios.tsx
index c1511a9a79..98d0a9f3c9 100644
--- a/apps/mobile/src/device-link/DeviceManagementList.ios.tsx
+++ b/apps/mobile/src/device-link/DeviceManagementList.ios.tsx
@@ -1,9 +1,10 @@
import { Host, ListItem } from '@expo/ui';
-import { Button, List, SwipeActions, Text } from '@expo/ui/swift-ui';
+import { Button, Circle, HStack, List, SwipeActions, Text } from '@expo/ui/swift-ui';
import {
disabled,
font,
foregroundStyle,
+ frame,
labelStyle,
listRowBackground,
listStyle,
@@ -45,25 +46,31 @@ export function DeviceManagementList({
<Monitor
size={iconSize.md}
strokeWidth={iconStroke.regular}
- color={
- device.online ? colors.statusReady : colors.textSecondary
- }
+ color={colors.textSecondary}
/>
}
supportingText={
- <Text
- modifiers={[
- font({ textStyle: 'caption' }),
- foregroundStyle({
- type: 'hierarchical',
- style: 'secondary',
- }),
- ]}
- >
- {device.online
- ? statusLabel
- : `${statusLabel} · ${statusDetail}`}
- </Text>
+ <HStack spacing={4} alignment="center">
+ <Circle
+ modifiers={[
+ frame({ width: 6, height: 6 }),
+ foregroundStyle(device.online ? colors.statusReady : colors.textTertiary),
+ ]}
+ />
+ <Text
+ modifiers={[
+ font({ textStyle: 'caption' }),
+ foregroundStyle({
+ type: 'hierarchical',
+ style: 'secondary',
+ }),
+ ]}
+ >
+ {device.online
+ ? statusLabel
+ : `${statusLabel} · ${statusDetail}`}
+ </Text>
+ </HStack>
}
testID={`deviceManagement.open.${device.deviceId}`}
>
diff --git a/apps/mobile/src/device-link/DeviceManagementList.tsx b/apps/mobile/src/device-link/DeviceManagementList.tsx
index 5a6ae34263..a640f897ea 100644
--- a/apps/mobile/src/device-link/DeviceManagementList.tsx
+++ b/apps/mobile/src/device-link/DeviceManagementList.tsx
@@ -13,6 +13,7 @@ import {
iconSize,
iconStroke,
spacing,
+ radius,
typeScale,
} from '@/theme/tokens';
import type { DeviceManagementListProps } from './DeviceManagementList.types';
@@ -86,7 +87,7 @@ function DeviceRow({
<Monitor
size={iconSize.md}
strokeWidth={iconStroke.regular}
- color={row.device.online ? colors.statusReady : colors.textSecondary}
+ color={colors.textSecondary}
/>
<View style={styles.labels}>
<Text
@@ -102,9 +103,17 @@ function DeviceRow({
>
{row.device.name}
</Text>
- <Text style={{ color: colors.textSecondary }}>
- {row.statusLabel} · {row.statusDetail}
- </Text>
+ <View style={styles.status}>
+ <View
+ style={[
+ styles.statusDot,
+ { backgroundColor: row.device.online ? colors.statusReady : colors.textTertiary },
+ ]}
+ />
+ <Text style={{ color: colors.textSecondary, flexShrink: 1 }}>
+ {row.statusLabel} · {row.statusDetail}
+ </Text>
+ </View>
</View>
</Pressable>
</ClassicSwipeable>
@@ -120,6 +129,8 @@ const styles = StyleSheet.create({
borderBottomWidth: StyleSheet.hairlineWidth,
},
labels: { flex: 1, gap: spacing.xs },
+ status: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
+ statusDot: { width: 6, height: 6, borderRadius: radius.pill, flexShrink: 0 },
action: {
minWidth: 88,
minHeight: 44,
diff --git a/apps/mobile/src/i18n/locales/en/index.ts b/apps/mobile/src/i18n/locales/en/index.ts
index 6e65f0e493..e3152d296b 100644
--- a/apps/mobile/src/i18n/locales/en/index.ts
+++ b/apps/mobile/src/i18n/locales/en/index.ts
@@ -6,6 +6,7 @@
*/
import apiErrors from './apiErrors.json';
+import remoteDesktop from './remoteDesktop.json';
import chat from './chat.json';
import composer from './composer.json';
import deviceLink from './deviceLink.json';
@@ -22,6 +23,7 @@ import startup from './startup.json';
import update from './update.json';
export default {
+ remoteDesktop,
apiErrors,
chat,
composer,
diff --git a/apps/mobile/src/i18n/locales/en/remoteDesktop.json b/apps/mobile/src/i18n/locales/en/remoteDesktop.json
new file mode 100644
index 0000000000..37299c16b5
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/en/remoteDesktop.json
@@ -0,0 +1,116 @@
+{
+ "takeoverConnection": "Take over connection",
+ "connectionBusyTakeover": "Another device is connected to this desktop. Taking over will disconnect that device.",
+ "clipboard": "Clipboard",
+ "copyToPhone": "Copy to phone",
+ "pasteFromPhone": "Paste from phone",
+ "clipboardUpgrade": "Update Cindy on your phone and computer to transfer images and rich text.",
+ "clipboardEmpty": "The clipboard is empty.",
+ "clipboardTooLong": "Clipboard content is too large. Reduce its size and try again.",
+ "clipboardCopyFailed": "Could not copy. Check the selected text or computer clipboard and try again.",
+ "clipboardPasteFailed": "Could not paste. Make sure remote control is available and try again.",
+ "clipboardDone": "Done",
+ "functionKeys": "Function keys",
+ "inputMethod": "Phone keyboard",
+ "computerKeyboard": "Computer keyboard",
+ "comboMode": "Combination keys",
+ "showMouseButtons": "Show mouse buttons",
+ "leftClick": "Left click",
+ "middleClick": "Middle click",
+ "mouseWheel": "Middle click; hold and drag to scroll",
+ "scrollUp": "Scroll up",
+ "scrollDown": "Scroll down",
+ "permissionsTitle": "Remote desktop permissions",
+ "permissionsIntro": "Screen recording lets you view the desktop. Accessibility also enables control. Complete authorization on the computer; status updates automatically.",
+ "permissionsReady": "System permissions are ready. You can reconnect.",
+ "screenRecording": "Screen recording",
+ "accessibility": "Accessibility",
+ "screenRecordingHelp": "Open System Settings and enable screen recording for this Cindy app. If macOS asks you to restart, reopen Cindy before connecting.",
+ "accessibilityHelp": "Open settings and enable accessibility for the app identified by the system prompt. The actual input permission is checked automatically when you return.",
+ "permissionChecking": "Checking…",
+ "permissionGranted": "Granted",
+ "permissionUnknown": "Unconfirmed",
+ "permissionMissing": "Not granted",
+ "openPermissionSettings": "Open System Settings",
+ "recheckPermissions": "Check again",
+ "permissionActionFailed": "Could not open the permission guide. Try again in Remote control settings on the computer.",
+ "permissionCheckFailed": "Could not check permissions. Make sure the computer is online and try again.",
+ "openGuideOnComputer": "Open guide on computer",
+ "permissionGuideOpened": "The permission guide is open on the computer. Continue there.",
+ "reconnectAfterPermissions": "Check and reconnect",
+ "closePermissionGuide": "Close",
+ "title": "Remote desktop",
+ "allow": "Allow remote desktop",
+ "allowHint": "Allow your signed-in devices to view and operate all apps on this computer. Also enable device control above.",
+ "permissionHint": "On the computer, allow screen recording and accessibility in system settings, then reconnect.",
+ "beingControlled": "Your desktop is being controlled",
+ "beingViewed": "Your desktop is being viewed",
+ "disconnect": "Disconnect",
+ "back": "Back",
+ "connect": "Connect",
+ "connecting": "Connecting…",
+ "reconnecting": "Reconnecting…",
+ "disconnected": "Disconnected",
+ "compatibility": "Compatibility mode · lower frame rate",
+ "live": "Live",
+ "controlling": "Controlling",
+ "viewOnly": "View only",
+ "upgrade": "Update Cindy on the computer to use remote desktop.",
+ "disabled": "On the computer, enable remote desktop in Settings → Remote control.",
+ "busy": "Desktop input is busy. Release control on the other device or wait for the Agent action to finish.",
+ "connectionBusy": "Another device is connected to this remote desktop. Exit remote desktop on that device, then try connecting again.",
+ "connectionError": "Connection ended. Check that the computer is online, then reconnect.",
+ "releaseControl": "Release control",
+ "takeControl": "Take control",
+ "pointer": "Trackpad",
+ "touch": "Touch",
+ "pan": "Move view",
+ "keyboard": "Keyboard",
+ "rightClick": "Right click",
+ "fit": "Fit",
+ "display": "Display",
+ "gestureHint": "Pinch to zoom. Two fingers scroll; Move view pans. Hold, then move to drag.",
+ "textPlaceholder": "Type on the computer",
+ "sendText": "Send text",
+ "keys": "Keys",
+ "showDesktop": "Desktop",
+ "allWindows": "All windows",
+ "operations": "Controls",
+ "inputMode": "Input mode",
+ "displayNumber": "Display {{number}}",
+ "touchHint": "Tap to click, hold to drag. Two fingers scroll; pinch to zoom.",
+ "pointerHint": "Slide to move the pointer, tap to click. Two fingers scroll; pinch to zoom.",
+ "panHint": "Slide to move the view; pinch to zoom. Turn off to restore your input mode.",
+ "viewOnlyHint": "View only is on. Slide to move the view or pinch to zoom without controlling the computer.",
+ "close": "Close",
+ "directConnection": "Direct to computer",
+ "videoRelay": "Server video relay",
+ "screenshotRelay": "Server screenshot relay",
+ "roundTrip": "RTT {{ms}} ms",
+ "frameTime": "Frame {{ms}} ms",
+ "rotate": "Rotate screen",
+ "sound": "Sound",
+ "smallWindow": "Picture in picture",
+ "displaySettings": "Display",
+ "frameRate": "Frame rate",
+ "fps": "{{count}} fps",
+ "quality": "Quality",
+ "automatic": "Auto",
+ "clear": "Clear",
+ "highDefinition": "HD",
+ "original": "Original",
+ "qualityHint": "Auto adapts to the network. Clear, HD and Original cap bitrate at 2, 8 and 20 Mbps. Actual frame rate depends on the computer and network.",
+ "resolution": "Computer resolution",
+ "settingUnsupported": "This computer does not support this setting yet",
+ "loadingSettings": "Loading…",
+ "retrySettings": "Could not load. Tap to retry.",
+ "followComputer": "Follow computer",
+ "resolutionHint": "Changes the computer’s display resolution and window layout, then briefly reconnects.",
+ "resolutionControlHint": "Take control to change the resolution.",
+ "videoSettingsFailed": "Live video is unavailable. Compatibility viewing does not apply frame rate, quality or sound settings. Select a setting again to retry.",
+ "settingFailed": "Could not apply the setting. Please retry.",
+ "pipUnavailable": "Picture in picture is unavailable. Keep Cindy open to view the desktop.",
+ "clipboardUnsupported": "This clipboard content is not supported yet. Copy a single image, text, or link. Files and app-specific formats cannot be transferred yet.",
+ "clipboardTransferring": "Transferring clipboard content…",
+ "nativeResolution": "Native"
+}
diff --git a/apps/mobile/src/i18n/locales/ja/index.ts b/apps/mobile/src/i18n/locales/ja/index.ts
index 6e65f0e493..e3152d296b 100644
--- a/apps/mobile/src/i18n/locales/ja/index.ts
+++ b/apps/mobile/src/i18n/locales/ja/index.ts
@@ -6,6 +6,7 @@
*/
import apiErrors from './apiErrors.json';
+import remoteDesktop from './remoteDesktop.json';
import chat from './chat.json';
import composer from './composer.json';
import deviceLink from './deviceLink.json';
@@ -22,6 +23,7 @@ import startup from './startup.json';
import update from './update.json';
export default {
+ remoteDesktop,
apiErrors,
chat,
composer,
diff --git a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json b/apps/mobile/src/i18n/locales/ja/remoteDesktop.json
new file mode 100644
index 0000000000..f7df5a4d79
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/ja/remoteDesktop.json
@@ -0,0 +1,116 @@
+{
+ "takeoverConnection": "接続を引き継ぐ",
+ "connectionBusyTakeover": "別のデバイスが接続中です。接続を引き継ぐと、そのデバイスは切断されます。",
+ "clipboard": "クリップボード",
+ "copyToPhone": "スマートフォンにコピー",
+ "pasteFromPhone": "スマートフォンから貼り付け",
+ "clipboardUpgrade": "画像とリッチテキストを転送するには、スマートフォンとパソコンの Cindy を更新してください。",
+ "clipboardEmpty": "クリップボードは空です。",
+ "clipboardTooLong": "内容が大きすぎます。サイズを小さくして再試行してください。",
+ "clipboardCopyFailed": "コピーできませんでした。選択したテキストまたはコンピューターのクリップボードを確認して再試行してください。",
+ "clipboardPasteFailed": "貼り付けできませんでした。リモート操作が可能か確認して再試行してください。",
+ "clipboardDone": "完了",
+ "functionKeys": "機能キー",
+ "inputMethod": "スマホキーボード",
+ "computerKeyboard": "PCキーボード",
+ "comboMode": "組み合わせキー",
+ "showMouseButtons": "マウスボタンを表示",
+ "leftClick": "左クリック",
+ "middleClick": "中クリック",
+ "mouseWheel": "中クリック。長押ししてドラッグでスクロール",
+ "scrollUp": "上にスクロール",
+ "scrollDown": "下にスクロール",
+ "permissionsTitle": "リモートデスクトップの権限",
+ "permissionsIntro": "画面の表示には画面収録、操作にはアクセシビリティの権限も必要です。コンピューターで許可すると、状態が自動更新されます。",
+ "permissionsReady": "システム権限の準備ができました。再接続できます。",
+ "screenRecording": "画面収録",
+ "accessibility": "アクセシビリティ",
+ "screenRecordingHelp": "システム設定を開き、この Cindy の画面収録を許可してください。再起動を求められた場合は、Cindy を開き直してから接続してください。",
+ "accessibilityHelp": "設定を開き、システムの許可ダイアログに表示されたアプリのアクセシビリティを有効にしてください。戻ると実際の入力権限を自動確認します。",
+ "permissionChecking": "確認中…",
+ "permissionGranted": "許可済み",
+ "permissionUnknown": "未確認",
+ "permissionMissing": "未許可",
+ "openPermissionSettings": "システム設定を開く",
+ "recheckPermissions": "再確認",
+ "permissionActionFailed": "権限ガイドを開けませんでした。コンピューターのリモート操作設定で再試行してください。",
+ "permissionCheckFailed": "権限を確認できません。コンピューターがオンラインか確認して再試行してください。",
+ "openGuideOnComputer": "コンピューターでガイドを開く",
+ "permissionGuideOpened": "コンピューターに権限ガイドを表示しました。そちらで続けてください。",
+ "reconnectAfterPermissions": "確認して再接続",
+ "closePermissionGuide": "閉じる",
+ "title": "リモートデスクトップ",
+ "allow": "リモートデスクトップを許可",
+ "allowHint": "同じアカウントのデバイスから、このコンピューターの全アプリの表示と操作を許可します。上のデバイス操作も有効にしてください。",
+ "permissionHint": "コンピューターのシステム設定で画面収録とアクセシビリティを許可し、再接続してください。",
+ "beingControlled": "デスクトップが操作されています",
+ "beingViewed": "デスクトップが表示されています",
+ "disconnect": "切断",
+ "back": "戻る",
+ "connect": "接続",
+ "connecting": "接続中…",
+ "reconnecting": "再接続中…",
+ "disconnected": "切断済み",
+ "compatibility": "互換モード · 低フレームレート",
+ "live": "ライブ映像",
+ "controlling": "操作中",
+ "viewOnly": "表示のみ",
+ "upgrade": "コンピューター側の Cindy を更新してください。",
+ "disabled": "コンピューターの設定 → リモート操作でリモートデスクトップを有効にしてください。",
+ "busy": "デスクトップ操作中です。他のデバイスの操作を解除するか、Agent の操作終了を待ってください。",
+ "connectionBusy": "別のデバイスがこのリモートデスクトップに接続しています。そのデバイスでリモートデスクトップを終了してから、もう一度接続してください。",
+ "connectionError": "接続が終了しました。コンピューターがオンラインか確認し、再接続してください。",
+ "releaseControl": "操作を解除",
+ "takeControl": "操作を開始",
+ "pointer": "トラックパッド",
+ "touch": "タッチ",
+ "pan": "画面を移動",
+ "keyboard": "キーボード",
+ "rightClick": "右クリック",
+ "fit": "全体表示",
+ "display": "ディスプレイ",
+ "gestureHint": "ピンチで拡大縮小。2本指でスクロール、画面移動モードではパン。長押しして移動するとドラッグします。",
+ "textPlaceholder": "コンピューターに文字を入力",
+ "sendText": "文字を送信",
+ "keys": "キー",
+ "showDesktop": "デスクトップ",
+ "allWindows": "すべてのウィンドウ",
+ "operations": "操作",
+ "inputMode": "操作方法",
+ "displayNumber": "ディスプレイ {{number}}",
+ "touchHint": "タップでクリック、長押しでドラッグ。2本指でスクロール、ピンチで拡大縮小。",
+ "pointerHint": "スライドでポインター移動、タップでクリック。2本指でスクロール、ピンチで拡大縮小。",
+ "panHint": "スライドで画面移動、ピンチで拡大縮小。オフにすると元の操作方法に戻ります。",
+ "viewOnlyHint": "表示のみのため、コンピューターは操作されません。画面移動や拡大縮小はできます。",
+ "close": "閉じる",
+ "directConnection": "パソコンに直接接続",
+ "videoRelay": "サーバー経由の映像",
+ "screenshotRelay": "サーバー経由のスクリーンショット",
+ "roundTrip": "往復 {{ms}} ms",
+ "frameTime": "画像取得 {{ms}} ms",
+ "rotate": "画面を回転",
+ "sound": "サウンド",
+ "smallWindow": "ピクチャインピクチャ",
+ "displaySettings": "表示",
+ "frameRate": "フレームレート",
+ "fps": "{{count}} fps",
+ "quality": "画質",
+ "automatic": "自動",
+ "clear": "標準",
+ "highDefinition": "高画質",
+ "original": "オリジナル",
+ "qualityHint": "自動は通信状況に合わせて調整します。標準・高画質・オリジナルの上限は 2・8・20 Mbps です。実際のフレームレートはパソコンと通信状況によって変わります。",
+ "resolution": "パソコンの解像度",
+ "settingUnsupported": "このパソコンはまだこの設定に対応していません",
+ "loadingSettings": "読み込み中…",
+ "retrySettings": "読み込み失敗。タップして再試行。",
+ "followComputer": "パソコンに合わせる",
+ "resolutionHint": "パソコンの実際の解像度とウィンドウ配置を変更し、一時的に再接続します。",
+ "resolutionControlHint": "解像度を変更するには操作権を取得してください。",
+ "videoSettingsFailed": "リアルタイム映像に接続できません。互換表示ではフレームレート・画質・サウンド設定は適用されません。設定を選び直して再試行できます。",
+ "settingFailed": "設定を適用できませんでした。再試行してください。",
+ "pipUnavailable": "ピクチャインピクチャを開始できません。Cindy を開いたまま表示してください。",
+ "clipboardUnsupported": "この形式にはまだ対応していません。画像1枚、テキスト、またはリンクをコピーしてください。ファイルやアプリ独自の形式は転送できません。",
+ "clipboardTransferring": "クリップボードの内容を転送中…",
+ "nativeResolution": "ネイティブ"
+}
diff --git a/apps/mobile/src/i18n/locales/ko/index.ts b/apps/mobile/src/i18n/locales/ko/index.ts
index 6e65f0e493..e3152d296b 100644
--- a/apps/mobile/src/i18n/locales/ko/index.ts
+++ b/apps/mobile/src/i18n/locales/ko/index.ts
@@ -6,6 +6,7 @@
*/
import apiErrors from './apiErrors.json';
+import remoteDesktop from './remoteDesktop.json';
import chat from './chat.json';
import composer from './composer.json';
import deviceLink from './deviceLink.json';
@@ -22,6 +23,7 @@ import startup from './startup.json';
import update from './update.json';
export default {
+ remoteDesktop,
apiErrors,
chat,
composer,
diff --git a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json b/apps/mobile/src/i18n/locales/ko/remoteDesktop.json
new file mode 100644
index 0000000000..54bb4a20b9
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/ko/remoteDesktop.json
@@ -0,0 +1,116 @@
+{
+ "takeoverConnection": "연결 넘겨받기",
+ "connectionBusyTakeover": "다른 기기가 연결되어 있습니다. 연결을 넘겨받으면 해당 기기의 연결이 끊어집니다.",
+ "clipboard": "클립보드",
+ "copyToPhone": "휴대폰으로 복사",
+ "pasteFromPhone": "휴대폰에서 붙여넣기",
+ "clipboardUpgrade": "이미지와 서식 있는 텍스트를 전송하려면 휴대폰과 컴퓨터의 Cindy를 업데이트하세요.",
+ "clipboardEmpty": "클립보드가 비어 있습니다.",
+ "clipboardTooLong": "클립보드 내용이 너무 큽니다. 크기를 줄여 다시 시도하세요.",
+ "clipboardCopyFailed": "복사하지 못했습니다. 선택한 텍스트 또는 컴퓨터 클립보드를 확인하고 다시 시도하세요.",
+ "clipboardPasteFailed": "붙여넣지 못했습니다. 원격 제어가 가능한지 확인하고 다시 시도하세요.",
+ "clipboardDone": "완료",
+ "functionKeys": "기능 키",
+ "inputMethod": "휴대폰 키보드",
+ "computerKeyboard": "컴퓨터 키보드",
+ "comboMode": "조합 키",
+ "showMouseButtons": "마우스 버튼 표시",
+ "leftClick": "왼쪽 클릭",
+ "middleClick": "가운데 클릭",
+ "mouseWheel": "가운데 클릭. 길게 누른 채 드래그하여 스크롤",
+ "scrollUp": "위로 스크롤",
+ "scrollDown": "아래로 스크롤",
+ "permissionsTitle": "원격 데스크톱 권한",
+ "permissionsIntro": "데스크톱을 보려면 화면 기록 권한이, 조작하려면 손쉬운 사용 권한도 필요합니다. 컴퓨터에서 허용하면 상태가 자동으로 갱신됩니다.",
+ "permissionsReady": "시스템 권한이 준비되었습니다. 다시 연결할 수 있습니다.",
+ "screenRecording": "화면 기록",
+ "accessibility": "손쉬운 사용",
+ "screenRecordingHelp": "시스템 설정을 열고 현재 Cindy 앱의 화면 기록을 허용하세요. 재시작을 요청하면 Cindy를 다시 연 후 연결하세요.",
+ "accessibilityHelp": "설정을 열고 시스템 권한 안내에 표시된 앱의 손쉬운 사용을 허용하세요. 돌아오면 실제 입력 권한을 자동 확인합니다.",
+ "permissionChecking": "확인 중…",
+ "permissionGranted": "허용됨",
+ "permissionUnknown": "확인되지 않음",
+ "permissionMissing": "허용되지 않음",
+ "openPermissionSettings": "시스템 설정 열기",
+ "recheckPermissions": "다시 확인",
+ "permissionActionFailed": "권한 안내를 열지 못했습니다. 컴퓨터의 원격 제어 설정에서 다시 시도하세요.",
+ "permissionCheckFailed": "권한을 확인하지 못했습니다. 컴퓨터가 온라인인지 확인하고 다시 시도하세요.",
+ "openGuideOnComputer": "컴퓨터에서 권한 안내 열기",
+ "permissionGuideOpened": "컴퓨터에 권한 안내를 표시했습니다. 컴퓨터에서 계속하세요.",
+ "reconnectAfterPermissions": "확인 후 다시 연결",
+ "closePermissionGuide": "닫기",
+ "title": "원격 데스크톱",
+ "allow": "원격 데스크톱 허용",
+ "allowHint": "같은 계정의 기기에서 이 컴퓨터의 모든 앱을 보고 조작하도록 허용합니다. 위의 기기 제어도 켜주세요.",
+ "permissionHint": "컴퓨터 시스템 설정에서 화면 기록과 손쉬운 사용을 허용한 후 다시 연결하세요.",
+ "beingControlled": "데스크톱을 원격으로 제어 중",
+ "beingViewed": "데스크톱을 원격으로 보는 중",
+ "disconnect": "연결 끊기",
+ "back": "뒤로",
+ "connect": "연결",
+ "connecting": "연결 중…",
+ "reconnecting": "다시 연결 중…",
+ "disconnected": "연결 끊김",
+ "compatibility": "호환 모드 · 낮은 프레임 속도",
+ "live": "실시간 화면",
+ "controlling": "제어 중",
+ "viewOnly": "보기 전용",
+ "upgrade": "컴퓨터의 Cindy를 업데이트하세요.",
+ "disabled": "컴퓨터의 설정 → 원격 제어에서 원격 데스크톱을 켜주세요.",
+ "busy": "데스크톱 입력을 사용 중입니다. 다른 기기의 제어를 해제하거나 Agent 작업이 끝날 때까지 기다리세요.",
+ "connectionBusy": "다른 기기가 이 원격 데스크톱에 연결되어 있습니다. 해당 기기에서 원격 데스크톱을 종료한 후 다시 연결하세요.",
+ "connectionError": "연결이 종료되었습니다. 컴퓨터가 온라인인지 확인하고 다시 연결하세요.",
+ "releaseControl": "제어 해제",
+ "takeControl": "제어 시작",
+ "pointer": "트랙패드",
+ "touch": "터치",
+ "pan": "화면 이동",
+ "keyboard": "키보드",
+ "rightClick": "오른쪽 클릭",
+ "fit": "화면 맞춤",
+ "display": "디스플레이",
+ "gestureHint": "두 손가락으로 확대/축소 및 스크롤합니다. 화면 이동 모드에서는 이동합니다. 길게 누른 후 움직이면 드래그합니다.",
+ "textPlaceholder": "컴퓨터에 텍스트 입력",
+ "sendText": "텍스트 전송",
+ "keys": "키",
+ "showDesktop": "데스크톱",
+ "allWindows": "모든 창",
+ "operations": "조작",
+ "inputMode": "입력 방식",
+ "displayNumber": "디스플레이 {{number}}",
+ "touchHint": "탭하여 클릭하고 길게 눌러 드래그합니다. 두 손가락으로 스크롤하거나 확대·축소합니다.",
+ "pointerHint": "밀어서 포인터를 움직이고 탭하여 클릭합니다. 두 손가락으로 스크롤하거나 확대·축소합니다.",
+ "panHint": "밀어서 화면을 이동하거나 확대·축소합니다. 끄면 이전 입력 방식으로 돌아갑니다.",
+ "viewOnlyHint": "보기 전용 상태로 컴퓨터를 조작하지 않습니다. 화면 이동과 확대·축소는 가능합니다.",
+ "close": "닫기",
+ "directConnection": "컴퓨터에 직접 연결",
+ "videoRelay": "서버 영상 중계",
+ "screenshotRelay": "서버 스크린샷 중계",
+ "roundTrip": "왕복 {{ms}} ms",
+ "frameTime": "화면 수신 {{ms}} ms",
+ "rotate": "화면 회전",
+ "sound": "소리",
+ "smallWindow": "화면 속 화면",
+ "displaySettings": "디스플레이",
+ "frameRate": "프레임 속도",
+ "fps": "{{count}} fps",
+ "quality": "화질",
+ "automatic": "자동",
+ "clear": "표준",
+ "highDefinition": "고화질",
+ "original": "원본",
+ "qualityHint": "자동은 네트워크에 맞춰 조정합니다. 표준, 고화질, 원본의 최대 비트레이트는 2, 8, 20 Mbps입니다. 실제 프레임 속도는 컴퓨터와 네트워크에 따라 달라집니다.",
+ "resolution": "컴퓨터 해상도",
+ "settingUnsupported": "이 컴퓨터는 아직 이 설정을 지원하지 않습니다",
+ "loadingSettings": "불러오는 중…",
+ "retrySettings": "불러오지 못했습니다. 눌러서 다시 시도하세요.",
+ "followComputer": "컴퓨터에 맞춤",
+ "resolutionHint": "컴퓨터의 실제 해상도와 창 배치를 변경하고 잠시 다시 연결합니다.",
+ "resolutionControlHint": "해상도를 변경하려면 제어권을 가져오세요.",
+ "videoSettingsFailed": "실시간 영상에 연결하지 못했습니다. 호환 모드에서는 프레임 속도, 화질, 소리가 적용되지 않습니다. 설정을 다시 선택해 재시도하세요.",
+ "settingFailed": "설정을 적용하지 못했습니다. 다시 시도하세요.",
+ "pipUnavailable": "화면 속 화면을 시작할 수 없습니다. Cindy를 열어 둔 상태로 시청하세요.",
+ "clipboardUnsupported": "아직 지원하지 않는 형식입니다. 이미지 한 장, 텍스트 또는 링크를 복사해 주세요. 파일과 앱 전용 형식은 아직 전송할 수 없습니다.",
+ "clipboardTransferring": "클립보드 내용을 전송하는 중…",
+ "nativeResolution": "기본 해상도"
+}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/index.ts b/apps/mobile/src/i18n/locales/zh-CN/index.ts
index 6e65f0e493..e3152d296b 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/index.ts
+++ b/apps/mobile/src/i18n/locales/zh-CN/index.ts
@@ -6,6 +6,7 @@
*/
import apiErrors from './apiErrors.json';
+import remoteDesktop from './remoteDesktop.json';
import chat from './chat.json';
import composer from './composer.json';
import deviceLink from './deviceLink.json';
@@ -22,6 +23,7 @@ import startup from './startup.json';
import update from './update.json';
export default {
+ remoteDesktop,
apiErrors,
chat,
composer,
diff --git a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json
new file mode 100644
index 0000000000..97e2af589d
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json
@@ -0,0 +1,116 @@
+{
+ "takeoverConnection": "接管连接",
+ "connectionBusyTakeover": "已有其他设备连接此远程桌面。接管连接后,上一台设备会断开。",
+ "clipboard": "剪贴板",
+ "copyToPhone": "复制到手机",
+ "pasteFromPhone": "粘贴自手机",
+ "clipboardUpgrade": "请更新手机和电脑上的 Cindy,以使用图片和富文本剪贴板。",
+ "clipboardEmpty": "剪贴板为空。",
+ "clipboardTooLong": "剪贴板内容过大,请缩小后重试。",
+ "clipboardCopyFailed": "未能复制,请检查电脑选中的文字或剪贴板内容后重试。",
+ "clipboardPasteFailed": "未能粘贴,请确认远程桌面仍可操作后重试。",
+ "clipboardDone": "已完成",
+ "functionKeys": "功能键",
+ "inputMethod": "手机键盘",
+ "computerKeyboard": "电脑键盘",
+ "comboMode": "组合键",
+ "showMouseButtons": "显示鼠标按键",
+ "leftClick": "左键",
+ "middleClick": "中键",
+ "mouseWheel": "中键;长按拖动滚动",
+ "scrollUp": "向上滚动",
+ "scrollDown": "向下滚动",
+ "permissionsTitle": "远程桌面权限",
+ "permissionsIntro": "查看桌面需要屏幕录制权限;操作桌面还需要辅助功能权限。请在电脑上完成授权,结果会自动更新。",
+ "permissionsReady": "系统权限已就绪,可以重新连接。",
+ "screenRecording": "屏幕录制",
+ "accessibility": "辅助功能",
+ "screenRecordingHelp": "打开系统设置,为当前 Cindy 开启屏幕录制。若系统要求重新启动,请重新打开 Cindy 后连接。",
+ "accessibilityHelp": "点击打开设置后,为系统授权提示中的应用开启辅助功能。返回后会自动检测实际输入权限。",
+ "permissionChecking": "检测中…",
+ "permissionGranted": "已授权",
+ "permissionUnknown": "未确认",
+ "permissionMissing": "未授权",
+ "openPermissionSettings": "打开系统设置",
+ "recheckPermissions": "重新检测",
+ "permissionActionFailed": "未能打开授权引导。请在电脑端的远程控制设置中重试。",
+ "permissionCheckFailed": "暂时无法检测权限,请确认电脑在线后重试。",
+ "openGuideOnComputer": "在电脑上打开授权引导",
+ "permissionGuideOpened": "已在电脑上显示授权引导,请在电脑上继续。",
+ "reconnectAfterPermissions": "重新检测并连接",
+ "closePermissionGuide": "关闭",
+ "title": "远程桌面",
+ "allow": "允许远程桌面",
+ "allowHint": "允许已登录的同账号设备查看和操作这台电脑的所有应用。需同时开启上方的设备控制。",
+ "permissionHint": "请在电脑的系统设置中允许屏幕录制和辅助功能,然后重新连接。",
+ "beingControlled": "手机正在控制桌面",
+ "beingViewed": "手机正在查看桌面",
+ "disconnect": "断开连接",
+ "back": "返回",
+ "connect": "连接",
+ "connecting": "连接中…",
+ "reconnecting": "正在重新连接…",
+ "disconnected": "已断开",
+ "compatibility": "兼容模式 · 帧率较低",
+ "live": "实时画面",
+ "controlling": "正在控制",
+ "viewOnly": "仅查看",
+ "upgrade": "请升级电脑端 Cindy 后使用远程桌面。",
+ "disabled": "请在电脑端的设置 → 远程控制中开启远程桌面。",
+ "busy": "桌面输入正在使用中。请让其他设备释放控制,或等待 Agent 操作结束。",
+ "connectionBusy": "已有其他设备连接此远程桌面。请先在那台设备上退出远程桌面,再尝试连接。",
+ "connectionError": "连接已结束。请检查电脑是否在线,然后重新连接。",
+ "releaseControl": "释放控制",
+ "takeControl": "接管操作",
+ "pointer": "触控板",
+ "touch": "触屏",
+ "pan": "移动画面",
+ "keyboard": "键盘",
+ "rightClick": "右键",
+ "fit": "适应屏幕",
+ "display": "显示器",
+ "gestureHint": "双指缩放;双指移动可滚动,移动画面模式下可平移。长按后移动可拖拽。",
+ "textPlaceholder": "在电脑上输入文字",
+ "sendText": "发送文字",
+ "keys": "按键",
+ "showDesktop": "显示桌面",
+ "allWindows": "所有窗口",
+ "operations": "操作",
+ "inputMode": "操作方式",
+ "displayNumber": "显示器 {{number}}",
+ "touchHint": "轻点点击,长按拖拽;双指滚动,捏合缩放。",
+ "pointerHint": "滑动移动鼠标,轻点点击;双指滚动,捏合缩放。",
+ "panHint": "滑动只移动画面,捏合缩放。关闭后恢复原来的操作方式。",
+ "viewOnlyHint": "当前仅查看,不会操作电脑。可滑动移动画面、捏合缩放。",
+ "close": "关闭",
+ "directConnection": "电脑直连",
+ "videoRelay": "服务器视频中转",
+ "screenshotRelay": "服务器截图中转",
+ "roundTrip": "延迟 {{ms}} ms",
+ "frameTime": "取帧 {{ms}} ms",
+ "rotate": "旋转屏幕",
+ "sound": "声音",
+ "smallWindow": "小窗模式",
+ "displaySettings": "显示",
+ "frameRate": "帧率",
+ "fps": "{{count}} 帧",
+ "quality": "画质",
+ "automatic": "自动",
+ "clear": "清晰",
+ "highDefinition": "高清",
+ "original": "原画",
+ "qualityHint": "自动根据网络调整;清晰、高清和原画的码率上限分别为 2、8 和 20 Mbps。实际帧率取决于电脑与网络。",
+ "resolution": "电脑分辨率",
+ "settingUnsupported": "当前电脑端暂不支持此设置",
+ "loadingSettings": "读取中…",
+ "retrySettings": "读取失败,轻点重试",
+ "followComputer": "跟随电脑",
+ "resolutionHint": "更改电脑实际分辨率,会调整电脑上的窗口布局,并短暂重新连接。",
+ "resolutionControlHint": "接管操作后可以更改分辨率。",
+ "videoSettingsFailed": "实时传输未建立,当前使用兼容画面。帧率、画质和声音暂未生效,可重新选择设置重试。",
+ "settingFailed": "设置未能应用,请重试。",
+ "pipUnavailable": "当前无法开启系统画中画,请保持 Cindy 在前台观看。",
+ "clipboardUnsupported": "这种剪贴板内容暂不支持,请单独复制一张图片、文字或链接。文件和应用专有格式暂不能传输。",
+ "clipboardTransferring": "正在传输剪贴板内容…",
+ "nativeResolution": "原生"
+}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/index.ts b/apps/mobile/src/i18n/locales/zh-TW/index.ts
index 6e65f0e493..e3152d296b 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/index.ts
+++ b/apps/mobile/src/i18n/locales/zh-TW/index.ts
@@ -6,6 +6,7 @@
*/
import apiErrors from './apiErrors.json';
+import remoteDesktop from './remoteDesktop.json';
import chat from './chat.json';
import composer from './composer.json';
import deviceLink from './deviceLink.json';
@@ -22,6 +23,7 @@ import startup from './startup.json';
import update from './update.json';
export default {
+ remoteDesktop,
apiErrors,
chat,
composer,
diff --git a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json
new file mode 100644
index 0000000000..926cd9da44
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json
@@ -0,0 +1,116 @@
+{
+ "takeoverConnection": "接管連線",
+ "connectionBusyTakeover": "已有其他裝置連線至此遠端桌面。接管連線後,上一台裝置會中斷。",
+ "clipboard": "剪貼簿",
+ "copyToPhone": "複製到手機",
+ "pasteFromPhone": "貼上自手機",
+ "clipboardUpgrade": "請更新手機和電腦上的 Cindy,以使用圖片和格式化文字剪貼簿。",
+ "clipboardEmpty": "剪貼簿為空。",
+ "clipboardTooLong": "剪貼簿內容過大,請縮小後重試。",
+ "clipboardCopyFailed": "無法複製,請檢查電腦選取的文字或剪貼簿內容後重試。",
+ "clipboardPasteFailed": "無法貼上,請確認遠端桌面仍可操作後重試。",
+ "clipboardDone": "已完成",
+ "functionKeys": "功能鍵",
+ "inputMethod": "手機鍵盤",
+ "computerKeyboard": "電腦鍵盤",
+ "comboMode": "組合鍵",
+ "showMouseButtons": "顯示滑鼠按鍵",
+ "leftClick": "左鍵",
+ "middleClick": "中鍵",
+ "mouseWheel": "中鍵;長按拖動捲動",
+ "scrollUp": "向上捲動",
+ "scrollDown": "向下捲動",
+ "permissionsTitle": "遠端桌面權限",
+ "permissionsIntro": "檢視桌面需要螢幕錄製權限;操作桌面還需要輔助使用權限。請在電腦上完成授權,結果會自動更新。",
+ "permissionsReady": "系統權限已就緒,可以重新連線。",
+ "screenRecording": "螢幕錄製",
+ "accessibility": "輔助使用",
+ "screenRecordingHelp": "開啟系統設定,為目前的 Cindy 啟用螢幕錄製。若系統要求重新啟動,請重新開啟 Cindy 後連線。",
+ "accessibilityHelp": "點擊開啟設定後,為系統授權提示中的應用程式啟用輔助使用。返回後會自動檢測實際輸入權限。",
+ "permissionChecking": "檢測中…",
+ "permissionGranted": "已授權",
+ "permissionUnknown": "未確認",
+ "permissionMissing": "未授權",
+ "openPermissionSettings": "開啟系統設定",
+ "recheckPermissions": "重新檢測",
+ "permissionActionFailed": "無法開啟授權引導。請在電腦端的遠端控制設定中重試。",
+ "permissionCheckFailed": "暫時無法檢測權限,請確認電腦在線後重試。",
+ "openGuideOnComputer": "在電腦上開啟授權引導",
+ "permissionGuideOpened": "已在電腦上顯示授權引導,請在電腦上繼續。",
+ "reconnectAfterPermissions": "重新檢測並連線",
+ "closePermissionGuide": "關閉",
+ "title": "遠端桌面",
+ "allow": "允許遠端桌面",
+ "allowHint": "允許已登入的同帳號裝置檢視和操作這台電腦的所有應用程式。需同時開啟上方的裝置控制。",
+ "permissionHint": "請在電腦的系統設定中允許螢幕錄製和輔助使用,然後重新連線。",
+ "beingControlled": "手機正在控制桌面",
+ "beingViewed": "手機正在檢視桌面",
+ "disconnect": "中斷連線",
+ "back": "返回",
+ "connect": "連線",
+ "connecting": "連線中…",
+ "reconnecting": "正在重新連線…",
+ "disconnected": "已中斷",
+ "compatibility": "相容模式 · 畫格率較低",
+ "live": "即時畫面",
+ "controlling": "正在控制",
+ "viewOnly": "僅檢視",
+ "upgrade": "請升級電腦端 Cindy 後使用遠端桌面。",
+ "disabled": "請在電腦端的設定 → 遠端控制中開啟遠端桌面。",
+ "busy": "桌面輸入正在使用中。請讓其他裝置釋放控制,或等待 Agent 操作結束。",
+ "connectionBusy": "已有其他裝置連線至此遠端桌面。請先在該裝置上退出遠端桌面,再嘗試連線。",
+ "connectionError": "連線已結束。請檢查電腦是否在線,然後重新連線。",
+ "releaseControl": "釋放控制",
+ "takeControl": "接管操作",
+ "pointer": "觸控板",
+ "touch": "觸控",
+ "pan": "移動畫面",
+ "keyboard": "鍵盤",
+ "rightClick": "右鍵",
+ "fit": "符合螢幕",
+ "display": "顯示器",
+ "gestureHint": "雙指縮放;雙指移動可捲動,移動畫面模式下可平移。長按後移動可拖曳。",
+ "textPlaceholder": "在電腦上輸入文字",
+ "sendText": "傳送文字",
+ "keys": "按鍵",
+ "showDesktop": "顯示桌面",
+ "allWindows": "所有視窗",
+ "operations": "操作",
+ "inputMode": "操作方式",
+ "displayNumber": "顯示器 {{number}}",
+ "touchHint": "輕點點擊,長按拖曳;雙指捲動,捏合縮放。",
+ "pointerHint": "滑動移動游標,輕點點擊;雙指捲動,捏合縮放。",
+ "panHint": "滑動只移動畫面,捏合縮放。關閉後恢復原本的操作方式。",
+ "viewOnlyHint": "目前僅檢視,不會操作電腦。可滑動移動畫面、捏合縮放。",
+ "close": "關閉",
+ "directConnection": "電腦直連",
+ "videoRelay": "伺服器影片中繼",
+ "screenshotRelay": "伺服器截圖中繼",
+ "roundTrip": "延遲 {{ms}} ms",
+ "frameTime": "取幀 {{ms}} ms",
+ "rotate": "旋轉螢幕",
+ "sound": "聲音",
+ "smallWindow": "小窗模式",
+ "displaySettings": "顯示",
+ "frameRate": "幀率",
+ "fps": "{{count}} 幀",
+ "quality": "畫質",
+ "automatic": "自動",
+ "clear": "清晰",
+ "highDefinition": "高清",
+ "original": "原畫",
+ "qualityHint": "自動依網路調整;清晰、高清與原畫的位元率上限分別為 2、8 與 20 Mbps。實際幀率取決於電腦與網路。",
+ "resolution": "電腦解析度",
+ "settingUnsupported": "目前電腦端尚不支援此設定",
+ "loadingSettings": "讀取中…",
+ "retrySettings": "讀取失敗,輕點重試",
+ "followComputer": "跟隨電腦",
+ "resolutionHint": "變更電腦實際解析度,會調整電腦上的視窗配置,並短暫重新連線。",
+ "resolutionControlHint": "接管操作後可以變更解析度。",
+ "videoSettingsFailed": "即時傳輸未建立,目前使用相容畫面。幀率、畫質與聲音尚未生效,可重新選擇設定重試。",
+ "settingFailed": "設定未能套用,請重試。",
+ "pipUnavailable": "目前無法開啟系統子母畫面,請保持 Cindy 在前景觀看。",
+ "clipboardUnsupported": "暫不支援這種剪貼簿內容,請單獨複製一張圖片、文字或連結。檔案及應用程式專有格式暫時無法傳輸。",
+ "clipboardTransferring": "正在傳輸剪貼簿內容…",
+ "nativeResolution": "原生"
+}
diff --git a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
index 8c5045e6f9..a6c782a597 100644
--- a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
@@ -1,5 +1,5 @@
import { Stack } from "expo-router";
-import { ChevronDown, Ellipsis, Menu } from "lucide-react-native";
+import { ChevronDown, Ellipsis, Menu, Monitor } from "lucide-react-native";
import { Pressable, StyleSheet, View } from "react-native";
import { Text } from "@/components/AppText";
import {
@@ -17,7 +17,7 @@ import {
useThemedStyles,
type ThemeColors,
} from "@/theme";
-import { lineHeight, spacing } from "@/theme/tokens";
+import { lineHeight, radius, spacing } from "@/theme/tokens";
/**
* 首页 iOS 顶栏走系统 UINavigationBar。
@@ -31,6 +31,8 @@ export function HomeNativeStackHeader({
onOpenDeviceMenu,
onOpenDisplaySettings,
onOpenMenu,
+ onOpenRemoteDesktop,
+ remoteDesktopA11y,
onSelectScope,
scopeActions,
showRemoteGuide,
@@ -44,6 +46,8 @@ export function HomeNativeStackHeader({
onOpenDeviceMenu(): void;
onOpenDisplaySettings(): void;
onOpenMenu(): void;
+ onOpenRemoteDesktop?: () => void;
+ remoteDesktopA11y: string;
onSelectScope(id: string): void;
scopeActions: readonly NativePullDownAction[];
showRemoteGuide: boolean;
@@ -109,10 +113,10 @@ export function HomeNativeStackHeader({
<Stack.Toolbar placement="left">
<Stack.Toolbar.View>
<Pressable
- accessibilityLabel={menuA11y}
accessibilityRole="button"
- onPress={onOpenMenu}
style={({ pressed }) => [styles.iconHit, pressed && styles.pressed]}
+ accessibilityLabel={menuA11y}
+ onPress={onOpenMenu}
testID="home.chromeMenu"
>
<Menu
@@ -126,27 +130,49 @@ export function HomeNativeStackHeader({
{showRemoteGuide ? null : (
<Stack.Toolbar placement="right">
<Stack.Toolbar.View>
- <NativePullDownMenu
- actions={displayActions}
- onAction={onDisplayAction}
- >
- <Pressable
- accessibilityLabel={displayA11y}
- accessibilityRole="button"
- onPress={nativeMenus ? () => undefined : onOpenDisplaySettings}
- style={({ pressed }) => [
- styles.iconHit,
- pressed && styles.pressed,
- ]}
- testID="home.displaySettingsButton"
+ <View style={styles.trailingActions}>
+ {onOpenRemoteDesktop ? (
+ <Pressable
+ accessibilityRole="button"
+ style={({ pressed }) => [
+ styles.iconHit,
+ pressed && styles.pressed,
+ ]}
+ accessibilityLabel={remoteDesktopA11y}
+ onPress={onOpenRemoteDesktop}
+ testID="home.remoteDesktopButton"
+ >
+ <Monitor
+ color={colors.textPrimary}
+ size={iconSize.xl}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ ) : null}
+ <NativePullDownMenu
+ actions={displayActions}
+ onAction={onDisplayAction}
>
- <Ellipsis
- color={colors.textPrimary}
- size={iconSize.xl}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
- </NativePullDownMenu>
+ <Pressable
+ accessibilityRole="button"
+ style={({ pressed }) => [
+ styles.iconHit,
+ pressed && styles.pressed,
+ ]}
+ accessibilityLabel={displayA11y}
+ onPress={
+ nativeMenus ? () => undefined : onOpenDisplaySettings
+ }
+ testID="home.displaySettingsButton"
+ >
+ <Ellipsis
+ color={colors.textPrimary}
+ size={iconSize.xl}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ </NativePullDownMenu>
+ </View>
</Stack.Toolbar.View>
</Stack.Toolbar>
)}
@@ -156,11 +182,16 @@ export function HomeNativeStackHeader({
const makeStyles = (colors: ThemeColors) =>
StyleSheet.create({
+ trailingActions: {
+ flexDirection: "row",
+ alignItems: "center",
+ },
iconHit: {
alignItems: "center",
- height: 44,
justifyContent: "center",
+ height: 44,
width: 44,
+ borderRadius: radius.pill,
},
pressed: { opacity: 0.72 },
title: {
diff --git a/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx b/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx
index 56dd9c426f..6d0430c255 100644
--- a/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx
+++ b/apps/mobile/src/platform/chrome/NativePullDownMenu.tsx
@@ -1,12 +1,15 @@
import { MenuView, type MenuAction } from "@react-native-menu/menu";
import { type ReactNode } from "react";
import { NativeModules, Platform, UIManager } from "react-native";
+import { useTheme } from "@/theme";
export type NativePullDownAction = {
disabled?: boolean;
destructive?: boolean;
displayInline?: boolean;
id: string;
+ /** iOS SF Symbol name. */
+ image?: string;
keepPresented?: boolean;
preferredElementSize?: "small" | "medium" | "large";
state?: "on" | "off" | "mixed";
@@ -26,10 +29,12 @@ export function usesNativePullDownMenu(): boolean {
return nativePullDownAvailable;
}
-function toMenuAction(action: NativePullDownAction): MenuAction {
+function toMenuAction(action: NativePullDownAction, imageColor: string): MenuAction {
return {
id: action.id,
title: action.title,
+ // Menu 2.0 Fabric forwards an omitted imageColor as transparent (0).
+ ...(action.image ? { image: action.image, imageColor } : {}),
...(action.subtitle ? { subtitle: action.subtitle } : {}),
...(action.state ? { state: action.state } : {}),
...(action.displayInline ? { displayInline: true } : {}),
@@ -46,7 +51,7 @@ function toMenuAction(action: NativePullDownAction): MenuAction {
}
: {}),
...(action.subactions?.length
- ? { subactions: action.subactions.map(toMenuAction) }
+ ? { subactions: action.subactions.map((child) => toMenuAction(child, imageColor)) }
: {}),
};
}
@@ -68,10 +73,11 @@ export function NativePullDownMenu({
onAction(id: string): void;
testID?: string;
}) {
+ const { colors } = useTheme();
if (!usesNativePullDownMenu()) return children;
return (
<MenuView
- actions={actions.map(toMenuAction)}
+ actions={actions.map((action) => toMenuAction(action, colors.textPrimary))}
onPressAction={({ nativeEvent }) => {
if (nativeEvent.event) onAction(nativeEvent.event);
}}
diff --git a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
index 4d88572651..07c22941a2 100644
--- a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
@@ -1,4 +1,5 @@
import { Stack } from "expo-router";
+import type { ReactNode } from "react";
import { Platform, StyleSheet, View } from "react-native";
import type { Edge } from "react-native-safe-area-context";
import { Text } from "@/components/AppText";
@@ -33,6 +34,7 @@ export function simpleScreenSafeAreaEdges(): readonly Edge[] | undefined {
export function SimpleStackHeader({
action,
+ right,
backTestID,
eyebrow,
onBack,
@@ -41,6 +43,7 @@ export function SimpleStackHeader({
titleTestID,
}: {
action?: MainWindowAction;
+ right?: ReactNode;
backTestID?: string;
eyebrow?: string;
onBack?: () => void;
@@ -55,6 +58,7 @@ export function SimpleStackHeader({
return (
<ScreenHeader
action={action}
+ right={right}
backTestID={backTestID}
eyebrow={eyebrow}
onBack={onBack}
@@ -89,7 +93,7 @@ export function SimpleStackHeader({
/>
)
: undefined,
- headerRight: action
+ headerRight: right ? () => right : action
? () => <MainWindowActionButton action={action} density="compact" />
: undefined,
}}
diff --git a/apps/mobile/src/remote-desktop/PermissionGuide.tsx b/apps/mobile/src/remote-desktop/PermissionGuide.tsx
new file mode 100644
index 0000000000..4cfdecba52
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/PermissionGuide.tsx
@@ -0,0 +1,175 @@
+import { useEffect, useRef, useState } from "react";
+import { AppState, Pressable, StyleSheet, View } from "react-native";
+import { useTranslation } from "react-i18next";
+import {
+ desktopPermissionReady,
+ type RemoteDesktopPermissions,
+ type RemoteDesktopRequest,
+} from "@cindy/device-link";
+import { Text } from "@/components/AppText";
+import {
+ spacing,
+ radius,
+ typeScale,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+
+export function PermissionGuide({
+ initial,
+ request,
+ reconnect,
+}: {
+ initial?: RemoteDesktopPermissions;
+ request<T>(message: RemoteDesktopRequest): Promise<T>;
+ reconnect(): void;
+}) {
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const [status, setStatus] = useState(initial);
+ const [pending, setPending] = useState(false);
+ const [notice, setNotice] = useState<string | null>(null);
+ const mounted = useRef(false);
+ useEffect(() => {
+ mounted.current = true;
+ if (!initial)
+ return () => {
+ mounted.current = false;
+ };
+ let busy = false;
+ const refresh = async () => {
+ if (busy || AppState.currentState !== "active") return;
+ busy = true;
+ try {
+ const next = await request<RemoteDesktopPermissions>({
+ op: "permissions",
+ action: "check",
+ });
+ if (mounted.current) {
+ setStatus(next);
+ setNotice((previous) =>
+ previous === "permissionCheckFailed" ? null : previous,
+ );
+ }
+ } catch {
+ if (mounted.current) setNotice("permissionCheckFailed");
+ } finally {
+ busy = false;
+ }
+ };
+ void refresh();
+ const timer = setInterval(() => {
+ void refresh();
+ }, 2000);
+ return () => {
+ mounted.current = false;
+ clearInterval(timer);
+ };
+ }, [initial, request]);
+ const guide = async () => {
+ if (pending) return;
+ setPending(true);
+ setNotice(null);
+ try {
+ const next = await request<RemoteDesktopPermissions>({
+ op: "permissions",
+ action: "guide",
+ });
+ if (mounted.current) {
+ setStatus(next);
+ setNotice("permissionGuideOpened");
+ }
+ } catch {
+ if (mounted.current) setNotice("permissionActionFailed");
+ } finally {
+ if (mounted.current) setPending(false);
+ }
+ };
+ const ready =
+ status &&
+ desktopPermissionReady(status.screenRecording) &&
+ desktopPermissionReady(status.accessibility);
+ return (
+ <View style={styles.panel}>
+ <Text style={styles.text}>
+ {t(
+ ready
+ ? "remoteDesktop.permissionsReady"
+ : "remoteDesktop.permissionsIntro",
+ )}
+ </Text>
+ {status &&
+ (["screenRecording", "accessibility"] as const).map((permission) => (
+ <View style={styles.row} key={permission}>
+ <Text style={styles.text}>{t(`remoteDesktop.${permission}`)}</Text>
+ <Text style={styles.caption}>
+ {t(
+ desktopPermissionReady(status[permission])
+ ? "remoteDesktop.permissionGranted"
+ : status[permission] === "unknown"
+ ? "remoteDesktop.permissionUnknown"
+ : "remoteDesktop.permissionMissing",
+ )}
+ </Text>
+ </View>
+ ))}
+ <View style={styles.actions}>
+ {status && !ready && (
+ <Pressable
+ accessibilityRole="button"
+ disabled={pending}
+ onPress={() => {
+ void guide();
+ }}
+ style={styles.button}
+ >
+ <Text style={styles.text}>
+ {t(
+ pending
+ ? "remoteDesktop.permissionChecking"
+ : "remoteDesktop.openGuideOnComputer",
+ )}
+ </Text>
+ </Pressable>
+ )}
+ <Pressable
+ accessibilityRole="button"
+ onPress={reconnect}
+ style={styles.button}
+ >
+ <Text style={styles.text}>
+ {t("remoteDesktop.reconnectAfterPermissions")}
+ </Text>
+ </Pressable>
+ </View>
+ {notice && (
+ <Text accessibilityRole="alert" style={styles.caption}>
+ {t(`remoteDesktop.${notice}`)}
+ </Text>
+ )}
+ </View>
+ );
+}
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ panel: {
+ padding: spacing.md,
+ gap: spacing.sm,
+ backgroundColor: colors.surface,
+ },
+ row: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ gap: spacing.sm,
+ },
+ actions: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },
+ button: {
+ minHeight: 44,
+ justifyContent: "center",
+ paddingHorizontal: spacing.md,
+ borderRadius: radius.control,
+ backgroundColor: colors.surfaceElevated,
+ },
+ text: { fontSize: typeScale.body, color: colors.textPrimary },
+ caption: { fontSize: typeScale.caption, color: colors.textSecondary },
+ });
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx
new file mode 100644
index 0000000000..cf921ebab0
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx
@@ -0,0 +1,45 @@
+import { Host } from "@expo/ui";
+import { Button } from "@expo/ui/swift-ui";
+import {
+ buttonBorderShape,
+ buttonStyle,
+ controlSize,
+ frame,
+ labelStyle,
+} from "@expo/ui/swift-ui/modifiers";
+import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
+import { useTheme } from "@/theme";
+
+export function RemoteDesktopBackButton({
+ label,
+ onPress,
+}: {
+ label: string;
+ onPress(): void;
+}) {
+ const { colors, mode } = useTheme();
+ const liquidGlass = useLiquidGlassAvailable();
+
+ return (
+ <Host
+ colorScheme={mode}
+ seedColor={colors.textPrimary}
+ ignoreSafeArea="all"
+ style={{ width: 44, height: 44 }}
+ >
+ <Button
+ label={label}
+ systemImage="chevron.backward"
+ onPress={onPress}
+ testID="remoteDesktop.back"
+ modifiers={[
+ labelStyle("iconOnly"),
+ buttonStyle(liquidGlass ? "glass" : "bordered"),
+ buttonBorderShape("circle"),
+ controlSize("large"),
+ frame({ width: 44, height: 44 }),
+ ]}
+ />
+ </Host>
+ );
+}
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx
new file mode 100644
index 0000000000..507ccd9539
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx
@@ -0,0 +1,33 @@
+import { ChevronLeft } from "lucide-react-native";
+import { Pressable, StyleSheet } from "react-native";
+import { useTheme, iconSize } from "@/theme";
+
+export function RemoteDesktopBackButton({
+ label,
+ onPress,
+}: {
+ label: string;
+ onPress(): void;
+}) {
+ const { colors } = useTheme();
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={label}
+ onPress={onPress}
+ testID="remoteDesktop.back"
+ style={styles.button}
+ >
+ <ChevronLeft size={iconSize.xl} color={colors.textPrimary} />
+ </Pressable>
+ );
+}
+
+const styles = StyleSheet.create({
+ button: {
+ width: 44,
+ height: 44,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+});
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx
new file mode 100644
index 0000000000..9daf904c47
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx
@@ -0,0 +1,263 @@
+import type { ReactNode } from "react";
+import { Pressable, ScrollView, StyleSheet, View } from "react-native";
+import {
+ Keyboard,
+ SlidersHorizontal,
+ X,
+ type LucideIcon,
+} from "lucide-react-native";
+import { AllWindowsIcon, ShowDesktopIcon } from "./RemoteDesktopIcons";
+import { useTranslation } from "react-i18next";
+import { Text } from "@/components/AppText";
+import {
+ iconSize,
+ iconStroke,
+ fontWeight,
+ radius,
+ spacing,
+ typeScale,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+
+export function RemoteDesktopToolbar({
+ landscape,
+ canControl,
+ keyboard,
+ operations,
+ onWindows,
+ onDesktop,
+ onKeyboard,
+ onOperations,
+}: {
+ landscape: boolean;
+ canControl: boolean;
+ keyboard: boolean;
+ operations: boolean;
+ onWindows(): void;
+ onDesktop(): void;
+ onKeyboard(): void;
+ onOperations(): void;
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ const actions: Array<{
+ key: string;
+ icon: LucideIcon;
+ press(): void;
+ selected?: boolean;
+ disabled?: boolean;
+ }> = [
+ {
+ key: "allWindows",
+ icon: AllWindowsIcon,
+ press: onWindows,
+ disabled: !canControl,
+ },
+ {
+ key: "showDesktop",
+ icon: ShowDesktopIcon,
+ press: onDesktop,
+ disabled: !canControl,
+ },
+ {
+ key: "keyboard",
+ icon: Keyboard,
+ press: onKeyboard,
+ selected: keyboard,
+ disabled: !canControl,
+ },
+ {
+ key: "operations",
+ icon: SlidersHorizontal,
+ press: onOperations,
+ selected: operations,
+ },
+ ];
+ return (
+ <View
+ style={[styles.toolbar, landscape && styles.rail]}
+ testID="remoteDesktop.toolbar"
+ >
+ {(landscape ? [...actions].reverse() : actions).map(
+ ({ key, icon: Icon, press, selected, disabled }) => (
+ <Pressable
+ key={key}
+ testID={`remoteDesktop.${key}`}
+ accessibilityRole="button"
+ accessibilityLabel={t(`remoteDesktop.${key}`)}
+ accessibilityState={{ selected, disabled }}
+ disabled={disabled}
+ onPress={press}
+ style={({ pressed }) => [
+ styles.tool,
+ landscape && styles.railTool,
+ (pressed || selected) && styles.selected,
+ disabled && styles.disabled,
+ ]}
+ >
+ <Icon
+ size={iconSize.action}
+ strokeWidth={iconStroke.regular}
+ color={colors.textPrimary}
+ />
+ <Text numberOfLines={2} style={styles.label}>
+ {t(`remoteDesktop.${key}`)}
+ </Text>
+ </Pressable>
+ ),
+ )}
+ </View>
+ );
+}
+
+// Keep the panel inside the viewport so it can anchor at the bottom or right
+// without covering the four tools or resizing the remote desktop underneath it.
+export function RemoteDesktopPanel({
+ landscape,
+ topInset,
+ title,
+ caption,
+ onClose,
+ children,
+ footer,
+}: {
+ landscape: boolean;
+ topInset: number;
+ title: string;
+ caption: string;
+ onClose(): void;
+ children: ReactNode;
+ footer?: ReactNode;
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ return (
+ <View
+ style={StyleSheet.absoluteFill}
+ testID="remoteDesktop.operationsPanel"
+ >
+ <Pressable
+ style={StyleSheet.absoluteFill}
+ onPress={onClose}
+ accessibilityLabel={t("remoteDesktop.close")}
+ accessibilityRole="button"
+ />
+ <View
+ accessibilityViewIsModal
+ style={[
+ styles.panel,
+ landscape ? styles.sidePanel : styles.bottomPanel,
+ { top: landscape ? topInset : undefined },
+ ]}
+ >
+ <View style={styles.panelHeader}>
+ <View style={styles.heading}>
+ <Text numberOfLines={1} style={styles.title}>
+ {title}
+ </Text>
+ <Text numberOfLines={1} style={styles.caption}>
+ {caption}
+ </Text>
+ </View>
+ <Pressable
+ onPress={onClose}
+ accessibilityRole="button"
+ accessibilityLabel={t("remoteDesktop.close")}
+ style={styles.close}
+ >
+ <X
+ size={iconSize.action}
+ strokeWidth={iconStroke.regular}
+ color={colors.textPrimary}
+ />
+ </Pressable>
+ </View>
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ showsVerticalScrollIndicator={false}
+ contentContainerStyle={styles.panelContent}
+ >
+ {children}
+ </ScrollView>
+ {footer && <View style={styles.panelFooter}>{footer}</View>}
+ </View>
+ </View>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ toolbar: { flexDirection: "row", padding: spacing.xs, gap: spacing.xs },
+ rail: {
+ flexDirection: "column",
+ flex: 1,
+ width: 64,
+ justifyContent: "space-around",
+ },
+ tool: {
+ flex: 1,
+ minHeight: 56,
+ minWidth: 44,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: spacing.xs,
+ borderRadius: radius.control,
+ padding: spacing.xs,
+ },
+ railTool: { flex: 0, width: "100%" },
+ label: {
+ color: colors.textPrimary,
+ fontSize: typeScale.caption,
+ textAlign: "center",
+ },
+ selected: { backgroundColor: colors.surfaceChip },
+ disabled: { opacity: 0.4 },
+ panel: {
+ position: "absolute",
+ bottom: 0,
+ right: 0,
+ backgroundColor: colors.sheetSurface,
+ borderTopLeftRadius: radius.container,
+ borderLeftWidth: StyleSheet.hairlineWidth,
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.sheetActionBorder,
+ overflow: "hidden",
+ },
+ bottomPanel: {
+ left: 0,
+ maxHeight: "72%",
+ borderTopRightRadius: radius.container,
+ },
+ sidePanel: { width: "48%", minWidth: 280, maxWidth: 360 },
+ panelHeader: {
+ flexDirection: "row",
+ alignItems: "center",
+ paddingHorizontal: spacing.md,
+ paddingVertical: spacing.sm,
+ gap: spacing.sm,
+ },
+ heading: { flex: 1, gap: spacing.xs },
+ title: {
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.semibold,
+ },
+ caption: { color: colors.textTertiary, fontSize: typeScale.caption },
+ close: {
+ width: 44,
+ height: 44,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ panelContent: { padding: spacing.md, paddingTop: 0, gap: spacing.md },
+ panelFooter: {
+ paddingHorizontal: spacing.md,
+ paddingVertical: spacing.xs,
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: colors.sheetActionBorder,
+ },
+ });
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx
new file mode 100644
index 0000000000..f202bedd83
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx
@@ -0,0 +1,237 @@
+import { useEffect, useRef, useState } from "react";
+import {
+ ActivityIndicator,
+ Alert,
+ Modal,
+ Pressable,
+ StyleSheet,
+ View,
+} from "react-native";
+import { ClipboardList, Check } from "lucide-react-native";
+import { useTranslation } from "react-i18next";
+import {
+ NativePullDownMenu,
+ usesNativePullDownMenu,
+} from "@/platform/chrome/NativePullDownMenu";
+import { Text } from "@/components/AppText";
+import { useTheme, radius, iconSize, iconStroke, spacing } from "@/theme";
+
+export function RemoteDesktopClipboardButton({
+ enabled,
+ supported,
+ transfer,
+}: {
+ enabled: boolean;
+ supported: boolean;
+ transfer(action: "copy" | "paste"): Promise<void>;
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const [busy, setBusy] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [failure, setFailure] = useState<string | null>(null);
+ const loadingVisible = useRef(false);
+ const loadingTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const [done, setDone] = useState(false);
+ const pending = useRef(false);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ if (loadingTimer.current) clearTimeout(loadingTimer.current);
+ };
+ }, []);
+ useEffect(() => {
+ if (!done) return;
+ const timer = setTimeout(() => setDone(false), 1800);
+ return () => clearTimeout(timer);
+ }, [done]);
+ const run = async (action: string) => {
+ if (
+ !enabled ||
+ pending.current ||
+ (action !== "copy" && action !== "paste")
+ )
+ return;
+ if (!supported) {
+ Alert.alert(
+ t("remoteDesktop.clipboard"),
+ t("remoteDesktop.clipboardUpgrade"),
+ );
+ return;
+ }
+ pending.current = true;
+ setBusy(true);
+ setDone(false);
+ loadingTimer.current = setTimeout(() => {
+ if (!mounted.current || !pending.current) return;
+ loadingVisible.current = true;
+ setLoading(true);
+ }, 400);
+ try {
+ await transfer(action);
+ if (mounted.current) setDone(true);
+ } catch (error) {
+ if (mounted.current) {
+ const message = t(
+ error instanceof Error && error.message.includes("CLIPBOARD_UPGRADE")
+ ? "remoteDesktop.clipboardUpgrade"
+ : error instanceof Error && error.message.includes("CLIPBOARD_UNSUPPORTED")
+ ? "remoteDesktop.clipboardUnsupported"
+ : error instanceof Error && error.message.includes("CLIPBOARD_EMPTY")
+ ? "remoteDesktop.clipboardEmpty"
+ : error instanceof Error && error.message.includes("CLIPBOARD_TOO_LONG")
+ ? "remoteDesktop.clipboardTooLong"
+ : action === "copy"
+ ? "remoteDesktop.clipboardCopyFailed"
+ : "remoteDesktop.clipboardPasteFailed",
+ );
+ // Keep errors in the same presented modal; presenting Alert during its
+ // dismissal can lose the error on iOS.
+ if (loadingVisible.current) setFailure(message);
+ else Alert.alert(t("remoteDesktop.clipboard"), message);
+ }
+ } finally {
+ pending.current = false;
+ if (loadingTimer.current) clearTimeout(loadingTimer.current);
+ loadingTimer.current = null;
+ loadingVisible.current = false;
+ if (mounted.current) {
+ setBusy(false);
+ setLoading(false);
+ }
+ }
+ };
+ const actions = [
+ {
+ id: "copy",
+ title: t("remoteDesktop.copyToPhone"),
+ image: "doc.on.doc",
+ disabled: !enabled || busy,
+ },
+ {
+ id: "paste",
+ title: t("remoteDesktop.pasteFromPhone"),
+ image: "doc.on.clipboard",
+ disabled: !enabled || busy,
+ },
+ ];
+ return (
+ <>
+ <NativePullDownMenu
+ actions={actions}
+ onAction={(action) => {
+ void run(action);
+ }}
+ >
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t("remoteDesktop.clipboard")}
+ accessibilityState={{ disabled: !enabled || busy, busy }}
+ disabled={!enabled || busy}
+ onPress={
+ usesNativePullDownMenu()
+ ? undefined
+ : () =>
+ Alert.alert(t("remoteDesktop.clipboard"), undefined, [
+ ...actions.map((action) => ({
+ text: action.title,
+ onPress: () => {
+ void run(action.id);
+ },
+ })),
+ { text: t("remoteDesktop.close"), style: "cancel" },
+ ])
+ }
+ style={({ pressed }) => [
+ styles.button,
+ {
+ borderRadius: radius.pill,
+ backgroundColor: pressed ? colors.surfaceChip : "transparent",
+ opacity: enabled ? 1 : 0.4,
+ },
+ ]}
+ >
+ {busy ? (
+ <ActivityIndicator size="small" color={colors.textPrimary} />
+ ) : done ? (
+ <View accessibilityLabel={t("remoteDesktop.clipboardDone")}>
+ <Check size={iconSize.action} strokeWidth={iconStroke.regular} color={colors.textPrimary} />
+ </View>
+ ) : (
+ <ClipboardList size={iconSize.action} strokeWidth={iconStroke.regular} color={colors.textPrimary} />
+ )}
+ </Pressable>
+ </NativePullDownMenu>
+ <Modal
+ transparent
+ animationType="none"
+ visible={loading || failure !== null}
+ onRequestClose={() => { if (!pending.current) setFailure(null); }}
+ supportedOrientations={["portrait", "landscape"]}
+ statusBarTranslucent
+ >
+ <View style={[styles.backdrop, { backgroundColor: colors.overlay }]}>
+ <View
+ accessibilityViewIsModal
+ accessibilityLiveRegion="polite"
+ accessibilityState={{ busy: loading }}
+ style={[styles.loadingCard, {
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ }]}
+ >
+ {loading && <ActivityIndicator size="large" color={colors.textPrimary} />}
+ <Text style={[styles.loadingText, { color: colors.textPrimary }]}>
+ {failure ?? t("remoteDesktop.clipboardTransferring")}
+ </Text>
+ {failure !== null && (
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => setFailure(null)}
+ style={({ pressed }) => [styles.dismiss, {
+ backgroundColor: pressed ? colors.surfaceElevated : colors.surfaceChip,
+ }]}
+ >
+ <Text style={{ color: colors.textPrimary }}>{t("remoteDesktop.close")}</Text>
+ </Pressable>
+ )}
+ </View>
+ </View>
+ </Modal>
+ </>
+ );
+}
+const styles = StyleSheet.create({
+ backdrop: {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center",
+ padding: spacing.lg,
+ },
+ loadingCard: {
+ width: 280,
+ maxWidth: "100%",
+ alignItems: "center",
+ gap: spacing.md,
+ padding: spacing.lg,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ },
+ loadingText: { textAlign: "center" },
+ dismiss: {
+ alignSelf: "stretch",
+ minHeight: 44,
+ alignItems: "center",
+ justifyContent: "center",
+ borderRadius: radius.pill,
+ paddingHorizontal: spacing.md,
+ },
+ button: {
+ width: 44,
+ height: 44,
+ justifyContent: "center",
+ alignItems: "center",
+ },
+});
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx
new file mode 100644
index 0000000000..4485d031d8
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx
@@ -0,0 +1,444 @@
+import { useState } from "react";
+import { Pressable, StyleSheet, View } from "react-native";
+import {
+ Check,
+ ChevronDown,
+ ChevronRight,
+ Eye,
+ RotateCw,
+ Volume2,
+ PictureInPicture2,
+ ChevronLeft,
+ LogOut,
+ Monitor,
+ type LucideIcon,
+} from "lucide-react-native";
+import { useTranslation } from "react-i18next";
+import type {
+ RemoteDesktopDisplay,
+ RemoteDesktopVideoSettings,
+ RemoteDesktopDisplayMode,
+} from "@cindy/device-link";
+import { RemoteDesktopDisplaySettings } from "./RemoteDesktopDisplaySettings";
+import { Text } from "@/components/AppText";
+import { MainWindowOptionButton } from "@/components/MobilePrimitives";
+import { NativeSwitch } from "@/platform/chrome/NativeSwitch";
+import {
+ fontWeight,
+ iconSize,
+ iconStroke,
+ radius,
+ spacing,
+ typeScale,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+
+export function RemoteDesktopControls({
+ connected,
+ controlling,
+ controlDisabled,
+ inputMode,
+ displays,
+ displayId,
+ onViewOnly,
+ onInputMode,
+ showMouseButtons,
+ onShowMouseButtons,
+ onDisplay,
+ presentation,
+ video,
+}: {
+ connected: boolean;
+ controlling: boolean;
+ controlDisabled: boolean;
+ inputMode: "touch" | "pointer";
+ displays: RemoteDesktopDisplay[];
+ displayId?: string;
+ onViewOnly(): void;
+ onInputMode(mode: "touch" | "pointer"): void;
+ showMouseButtons: boolean;
+ onShowMouseButtons(value: boolean): void;
+ onDisplay(id: string): void;
+ presentation: {
+ canRotate: boolean;
+ canPip: boolean;
+ canAudio: boolean;
+ onRotate(): void;
+ onPip(): void;
+ };
+ video: {
+ supported: boolean;
+ settings: RemoteDesktopVideoSettings;
+ busy: boolean;
+ modesSupported: boolean;
+ notice: string | null;
+ onChange(settings: RemoteDesktopVideoSettings): void;
+ readModes(): Promise<RemoteDesktopDisplayMode[]>;
+ onResolution(id: string): Promise<void>;
+ };
+}) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ const [showDisplays, setShowDisplays] = useState(false);
+ const [displaySettings, setDisplaySettings] = useState(false);
+ const currentDisplay = displays.find((display) => display.id === displayId);
+ const canChooseDisplay = connected && displays.length > 1;
+ const hint = !controlling ? "viewOnlyHint" : `${inputMode}Hint`;
+ const displayLabel = (display: RemoteDesktopDisplay, index: number) =>
+ display.name?.trim() ||
+ t("remoteDesktop.displayNumber", { number: index + 1 });
+ const quickActions: Array<{
+ key: string;
+ icon: LucideIcon;
+ onPress(): void;
+ disabled?: boolean;
+ selected?: boolean;
+ }> = [
+ {
+ key: "rotate",
+ icon: RotateCw,
+ onPress: presentation.onRotate,
+ disabled: !presentation.canRotate,
+ },
+ {
+ key: "sound",
+ icon: Volume2,
+ onPress: () =>
+ video.onChange({ ...video.settings, audio: !video.settings.audio }),
+ disabled: !presentation.canAudio || video.busy || !connected,
+ selected: video.settings.audio,
+ },
+ {
+ key: "viewOnly",
+ icon: Eye,
+ onPress: onViewOnly,
+ disabled: controlDisabled,
+ selected: connected && !controlling,
+ },
+ {
+ key: "smallWindow",
+ icon: PictureInPicture2,
+ onPress: presentation.onPip,
+ disabled: !presentation.canPip || !connected,
+ },
+ ];
+
+ return (
+ <>
+ {!displaySettings && (
+ <View style={styles.quickActions}>
+ {quickActions.map(
+ ({ key, icon: Icon, onPress, disabled, selected }) => (
+ <Pressable
+ key={key}
+ testID={`remoteDesktop.${key}`}
+ accessibilityRole="button"
+ accessibilityLabel={t(`remoteDesktop.${key}`)}
+ accessibilityState={{ disabled, selected }}
+ disabled={disabled}
+ onPress={onPress}
+ style={({ pressed }) => [
+ styles.quickAction,
+ selected && styles.quickSelected,
+ pressed && styles.pressed,
+ disabled && styles.disabled,
+ ]}
+ >
+ <Icon
+ size={iconSize.action}
+ strokeWidth={iconStroke.regular}
+ color={selected ? colors.ctaText : colors.textPrimary}
+ />
+ <Text
+ style={[
+ styles.quickLabel,
+ selected && styles.quickSelectedLabel,
+ ]}
+ >
+ {t(`remoteDesktop.${key}`)}
+ </Text>
+ </Pressable>
+ ),
+ )}
+ </View>
+ )}
+
+ {!displaySettings && (
+ <View style={styles.section}>
+ <Text style={styles.sectionTitle}>
+ {t("remoteDesktop.inputMode")}
+ </Text>
+ <View style={styles.segments}>
+ {(["touch", "pointer"] as const).map((value) => (
+ <MainWindowOptionButton
+ key={value}
+ label={t(`remoteDesktop.${value}`)}
+ testID={`remoteDesktop.${value}`}
+ variant="segmented"
+ density="default"
+ selected={inputMode === value}
+ disabled={!connected}
+ onPress={() => onInputMode(value)}
+ style={styles.segment}
+ />
+ ))}
+ </View>
+ <Text style={styles.hint}>{t(`remoteDesktop.${hint}`)}</Text>
+ <View style={styles.row}>
+ <Text style={[styles.rowTitle, styles.expand]}>
+ {t("remoteDesktop.showMouseButtons")}
+ </Text>
+ <NativeSwitch
+ accessibilityLabel={t("remoteDesktop.showMouseButtons")}
+ testID="remoteDesktop.showMouseButtons"
+ value={showMouseButtons}
+ onValueChange={onShowMouseButtons}
+ />
+ </View>
+ </View>
+ )}
+ {video.notice && (
+ <Text style={styles.hint} accessibilityRole="alert">
+ {video.notice}
+ </Text>
+ )}
+ {!displaySettings && (
+ <Pressable
+ onPress={() => setDisplaySettings(true)}
+ style={styles.row}
+ accessibilityRole="button"
+ >
+ <Monitor size={iconSize.action} color={colors.textPrimary} />
+ <View style={styles.displayText}>
+ <Text style={styles.rowTitle}>
+ {t("remoteDesktop.displaySettings")}
+ </Text>
+ {currentDisplay && (
+ <Text style={styles.hint}>
+ {currentDisplay.width} × {currentDisplay.height}
+ </Text>
+ )}
+ </View>
+ <ChevronRight size={iconSize.md} color={colors.textTertiary} />
+ </Pressable>
+ )}
+ {displaySettings && (
+ <>
+ <View style={styles.row}>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t("remoteDesktop.back")}
+ onPress={() => setDisplaySettings(false)}
+ style={{ padding: spacing.sm }}
+ >
+ <ChevronLeft size={iconSize.action} color={colors.textPrimary} />
+ </Pressable>
+ <Text style={styles.rowTitle}>
+ {t("remoteDesktop.displaySettings")}
+ </Text>
+ </View>
+ <RemoteDesktopDisplaySettings
+ key={displayId}
+ video={video}
+ connected={connected}
+ controlling={controlling}
+ displayControl={
+ <View>
+ {displays.length > 0 && (
+ <>
+ <Pressable
+ testID="remoteDesktop.display"
+ accessibilityRole={canChooseDisplay ? "button" : "text"}
+ accessibilityLabel={t("remoteDesktop.display")}
+ accessibilityState={
+ canChooseDisplay
+ ? { expanded: showDisplays }
+ : undefined
+ }
+ disabled={!canChooseDisplay}
+ onPress={() => setShowDisplays(!showDisplays)}
+ style={({ pressed }) => [
+ styles.row,
+ pressed && styles.pressed,
+ ]}
+ >
+ <Monitor
+ size={iconSize.action}
+ color={colors.textPrimary}
+ strokeWidth={iconStroke.regular}
+ />
+ <View style={styles.displayText}>
+ <Text style={styles.rowTitle}>
+ {currentDisplay
+ ? displayLabel(
+ currentDisplay,
+ displays.indexOf(currentDisplay),
+ )
+ : t("remoteDesktop.display")}
+ </Text>
+ </View>
+ {canChooseDisplay &&
+ (showDisplays ? (
+ <ChevronDown
+ size={iconSize.md}
+ color={colors.textTertiary}
+ />
+ ) : (
+ <ChevronRight
+ size={iconSize.md}
+ color={colors.textTertiary}
+ />
+ ))}
+ </Pressable>
+ {canChooseDisplay &&
+ showDisplays &&
+ displays.map((display, index) => (
+ <Pressable
+ key={display.id}
+ testID={`remoteDesktop.display.${display.id}`}
+ accessibilityRole="radio"
+ accessibilityLabel={displayLabel(display, index)}
+ accessibilityState={{
+ checked: display.id === displayId,
+ }}
+ onPress={() => {
+ if (display.id !== displayId) onDisplay(display.id);
+ }}
+ style={({ pressed }) => [
+ styles.displayOption,
+ pressed && styles.pressed,
+ ]}
+ >
+ <View style={styles.displayText}>
+ <Text style={styles.rowTitle}>
+ {displayLabel(display, index)}
+ </Text>
+ <Text style={styles.hint}>
+ {display.width} × {display.height}
+ </Text>
+ </View>
+ {display.id === displayId && (
+ <Check
+ size={iconSize.md}
+ color={colors.textPrimary}
+ />
+ )}
+ </Pressable>
+ ))}
+ </>
+ )}
+ </View>
+ }
+ />
+ </>
+ )}
+ </>
+ );
+}
+
+export function RemoteDesktopDisconnect({ onPress }: { onPress(): void }) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ return (
+ <Pressable
+ testID="remoteDesktop.disconnect"
+ accessibilityRole="button"
+ accessibilityLabel={t("remoteDesktop.disconnect")}
+ onPress={onPress}
+ style={({ pressed }) => [styles.disconnect, pressed && styles.pressed]}
+ >
+ <LogOut
+ size={iconSize.md}
+ color={colors.destructive}
+ strokeWidth={iconStroke.regular}
+ />
+ <Text style={styles.disconnectLabel}>
+ {t("remoteDesktop.disconnect")}
+ </Text>
+ </Pressable>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ quickActions: { flexDirection: "row", gap: spacing.sm },
+ quickAction: {
+ flex: 1,
+ minHeight: 80,
+ padding: spacing.sm,
+ gap: spacing.sm,
+ borderRadius: radius.container,
+ backgroundColor: colors.surfaceChip,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ quickSelected: { backgroundColor: colors.cta },
+ quickLabel: {
+ color: colors.textPrimary,
+ fontSize: typeScale.caption,
+ textAlign: "center",
+ },
+ quickSelectedLabel: { color: colors.ctaText },
+ section: { gap: spacing.sm },
+ sectionTitle: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ },
+ segments: {
+ flexDirection: "row",
+ gap: spacing.xs,
+ backgroundColor: colors.surfaceChip,
+ padding: spacing.xs,
+ borderRadius: radius.control,
+ },
+ segment: { flex: 1, minHeight: 44, borderRadius: radius.control },
+ hint: { color: colors.textTertiary, fontSize: typeScale.caption },
+ group: {
+ backgroundColor: colors.sheetActionSurface,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.sheetActionBorder,
+ overflow: "hidden",
+ },
+ row: {
+ minHeight: 58,
+ paddingHorizontal: spacing.md,
+ paddingVertical: spacing.sm,
+ flexDirection: "row",
+ alignItems: "center",
+ gap: spacing.sm,
+ },
+ rowTitle: { color: colors.textPrimary, fontSize: typeScale.body },
+ expand: { flex: 1 },
+ divider: {
+ height: StyleSheet.hairlineWidth,
+ backgroundColor: colors.sheetActionBorder,
+ marginLeft: spacing.md,
+ },
+ displayText: { flex: 1, gap: spacing.xs },
+ displayOption: {
+ minHeight: 52,
+ paddingVertical: spacing.sm,
+ paddingLeft: spacing.xl,
+ paddingRight: spacing.md,
+ flexDirection: "row",
+ alignItems: "center",
+ gap: spacing.sm,
+ },
+ disconnect: {
+ minHeight: 44,
+ flexDirection: "row",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: spacing.sm,
+ borderRadius: radius.control,
+ },
+ disconnectLabel: { color: colors.destructive, fontSize: typeScale.body },
+ disabled: { opacity: 0.4 },
+ pressed: { opacity: 0.72 },
+ });
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx
new file mode 100644
index 0000000000..8d12230f66
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx
@@ -0,0 +1,269 @@
+import { useEffect, useState, type ReactNode } from "react";
+import { Platform, Pressable, StyleSheet, View } from "react-native";
+import SegmentedControl from "@expo/ui/community/segmented-control";
+import { Check, ChevronDown } from "lucide-react-native";
+import { useTranslation } from "react-i18next";
+import type {
+ RemoteDesktopDisplayMode,
+ RemoteDesktopVideoSettings,
+} from "@cindy/device-link";
+import { Text } from "@/components/AppText";
+import {
+ NativePullDownMenu,
+ usesNativePullDownMenu,
+} from "@/platform/chrome/NativePullDownMenu";
+import {
+ spacing,
+ radius,
+ typeScale,
+ iconSize,
+ fontWeight,
+ useTheme,
+} from "@/theme";
+
+type Props = {
+ video: {
+ supported: boolean;
+ settings: RemoteDesktopVideoSettings;
+ busy: boolean;
+ modesSupported: boolean;
+ onChange(settings: RemoteDesktopVideoSettings): void;
+ readModes(): Promise<RemoteDesktopDisplayMode[]>;
+ onResolution(id: string): Promise<void>;
+ };
+ connected: boolean;
+ controlling: boolean;
+ displayControl: ReactNode;
+};
+export function RemoteDesktopDisplaySettings({
+ video,
+ connected,
+ controlling,
+ displayControl,
+}: Props) {
+ const { t } = useTranslation();
+ const { colors, mode: colorScheme } = useTheme();
+ const [modes, setModes] = useState<RemoteDesktopDisplayMode[]>([]);
+ const [expanded, setExpanded] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [failure, setFailure] = useState(false);
+ const [reload, setReload] = useState(0);
+ useEffect(() => {
+ if (!connected || !video.modesSupported) return;
+ let active = true;
+ setLoading(true);
+ setFailure(false);
+ void video
+ .readModes()
+ .then((next) => {
+ if (active) setModes(next);
+ })
+ .catch(() => {
+ if (active) setFailure(true);
+ })
+ .finally(() => {
+ if (active) setLoading(false);
+ });
+ return () => {
+ active = false;
+ };
+ }, [connected, video.modesSupported, reload]);
+ const disabled = !connected || !video.supported || video.busy;
+ const title = { color: colors.textPrimary, fontSize: typeScale.body };
+ const hint = { color: colors.textTertiary, fontSize: typeScale.caption };
+ const segment = (label: string, selected: boolean, onPress: () => void) => (
+ <Pressable
+ key={label}
+ accessibilityRole="radio"
+ accessibilityState={{ checked: selected, disabled }}
+ disabled={disabled}
+ onPress={onPress}
+ style={({ pressed }) => [
+ {
+ flex: 1,
+ minHeight: 44,
+ borderRadius: radius.control,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: selected ? colors.cta : "transparent",
+ opacity: disabled ? 0.6 : pressed ? 0.85 : 1,
+ },
+ ]}
+ >
+ <Text
+ style={{
+ ...title,
+ color: selected ? colors.ctaText : colors.textPrimary,
+ fontWeight: selected ? fontWeight.semibold : fontWeight.medium,
+ }}
+ >
+ {label}
+ </Text>
+ </Pressable>
+ );
+ const segments = {
+ flexDirection: "row" as const,
+ padding: spacing.xs,
+ borderRadius: radius.control,
+ backgroundColor: colors.surfaceChip,
+ };
+ const segmented = (
+ values: string[],
+ selectedIndex: number,
+ onSelect: (index: number) => void,
+ ) =>
+ Platform.OS === "ios" ? (
+ <SegmentedControl
+ values={values}
+ selectedIndex={selectedIndex}
+ enabled={!disabled}
+ appearance={colorScheme}
+ style={{ minHeight: 44 }}
+ onChange={({ nativeEvent }) => {
+ const index = nativeEvent.selectedSegmentIndex;
+ if (!disabled && index >= 0 && index < values.length) onSelect(index);
+ }}
+ />
+ ) : (
+ <View style={segments}>
+ {values.map((label, index) =>
+ segment(label, index === selectedIndex, () => onSelect(index)),
+ )}
+ </View>
+ );
+ const fpsValues = [30, 60] as const;
+ const qualityValues = [0, 2000000, 8000000, 20000000] as const;
+ const current = modes.find((mode) => mode.current);
+ const modeLabel = (mode: RemoteDesktopDisplayMode) =>
+ `${mode.width} × ${mode.height}${mode.native === true ? ` · ${t("remoteDesktop.nativeResolution")}` : ""}`;
+ const chooseMode = (id: string) => {
+ const mode = modes.find((item) => item.id === id);
+ if (!mode || mode.current || !controlling || video.busy || !connected)
+ return;
+ void video
+ .onResolution(id)
+ .then(() => setExpanded(false))
+ .catch(() => {});
+ };
+ const nativeMenu =
+ usesNativePullDownMenu() &&
+ connected &&
+ video.modesSupported &&
+ !loading &&
+ !failure &&
+ !video.busy &&
+ modes.length > 0;
+ const resolutionTrigger = (
+ <Pressable
+ disabled={!connected || !video.modesSupported || loading || video.busy}
+ onPress={() =>
+ failure ? setReload(reload + 1) : !nativeMenu && setExpanded(!expanded)
+ }
+ style={styles.row}
+ accessibilityRole="button"
+ accessibilityState={{ expanded: nativeMenu ? undefined : expanded }}
+ >
+ <View style={{ flex: 1, gap: spacing.xs }}>
+ <Text style={title}>{t("remoteDesktop.resolution")}</Text>
+ <Text style={hint}>
+ {!video.modesSupported
+ ? t("remoteDesktop.settingUnsupported")
+ : loading
+ ? t("remoteDesktop.loadingSettings")
+ : failure
+ ? t("remoteDesktop.retrySettings")
+ : current
+ ? modeLabel(current)
+ : t("remoteDesktop.followComputer")}
+ </Text>
+ </View>
+ <ChevronDown size={iconSize.md} color={colors.textTertiary} />
+ </Pressable>
+ );
+ return (
+ <View style={{ gap: spacing.md }}>
+ <Text style={hint}>{t("remoteDesktop.frameRate")}</Text>
+ {segmented(
+ fpsValues.map((fps) => t("remoteDesktop.fps", { count: fps })),
+ fpsValues.indexOf(video.settings.fps),
+ (index) => video.onChange({ ...video.settings, fps: fpsValues[index] }),
+ )}
+ <Text style={hint}>{t("remoteDesktop.quality")}</Text>
+ {segmented(
+ ["automatic", "clear", "highDefinition", "original"].map((key) =>
+ t(`remoteDesktop.${key}`),
+ ),
+ qualityValues.indexOf(video.settings.bitrate),
+ (index) =>
+ video.onChange({ ...video.settings, bitrate: qualityValues[index] }),
+ )}
+ <Text style={hint}>{t("remoteDesktop.qualityHint")}</Text>
+ <View
+ style={{
+ backgroundColor: colors.surfaceChip,
+ borderRadius: radius.container,
+ padding: spacing.md,
+ gap: spacing.sm,
+ }}
+ >
+ {displayControl}
+ <View
+ style={{
+ height: StyleSheet.hairlineWidth,
+ backgroundColor: colors.border,
+ }}
+ />
+ {nativeMenu ? (
+ <NativePullDownMenu
+ actions={modes.map((mode) => ({
+ id: mode.id,
+ title: modeLabel(mode),
+ state: mode.current ? "on" : "off",
+ disabled: !controlling || mode.current,
+ }))}
+ onAction={chooseMode}
+ >
+ {resolutionTrigger}
+ </NativePullDownMenu>
+ ) : (
+ resolutionTrigger
+ )}
+ <Text style={hint}>{t("remoteDesktop.resolutionHint")}</Text>
+ {!controlling && (
+ <Text style={hint}>{t("remoteDesktop.resolutionControlHint")}</Text>
+ )}
+ {!nativeMenu &&
+ expanded &&
+ modes.map((mode) => (
+ <Pressable
+ key={mode.id}
+ disabled={!controlling || video.busy || mode.current}
+ accessibilityRole="radio"
+ accessibilityState={{ checked: mode.current }}
+ onPress={() => chooseMode(mode.id)}
+ style={({ pressed }) => [
+ styles.row,
+ { opacity: pressed ? 0.6 : !controlling ? 0.4 : 1 },
+ ]}
+ >
+ <Text style={[title, { flex: 1 }]}>{modeLabel(mode)}</Text>
+ {mode.current && (
+ <Check size={iconSize.md} color={colors.textPrimary} />
+ )}
+ </Pressable>
+ ))}
+ </View>
+ {!video.supported && (
+ <Text style={hint}>{t("remoteDesktop.settingUnsupported")}</Text>
+ )}
+ </View>
+ );
+}
+const styles = StyleSheet.create({
+ row: {
+ minHeight: 44,
+ flexDirection: "row",
+ alignItems: "center",
+ gap: spacing.sm,
+ },
+});
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx
new file mode 100644
index 0000000000..c3dbb22ba3
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx
@@ -0,0 +1,15 @@
+import { createLucideIcon } from "lucide-react-native";
+
+// Same 24-point grid and round line endings as the adjacent Lucide controls.
+// The rear window stops at the foreground outline instead of showing through it.
+export const AllWindowsIcon = createLucideIcon("RemoteDesktopAllWindows", [
+ ["path", { d: "M4 16a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v1", key: "rear" }],
+ ["rect", { x: "7", y: "8", width: "15", height: "13", rx: "2", key: "front" }],
+ ["path", { d: "M7 12h15", key: "titlebar" }],
+]);
+
+export const ShowDesktopIcon = createLucideIcon("RemoteDesktopShowDesktop", [
+ ["rect", { x: "2", y: "3", width: "20", height: "14", rx: "2", key: "screen" }],
+ ["path", { d: "M8 13h8", key: "dock" }],
+ ["path", { d: "M12 17v4M8 21h8", key: "stand" }],
+]);
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx
new file mode 100644
index 0000000000..35ee1ab200
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx
@@ -0,0 +1,68 @@
+import { StyleSheet, View } from "react-native";
+import { useTranslation } from "react-i18next";
+import { Text } from "@/components/AppText";
+import {
+ radius,
+ spacing,
+ typeScale,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+import { formatReceiveRate, type DesktopNetworkStats } from "./networkStats";
+
+export function RemoteDesktopNetworkStatus({
+ stats,
+ video,
+ top,
+}: {
+ stats: DesktopNetworkStats | null;
+ video: boolean;
+ top: number;
+}) {
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const transport = stats?.transport ?? (video ? "video" : "screenshots");
+ const label =
+ !stats && !video
+ ? "connecting"
+ : {
+ video: "live",
+ direct: "directConnection",
+ relay: "videoRelay",
+ screenshots: "screenshotRelay",
+ }[transport];
+ const latency = stats?.latencyMs;
+ return (
+ <View
+ pointerEvents="none"
+ style={[styles.badge, { top }]}
+ testID="remoteDesktop.network"
+ >
+ <Text style={styles.text}>{t(`remoteDesktop.${label}`)}</Text>
+ <Text style={styles.text}>
+ {`↓ ${formatReceiveRate(stats?.bytesPerSecond ?? null)}`}
+ {latency != null
+ ? ` · ${t(`remoteDesktop.${transport === "screenshots" ? "frameTime" : "roundTrip"}`, { ms: Math.round(latency) })}`
+ : ""}
+ </Text>
+ </View>
+ );
+}
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ badge: {
+ position: "absolute",
+ right: spacing.sm,
+ maxWidth: "75%",
+ paddingHorizontal: spacing.sm,
+ paddingVertical: spacing.xs,
+ borderRadius: radius.control,
+ backgroundColor: colors.surfaceTranslucent,
+ },
+ text: {
+ fontSize: typeScale.caption,
+ color: colors.textSecondary,
+ textAlign: "right",
+ fontVariant: ["tabular-nums"],
+ },
+ });
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
new file mode 100644
index 0000000000..938cc8f218
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -0,0 +1,1745 @@
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ComponentRef,
+} from "react";
+import {
+ AppState,
+ ActivityIndicator,
+ Dimensions,
+ StatusBar,
+ Keyboard,
+ KeyboardAvoidingView,
+ Platform,
+ Pressable,
+ ScrollView,
+ StyleSheet,
+ View,
+ useWindowDimensions,
+} from "react-native";
+import {
+ Stack,
+ useLocalSearchParams,
+ useRouter,
+ useIsFocused,
+} from "expo-router";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { WebView, type WebViewMessageEvent } from "react-native-webview";
+import { transferClipboardContent } from "./clipboardTransfer";
+import * as Clipboard from "expo-clipboard";
+import { RemoteDesktopClipboardButton } from "./RemoteDesktopClipboardButton";
+import { X } from "lucide-react-native";
+import { useTranslation } from "react-i18next";
+import {
+ REMOTE_DESKTOP_CHANNEL,
+ isRemoteDesktopCursor,
+ type RemoteDesktopCursor,
+ REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS,
+ isDesktopInput,
+ type DesktopInput,
+ type RemoteDesktopCapabilities,
+ type RemoteDesktopLease,
+ type RemoteDesktopRequest,
+ type RemoteDesktopVideoSettings,
+ type RemoteDesktopDisplayMode,
+} from "@cindy/device-link";
+import { useDeviceLink } from "@/device-link/DeviceLinkContext";
+import { Text } from "@/components/AppText";
+import { useScreenEdgePadding } from "@/components/screenEdgeInsets";
+import { goBackGuarded } from "@/utils/backGuard";
+import {
+ fontWeight,
+ iconSize,
+ iconStroke,
+ radius,
+ spacing,
+ typeScale,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+import { remotePresentation } from "../../modules/cindy-remote-presentation/src";
+import { remoteDesktopViewerHtml } from "./viewerHtml";
+import { useMouseButtonsPreference } from "./useMouseButtonsPreference";
+import { useInputModePreference } from "./useInputModePreference";
+import { useVideoSettingsPreference } from "./useVideoSettingsPreference";
+import { PermissionGuide } from "./PermissionGuide";
+import { RemoteDesktopBackButton } from "./RemoteDesktopBackButton";
+import { RemoteDesktopNetworkStatus } from "./RemoteDesktopNetworkStatus";
+import type { DesktopNetworkStats } from "./networkStats";
+import {
+ RemoteDesktopControls,
+ RemoteDesktopDisconnect,
+} from "./RemoteDesktopControls";
+import {
+ RemoteDesktopPanel,
+ RemoteDesktopToolbar,
+} from "./RemoteDesktopChrome";
+
+type Mode = "pointer" | "touch" | "pan";
+const MODIFIERS = ["ControlLeft", "ShiftLeft", "AltLeft", "MetaLeft"];
+const KEY_PAGES = [
+ [
+ [
+ "Minus",
+ "Equal",
+ "BracketLeft",
+ "BracketRight",
+ "Backslash",
+ "Semicolon",
+ "Quote",
+ "Comma",
+ "Period",
+ "Slash",
+ ],
+ [..."1234567890"].map((key) => `Digit${key}`),
+ [..."QWERTYUIOP"].map((key) => `Key${key}`),
+ [..."ASDFGHJKL"].map((key) => `Key${key}`).concat("Backspace"),
+ [..."ZXCVBNM"].map((key) => `Key${key}`).concat("Space", "Enter"),
+ ],
+ [
+ ["Escape", "Tab", "Backquote", "Insert", "Home", "PageUp"],
+ ["F1", "F2", "F3", "Delete", "End", "PageDown"],
+ ["F4", "F5", "F6", "Backspace", "Space", "Enter"],
+ ["F7", "F8", "F9", null, "ArrowUp", null],
+ ["F10", "F11", "F12", "ArrowLeft", "ArrowDown", "ArrowRight"],
+ ],
+];
+const LABELS: Record<string, string> = {
+ Minus: "− _",
+ Equal: "= +",
+ BracketLeft: "[ {",
+ BracketRight: "] }",
+ Backslash: "\\ |",
+ Semicolon: "; :",
+ Quote: "' \"",
+ Comma: ", <",
+ Period: ". >",
+ Slash: "/ ?",
+ Backquote: "` ~",
+ Backspace: "⌫",
+ Escape: "Esc",
+ PageUp: "PgUp",
+ PageDown: "PgDn",
+ ControlLeft: "Ctrl",
+ AltLeft: "Alt",
+ ShiftLeft: "Shift",
+ MetaLeft: "Meta",
+ ArrowLeft: "←",
+ ArrowRight: "→",
+ ArrowUp: "↑",
+ ArrowDown: "↓",
+};
+
+export default function RemoteDesktopScreen() {
+ const { deviceId: rawId, deviceName: rawName } = useLocalSearchParams<{
+ deviceId: string;
+ deviceName?: string;
+ }>();
+ const deviceId = typeof rawId === "string" ? rawId : "";
+ const deviceName = typeof rawName === "string" ? rawName : deviceId;
+ const router = useRouter();
+ const focused = useIsFocused();
+ const focusedRef = useRef(focused);
+ focusedRef.current = focused;
+ const link = useDeviceLink();
+ const linkRef = useRef(link);
+ linkRef.current = link;
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ const insets = useSafeAreaInsets();
+ const windowSize = useWindowDimensions();
+ const edgePadding = useScreenEdgePadding({
+ insets,
+ windowWidth: windowSize.width,
+ windowHeight: windowSize.height,
+ });
+ const screenSize = Dimensions.get("screen");
+ const landscape = screenSize.width > screenSize.height;
+ const webview = useRef<ComponentRef<typeof WebView>>(null);
+ const html = useRef(
+ remoteDesktopViewerHtml(colors.surface, colors.textPrimary),
+ ).current;
+ const active = useRef<RemoteDesktopLease | null>(null);
+ const wantsControl = useRef(true);
+ const recovery = useRef({
+ enabled: true,
+ at: 0,
+ delay: 1000,
+ displayId: undefined as string | undefined,
+ resuming: false,
+ });
+ const generation = useRef(0);
+ const alive = useRef(true);
+ const connecting = useRef(false);
+ const ready = useRef(false);
+ const streaming = useRef(false);
+ const receiveWindow = useRef({
+ since: Date.now(),
+ bytes: 0,
+ frameMs: null as number | null,
+ frameAt: 0,
+ });
+ const [network, setNetwork] = useState<DesktopNetworkStats | null>(null);
+ const frameBusy = useRef<string | null>(null);
+ const inputBusy = useRef<string | null>(null);
+ const [lease, setLease] = useState<RemoteDesktopLease | null>(null);
+ const [caps, setCaps] = useState<RemoteDesktopCapabilities | null>(null);
+ const capsRef = useRef(caps);
+ capsRef.current = caps;
+ const [status, setStatus] = useState("connecting");
+ const [error, setError] = useState<string | null>(null);
+ const [frameReady, setFrameReady] = useState(false);
+ const [controlReady, setControlReady] = useState(false);
+ const connectionPending = !error && (!lease || !frameReady || !controlReady);
+ const connectionLabel = t(
+ recovery.current.at ? "remoteDesktop.reconnecting" : "remoteDesktop.connecting",
+ );
+ const [busy, setBusy] = useState(false);
+ const [inputMode, setInputMode] = useInputModePreference();
+ const mode: Mode = lease?.controlling ? inputMode : "pan";
+ const [operations, setOperations] = useState(false);
+ const [toolbarSize, setToolbarSize] = useState({ width: 0, height: 0 });
+ const [videoSettings, setVideoSettings, videoPreferencesLoaded] = useVideoSettingsPreference();
+ const videoSettingsRef = useRef(videoSettings);
+ videoSettingsRef.current = videoSettings;
+ const [settingNotice, setSettingNotice] = useState<string | null>(null);
+ const [settingBusy, setSettingBusy] = useState(false);
+ const settingInFlight = useRef(false);
+ const [canPip, setCanPip] = useState(false);
+ const presentation = useRef(false);
+ const presentationTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const [showMouseButtons, setShowMouseButtons] = useMouseButtonsPreference();
+ const [keyboard, setKeyboard] = useState(false);
+ const [fullKeys, setFullKeys] = useState(false);
+ const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
+ const [nativeKeyboard, setNativeKeyboard] = useState(false);
+ const heldKeys = useRef(new Map<string, string[]>());
+ const [keyPage, setKeyPage] = useState(0);
+ const [comboMode, setComboMode] = useState(true);
+ const [modifiers, setModifiers] = useState<string[]>([]);
+ const send = useCallback(
+ (message: object) => webview.current?.postMessage(JSON.stringify(message)),
+ [],
+ );
+ useEffect(() => {
+ const enabled =
+ keyboard && !fullKeys && focused && Boolean(lease?.controlling);
+ if (!enabled) {
+ send({ type: "keyboard", enabled: false });
+ Keyboard.dismiss();
+ return;
+ }
+ // Focus synchronously in the native-to-WebView script call. Deferring DOM
+ // focus to a web animation frame loses WebKit's user-interaction context.
+ webview.current?.requestFocus();
+ send({ type: "keyboard", enabled: true });
+ }, [
+ keyboard,
+ fullKeys,
+ focused,
+ lease?.controlling,
+ keyboardFocusRequest,
+ send,
+ ]);
+ const request = useCallback(
+ <T,>(message: RemoteDesktopRequest) =>
+ linkRef.current.invoke<T>(deviceId, REMOTE_DESKTOP_CHANNEL, [message]),
+ [deviceId],
+ );
+ const transferClipboard = async (action: "copy" | "paste") => {
+ const current = active.current;
+ const epoch = generation.current;
+ const check = () => {
+ if (!alive.current || generation.current !== epoch || active.current !== current || !current?.controlling || AppState.currentState !== "active")
+ throw new Error("DESKTOP_LEASE_EXPIRED");
+ };
+ check();
+ send({ type: "events", events: [{ kind: "release" }] });
+ heldKeys.current.clear();
+ setModifiers([]);
+ if (caps?.clipboardContent && remotePresentation?.readClipboard && remotePresentation?.writeClipboard) {
+ await transferClipboardContent(action, current!.lease, request, check);
+ return;
+ }
+ if (action === "paste" && (await Clipboard.hasImageAsync())) throw new Error("CLIPBOARD_UPGRADE");
+ if (action === "copy") {
+ const result = await request<{ text: string }>({ op: "clipboard", lease: current!.lease, action });
+ check();
+ if (typeof result.text !== "string" || !result.text) throw new Error("CLIPBOARD_EMPTY");
+ if (result.text.length > REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS) throw new Error("CLIPBOARD_TOO_LONG");
+ if (!(await Clipboard.setStringAsync(result.text))) throw new Error("CLIPBOARD_WRITE_FAILED");
+ } else {
+ const text = await Clipboard.getStringAsync();
+ check();
+ if (!text) throw new Error("CLIPBOARD_EMPTY");
+ if (text.length > REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS) throw new Error("CLIPBOARD_TOO_LONG");
+ await request({ op: "clipboard", lease: current!.lease, action, text });
+ check();
+ }
+ };
+ useEffect(() => {
+ const show = Keyboard.addListener("keyboardDidShow", () => {
+ setNativeKeyboard(true);
+ });
+ const hide = Keyboard.addListener("keyboardDidHide", () =>
+ setNativeKeyboard(false),
+ );
+ return () => {
+ show.remove();
+ hide.remove();
+ };
+ }, []);
+
+ const stop = useCallback((preserveFrame = false) => {
+ generation.current++;
+ presentation.current = false;
+ if (presentationTimer.current) clearTimeout(presentationTimer.current);
+ presentationTimer.current = null;
+ void remotePresentation?.playback(false).catch(() => {});
+ connecting.current = false;
+ const previous = active.current;
+ active.current = null;
+ heldKeys.current.clear();
+ streaming.current = false;
+ receiveWindow.current = {
+ since: Date.now(),
+ bytes: 0,
+ frameMs: null,
+ frameAt: 0,
+ };
+ send({ type: "stop", preserveFrame });
+ if (alive.current) {
+ setLease(null);
+ setFrameReady(false);
+ setControlReady(false);
+ setCanPip(false);
+ setSettingBusy(false);
+ setNetwork(null);
+ setStatus("disconnected");
+ setModifiers([]);
+ setKeyboard(false);
+ setBusy(false);
+ }
+ if (previous)
+ void request({ op: "stop", lease: previous.lease }).catch(() => {});
+ }, [request, send]);
+ const fail = useCallback(
+ (cause: unknown) => {
+ if (!alive.current) return;
+ const message = cause instanceof Error ? cause.message : String(cause);
+ const code =
+ cause &&
+ typeof cause === "object" &&
+ "code" in cause &&
+ typeof cause.code === "string"
+ ? cause.code
+ : message.match(
+ /\b(?:DESKTOP|CHANNEL|DEVICE|INVOKE|REMOTE)_[A-Z_]+\b/,
+ )?.[0];
+ // Keep diagnostics free of device names, input and signaling payloads.
+ console.debug("[remote-desktop] connection failed", {
+ code: code && /^[A-Z_]+$/.test(code) ? code : "UNKNOWN",
+ });
+ const blocked =
+ code === "DESKTOP_BUSY"
+ ? "connectionBusy"
+ : code === "CHANNEL_NOT_ALLOWED"
+ ? "upgrade"
+ : message.includes("DESKTOP_DISABLED")
+ ? "disabled"
+ : message.includes("PERMISSION") ||
+ message.includes("ACCESSIBILITY")
+ ? "permissionHint"
+ : message.includes("DESKTOP_STOPPED")
+ ? "disconnected"
+ : null;
+ stop(!blocked);
+ setError(blocked);
+ if (blocked) recovery.current.enabled = false;
+ else {
+ recovery.current.at = Date.now() + recovery.current.delay;
+ recovery.current.delay = Math.min(15_000, recovery.current.delay * 2);
+ setStatus("reconnecting");
+ }
+ },
+ [stop],
+ );
+ const connect = useCallback(
+ async (displayId?: string, takeover = false) => {
+ if (
+ connecting.current ||
+ !alive.current ||
+ !focusedRef.current ||
+ !recovery.current.enabled ||
+ linkRef.current.status !== "online" ||
+ !ready.current ||
+ !videoPreferencesLoaded ||
+ !deviceId ||
+ AppState.currentState !== "active"
+ )
+ return;
+ stop(!displayId || displayId === recovery.current.displayId);
+ if (displayId) recovery.current.resuming = false; // Explicit display selection.
+ connecting.current = true;
+ const current = generation.current;
+ setError(null);
+ setStatus(recovery.current.at ? "reconnecting" : "connecting");
+ try {
+ await linkRef.current.openLink(deviceId);
+ if (current !== generation.current) return;
+ const result = await request<RemoteDesktopCapabilities>({
+ op: "capabilities",
+ });
+ if (current !== generation.current) return;
+ if (result?.version !== 1) throw new Error("CHANNEL_NOT_ALLOWED");
+ setCaps(result);
+ if (!result.enabled) throw new Error("DESKTOP_DISABLED");
+ if (recovery.current.resuming && !result.automaticReconnect)
+ throw new Error("CHANNEL_NOT_ALLOWED");
+ const display =
+ result.displays.find(
+ (d) => d.id === (displayId ?? recovery.current.displayId),
+ ) ?? result.displays[0];
+ if (!display) throw new Error("DESKTOP_DISPLAY_MISSING");
+ recovery.current.displayId = display.id;
+ const resuming = recovery.current.resuming;
+ // The host may start successfully even when its reply is lost.
+ recovery.current.resuming = true;
+ const next = await request<RemoteDesktopLease>({
+ op: "start",
+ displayId: display.id,
+ ...(takeover && result.connectionTakeover ? { takeover: true } : resuming ? { resume: true } : {}),
+ });
+ if (current !== generation.current) {
+ void request({ op: "stop", lease: next.lease }).catch(() => {});
+ return;
+ }
+ active.current = next;
+ receiveWindow.current = {
+ since: Date.now(),
+ bytes: 0,
+ frameMs: null,
+ frameAt: 0,
+ };
+ setLease({ ...next });
+ setStatus("compatibility");
+ if (result.systemAudio && videoSettingsRef.current.audio) {
+ await remotePresentation?.playback(true);
+ if (current !== generation.current) return;
+ }
+ send({
+ type: "init",
+ epoch: next.lease,
+ width: display.width,
+ height: display.height,
+ fillHeight: landscape,
+ audio: result.systemAudio && videoSettingsRef.current.audio,
+ });
+ send({ type: "mode", mode });
+ // Entering remote desktop is the user's intent to control. The existing
+ // host permission and ownership gates still decide whether it is allowed.
+ if (result.canControl && wantsControl.current) {
+ const control = await request<{ controlling: boolean }>({
+ op: "control",
+ lease: next.lease,
+ enabled: true,
+ });
+ if (current !== generation.current) return;
+ // Control changes keep the same session identity for in-flight replies.
+ next.controlling = control.controlling;
+ setLease({ ...next });
+ send({ type: "control", enabled: control.controlling });
+ }
+ setControlReady(true);
+ } catch (cause) {
+ if (current === generation.current) fail(cause);
+ } finally {
+ if (current === generation.current) connecting.current = false;
+ }
+ },
+ [deviceId, fail, landscape, mode, request, send, stop, videoPreferencesLoaded],
+ );
+ const connectRef = useRef(connect);
+ connectRef.current = connect;
+ const pause = useCallback(() => {
+ stop(true);
+ if (recovery.current.enabled) {
+ recovery.current.at = Date.now();
+ setStatus("reconnecting");
+ }
+ }, [stop]);
+ const leave = () => {
+ recovery.current.enabled = false;
+ Keyboard.dismiss();
+ stop();
+ goBackGuarded(router);
+ };
+ const retry = () => {
+ recovery.current.enabled = true;
+ recovery.current.at = Date.now();
+ recovery.current.delay = 1000;
+ recovery.current.resuming = false;
+ setError(null);
+ setStatus("reconnecting");
+ if (!ready.current) webview.current?.reload();
+ else void connectRef.current(undefined, error === "connectionBusy" && caps?.connectionTakeover === true);
+ };
+ const restartViewer = () => {
+ ready.current = false;
+ if (!alive.current || !recovery.current.enabled) return;
+ fail(new Error("DESKTOP_VIEWER_ERROR"));
+ };
+ useEffect(() => {
+ send({ type: "viewport", fillHeight: landscape });
+ }, [landscape, send]);
+
+ useEffect(() => {
+ alive.current = true;
+ const subscription = AppState.addEventListener("change", (state) => {
+ // iOS enters inactive during an interrupted Home gesture or a system
+ // overlay. Release held input, but keep this viewer's lease and stream.
+ if (state === "inactive") {
+ send({ type: "releaseInput" });
+ heldKeys.current.clear();
+ setModifiers([]);
+ } else if (state === "background" && !presentation.current) pause();
+ else if (state === "active" && active.current)
+ send({ type: "resume" });
+ else if (state === "active" && recovery.current.enabled && !active.current)
+ void connectRef.current();
+ });
+ let heartbeatBusy: string | null = null;
+ const heartbeat = setInterval(() => {
+ const current = active.current;
+ if (
+ !current &&
+ recovery.current.enabled &&
+ Date.now() >= recovery.current.at
+ ) {
+ if (
+ !focusedRef.current ||
+ AppState.currentState !== "active" ||
+ linkRef.current.status !== "online"
+ )
+ return;
+ if (!ready.current && recovery.current.at) {
+ webview.current?.reload();
+ recovery.current.at = Date.now() + recovery.current.delay;
+ recovery.current.delay = Math.min(15_000, recovery.current.delay * 2);
+ return;
+ }
+ void connectRef.current();
+ return;
+ }
+ if (
+ !current ||
+ heartbeatBusy === current.lease ||
+ (presentation.current && AppState.currentState !== "active")
+ )
+ return;
+ heartbeatBusy = current.lease;
+ void request({ op: "heartbeat", lease: current.lease })
+ .catch((cause) => {
+ if (active.current === current && !presentation.current) fail(cause);
+ })
+ .finally(() => {
+ if (heartbeatBusy === current.lease) heartbeatBusy = null;
+ });
+ }, 3000);
+ const frames = setInterval(() => {
+ const current = active.current;
+ if (!current || streaming.current || frameBusy.current === current.lease)
+ return;
+ frameBusy.current = current.lease;
+ const requestedAt = Date.now();
+ void request<{ jpeg: string | null; cursor?: RemoteDesktopCursor | null }>({
+ op: "frame",
+ lease: current.lease,
+ cursorOverlay: capsRef.current?.cursorOverlay === true,
+ })
+ .then((result) => {
+ if (
+ active.current === current &&
+ !streaming.current &&
+ typeof result.jpeg === "string" &&
+ result.jpeg.length <= (capsRef.current?.cursorOverlay ? 1_333_336 : 240_000)
+ ) {
+ recovery.current.delay = 1000;
+ const meter = receiveWindow.current;
+ meter.bytes +=
+ Math.floor((result.jpeg.length * 3) / 4) -
+ (result.jpeg.endsWith("==")
+ ? 2
+ : result.jpeg.endsWith("=")
+ ? 1
+ : 0);
+ meter.frameMs = Date.now() - requestedAt;
+ meter.frameAt = Date.now();
+ send({ type: "frame", jpeg: result.jpeg, ...(isRemoteDesktopCursor(result.cursor) || result.cursor === null ? { cursor: result.cursor } : {}) });
+ }
+ })
+ .catch((cause) => {
+ if (active.current === current) fail(cause);
+ })
+ .finally(() => {
+ if (frameBusy.current === current.lease) frameBusy.current = null;
+ });
+ }, 350);
+ const metrics = setInterval(() => {
+ if (!active.current) return;
+ const now = Date.now();
+ if (streaming.current) {
+ setNetwork((previous) =>
+ previous &&
+ now - previous.at > 5000 &&
+ (previous.bytesPerSecond !== null || previous.latencyMs !== null)
+ ? { ...previous, bytesPerSecond: null, latencyMs: null }
+ : previous,
+ );
+ return;
+ }
+ const meter = receiveWindow.current;
+ const elapsed = now - meter.since;
+ if (elapsed <= 0 || meter.frameAt === 0) return;
+ setNetwork({
+ transport: "screenshots",
+ bytesPerSecond: (meter.bytes * 1000) / elapsed,
+ latencyMs: now - meter.frameAt <= 5000 ? meter.frameMs : null,
+ at: now,
+ });
+ meter.since = now;
+ meter.bytes = 0;
+ }, 1000);
+ return () => {
+ alive.current = false;
+ subscription.remove();
+ clearInterval(heartbeat);
+ clearInterval(frames);
+ clearInterval(metrics);
+ stop();
+ };
+ }, [request, fail, send, stop, pause]);
+ useEffect(() => {
+ if (!focused && !presentation.current) pause();
+ else if (!active.current) void connectRef.current();
+ }, [focused, pause, videoPreferencesLoaded]);
+ useEffect(() => {
+ send({
+ type: "theme",
+ surface: colors.surface,
+ foreground: colors.textPrimary,
+ });
+ }, [colors.surface, colors.textPrimary, send]);
+ useEffect(() => {
+ send({ type: "mode", mode });
+ }, [mode, send]);
+ useEffect(() => {
+ send({
+ type: "mouseButtons",
+ bottomInset: !keyboard && !landscape ? toolbarSize.height : 0,
+ rightInset: !keyboard && landscape ? toolbarSize.width : 0,
+ leftInset: landscape ? insets.left : 0,
+ enabled:
+ showMouseButtons &&
+ focused &&
+ !operations &&
+ !keyboard &&
+ Boolean(lease?.controlling),
+ labels: {
+ left: t("remoteDesktop.leftClick"),
+ right: t("remoteDesktop.rightClick"),
+ wheel: t("remoteDesktop.mouseWheel"),
+ },
+ });
+ }, [
+ showMouseButtons,
+ insets.left,
+ toolbarSize,
+ landscape,
+ focused,
+ operations,
+ keyboard,
+ lease?.lease,
+ lease?.controlling,
+ send,
+ t,
+ ]);
+ useEffect(() => {
+ if (link.status !== "online" && !presentation.current) pause();
+ else if (!active.current) void connectRef.current();
+ }, [link.status, pause]);
+
+ const onMessage = (event: WebViewMessageEvent) => {
+ if (!alive.current || event.nativeEvent.data.length > 65_536) return;
+ let message: Record<string, unknown>;
+ try {
+ message = JSON.parse(event.nativeEvent.data);
+ } catch {
+ return;
+ }
+ if (!message || typeof message !== "object") return;
+ if (message.type === "ready") {
+ ready.current = true;
+ void connectRef.current();
+ return;
+ }
+ const current = active.current;
+ if (!current || message.epoch !== current.lease) return;
+ switch (message.type) {
+ case "offer":
+ if (typeof message.sdp !== "string" || message.sdp.length > 64_000)
+ return;
+ void request<{ sdp: string }>({
+ op: "offer",
+ lease: current.lease,
+ sdp: message.sdp,
+ cursorOverlay: caps?.cursorOverlay === true,
+ ...(caps?.videoSettings
+ ? {
+ settings: {
+ ...videoSettingsRef.current,
+ audio: Boolean(
+ caps.systemAudio && videoSettingsRef.current.audio,
+ ),
+ },
+ }
+ : {}),
+ })
+ .then((answer) => {
+ if (active.current === current)
+ send({ type: "answer", sdp: answer.sdp });
+ })
+ .catch(() => {
+ if (active.current === current) {
+ send({ type: "fallback" });
+ setStatus("compatibility");
+ setSettingBusy(false);
+ setSettingNotice(t("remoteDesktop.videoSettingsFailed"));
+ }
+ });
+ break;
+ case "pipCapability":
+ setCanPip(message.supported === true);
+ break;
+ case "presentation":
+ if (presentationTimer.current) clearTimeout(presentationTimer.current);
+ presentationTimer.current = null;
+ presentation.current = message.active === true;
+ if (!presentation.current) {
+ void request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: false,
+ }).catch(() => {});
+ if (!videoSettingsRef.current.audio)
+ void remotePresentation?.playback(false).catch(() => {});
+ if (AppState.currentState === "background") pause();
+ }
+ break;
+ case "presentationFailed":
+ presentation.current = false;
+ if (presentationTimer.current) clearTimeout(presentationTimer.current);
+ presentationTimer.current = null;
+ void request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: false,
+ }).catch(() => {});
+ if (!videoSettingsRef.current.audio)
+ void remotePresentation?.playback(false).catch(() => {});
+ setSettingNotice(t("remoteDesktop.pipUnavailable"));
+ setOperations(true);
+ break;
+ case "streaming":
+ setFrameReady(true);
+ setSettingBusy(false);
+ recovery.current.delay = 1000;
+ streaming.current = true;
+ setNetwork(null);
+ setStatus("live");
+ break;
+ case "framePresented":
+ setFrameReady(true);
+ break;
+ case "fallback":
+ setCanPip(false);
+ setSettingBusy(false);
+ streaming.current = false;
+ receiveWindow.current = {
+ since: Date.now(),
+ bytes: 0,
+ frameMs: null,
+ frameAt: 0,
+ };
+ setNetwork(null);
+ setStatus("compatibility");
+ break;
+ case "network": {
+ if (
+ !streaming.current ||
+ !["video", "direct", "relay"].includes(String(message.transport))
+ )
+ return;
+ const metric = (value: unknown) =>
+ typeof value === "number" && Number.isFinite(value) && value >= 0
+ ? value
+ : null;
+ setNetwork({
+ transport: message.transport as DesktopNetworkStats["transport"],
+ bytesPerSecond: metric(message.bytesPerSecond),
+ latencyMs: metric(message.latencyMs),
+ at: Date.now(),
+ });
+ break;
+ }
+ case "inputOverflow":
+ fail(new Error("DESKTOP_INPUT_UNAVAILABLE"));
+ break;
+ case "input": {
+ const ack = {
+ type: "ack",
+ epoch: current.lease,
+ sequence: message.sequence,
+ };
+ if (
+ !current.controlling ||
+ inputBusy.current === current.lease ||
+ !Number.isSafeInteger(message.sequence) ||
+ !Array.isArray(message.events) ||
+ message.events.length > 64 ||
+ !message.events.every(isDesktopInput)
+ ) {
+ send(ack);
+ return;
+ }
+ inputBusy.current = current.lease;
+ void request({
+ op: "input",
+ lease: current.lease,
+ sequence: message.sequence as number,
+ events: message.events,
+ })
+ .catch((cause) => {
+ if (active.current === current) fail(cause);
+ })
+ .finally(() => {
+ if (inputBusy.current === current.lease) inputBusy.current = null;
+ send(ack);
+ });
+ break;
+ }
+ }
+ };
+ const toggleControl = async () => {
+ const current = active.current;
+ if (!current || busy) return;
+ setBusy(true);
+ setError(null);
+ try {
+ if (presentation.current) {
+ presentation.current = false;
+ send({ type: "presentation", enabled: false });
+ }
+ send({ type: "control", enabled: false });
+ const result = await request<{ controlling: boolean }>({
+ op: "control",
+ lease: current.lease,
+ enabled: !current.controlling,
+ });
+ if (active.current !== current) return;
+ wantsControl.current = result.controlling;
+ current.controlling = result.controlling;
+ setLease({ ...current });
+ send({ type: "control", enabled: result.controlling });
+ if (!result.controlling) {
+ heldKeys.current.clear();
+ setModifiers([]);
+ setKeyboard(false);
+ }
+ } catch (cause) {
+ if (active.current === current) fail(cause);
+ } finally {
+ if (alive.current) setBusy(false);
+ }
+ };
+ const changeVideoSettings = async (settings: RemoteDesktopVideoSettings) => {
+ if (
+ !active.current ||
+ !caps?.videoSettings ||
+ settingInFlight.current ||
+ settingBusy
+ )
+ return;
+ const current = active.current;
+ settingInFlight.current = true;
+ setSettingBusy(true);
+ setSettingNotice(null);
+ try {
+ if (presentation.current) {
+ presentation.current = false;
+ send({ type: "presentation", enabled: false });
+ await request({ op: "presentation", lease: current.lease, enabled: false });
+ }
+ if (settings.audio) await remotePresentation?.playback(true);
+ else if (!presentation.current) await remotePresentation?.playback(false);
+ if (active.current !== current) return;
+ videoSettingsRef.current = settings;
+ setVideoSettings(settings);
+ streaming.current = false;
+ setCanPip(false);
+ send({ type: "videoSettings", audio: settings.audio });
+ } catch {
+ setSettingNotice(t("remoteDesktop.settingFailed"));
+ setSettingBusy(false);
+ } finally {
+ settingInFlight.current = false;
+ }
+ };
+ const startPresentation = async () => {
+ const current = active.current;
+ if (
+ !current ||
+ !caps?.backgroundViewing ||
+ !canPip ||
+ !remotePresentation ||
+ settingInFlight.current
+ )
+ return;
+ settingInFlight.current = true;
+ setSettingNotice(null);
+ try {
+ await remotePresentation.playback(true);
+ if (active.current !== current) return;
+ send({ type: "control", enabled: false });
+ await request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: true,
+ });
+ if (active.current !== current) return;
+ current.controlling = false;
+ wantsControl.current = false;
+ heldKeys.current.clear();
+ setModifiers([]);
+ setKeyboard(false);
+ setLease({ ...current });
+ presentation.current = true;
+ setOperations(false);
+ send({ type: "presentation", enabled: true });
+ presentationTimer.current = setTimeout(() => {
+ presentationTimer.current = null;
+ presentation.current = false;
+ send({ type: "presentation", enabled: false });
+ void request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: false,
+ }).catch(() => {});
+ if (!videoSettingsRef.current.audio)
+ void remotePresentation?.playback(false).catch(() => {});
+ setSettingNotice(t("remoteDesktop.pipUnavailable"));
+ setOperations(true);
+ if (AppState.currentState === "background") pause();
+ }, 4000);
+ } catch {
+ presentation.current = false;
+ if (!videoSettingsRef.current.audio)
+ void remotePresentation?.playback(false).catch(() => {});
+ setSettingNotice(t("remoteDesktop.pipUnavailable"));
+ } finally {
+ settingInFlight.current = false;
+ }
+ };
+ const changeResolution = async (modeId: string) => {
+ const current = active.current;
+ if (!current?.controlling || settingInFlight.current) return;
+ settingInFlight.current = true;
+ setSettingBusy(true);
+ setSettingNotice(null);
+ try {
+ await request({ op: "resolution", lease: current.lease, modeId });
+ if (active.current === current) {
+ stop(true);
+ recovery.current.at = Date.now() + 500;
+ setStatus("reconnecting");
+ }
+ } catch (cause) {
+ // Geometry changes may end the old lease before its reply reaches us.
+ if (active.current === current)
+ setSettingNotice(t("remoteDesktop.settingFailed"));
+ } finally {
+ settingInFlight.current = false;
+ setSettingBusy(false);
+ }
+ };
+ const shortcut = (keys: string[]) =>
+ send({
+ type: "events",
+ events: [
+ ...keys.map((code) => ({ kind: "key", code, down: true })),
+ ...keys
+ .toReversed()
+ .map((code) => ({ kind: "key", code, down: false })),
+ ],
+ });
+ const button = (
+ label: string,
+ onPress: () => void,
+ selected = false,
+ disabled = false,
+ key = label,
+ ) => (
+ <Pressable
+ key={key}
+ accessibilityRole="button"
+ accessibilityLabel={label}
+ accessibilityState={{ selected, disabled }}
+ disabled={disabled}
+ onPress={onPress}
+ style={[
+ styles.button,
+ selected && styles.selected,
+ disabled && styles.disabled,
+ ]}
+ >
+ <Text style={styles.buttonText}>{label}</Text>
+ </Pressable>
+ );
+ const keyLabel = (code: string) => {
+ if (caps?.platform === "darwin") {
+ const mac: Record<string, string> = {
+ ControlLeft: "Control",
+ AltLeft: "Option",
+ MetaLeft: "Command",
+ Enter: "Return",
+ Delete: "⌦",
+ };
+ if (mac[code]) return mac[code];
+ }
+ if (code === "MetaLeft")
+ return caps?.platform === "win32"
+ ? "Win"
+ : caps?.platform === "linux"
+ ? "Super"
+ : "Meta";
+ if (code === "Backspace" && caps?.platform !== "darwin") return "Backspace";
+ return LABELS[code] ?? code.replace(/^Key|^Digit/, "");
+ };
+ const heldKey = (code: string) => (
+ <Pressable
+ key={code}
+ accessibilityRole="button"
+ accessibilityLabel={keyLabel(code)}
+ style={({ pressed }) => [
+ styles.computerKey,
+ pressed && styles.keyPressed,
+ ]}
+ onPressIn={() => {
+ if (!active.current?.controlling) return;
+ const alreadyHeld = new Set([...heldKeys.current.values()].flat());
+ const keys = comboMode ? [...modifiers, code] : [code];
+ heldKeys.current.set(code, keys);
+ send({
+ type: "events",
+ events: keys
+ .filter((key) => !alreadyHeld.has(key))
+ .map((key) => ({
+ kind: "key",
+ code: key,
+ down: true,
+ })),
+ });
+ }}
+ onPressOut={() => {
+ const keys = heldKeys.current.get(code) ?? [];
+ heldKeys.current.delete(code);
+ const stillHeld = new Set([...heldKeys.current.values()].flat());
+ send({
+ type: "events",
+ events: keys
+ .filter((key) => !stillHeld.has(key))
+ .toReversed()
+ .map((key) => ({ kind: "key", code: key, down: false })),
+ });
+ if (!comboMode) setModifiers([]);
+ }}
+ >
+ <Text
+ numberOfLines={1}
+ adjustsFontSizeToFit
+ style={[
+ /^Key|^Digit|^Arrow/.test(code)
+ ? styles.keyText
+ : styles.specialKeyText,
+ ]}
+ >
+ {keyLabel(code)}
+ </Text>
+ </Pressable>
+ );
+ return (
+ <KeyboardAvoidingView
+ behavior={Platform.OS === "ios" ? "padding" : undefined}
+ style={styles.root}
+ >
+ <Stack.Screen
+ options={{
+ headerShown: false,
+ gestureEnabled: false,
+ statusBarHidden: true,
+ }}
+ />
+ {Platform.OS === "android" && focused && <StatusBar hidden />}
+ <View style={[styles.body, landscape && styles.landscape]}>
+ <View style={[styles.canvas, { marginLeft: landscape ? 0 : edgePadding.paddingLeft }]}>
+ <WebView
+ ref={webview}
+ source={{ html, baseUrl: "https://cindy-desktop.invalid/" }}
+ originWhitelist={["*"]}
+ onShouldStartLoadWithRequest={(request) =>
+ request.url === "about:blank" ||
+ request.url === "https://cindy-desktop.invalid/"
+ }
+ onMessage={onMessage}
+ onError={restartViewer}
+ onContentProcessDidTerminate={restartViewer}
+ onRenderProcessGone={restartViewer}
+ keyboardDisplayRequiresUserAction={false}
+ hideKeyboardAccessoryView
+ textInteractionEnabled={false}
+ allowsLinkPreview={false}
+ dataDetectorTypes="none"
+ javaScriptEnabled
+ allowsInlineMediaPlayback
+ mediaPlaybackRequiresUserAction={false}
+ allowsPictureInPictureMediaPlayback
+ scrollEnabled={false}
+ bounces={false}
+ allowFileAccess={false}
+ allowUniversalAccessFromFileURLs={false}
+ allowFileAccessFromFileURLs={false}
+ setSupportMultipleWindows={false}
+ javaScriptCanOpenWindowsAutomatically={false}
+ mixedContentMode="never"
+ style={styles.webview}
+ testID="remoteDesktop.viewer"
+ />
+ {(connectionPending || (!lease && error)) && (
+ <View
+ pointerEvents="box-none"
+ style={[
+ styles.connectionStatus,
+ { top: edgePadding.paddingTop + spacing.xs + 44 + spacing.lg },
+ ]}
+ >
+ {connectionPending ? (
+ <View
+ style={styles.connectionBadge}
+ accessibilityRole="progressbar"
+ accessibilityLabel={connectionLabel}
+ accessibilityState={{ busy: true }}
+ testID="remoteDesktop.connectingStatus"
+ >
+ <ActivityIndicator size="small" color={colors.textPrimary} />
+ <Text style={styles.connectionLabel}>{connectionLabel}</Text>
+ </View>
+ ) : error !== "permissionHint" && (
+ <Text
+ accessibilityRole={error ? "alert" : undefined}
+ style={styles.caption}
+ >
+ {t(`remoteDesktop.${error === "connectionBusy" && caps?.connectionTakeover ? "connectionBusyTakeover" : error ?? status}`)}
+ </Text>
+ )}
+ {error &&
+ error !== "permissionHint" &&
+ button(t(error === "connectionBusy" && caps?.connectionTakeover ? "remoteDesktop.takeoverConnection" : "remoteDesktop.connect"), retry)}
+ {error === "permissionHint" && focused && (
+ <PermissionGuide
+ key={deviceId}
+ initial={caps?.permissions}
+ request={request}
+ reconnect={retry}
+ />
+ )}
+ </View>
+ )}
+ {lease && !connectionPending && !lease.controlling && !operations && (
+ <Text
+ style={[
+ styles.viewOnly,
+ { bottom: spacing.sm + (!keyboard && !landscape ? toolbarSize.height : 0), left: spacing.sm },
+ ]}
+ >
+ {t("remoteDesktop.viewOnly")}
+ </Text>
+ )}
+ {lease && !connectionPending && !operations && !landscape && (
+ <RemoteDesktopNetworkStatus
+ stats={network}
+ video={status === "live"}
+ top={edgePadding.paddingTop + spacing.sm}
+ />
+ )}
+ {operations && (
+ <View
+ pointerEvents="box-none"
+ style={[
+ StyleSheet.absoluteFill,
+ { bottom: landscape ? 0 : toolbarSize.height,
+ right: landscape ? toolbarSize.width : 0 },
+ ]}
+ >
+ <RemoteDesktopPanel
+ landscape={landscape}
+ topInset={edgePadding.paddingTop}
+ title={deviceName}
+ caption={connectionPending ? connectionLabel : `${t(`remoteDesktop.${status}`)}${lease ? ` · ${t(lease.controlling ? "remoteDesktop.controlling" : "remoteDesktop.viewOnly")}` : ""}`}
+ onClose={() => setOperations(false)}
+ footer={<RemoteDesktopDisconnect onPress={leave} />}
+ >
+ <RemoteDesktopControls
+ connected={Boolean(lease) && !connectionPending}
+ controlling={Boolean(lease?.controlling)}
+ controlDisabled={
+ !lease || busy || connecting.current || !caps?.canControl
+ }
+ presentation={{
+ canRotate: Boolean(remotePresentation),
+ canPip: Boolean(
+ remotePresentation && caps?.backgroundViewing && canPip,
+ ),
+ canAudio: Boolean(caps?.systemAudio),
+ onRotate: () => {
+ void remotePresentation
+ ?.rotate(!landscape)
+ .then(() => setOperations(false))
+ .catch(() =>
+ setSettingNotice(t("remoteDesktop.settingFailed")),
+ );
+ },
+ onPip: () => {
+ void startPresentation();
+ },
+ }}
+ video={{
+ supported: Boolean(caps?.videoSettings),
+ settings: videoSettings,
+ busy: settingBusy,
+ modesSupported: Boolean(caps?.displayModes),
+ notice: settingNotice,
+ onChange: (settings) => {
+ void changeVideoSettings(settings);
+ },
+ readModes: () =>
+ active.current
+ ? request<RemoteDesktopDisplayMode[]>({
+ op: "displayModes",
+ lease: active.current.lease,
+ })
+ : Promise.resolve([]),
+ onResolution: changeResolution,
+ }}
+ inputMode={inputMode}
+ displays={caps?.displays ?? []}
+ displayId={lease?.display.id}
+ onViewOnly={() => void toggleControl()}
+ onInputMode={(value) => {
+ setInputMode(value);
+ send({ type: "mode", mode: value });
+ }}
+ showMouseButtons={showMouseButtons}
+ onShowMouseButtons={setShowMouseButtons}
+ onDisplay={(id) => {
+ setOperations(false);
+ void connect(id);
+ }}
+ />
+ </RemoteDesktopPanel>
+ </View>
+ )}
+ </View>
+ {!keyboard && (
+ <View
+ onLayout={({ nativeEvent: { layout } }) => {
+ setToolbarSize((previous) =>
+ previous.width === layout.width && previous.height === layout.height
+ ? previous : { width: layout.width, height: layout.height });
+ }}
+ style={[styles.floatingToolbar, landscape ? styles.floatingRail : styles.floatingBottom, {
+ paddingRight: landscape
+ ? spacing.xs
+ : edgePadding.paddingRight,
+ paddingLeft: landscape ? 0 : edgePadding.paddingLeft,
+ paddingBottom: keyboard || nativeKeyboard ? 0 : insets.bottom,
+ }]}
+ >
+ <RemoteDesktopToolbar
+ landscape={landscape}
+ canControl={Boolean(lease?.controlling)}
+ keyboard={keyboard}
+ operations={operations}
+ onWindows={() =>
+ shortcut(
+ caps?.platform === "darwin"
+ ? ["ControlLeft", "ArrowUp"]
+ : ["MetaLeft", "Tab"],
+ )
+ }
+ onDesktop={() =>
+ shortcut(
+ caps?.platform === "darwin" ? ["F11"] : ["MetaLeft", "KeyD"],
+ )
+ }
+ onKeyboard={() => {
+ setOperations(false);
+ if (keyboard) {
+ Keyboard.dismiss();
+ send({ type: "events", events: [{ kind: "release" }] });
+ }
+ setKeyboard(!keyboard);
+ }}
+ onOperations={() => {
+ Keyboard.dismiss();
+ setKeyboard(false);
+ send({ type: "events", events: [{ kind: "release" }] });
+ setOperations(!operations);
+ }}
+ />
+ </View>
+ )}
+ </View>
+ {!landscape && (
+ <View
+ style={[
+ styles.back,
+ {
+ top: edgePadding.paddingTop + spacing.xs,
+ left: edgePadding.paddingLeft + spacing.lg,
+ },
+ ]}
+ >
+ <RemoteDesktopBackButton
+ label={t("remoteDesktop.back")}
+ onPress={leave}
+ />
+ </View>
+ )}
+ {keyboard && (
+ <View
+ style={[
+ styles.keyboard,
+ {
+ paddingLeft: Math.max(spacing.xs, edgePadding.paddingLeft),
+ paddingRight: Math.max(spacing.sm, edgePadding.paddingRight),
+ paddingBottom: fullKeys
+ ? Math.max(spacing.sm, insets.bottom)
+ : spacing.xs,
+ },
+ ]}
+ >
+ <View style={styles.keyboardHeader}>
+ <RemoteDesktopClipboardButton
+ enabled={!connectionPending && Boolean(lease?.controlling)}
+ supported={caps?.clipboardText === true}
+ transfer={transferClipboard}
+ />
+ <View style={styles.modeSegments}>
+ {[false, true].map((computer) => (
+ <Pressable
+ key={String(computer)}
+ accessibilityRole="tab"
+ accessibilityState={{ selected: fullKeys === computer }}
+ onPress={() => {
+ send({ type: "events", events: [{ kind: "release" }] });
+ heldKeys.current.clear();
+ setFullKeys(computer);
+ setModifiers([]);
+ if (!computer)
+ setKeyboardFocusRequest((value) => value + 1);
+ }}
+ style={({ pressed }) => [
+ styles.modeTab,
+ fullKeys === computer && styles.modeTabSelected,
+ pressed && styles.keyPressed,
+ ]}
+ >
+ <Text
+ numberOfLines={1}
+ style={[
+ styles.modeText,
+ fullKeys === computer && styles.modeTextSelected,
+ ]}
+ >
+ {t(
+ computer
+ ? "remoteDesktop.computerKeyboard"
+ : "remoteDesktop.inputMethod",
+ )}
+ </Text>
+ </Pressable>
+ ))}
+ </View>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t("remoteDesktop.close")}
+ onPress={() => {
+ setKeyboard(false);
+ heldKeys.current.clear();
+ setModifiers([]);
+ send({ type: "events", events: [{ kind: "release" }] });
+ }}
+ style={({ pressed }) => [
+ styles.closeKey,
+ pressed && styles.keyPressed,
+ ]}
+ >
+ <X size={iconSize.action} strokeWidth={iconStroke.thin} color={colors.textPrimary} />
+ </Pressable>
+ </View>
+ {fullKeys && (
+ <View>
+ <View style={styles.modifierRow}>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ selected: comboMode }}
+ accessibilityLabel={t("remoteDesktop.comboMode")}
+ onPress={() => {
+ send({ type: "events", events: [{ kind: "release" }] });
+ heldKeys.current.clear();
+ setComboMode(!comboMode);
+ setModifiers([]);
+ }}
+ style={({ pressed }) => [
+ styles.comboKey,
+ comboMode && styles.modifierSelected,
+ pressed && styles.keyPressed,
+ ]}
+ >
+ <Text
+ numberOfLines={2}
+ style={[
+ styles.modifierText,
+ comboMode && styles.modifierTextSelected,
+ ]}
+ >
+ {t("remoteDesktop.comboMode")}
+ </Text>
+ </Pressable>
+ {MODIFIERS.map((code) => (
+ <Pressable
+ key={code}
+ accessibilityRole="button"
+ accessibilityState={{ selected: modifiers.includes(code) }}
+ onPressIn={() => {
+ if (
+ comboMode ||
+ !active.current?.controlling ||
+ heldKeys.current.has(code)
+ )
+ return;
+ heldKeys.current.set(code, [code]);
+ send({
+ type: "events",
+ events: [{ kind: "key", code, down: true }],
+ });
+ }}
+ onPressOut={() => {
+ if (!heldKeys.current.has(code)) return;
+ heldKeys.current.delete(code);
+ send({
+ type: "events",
+ events: [{ kind: "key", code, down: false }],
+ });
+ }}
+ onPress={() => {
+ if (!comboMode || !active.current?.controlling) return;
+ setModifiers((previous) =>
+ previous.includes(code)
+ ? previous.filter((v) => v !== code)
+ : [...previous, code],
+ );
+ }}
+ style={({ pressed }) => [
+ styles.modifierKey,
+ modifiers.includes(code) && styles.modifierSelected,
+ pressed && styles.keyPressed,
+ ]}
+ >
+ <Text
+ style={[
+ styles.modifierText,
+ modifiers.includes(code) && styles.modifierTextSelected,
+ ]}
+ >
+ {keyLabel(code)}
+ </Text>
+ </Pressable>
+ ))}
+ </View>
+ <ScrollView
+ style={{ maxHeight: landscape ? 156 : 300 }}
+ keyboardShouldPersistTaps="always"
+ >
+ <View style={styles.tools}>
+ {KEY_PAGES[keyPage].map((row, index) => (
+ <View
+ key={index}
+ style={keyPage === 1 ? styles.functionRow : styles.keyRow}
+ >
+ {keyPage === 1
+ ? [row.slice(0, 3), row.slice(3)].map(
+ (group, groupIndex) => (
+ <View
+ key={groupIndex}
+ style={styles.functionGroup}
+ >
+ {group.map((code, slot) =>
+ code ? (
+ heldKey(code)
+ ) : (
+ <View
+ key={`gap-${slot}`}
+ style={styles.emptyKey}
+ pointerEvents="none"
+ />
+ ),
+ )}
+ </View>
+ ),
+ )
+ : row.map((code) => (code ? heldKey(code) : null))}
+ </View>
+ ))}
+ </View>
+ </ScrollView>
+ <View style={styles.pageNavigation}>
+ {[0, 1].map((page) => (
+ <Pressable
+ key={page}
+ accessibilityRole="tab"
+ accessibilityState={{ selected: keyPage === page }}
+ onPress={() => setKeyPage(page)}
+ style={styles.pageTab}
+ >
+ <Text
+ style={[
+ styles.pageLabel,
+ keyPage === page && styles.pageLabelSelected,
+ ]}
+ >
+ {page === 0 ? "ABC" : t("remoteDesktop.functionKeys")}
+ </Text>
+ <View
+ style={[
+ styles.pageIndicator,
+ keyPage === page && styles.pageIndicatorSelected,
+ ]}
+ />
+ </Pressable>
+ ))}
+ </View>
+ </View>
+ )}
+ </View>
+ )}
+ </KeyboardAvoidingView>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ root: { flex: 1, backgroundColor: colors.surface },
+ caption: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ paddingHorizontal: spacing.sm,
+ paddingVertical: spacing.xs,
+ },
+ back: {
+ position: "absolute",
+ },
+ connectionStatus: {
+ position: "absolute",
+ left: spacing.md,
+ right: spacing.md,
+ gap: spacing.sm,
+ },
+ connectionBadge: {
+ alignSelf: "center",
+ flexDirection: "row",
+ alignItems: "center",
+ gap: spacing.sm,
+ paddingHorizontal: spacing.lg,
+ paddingVertical: spacing.md,
+ borderRadius: radius.pill,
+ backgroundColor: colors.surfaceElevated,
+ },
+ connectionLabel: {
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.semibold,
+ },
+ actionRow: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },
+ viewOnly: {
+ position: "absolute",
+ alignSelf: "center",
+ color: colors.textPrimary,
+ fontSize: typeScale.caption,
+ backgroundColor: colors.surfaceElevated,
+ padding: spacing.xs,
+ borderRadius: radius.control,
+ },
+ body: { flex: 1 },
+ floatingToolbar: {
+ position: "absolute",
+ backgroundColor: colors.surfaceTranslucent,
+ },
+ floatingBottom: { left: 0, right: 0, bottom: 0 },
+ floatingRail: { right: 0, top: 0, bottom: 0 },
+ landscape: { flexDirection: "row" },
+ canvas: { flex: 1, overflow: "hidden" },
+ webview: { flex: 1, backgroundColor: colors.surface },
+ tools: { gap: spacing.xs, paddingVertical: spacing.xs },
+ keyRow: { flexDirection: "row", gap: spacing.xs },
+ functionRow: { flexDirection: "row", gap: spacing.md },
+ functionGroup: { flex: 1, flexDirection: "row", gap: spacing.xs },
+ emptyKey: { flex: 1, minHeight: 44 },
+ button: {
+ minHeight: 44,
+ minWidth: 44,
+ flexShrink: 1,
+ borderRadius: radius.pill,
+ backgroundColor: colors.surfaceElevated,
+ paddingHorizontal: spacing.sm,
+ justifyContent: "center",
+ alignItems: "center",
+ },
+ selected: {
+ backgroundColor: colors.surfaceChip,
+ borderWidth: 1,
+ borderColor: colors.textPrimary,
+ },
+ disabled: { opacity: 0.4 },
+ buttonText: { color: colors.textPrimary, fontSize: typeScale.caption },
+ keyboard: {
+ backgroundColor: colors.surface,
+ paddingHorizontal: spacing.sm,
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: colors.border,
+ },
+ keyboardHeader: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: spacing.sm,
+ paddingVertical: spacing.sm,
+ },
+ modeSegments: {
+ flex: 1,
+ flexDirection: "row",
+ backgroundColor: colors.surfaceChip,
+ borderRadius: radius.container,
+ padding: spacing.xs,
+ },
+ modeTab: {
+ flex: 1,
+ minHeight: 36,
+ alignItems: "center",
+ justifyContent: "center",
+ borderRadius: radius.control,
+ },
+ modeTabSelected: { backgroundColor: colors.surfaceElevated },
+ modeText: {
+ fontSize: typeScale.listBody,
+ fontWeight: fontWeight.regular,
+ color: colors.textTertiary,
+ },
+ modeTextSelected: {
+ color: colors.textPrimary,
+ fontWeight: fontWeight.semibold,
+ },
+ closeKey: {
+ width: 44,
+ height: 44,
+ justifyContent: "center",
+ alignItems: "center",
+ borderRadius: radius.pill,
+ },
+ modifierRow: {
+ flexDirection: "row",
+ gap: spacing.xs,
+ paddingBottom: spacing.xs,
+ },
+ comboKey: {
+ flex: 1.25,
+ minHeight: 44,
+ paddingHorizontal: spacing.xs,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.surfaceChip,
+ borderRadius: radius.control,
+ },
+ modifierKey: {
+ flex: 1,
+ minHeight: 40,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.surfaceChip,
+ borderRadius: radius.control,
+ },
+ modifierSelected: { backgroundColor: colors.textPrimary },
+ modifierText: {
+ color: colors.textPrimary,
+ fontSize: typeScale.footnote,
+ fontWeight: fontWeight.medium,
+ },
+ modifierTextSelected: { color: colors.surface },
+ keyPressed: { opacity: 0.55 },
+ keyText: {
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.medium,
+ },
+ specialKeyText: { color: colors.textPrimary, fontSize: typeScale.caption },
+ pageNavigation: {
+ flexDirection: "row",
+ justifyContent: "center",
+ gap: spacing.lg,
+ paddingTop: 0,
+ },
+ pageTab: {
+ minWidth: 64,
+ height: 22,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 0,
+ },
+ pageLabel: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ },
+ pageLabelSelected: { color: colors.textPrimary },
+ pageIndicator: {
+ width: 16,
+ height: 2,
+ borderRadius: radius.pill,
+ backgroundColor: "transparent",
+ },
+ pageIndicatorSelected: { backgroundColor: colors.textPrimary },
+ computerKey: {
+ flex: 1,
+ minHeight: 44,
+ paddingHorizontal: 2,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.surfaceElevated,
+ borderRadius: radius.control,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: colors.border,
+ },
+ });
diff --git a/apps/mobile/src/remote-desktop/__tests__/networkStats.test.ts b/apps/mobile/src/remote-desktop/__tests__/networkStats.test.ts
new file mode 100644
index 0000000000..9c56f2fa9d
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/networkStats.test.ts
@@ -0,0 +1,85 @@
+import vm from "node:vm";
+import { describe, expect, it } from "vitest";
+import {
+ DESKTOP_NETWORK_STATS_SCRIPT,
+ formatReceiveRate,
+} from "../networkStats";
+
+const measure = vm.runInNewContext(`(${DESKTOP_NETWORK_STATS_SCRIPT})`);
+const report = (
+ bytes = 1000,
+ time = 1000,
+ candidateType = "host",
+ path = "pair",
+) =>
+ new Map([
+ [
+ "video",
+ {
+ id: "video",
+ type: "inbound-rtp",
+ kind: "video",
+ bytesReceived: bytes,
+ timestamp: time,
+ },
+ ],
+ ["transport", { type: "transport", selectedCandidatePairId: path }],
+ [
+ path,
+ {
+ id: path,
+ type: "candidate-pair",
+ localCandidateId: "local",
+ remoteCandidateId: "remote",
+ currentRoundTripTime: 0.042,
+ },
+ ],
+ ["local", { candidateType }],
+ ["remote", { candidateType: "srflx" }],
+ ] as [string, Record<string, unknown>][]);
+
+describe("remote desktop receive statistics", () => {
+ it("measures media bytes over the report interval and converts RTT to ms", () => {
+ const first = measure(report());
+ expect(first.bytesPerSecond).toBeNull();
+ expect(measure(report(5000, 3000), first.sample)).toMatchObject({
+ transport: "direct",
+ bytesPerSecond: 2000,
+ latencyMs: 42,
+ });
+ });
+ it("distinguishes relay from unknown paths without assuming direct", () => {
+ expect(measure(report(1000, 1000, "relay")).transport).toBe("relay");
+ expect(measure(report(1000, 1000, "unknown")).transport).toBe("video");
+ const partial = report();
+ partial.delete("remote");
+ expect(measure(partial).transport).toBe("video");
+ expect(measure(new Map())).toMatchObject({
+ transport: "video",
+ bytesPerSecond: null,
+ latencyMs: null,
+ });
+ });
+ it("discards baselines after path changes, counter resets or duplicate timestamps", () => {
+ const previous = measure(report()).sample;
+ for (const next of [
+ report(5000, 2000, "host", "new-pair"),
+ report(500, 2000),
+ report(5000, 1000),
+ ]) {
+ expect(measure(next, previous).bytesPerSecond).toBeNull();
+ }
+ expect(measure(report(1000, 2000), previous).bytesPerSecond).toBe(0);
+ });
+ it("rejects unavailable statistics and formats compact byte units", () => {
+ const invalid = report(NaN);
+ invalid.get("pair")!.currentRoundTripTime = -1;
+ expect(measure(invalid)).toMatchObject({ sample: null, latencyMs: null });
+ expect([null, 0, 125000, 1500000].map(formatReceiveRate)).toEqual([
+ "— KB/s",
+ "0 KB/s",
+ "125 KB/s",
+ "1.5 MB/s",
+ ]);
+ });
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
new file mode 100644
index 0000000000..0b4e44e235
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -0,0 +1,731 @@
+// @vitest-environment jsdom
+import { act, createElement, forwardRef, useImperativeHandle } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import RemoteDesktopScreen from "../RemoteDesktopScreen";
+import { AppState } from "react-native";
+import { goBackGuarded } from "@/utils/backGuard";
+
+const fixture = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ openLink: vi.fn(),
+ post: vi.fn(),
+ reload: vi.fn(),
+ message: null as null | ((e: unknown) => void),
+ size: { width: 390, height: 844 },
+ canControl: true,
+ focused: true,
+ status: "online",
+ appState: null as null | ((state: string) => void),
+ crashed: null as null | (() => void),
+ retryPermissions: null as null | (() => void),
+}));
+vi.mock("react-native", async () => {
+ const { createElement } = await import("react");
+ const view = (tag: string) => (p: any) =>
+ createElement(
+ tag,
+ {
+ onClick: p.onPress,
+ disabled: p.disabled,
+ "aria-label": p.accessibilityLabel,
+ "aria-selected": p.accessibilityState?.selected,
+ "data-testid": p.testID,
+ },
+ p.children,
+ );
+ return {
+ View: view("div"),
+ Pressable: view("button"),
+ ScrollView: view("div"),
+ KeyboardAvoidingView: view("div"),
+ StatusBar: () => null,
+ ActivityIndicator: () => null,
+ StyleSheet: {
+ create: (s: unknown) => s,
+ absoluteFill: {},
+ hairlineWidth: 1,
+ },
+ AppState: {
+ currentState: "active",
+ addEventListener: (_event: string, listener: (state: string) => void) => {
+ fixture.appState = listener;
+ return { remove() {} };
+ },
+ },
+ Keyboard: { dismiss() {}, addListener: () => ({ remove() {} }) },
+ Dimensions: { get: () => fixture.size },
+ useWindowDimensions: () => fixture.size,
+ Platform: { OS: "ios" },
+ };
+});
+vi.mock("@/components/AppText", () => ({
+ Text: (p: any) => createElement("span", {}, p.children),
+ TextInput: () => createElement("input"),
+}));
+vi.mock("expo-router", () => ({
+ Stack: { Screen: () => null },
+ useIsFocused: () => fixture.focused,
+ useRouter: () => ({}),
+ useLocalSearchParams: () => ({ deviceId: "computer", deviceName: "My Mac" }),
+}));
+vi.mock("@/utils/backGuard", () => ({ goBackGuarded: vi.fn() }));
+vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 59, bottom: 34, left: 0, right: 0 }),
+}));
+vi.mock("react-i18next", () => {
+ const t = (key: string) => key;
+ return { useTranslation: () => ({ t }) };
+});
+vi.mock("expo-modules-core", () => ({ requireOptionalNativeModule: () => null }));
+vi.mock("expo-clipboard", () => ({ getStringAsync: vi.fn(), setStringAsync: vi.fn() }));
+vi.mock("@expo/ui/community/segmented-control", () => ({ default: () => null }));
+vi.mock("@/platform/chrome/NativePullDownMenu", () => ({
+ usesNativePullDownMenu: () => false, NativePullDownMenu: (p: any) => p.children,
+}));
+vi.mock("lucide-react-native", () => ({
+ createLucideIcon: () => () => null,
+ Clipboard: () => null,
+ ArrowLeft: () => null,
+ RotateCw: () => null,
+ Volume2: () => null,
+ VolumeX: () => null,
+ PictureInPicture2: () => null,
+ Check: () => null,
+ ChevronDown: () => null,
+ ChevronRight: () => null,
+ Eye: () => null,
+ LogOut: () => null,
+ Maximize: () => null,
+ MousePointer2: () => null,
+ Move: () => null,
+ ChevronLeft: () => null,
+ PanelsTopLeft: () => null,
+ Monitor: () => null,
+ Keyboard: () => null,
+ SlidersHorizontal: () => null,
+ X: () => null,
+}));
+vi.mock("@/platform/chrome/NativeSwitch", () => ({
+ NativeSwitch: (p: any) =>
+ createElement("button", {
+ "aria-label": p.accessibilityLabel,
+ "aria-checked": p.value,
+ "data-testid": p.testID,
+ disabled: p.disabled,
+ onClick: () => p.onValueChange(!p.value),
+ }),
+}));
+vi.mock("@/theme", async () => {
+ const tokens = await import("@/theme/tokens");
+ return {
+ ...tokens,
+ useTheme: () => ({ colors: tokens.lightColors }),
+ useThemedStyles: (make: any) => make(tokens.lightColors),
+ };
+});
+vi.mock("@/device-link/DeviceLinkContext", () => ({
+ useDeviceLink: () => ({
+ status: fixture.status,
+ invoke: fixture.invoke,
+ openLink: fixture.openLink,
+ }),
+}));
+vi.mock("../PermissionGuide", () => ({
+ PermissionGuide: (p: any) => {
+ fixture.retryPermissions = p.reconnect;
+ return createElement("span", {}, "permission guide");
+ },
+}));
+vi.mock("react-native-webview", () => ({
+ WebView: forwardRef((p: any, ref) => {
+ fixture.message = p.onMessage;
+ fixture.crashed = p.onContentProcessDidTerminate;
+ useImperativeHandle(ref, () => ({
+ postMessage: fixture.post,
+ reload: fixture.reload,
+ }));
+ return createElement("div", { "data-testid": p.testID });
+ }),
+}));
+
+let root: Root;
+let host: HTMLDivElement;
+let mounted: boolean;
+const display = { id: "display", width: 1920, height: 1080 };
+const requests = () => fixture.invoke.mock.calls.map((call) => call[2][0]);
+const sent = () => fixture.post.mock.calls.map(([data]) => JSON.parse(data));
+const button = (key: string) =>
+ host.querySelector<HTMLButtonElement>(`[aria-label="remoteDesktop.${key}"]`)!;
+beforeEach(() => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ fixture.focused = true;
+ fixture.status = "online";
+ AppState.currentState = "active";
+ fixture.canControl = true;
+ fixture.size = { width: 390, height: 844 };
+ fixture.openLink.mockResolvedValue({});
+ fixture.invoke.mockImplementation(async (_device, _channel, [request]) => {
+ switch (request.op) {
+ case "capabilities":
+ return {
+ version: 1,
+ automaticReconnect: true,
+ enabled: true,
+ canControl: fixture.canControl,
+ platform: "darwin",
+ displays: [display],
+ };
+ case "start":
+ return {
+ lease: "lease",
+ controlling: false,
+ display: { ...display, id: request.displayId },
+ };
+ case "control":
+ return { controlling: request.enabled };
+ default:
+ return {};
+ }
+ });
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ mounted = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+});
+afterEach(() => {
+ if (mounted) act(() => root.unmount());
+ host.remove();
+ vi.useRealTimers();
+});
+const connect = async () => {
+ await act(async () => {
+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } });
+ });
+ act(() => {
+ fixture.message!({ nativeEvent: { data: '{"type":"framePresented","epoch":"lease"}' } });
+ });
+};
+
+describe("remote desktop controls", () => {
+ it("keeps a video answer arriving after control initialization and ignores it after exit", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ let control!: (value: object) => void;
+ let answer!: (value: object) => void;
+ fixture.invoke.mockImplementation((...args) => {
+ if (args[2][0].op === "control")
+ return new Promise((resolve) => {
+ control = resolve;
+ });
+ if (args[2][0].op === "offer")
+ return new Promise((resolve) => {
+ answer = resolve;
+ });
+ return original(...args);
+ });
+ await connect();
+ expect(host.querySelector('[data-testid="remoteDesktop.connectingStatus"]')).not.toBeNull();
+ expect(host.textContent).not.toContain("remoteDesktop.viewOnly");
+ const offer = () =>
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({ type: "offer", epoch: "lease", sdp: "offer" }),
+ },
+ });
+ act(offer);
+ await act(async () => control({ controlling: true }));
+ expect(host.querySelector('[data-testid="remoteDesktop.connectingStatus"]')).toBeNull();
+ await act(async () => answer({ sdp: "valid-answer" }));
+ expect(sent()).toContainEqual({ type: "answer", sdp: "valid-answer" });
+ act(offer);
+ act(() => root.unmount());
+ mounted = false;
+ await act(async () => answer({ sdp: "late-answer" }));
+ expect(sent()).not.toContainEqual({ type: "answer", sdp: "late-answer" });
+ });
+ it("shows live receive rate, rejects old lease samples, and expires stale metrics", async () => {
+ await connect();
+ const message = (data: object) =>
+ act(() =>
+ fixture.message!({ nativeEvent: { data: JSON.stringify(data) } }),
+ );
+ message({ type: "streaming", epoch: "lease" });
+ message({
+ type: "network",
+ epoch: "lease",
+ transport: "direct",
+ bytesPerSecond: 125000,
+ latencyMs: 42,
+ });
+ const badge = () =>
+ host.querySelector('[data-testid="remoteDesktop.network"]')!.textContent;
+ expect(badge()).toContain("remoteDesktop.directConnection");
+ expect(badge()).toContain("125 KB/s");
+ expect(badge()).toContain("remoteDesktop.roundTrip");
+ message({
+ type: "network",
+ epoch: "old-lease",
+ transport: "relay",
+ bytesPerSecond: 999000,
+ });
+ expect(badge()).toContain("remoteDesktop.directConnection");
+ await act(async () => vi.advanceTimersByTimeAsync(6000));
+ expect(badge()).toContain("— KB/s");
+ expect(badge()).not.toContain("remoteDesktop.roundTrip");
+ message({ type: "fallback", epoch: "lease" });
+ message({
+ type: "network",
+ epoch: "lease",
+ transport: "direct",
+ bytesPerSecond: 999000,
+ });
+ expect(badge()).toContain("remoteDesktop.connecting");
+ expect(badge()).not.toContain("999 KB/s");
+ });
+ it("keeps waiting for a temporarily absent capture source without restarting the lease", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "frame"
+ ? Promise.resolve({ jpeg: null })
+ : original(...args),
+ );
+ await connect();
+ await act(async () => vi.advanceTimersByTimeAsync(8000));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ expect(requests().some((r) => r.op === "stop")).toBe(false);
+ expect(host.textContent).toContain("remoteDesktop.connecting");
+ expect(host.textContent).not.toContain("remoteDesktop.screenshotRelay");
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "frame"
+ ? Promise.resolve({ jpeg: "a".repeat(4000) })
+ : original(...args),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+ expect(host.textContent).toContain("remoteDesktop.screenshotRelay");
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ });
+ it("measures screenshot payloads separately and clears frame time when frames stop", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "frame"
+ ? new Promise((resolve) =>
+ setTimeout(() => resolve({ jpeg: "a".repeat(4000) }), 100),
+ )
+ : original(...args),
+ );
+ await connect();
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+ const badge = () =>
+ host.querySelector('[data-testid="remoteDesktop.network"]')!.textContent;
+ expect(badge()).toContain("remoteDesktop.screenshotRelay");
+ expect(badge()).toContain("6 KB/s");
+ expect(badge()).toContain("remoteDesktop.frameTime");
+ expect(badge()).not.toContain("remoteDesktop.roundTrip");
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "frame"
+ ? Promise.resolve({ jpeg: null })
+ : original(...args),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(6000));
+ expect(badge()).toContain("0 KB/s");
+ expect(badge()).not.toContain("remoteDesktop.frameTime");
+ });
+ it("shows upgrade for a structured unsupported-channel error without retrying", async () => {
+ fixture.invoke.mockRejectedValue(
+ Object.assign(
+ new Error(
+ "channel 'device-link:remote-desktop:v1' not allowed remotely",
+ ),
+ { code: "CHANNEL_NOT_ALLOWED" },
+ ),
+ );
+ await connect();
+ expect(host.textContent).toContain("remoteDesktop.upgrade");
+ await act(async () => vi.advanceTimersByTimeAsync(60_000));
+ expect(fixture.invoke).toHaveBeenCalledTimes(1);
+ expect(requests().some((r) => r.op === "start")).toBe(false);
+ });
+ it("marks retries as recovery even when the first start reply was lost", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "start"
+ ? Promise.reject(
+ new Error(
+ args[2][0].resume ? "DESKTOP_STOPPED" : "REQUEST_TIMEOUT",
+ ),
+ )
+ : original(...args),
+ );
+ await connect();
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(requests().filter((r) => r.op === "start")).toEqual([
+ { op: "start", displayId: "display" },
+ { op: "start", displayId: "display", resume: true },
+ ]);
+ expect(button("connect")).not.toBeNull();
+ });
+ it("keeps explicit display switching available on older hosts", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation(async (...args) => {
+ const result = await original(...args);
+ return args[2][0].op === "capabilities"
+ ? {
+ ...result,
+ automaticReconnect: undefined,
+ displays: [display, { ...display, id: "second" }],
+ }
+ : result;
+ });
+ await connect();
+ act(() => button("operations").click());
+ act(() => [...host.querySelectorAll("button")].find((item) => item.textContent?.includes("remoteDesktop.displaySettings"))!.click());
+ await act(async () => button("display").click());
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ await act(async () =>
+ host
+ .querySelector<HTMLButtonElement>(
+ '[data-testid="remoteDesktop.display.second"]',
+ )!
+ .click(),
+ );
+ expect(
+ requests()
+ .filter((r) => r.op === "start")
+ .at(-1),
+ ).toEqual({ op: "start", displayId: "second" });
+ expect(host.textContent).not.toContain("remoteDesktop.upgrade");
+ });
+ it("does not automatically resume through an older host that cannot preserve local stops", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation(async (...args) => {
+ const result = await original(...args);
+ return args[2][0].op === "capabilities"
+ ? { ...result, automaticReconnect: undefined }
+ : result;
+ });
+ await connect();
+ fixture.status = "offline";
+ act(() => root.render(<RemoteDesktopScreen />));
+ fixture.status = "online";
+ await act(async () => root.render(<RemoteDesktopScreen />));
+ expect(host.textContent).toContain("remoteDesktop.upgrade");
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ });
+ it("releases a late lease after Back without initializing the viewer", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ let finish!: (result: unknown) => void;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "start"
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ await connect();
+ act(() => button("back").click());
+ await act(async () =>
+ finish({ lease: "late", display, controlling: false }),
+ );
+ expect(requests()).toContainEqual({ op: "stop", lease: "late" });
+ expect(sent().some((m) => m.type === "init")).toBe(false);
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ });
+ it("preserves host stop while offline and lets only explicit reconnect start over", async () => {
+ await connect();
+ fixture.status = "offline";
+ act(() => root.render(<RemoteDesktopScreen />));
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "start" && args[2][0].resume
+ ? Promise.reject(new Error("DESKTOP_STOPPED"))
+ : original(...args),
+ );
+ fixture.status = "online";
+ await act(async () => root.render(<RemoteDesktopScreen />));
+ expect(requests()).toContainEqual({
+ op: "start",
+ displayId: "display",
+ resume: true,
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(2);
+ await act(async () => button("connect").click());
+ expect(
+ requests()
+ .filter((r) => r.op === "start")
+ .at(-1),
+ ).toEqual({ op: "start", displayId: "display" });
+ });
+ it("reloads a viewer that died while permissions were blocked", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "control"
+ ? Promise.reject(new Error("DESKTOP_ACCESSIBILITY_PERMISSION"))
+ : original(...args),
+ );
+ await connect();
+ act(() => fixture.crashed!());
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(fixture.reload).not.toHaveBeenCalled();
+ act(() => fixture.retryPermissions!());
+ expect(fixture.reload).toHaveBeenCalledTimes(1);
+ });
+ it("restores the chosen input mode after view-only control", async () => {
+ await connect();
+ act(() => button("operations").click());
+ act(() => button("pointer").click());
+ expect(sent().at(-1)).toEqual({ type: "mode", mode: "pointer" });
+ await act(async () => button("viewOnly").click());
+ expect(
+ sent()
+ .filter((m) => m.type === "mode")
+ .at(-1),
+ ).toEqual({ type: "mode", mode: "pan" });
+ expect(host.textContent).toContain("remoteDesktop.viewOnlyHint");
+ await act(async () => button("viewOnly").click());
+ expect(
+ sent()
+ .filter((m) => m.type === "mode")
+ .at(-1),
+ ).toEqual({ type: "mode", mode: "pointer" });
+ act(() => button("touch").click());
+ expect(button("pan")).toBeNull();
+ expect(sent().at(-1)).toEqual({ type: "mode", mode: "touch" });
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ });
+ it("shows virtual mouse buttons outside the panel and hides them while viewing only", async () => {
+ await connect();
+ act(() => button("operations").click());
+ expect(button("rightClick")).toBeNull();
+ act(() => button("showMouseButtons").click());
+ expect(button("showMouseButtons").getAttribute("aria-checked")).toBe(
+ "true",
+ );
+ act(() => button("close").click());
+ expect(
+ sent()
+ .filter((m) => m.type === "mouseButtons")
+ .at(-1),
+ ).toMatchObject({ enabled: true });
+ expect(
+ host.querySelector('[data-testid="remoteDesktop.operationsPanel"]'),
+ ).toBeNull();
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ expect(
+ sent()
+ .filter((m) => m.type === "mouseButtons")
+ .at(-1),
+ ).toMatchObject({ enabled: false });
+ expect(host.textContent).toContain("remoteDesktop.viewOnlyHint");
+ expect(button("fit")).toBeNull();
+ act(() => button("close").click());
+ expect(
+ host.querySelector('[data-testid="remoteDesktop.operationsPanel"]'),
+ ).toBeNull();
+ });
+ it("requests control on entry and keeps only four persistent tools", async () => {
+ await connect();
+ expect(requests()).toContainEqual({
+ op: "control",
+ lease: "lease",
+ enabled: true,
+ });
+ expect(sent()).toContainEqual({ type: "control", enabled: true });
+ expect(sent()).toContainEqual({ type: "mode", mode: "touch" });
+ expect(
+ host
+ .querySelector('[data-testid="remoteDesktop.toolbar"]')!
+ .querySelectorAll("button"),
+ ).toHaveLength(4);
+ expect(host.textContent).not.toContain("My Mac");
+ const viewer = host.querySelector('[data-testid="remoteDesktop.viewer"]');
+ act(() => button("operations").click());
+ expect(host.textContent).toContain("My Mac");
+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(
+ viewer,
+ );
+ await act(async () => button("viewOnly").click());
+ expect(requests()).toContainEqual({
+ op: "control",
+ lease: "lease",
+ enabled: false,
+ });
+ expect(button("keyboard").disabled).toBe(true);
+ await connect();
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled),
+ ).toHaveLength(1);
+ expect(button("keyboard").disabled).toBe(true);
+ await act(async () => button("viewOnly").click());
+ expect(button("keyboard").disabled).toBe(false);
+ });
+ it("rotation preserves the viewer and control lease", async () => {
+ await connect();
+ expect(button("back")).not.toBeNull();
+ const viewer = host.querySelector('[data-testid="remoteDesktop.viewer"]');
+ fixture.size = { width: 844, height: 390 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ expect(button("back")).toBeNull();
+ fixture.size = { width: 390, height: 844 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ expect(button("back")).not.toBeNull();
+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(
+ viewer,
+ );
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ });
+ it("does not request unsupported input and preserves permission failures", async () => {
+ fixture.canControl = false;
+ await connect();
+ expect(requests().some((r) => r.op === "control")).toBe(false);
+ expect(button("keyboard").disabled).toBe(true);
+ });
+ it("ends the lease and displays the permission guide when control is denied", async () => {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "control"
+ ? Promise.reject(new Error("DESKTOP_ACCESSIBILITY_PERMISSION"))
+ : original(...args),
+ );
+ await connect();
+ expect(requests()).toContainEqual({ op: "stop", lease: "lease" });
+ expect(host.textContent).toContain("permission guide");
+ expect(host.textContent).not.toContain("remoteDesktop.permissionHint");
+ expect(sent()).not.toContainEqual({ type: "control", enabled: true });
+ });
+ it("does not restore control when its grant arrives after leaving", async () => {
+ let resolve!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "control"
+ ? new Promise((r) => {
+ resolve = r;
+ })
+ : original(...args),
+ );
+ await connect();
+ act(() => root.unmount());
+ mounted = false;
+ await act(async () => resolve({ controlling: true }));
+ expect(requests()).toContainEqual({ op: "stop", lease: "lease" });
+ expect(sent()).not.toContainEqual({ type: "control", enabled: true });
+ });
+ it("keeps portrait Back available before connection, while controlling and during recovery", async () => {
+ expect(button("back").disabled).toBe(false);
+ expect(button("connect")).toBeNull();
+ await connect();
+ expect(button("back").disabled).toBe(false);
+ fixture.status = "offline";
+ act(() => root.render(<RemoteDesktopScreen />));
+ expect(host.textContent).toContain("remoteDesktop.reconnecting");
+ expect(host.textContent).not.toContain("My Mac");
+ act(() => button("back").click());
+ expect(goBackGuarded).toHaveBeenCalledTimes(1);
+ fixture.status = "online";
+ await act(async () => root.render(<RemoteDesktopScreen />));
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ await connect(); // Even a late WebView ready event cannot re-enter.
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ });
+ it("automatically resumes after network loss and keeps view-only preference", async () => {
+ await connect();
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ fixture.status = "offline";
+ act(() => root.render(<RemoteDesktopScreen />));
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ fixture.status = "online";
+ await act(async () => root.render(<RemoteDesktopScreen />));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(2);
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled),
+ ).toHaveLength(1);
+ expect(fixture.openLink.mock.calls.every(([id]) => id === "computer")).toBe(
+ true,
+ );
+ });
+ it("keeps the lease during an interrupted iOS Home gesture", async () => {
+ await connect();
+ const starts = requests().filter((r) => r.op === "start").length;
+ const stops = requests().filter((r) => r.op === "stop").length;
+ act(() => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(stops);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ await act(async () => {
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(starts);
+ });
+ it("releases in background and reconnects only after foreground and focus return", async () => {
+ await connect();
+ act(() => {
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ fixture.focused = false;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await act(async () => {
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ fixture.focused = true;
+ await act(async () => root.render(<RemoteDesktopScreen />));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(2);
+ });
+ it("backs off transient failures and cancels pending recovery when leaving", async () => {
+ fixture.openLink.mockRejectedValue(new Error("DEVICE_OFFLINE"));
+ await connect();
+ expect(host.textContent).toContain("remoteDesktop.reconnecting");
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(fixture.openLink.mock.calls.length).toBeGreaterThan(1);
+ expect(fixture.openLink.mock.calls.length).toBeLessThanOrEqual(6);
+ const attempts = fixture.openLink.mock.calls.length;
+ act(() => button("back").click());
+ await act(async () => vi.advanceTimersByTimeAsync(60_000));
+ expect(fixture.openLink).toHaveBeenCalledTimes(attempts);
+ });
+ it("restarts a crashed viewer automatically without restoring it after exit", async () => {
+ await connect();
+ act(() => fixture.crashed!());
+ expect(host.textContent).toContain("remoteDesktop.reconnecting");
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ expect(fixture.reload).toHaveBeenCalledTimes(1);
+ await connect();
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(2);
+ act(() => button("back").click());
+ act(() => fixture.crashed!());
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(fixture.reload).toHaveBeenCalledTimes(1);
+ });
+ it.each([
+ "DESKTOP_STOPPED",
+ "DESKTOP_DISABLED",
+ "DESKTOP_ACCESSIBILITY_PERMISSION",
+ ])("does not retry a terminal host decision: %s", async (error) => {
+ await connect();
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "heartbeat"
+ ? Promise.reject(new Error(error))
+ : original(...args),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
+ expect(button("back").disabled).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
new file mode 100644
index 0000000000..9526670151
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
@@ -0,0 +1,480 @@
+import { describe, expect, it, vi } from "vitest";
+import vm from "node:vm";
+import { DESKTOP_TRANSFORM_SCRIPT } from "../geometry";
+import { remoteDesktopViewerHtml } from "../viewerHtml";
+
+const desktopTransform = vm.runInNewContext(
+ `(${DESKTOP_TRANSFORM_SCRIPT})`,
+) as (
+ vw: number,
+ vh: number,
+ dw: number,
+ dh: number,
+ zoom: number,
+ fx: number,
+ fy: number,
+ fillHeight?: boolean,
+) => { x: number; y: number; width: number; height: number; scale: number };
+
+function viewer() {
+ const messages: Array<{
+ type: string;
+ epoch: string;
+ sequence: number;
+ events?: Array<{ kind: string; code?: string }>;
+ }> = [];
+ const listeners: Record<string, (event: unknown) => void> = {};
+ const documentListeners: Record<string, (event: unknown) => void> = {};
+ const windowListeners: Record<string, (event: unknown) => void> = {};
+ const elements = Object.fromEntries(
+ [
+ "stage",
+ "keyboard-input",
+ "image",
+ "video",
+ "cursor",
+ "cursor-image",
+ "mouse-buttons",
+ "mouse-left",
+ "mouse-right",
+ "mouse-middle",
+ "mouse-wheel",
+ "mouse-wheel-grip",
+ "mouse-up",
+ "mouse-down",
+ ].map((id) => [
+ id,
+ {
+ clientWidth: 400,
+ clientHeight: 600,
+ style: {} as Record<string, string>,
+ addEventListener: (name: string, handler: (e: unknown) => void) => {
+ listeners[`${id}:${name}`] = handler;
+ },
+ value: "",
+ focus() {},
+ blur() {},
+ setSelectionRange() {},
+ setAttribute() {},
+ setPointerCapture() {},
+ removeAttribute() {},
+ play: async () => {},
+ },
+ ]),
+ );
+ const intervals: Array<() => void> = [];
+ const frames = new Map<number, () => void>();
+ let id = 0;
+ let now = 0;
+ const source = remoteDesktopViewerHtml("#fff", "#111").match(
+ /<script>([\s\S]*)<\/script>/,
+ )![1];
+ vm.runInNewContext(source, {
+ Date: { now: () => now },
+ performance: { now: () => now },
+ matchMedia: () => ({ matches: false }),
+ document: {
+ getElementById: (key: string) => elements[key],
+ addEventListener: (key: string, fn: (e: unknown) => void) => {
+ documentListeners[key] = fn;
+ },
+ body: { style: {} },
+ documentElement: { style: { setProperty() {} } },
+ },
+ window: {
+ ReactNativeWebView: {
+ postMessage: (text: string) => messages.push(JSON.parse(text)),
+ },
+ addEventListener: (key: string, fn: (e: unknown) => void) => {
+ windowListeners[key] = fn;
+ },
+ },
+ ResizeObserver: class {
+ observe() {}
+ },
+ setInterval: (fn: () => void) => intervals.push(fn),
+ clearInterval() {},
+ setTimeout: () => 1,
+ clearTimeout() {},
+ requestAnimationFrame: (fn: () => void) => {
+ frames.set(++id, fn);
+ return id;
+ },
+ cancelAnimationFrame: (key: number) => frames.delete(key),
+ });
+ return {
+ messages,
+ elements,
+ send: (message: object) =>
+ windowListeners.message({ data: JSON.stringify(message) }),
+ flush: () => intervals.forEach((fn) => fn()),
+ frame: (elapsed = 16) => {
+ now += elapsed;
+ const pending = [...frames.values()];
+ frames.clear();
+ pending.forEach((fn) => fn());
+ },
+ pointer: (type: string, pointerId: number, x: number, y: number) =>
+ listeners[`stage:${type}`]({
+ type,
+ pointerId,
+ clientX: x,
+ clientY: y,
+ preventDefault() {},
+ }),
+ mouse: (name: string, type: string, y = 0, target = `mouse-${name}`) =>
+ listeners[`mouse-${name}:${type}`]({
+ type,
+ pointerId: 9,
+ clientY: y,
+ target: { id: target },
+ detail: 1,
+ preventDefault() {},
+ }),
+ ack: () => {
+ const last = messages.filter((m) => m.type === "input").at(-1);
+ if (last)
+ windowListeners.message({
+ data: JSON.stringify({
+ type: "ack",
+ epoch: last.epoch,
+ sequence: last.sequence,
+ }),
+ });
+ },
+ blur: () => windowListeners.blur({}),
+ key: (type: string, code: string) =>
+ documentListeners[type]({ code, preventDefault() {} }),
+ };
+}
+
+describe("remote desktop viewport", () => {
+ it.each([
+ ["left", 0],
+ ["right", 2],
+ ] as const)(
+ "holds and releases the virtual %s button without adding stage clicks",
+ (name, button) => {
+ const v = viewer();
+ v.send({ type: "init", epoch: "one", width: 1920, height: 1080 });
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse(name, "pointerdown");
+ v.ack();
+ v.pointer("pointerdown", 1, 200, 200);
+ v.pointer("pointerup", 1, 200, 200);
+ v.mouse(name, "pointerup");
+ expect(
+ v.messages
+ .flatMap((m) => m.events ?? [])
+ .filter((e) => e.kind === "button"),
+ ).toEqual([
+ { kind: "button", button, down: true, x: 0.5, y: 0.5 },
+ { kind: "button", button, down: false, x: 0.5, y: 0.5 },
+ ]);
+ },
+ );
+ it.each(["pointercancel", "lostpointercapture"])(
+ "releases held buttons on %s",
+ (end) => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse("left", "pointerdown");
+ v.ack();
+ v.mouse("left", end);
+ expect(v.messages.at(-1)?.events?.[0]).toMatchObject({
+ kind: "button",
+ button: 0,
+ down: false,
+ });
+ },
+ );
+ it("releases when hidden and prevents input in view-only mode", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse("right", "pointerdown");
+ v.ack();
+ v.send({ type: "mouseButtons", enabled: false });
+ expect(v.messages.at(-1)?.events?.[0]).toMatchObject({
+ kind: "button",
+ button: 2,
+ down: false,
+ });
+ expect(v.elements["mouse-buttons"].style.display).toBe("none");
+ v.ack();
+ v.send({ type: "control", enabled: false });
+ v.send({ type: "mouseButtons", enabled: true });
+ const count = v.messages.length;
+ v.mouse("left", "pointerdown");
+ v.mouse("wheel", "pointerdown", 100);
+ v.mouse("wheel", "pointermove", 50);
+ v.flush();
+ expect(v.messages).toHaveLength(count);
+ expect(v.elements["mouse-buttons"].style.display).toBe("none");
+ });
+ it("scrolls by dragging the wheel and cancels without an extra step", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse("wheel", "pointerdown", 100);
+ v.frame(300);
+ v.mouse("wheel", "pointermove", 80);
+ v.flush();
+ v.ack();
+ v.mouse("wheel", "pointercancel", 80);
+ v.mouse("wheel", "pointerup", 80);
+ v.flush();
+ expect(v.messages.flatMap((m) => m.events ?? [])).toEqual([
+ { kind: "scroll", dx: 0, dy: -24 },
+ ]);
+ });
+ it("taps the combined wheel as middle click without scrolling", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse("wheel", "pointerdown", 100);
+ v.frame(100);
+ v.mouse("wheel", "pointerup", 100);
+ expect(v.messages.flatMap((m) => m.events ?? [])).toEqual([
+ { kind: "button", button: 1, down: true, x: .5, y: .5 },
+ { kind: "button", button: 1, down: false, x: .5, y: .5 },
+ ]);
+ });
+ it("keeps scrolling while held, reverses direction and stops on release", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse("wheel", "pointerdown", 100);
+ v.mouse("wheel", "pointermove", 90);
+ v.flush(); v.ack();
+ v.flush(); v.ack(); // No new movement: still scrolls.
+ v.mouse("wheel", "pointermove", 124);
+ v.flush(); v.ack();
+ v.mouse("wheel", "pointermove", 100);
+ v.flush(); // Center dead zone stops scrolling.
+ v.mouse("wheel", "pointerup", 100);
+ v.flush();
+ expect(v.messages.flatMap((m) => m.events ?? [])).toEqual([
+ { kind: "scroll", dx: 0, dy: -9 },
+ { kind: "scroll", dx: 0, dy: -9 },
+ { kind: "scroll", dx: 0, dy: 30 },
+ ]);
+ expect(v.elements["mouse-wheel-grip"].style.transform).toBe("translateY(0px)");
+ });
+ it("does not accumulate held wheel ticks while awaiting acknowledgement", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "mouseButtons", enabled: true });
+ v.mouse("wheel", "pointerdown", 1000);
+ v.mouse("wheel", "pointermove", 990);
+ v.flush();
+ for (let y = 989; y >= 890; y--) {
+ v.mouse("wheel", "pointermove", y);
+ v.flush();
+ }
+ expect(v.messages.some((message) => message.type === "inputOverflow")).toBe(false);
+ v.ack();
+ v.flush();
+ expect(v.messages.flatMap((message) => message.events ?? [])).toEqual([
+ { kind: "scroll", dx: 0, dy: -9 },
+ { kind: "scroll", dx: 0, dy: -30 },
+ ]);
+ });
+ it("fills landscape height for wide desktops and restores portrait fitting", () => {
+ const v = viewer();
+ v.elements.stage.clientWidth = 678;
+ v.elements.stage.clientHeight = 402;
+ v.send({
+ type: "init",
+ epoch: "landscape",
+ width: 2560,
+ height: 1080,
+ fillHeight: true,
+ });
+ for (const element of [v.elements.image, v.elements.video]) {
+ expect(element.style.height).toBe("402px");
+ expect(element.style.top).toBe("0px");
+ expect(parseFloat(element.style.width)).toBeGreaterThan(678);
+ }
+ v.send({ type: "fit" });
+ expect(v.elements.image.style.top).toBe("0px");
+ v.elements.stage.clientWidth = 400;
+ v.elements.stage.clientHeight = 700;
+ v.send({ type: "viewport", fillHeight: false });
+ expect(v.elements.image.style.width).toBe("400px");
+ expect(parseFloat(v.elements.image.style.top)).toBeGreaterThan(0);
+ });
+ it("initializes when the native engine cannot serialize function source", () => {
+ const stringify = vi
+ .spyOn(Function.prototype, "toString")
+ .mockReturnValue("function () { [native code] }");
+ let result: ReturnType<typeof viewer>;
+ try {
+ result = viewer();
+ } finally {
+ stringify.mockRestore();
+ }
+ expect(result.messages[0]).toMatchObject({ type: "ready" });
+ expect(result.elements.image.style.width).toBe("400px");
+ });
+ it("fits without cropping the computer in portrait and landscape", () => {
+ for (const [w, h] of [
+ [390, 650],
+ [760, 300],
+ [390, 260],
+ ]) {
+ const rect = desktopTransform(w, h, 1920, 1080, 1, 0.5, 0.5);
+ expect(rect.x).toBeGreaterThanOrEqual(0);
+ expect(rect.y).toBeGreaterThanOrEqual(0);
+ expect(rect.x + rect.width).toBeLessThanOrEqual(w);
+ expect(rect.y + rect.height).toBeLessThanOrEqual(h);
+ }
+ });
+ it("preserves the focus at the viewport center across rotation and keyboard resize", () => {
+ for (const [w, h] of [
+ [390, 650],
+ [760, 300],
+ [390, 260],
+ ]) {
+ const rect = desktopTransform(w, h, 1920, 1080, 5, 0.6, 0.6);
+ expect((w / 2 - rect.x) / rect.width).toBeCloseTo(0.6);
+ expect((h / 2 - rect.y) / rect.height).toBeCloseTo(0.6);
+ }
+ });
+ it("compiles the actual inline viewer and rejects HTML injection through theme values", () => {
+ const html = remoteDesktopViewerHtml(
+ "</style><script>alert(1)</script>",
+ "#fff",
+ );
+ expect(html).not.toContain("alert(1)");
+ const source = html.match(/<script>([\s\S]*)<\/script>/)?.[1];
+ expect(source).toBeTruthy();
+ expect(() => new vm.Script(source!)).not.toThrow();
+ });
+ it("keeps ArrowRight and reconnects after a bridge input was left unacknowledged", () => {
+ const v = viewer();
+ v.send({ type: "init", epoch: "first", width: 1920, height: 1080 });
+ v.send({ type: "control", enabled: true });
+ v.key("keydown", "ArrowRight");
+ v.flush();
+ expect(v.messages.at(-1)?.events?.[0]).toEqual({
+ kind: "key",
+ code: "ArrowRight",
+ down: true,
+ });
+ v.send({ type: "stop" });
+ v.send({ type: "init", epoch: "second", width: 1920, height: 1080 });
+ v.send({ type: "control", enabled: true });
+ v.send({ type: "ack", epoch: "first", sequence: 1 });
+ v.key("keydown", "KeyA");
+ v.flush();
+ expect(v.messages.at(-1)?.epoch).toBe("second");
+ expect(v.messages.at(-1)?.events?.[0].code).toBe("KeyA");
+ });
+ it.each([false, true])(
+ "recognizes a small pinch with control=%s",
+ (control) => {
+ const v = viewer();
+ v.send({ type: "control", enabled: control });
+ v.pointer("pointerdown", 1, 100, 200);
+ v.pointer("pointerdown", 2, 300, 200);
+ v.pointer("pointermove", 1, 95, 200);
+ v.pointer("pointermove", 2, 305, 200);
+ v.frame();
+ v.frame(40);
+ expect(parseFloat(v.elements.image.style.width)).toBeCloseTo(420);
+ v.flush();
+ expect(v.messages.flatMap((m) => m.events ?? [])).toEqual([]);
+ },
+ );
+ it("allows one finger to lead a pinch instead of locking into scroll", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.pointer("pointerdown", 1, 100, 200);
+ v.pointer("pointerdown", 2, 300, 200);
+ v.pointer("pointermove", 1, 86, 200);
+ v.frame();
+ v.frame(40);
+ expect(parseFloat(v.elements.image.style.width)).toBeCloseTo(428);
+ v.pointer("pointermove", 2, 320, 200);
+ v.frame();
+ expect(parseFloat(v.elements.image.style.width)).toBeCloseTo(468);
+ });
+ it("can turn an initial scroll into a pinch without a zoom jump", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.pointer("pointerdown", 1, 100, 200);
+ v.pointer("pointerdown", 2, 300, 200);
+ v.pointer("pointermove", 1, 110, 200);
+ v.pointer("pointermove", 2, 310, 200);
+ v.frame();
+ v.flush();
+ expect(v.messages.at(-1)?.events?.[0].kind).toBe("scroll");
+ v.pointer("pointermove", 1, 82, 200);
+ v.pointer("pointermove", 2, 320, 200);
+ v.frame();
+ v.frame(40);
+ expect(v.elements.image.style.width).toBe("400px");
+ v.pointer("pointermove", 1, 72, 200);
+ v.pointer("pointermove", 2, 330, 200);
+ v.frame();
+ expect(parseFloat(v.elements.image.style.width)).toBeCloseTo(
+ (400 * 258) / 238,
+ );
+ });
+ it("does not mistake staggered parallel updates for a pinch", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.pointer("pointerdown", 1, 100, 200);
+ v.pointer("pointerdown", 2, 300, 200);
+ for (const delta of [10, 20, 30]) {
+ v.pointer("pointermove", 1, 100 + delta, 200);
+ v.frame();
+ v.pointer("pointermove", 2, 300 + delta, 200);
+ v.frame();
+ }
+ v.frame(60);
+ v.flush();
+ expect(v.elements.image.style.width).toBe("400px");
+ expect(v.messages.at(-1)?.events?.every((e) => e.kind === "scroll")).toBe(
+ true,
+ );
+ });
+ it("applies the last pinch position before lifting a finger without clicking", () => {
+ const v = viewer();
+ v.send({ type: "control", enabled: true });
+ v.pointer("pointerdown", 1, 100, 200);
+ v.pointer("pointerdown", 2, 300, 200);
+ v.pointer("pointermove", 1, 90, 200);
+ v.pointer("pointermove", 2, 310, 200);
+ v.frame();
+ v.frame(40);
+ v.pointer("pointermove", 1, 80, 200);
+ v.pointer("pointerup", 2, 340, 200);
+ expect(parseFloat(v.elements.image.style.width)).toBeCloseTo(520);
+ v.pointer("pointerup", 1, 80, 200);
+ v.frame();
+ v.flush();
+ expect(v.messages.flatMap((m) => m.events ?? [])).toEqual([]);
+ });
+ it("recognizes parallel two-finger movement as scrolling, not a pinch", () => {
+ const v = viewer();
+ v.send({ type: "init", epoch: "one", width: 1920, height: 1080 });
+ v.send({ type: "control", enabled: true });
+ v.pointer("pointerdown", 1, 100, 200);
+ v.pointer("pointerdown", 2, 200, 200);
+ v.pointer("pointermove", 1, 110, 200);
+ v.pointer("pointermove", 2, 210, 200);
+ v.frame();
+ v.pointer("pointermove", 1, 120, 200);
+ v.pointer("pointermove", 2, 220, 200);
+ v.frame();
+ v.flush();
+ expect(v.elements.image.style.width).toBe("400px");
+ expect(
+ v.messages.at(-1)?.events?.every((event) => event.kind === "scroll"),
+ ).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/remote-desktop/clipboardTransfer.ts b/apps/mobile/src/remote-desktop/clipboardTransfer.ts
new file mode 100644
index 0000000000..5be6e8a2fa
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/clipboardTransfer.ts
@@ -0,0 +1,54 @@
+import {
+ CLIPBOARD_CHUNK_CHARS, CLIPBOARD_MAX_CHARS, parseClipboardContent,
+ type RemoteDesktopRequest,
+} from "@cindy/device-link";
+import { remotePresentation } from "../../modules/cindy-remote-presentation/src";
+
+/** Explicit transfer only. Sequential bounded invokes keep screen traffic responsive. */
+export async function transferClipboardContent(
+ action: "copy" | "paste",
+ lease: string,
+ request: <T>(message: RemoteDesktopRequest) => Promise<T>,
+ check: () => void,
+): Promise<void> {
+ if (!remotePresentation?.readClipboard || !remotePresentation.writeClipboard)
+ throw new Error("CLIPBOARD_UPGRADE");
+ let id: string | undefined;
+ try {
+ check();
+ if (action === "paste") {
+ const json = await remotePresentation.readClipboard();
+ check();
+ parseClipboardContent(json);
+ const result = await request<{ id: string }>({ op: "clipboardContent", lease, action: "begin", length: json.length });
+ id = result.id;
+ for (let offset = 0; offset < json.length; offset += CLIPBOARD_CHUNK_CHARS) {
+ check();
+ await request({ op: "clipboardContent", lease, action: "write", id, offset, data: json.slice(offset, offset + CLIPBOARD_CHUNK_CHARS) });
+ }
+ check();
+ await request({ op: "clipboardContent", lease, action: "commit", id });
+ check();
+ } else {
+ const result = await request<{ id: string; length: number }>({ op: "clipboardContent", lease, action: "copy" });
+ id = result.id;
+ if (!Number.isSafeInteger(result.length) || result.length <= 0 || result.length > CLIPBOARD_MAX_CHARS)
+ throw new Error("CLIPBOARD_TOO_LONG");
+ let json = "";
+ while (json.length < result.length) {
+ check();
+ const { data } = await request<{ data: string }>({ op: "clipboardContent", lease, action: "read", id, offset: json.length });
+ if (typeof data !== "string" || !data.length || data.length > CLIPBOARD_CHUNK_CHARS || json.length + data.length > result.length)
+ throw new Error("CLIPBOARD_UNSUPPORTED");
+ json += data;
+ }
+ check();
+ parseClipboardContent(json);
+ await remotePresentation.writeClipboard(json);
+ check();
+ }
+ } finally {
+ // Best-effort disposal only; never retry a paste after an uncertain response.
+ if (id) void request({ op: "clipboardContent", lease, action: "cancel", id }).catch(() => {});
+ }
+}
diff --git a/apps/mobile/src/remote-desktop/geometry.ts b/apps/mobile/src/remote-desktop/geometry.ts
new file mode 100644
index 0000000000..ad7826952f
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/geometry.ts
@@ -0,0 +1,28 @@
+// This runs inside the WebView. Keep its source literal: Hermes function.toString()
+// does not preserve executable JavaScript source, even in development builds.
+/** Preserve the remote focus point when the phone rotates or the keyboard resizes it. */
+export const DESKTOP_TRANSFORM_SCRIPT = String.raw`function desktopTransform(
+ vw,
+ vh,
+ dw,
+ dh,
+ zoom,
+ fx,
+ fy,
+ fillHeight = false,
+) {
+ const scale =
+ (fillHeight ? vh / Math.max(1, dh) : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *
+ Math.max(1, Math.min(5, zoom));
+ const width = dw * scale;
+ const height = dh * scale;
+ const x =
+ width <= vw
+ ? (vw - width) / 2
+ : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));
+ const y =
+ height <= vh
+ ? (vh - height) / 2
+ : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));
+ return { x, y, width, height, scale };
+}`;
diff --git a/apps/mobile/src/remote-desktop/networkStats.ts b/apps/mobile/src/remote-desktop/networkStats.ts
new file mode 100644
index 0000000000..121858e88a
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/networkStats.ts
@@ -0,0 +1,32 @@
+export type DesktopNetworkStats = {
+ transport: "video" | "direct" | "relay" | "screenshots";
+ bytesPerSecond: number | null;
+ latencyMs: number | null;
+ at: number;
+};
+
+export function formatReceiveRate(bytes: number | null): string {
+ if (bytes === null) return "— KB/s";
+ return bytes >= 1_000_000
+ ? `${(bytes / 1_000_000).toFixed(1)} MB/s`
+ : `${Math.round(bytes / 1000)} KB/s`;
+}
+
+// Executed in the WebView; keep literal source for Hermes.
+// https://www.w3.org/TR/webrtc-stats/ — received media bytes, selected ICE path, RTT.
+export const DESKTOP_NETWORK_STATS_SCRIPT = String.raw`function networkStats(stats, previous) {
+ const rows=[...stats.values()];
+ const video=rows.find(s=>s.type==='inbound-rtp'&&(s.kind==='video'||s.mediaType==='video'));
+ const transport=rows.find(s=>s.type==='transport'&&s.selectedCandidatePairId);
+ const pair=transport?stats.get(transport.selectedCandidatePairId):rows.find(s=>s.type==='candidate-pair'&&s.state==='succeeded'&&s.nominated);
+ const local=pair&&stats.get(pair.localCandidateId),remote=pair&&stats.get(pair.remoteCandidateId);
+ const direct=['host','srflx','prflx'];
+ const route=local?.candidateType==='relay'||remote?.candidateType==='relay'?'relay':direct.includes(local?.candidateType)&&direct.includes(remote?.candidateType)?'direct':'video';
+ const sample=video&&Number.isFinite(video.bytesReceived)&&Number.isFinite(video.timestamp)
+ ?{id:video.id,path:pair?.id,bytes:video.bytesReceived,time:video.timestamp}:null;
+ let bytesPerSecond=null;
+ if(sample&&previous&&sample.id===previous.id&&sample.path===previous.path&&sample.time>previous.time&&sample.bytes>=previous.bytes)
+ bytesPerSecond=(sample.bytes-previous.bytes)*1000/(sample.time-previous.time);
+ const latencyMs=Number.isFinite(pair?.currentRoundTripTime)&&pair.currentRoundTripTime>=0?pair.currentRoundTripTime*1000:null;
+ return {transport:route,bytesPerSecond,latencyMs,sample};
+}`;
diff --git a/apps/mobile/src/remote-desktop/useInputModePreference.ts b/apps/mobile/src/remote-desktop/useInputModePreference.ts
new file mode 100644
index 0000000000..d6107d2e9e
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/useInputModePreference.ts
@@ -0,0 +1,39 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+type InputMode = "touch" | "pointer";
+// Phone-local preference shared across remote computers. Only explicit choices
+// are persisted; absent or invalid values follow the default touch mode.
+const STORAGE_KEY = "cindy.mobile.remote-desktop.input-mode.v1";
+let writes: Promise<void> = Promise.resolve();
+
+export function useInputModePreference() {
+ const [mode, setMode] = useState<InputMode>("touch");
+ const edited = useRef(false);
+
+ useEffect(() => {
+ let active = true;
+ void writes
+ .then(() => AsyncStorage.getItem(STORAGE_KEY))
+ .then((value) => {
+ if (active && !edited.current && (value === "touch" || value === "pointer")) {
+ setMode(value);
+ }
+ })
+ .catch(() => undefined);
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ const update = useCallback((value: InputMode) => {
+ edited.current = true;
+ setMode(value);
+ // Serialize rapid changes and let a newly mounted screen await pending saves.
+ writes = writes
+ .then(() => AsyncStorage.setItem(STORAGE_KEY, value))
+ .catch(() => undefined);
+ }, []);
+
+ return [mode, update] as const;
+}
diff --git a/apps/mobile/src/remote-desktop/useMouseButtonsPreference.ts b/apps/mobile/src/remote-desktop/useMouseButtonsPreference.ts
new file mode 100644
index 0000000000..b53c7b7c38
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/useMouseButtonsPreference.ts
@@ -0,0 +1,36 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+// Device-local display preference, shared across remote computers. Absence means
+// the default (off); only an explicit toggle writes a boolean override.
+const STORAGE_KEY = "cindy.mobile.remote-desktop.show-mouse-buttons.v1";
+let writes: Promise<void> = Promise.resolve();
+
+export function useMouseButtonsPreference() {
+ const [enabled, setEnabled] = useState(false);
+ const edited = useRef(false);
+
+ useEffect(() => {
+ let active = true;
+ void writes
+ .then(() => AsyncStorage.getItem(STORAGE_KEY))
+ .then((value) => {
+ if (active && !edited.current) setEnabled(value === "true");
+ })
+ .catch(() => undefined);
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ const update = useCallback((value: boolean) => {
+ edited.current = true;
+ setEnabled(value);
+ // Preserve toggle order, including a quick exit and re-entry into the page.
+ writes = writes
+ .then(() => AsyncStorage.setItem(STORAGE_KEY, String(value)))
+ .catch(() => undefined);
+ }, []);
+
+ return [enabled, update] as const;
+}
diff --git a/apps/mobile/src/remote-desktop/useVideoSettingsPreference.ts b/apps/mobile/src/remote-desktop/useVideoSettingsPreference.ts
new file mode 100644
index 0000000000..8a9119551d
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/useVideoSettingsPreference.ts
@@ -0,0 +1,43 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import type { RemoteDesktopVideoSettings } from "@cindy/device-link";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+// Only the audio override persists on this phone; video quality stays session-local.
+const AUDIO_KEY = "cindy.mobile.remote-desktop.audio.v1";
+let writes: Promise<void> = Promise.resolve();
+
+export function useVideoSettingsPreference() {
+ const [settings, setSettings] = useState<RemoteDesktopVideoSettings>({
+ fps: 30, bitrate: 0, audio: true,
+ });
+ const [loaded, setLoaded] = useState(false);
+ const current = useRef(settings);
+ const edited = useRef(false);
+
+ useEffect(() => {
+ let active = true;
+ void writes
+ .then(() => AsyncStorage.getItem(AUDIO_KEY))
+ .then((value) => {
+ if (!active || edited.current || (value !== "true" && value !== "false")) return;
+ current.current = { ...current.current, audio: value === "true" };
+ setSettings(current.current);
+ })
+ .catch(() => undefined)
+ .finally(() => { if (active) setLoaded(true); });
+ return () => { active = false; };
+ }, []);
+
+ const update = useCallback((value: RemoteDesktopVideoSettings) => {
+ edited.current = true;
+ if (value.audio !== current.current.audio) {
+ writes = writes
+ .then(() => AsyncStorage.setItem(AUDIO_KEY, String(value.audio)))
+ .catch(() => undefined);
+ }
+ current.current = value;
+ setSettings(value);
+ }, []);
+
+ return [settings, update, loaded] as const;
+}
diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.ts
new file mode 100644
index 0000000000..7973630584
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts
@@ -0,0 +1,341 @@
+import { DESKTOP_TRANSFORM_SCRIPT } from "./geometry";
+import { DESKTOP_KEY_CODES } from "@cindy/device-link";
+import { DESKTOP_NETWORK_STATS_SCRIPT } from "./networkStats";
+
+export function remoteDesktopViewerHtml(
+ surface: string,
+ foreground: string,
+): string {
+ // Only theme token colors enter markup. No device names, SDP, or remote HTML.
+ const color = (v: string) =>
+ /^#[0-9a-f]{3,8}$/i.test(v) ? v : "transparent";
+ return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; media-src blob:; connect-src 'none'"><style>
+ *{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${color(surface)};touch-action:none;overscroll-behavior:none}#stage{position:absolute;inset:0;overflow:hidden;z-index:0}video,img{position:absolute;max-width:none;pointer-events:none;transform-origin:0 0}video{display:none}#cursor{position:absolute;z-index:2;width:18px;height:18px;border:2px solid ${color(foreground)};border-radius:50%;pointer-events:none;display:none;transform:translate(-50%,-50%)}
+ #cursor-image{position:absolute;inset:0;width:100%;height:100%}
+ #stage,#stage *{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-user-drag:none}
+ video,img{border:0;outline:0}img:not([src]){visibility:hidden}
+ :root{--surface:${color(surface)};--foreground:${color(foreground)}}
+ #keyboard-input{position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:.01;font-size:16px;pointer-events:none;border:0;padding:0;resize:none}
+ #mouse-buttons{position:absolute;inset:0;pointer-events:none;display:none;color:var(--foreground);opacity:.85}
+ #mouse-buttons button,#mouse-wheel{pointer-events:auto;touch-action:none;user-select:none;-webkit-user-select:none;color:inherit;background:color-mix(in srgb,var(--surface) 90%,var(--foreground));border:1px solid color-mix(in srgb,var(--foreground) 18%,transparent)}
+ .mouse-button{position:absolute;width:56px;height:56px;border-radius:9999px;padding:14px}
+ .mouse-button svg{width:100%;height:100%;pointer-events:none}
+ .mouse-button[aria-pressed="true"]{background:var(--foreground)!important;color:var(--surface)!important}
+ #mouse-left{left:calc(50% - 96px);bottom:16px}#mouse-right{left:calc(50% + 40px);bottom:16px}
+ #mouse-wheel{position:absolute;right:12px;bottom:80px;width:56px;height:120px;padding:12px 0;border-radius:9999px;display:flex;flex-direction:column;align-items:center;justify-content:space-between;font-size:20px}
+ #mouse-wheel:active{background:var(--foreground);color:var(--surface)}
+ #mouse-wheel>*{pointer-events:none}
+ #mouse-wheel-grip{width:20px;height:34px}
+ @media(max-height:400px){#mouse-wheel{bottom:12px}}
+ </style></head><body><div id="stage"><img id="image" alt=""><video id="video" autoplay muted playsinline></video><div id="cursor"><img id="cursor-image" alt=""></div></div>
+ <div id="mouse-buttons">
+ ${(["left", "right"] as const).map((button) => `<button type="button" id="mouse-${button}" class="mouse-button" aria-pressed="false"><svg viewBox="0 0 24 32" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="2" width="18" height="28" rx="9"/><path d="M12 2v12M3 14h18"/><path d="${button === "left" ? "M11 3C6 3 4 6 4 10v3h7Z" : "M13 3c5 0 7 3 7 7v3h-7Z"}" fill="currentColor" stroke="none"/></svg></button>`).join("")}
+ <button type="button" id="mouse-wheel"><span aria-hidden="true">▴</span><svg id="mouse-wheel-grip" viewBox="0 0 20 34" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="1" y="1" width="18" height="32" rx="8"/><path d="M3 10h14M2 17h16M3 24h14"/></svg><span aria-hidden="true">▾</span></button>
+ </div><textarea id="keyboard-input" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="Keyboard"></textarea><script>
+ const transform=${DESKTOP_TRANSFORM_SCRIPT};
+ const networkStats=${DESKTOP_NETWORK_STATS_SCRIPT};
+ const validKeys=new Set(${JSON.stringify(DESKTOP_KEY_CODES)});
+ ${VIEWER_SCRIPT}
+ </script></body></html>`;
+}
+
+const VIEWER_SCRIPT = String.raw`
+(() => {
+ const stage=document.getElementById('stage'), image=document.getElementById('image'), video=document.getElementById('video'), cursor=document.getElementById('cursor');
+ let dw=1920,dh=1080,zoom=1,fx=.5,fy=.5,mode='pointer',control=false,pc=null,dc=null,seq=0,generation=0,epoch=null,gestureFrame=null;
+ let remoteCursor=null,lastLocalMove=0,localCursorAwake=false;
+ let touchCursor=null,touchCursorTimer=null,touchCursorVisible=false;
+ const reducedMotion=matchMedia("(prefers-reduced-motion: reduce)");
+ const cursorImage=document.getElementById('cursor-image');
+ let pending=[],sending=false,cx=.5,cy=.5,drag=false,start=null,last=null,multi=null,hold=null,moved=false;
+ const pointers=new Map();
+ const mouseButtons=document.getElementById('mouse-buttons'), wheel=document.getElementById('mouse-wheel'), wheelGrip=document.getElementById('mouse-wheel-grip');
+ const keyboardInput=document.getElementById('keyboard-input');
+ let keyboardEnabled=false,composing=false;
+ const keyboardSentinel='\u200b';
+ function resetKeyboard(){keyboardInput.value=keyboardSentinel;keyboardInput.setSelectionRange(1,1);}
+ function showKeyboard(enabled){
+ keyboardEnabled=enabled&&control;
+ if(!keyboardEnabled){composing=false;resetKeyboard();keyboardInput.blur();return;}
+ if(composing)return;
+ // Keep focus inside the native evaluateJavaScript call; WebKit can reject
+ // keyboard presentation after requestAnimationFrame loses user activation.
+ keyboardInput.blur();resetKeyboard();keyboardInput.focus({preventScroll:true});
+ }
+ function keyboardKey(code){if(!keyboardEnabled||!control)return;queue({kind:'key',code,down:true});queue({kind:'key',code,down:false});flush();}
+ function commitKeyboard(){if(!keyboardEnabled||!control||composing)return;const text=keyboardInput.value.replace(keyboardSentinel,'');if(text){for(let i=0;i<text.length;i+=4096)queue({kind:'text',text:text.slice(i,i+4096)});flush();}resetKeyboard();}
+ keyboardInput.addEventListener('compositionstart',()=>{composing=true;});
+ keyboardInput.addEventListener('compositionend',()=>{composing=false;commitKeyboard();});
+ keyboardInput.addEventListener('input',e=>{if(!e.isComposing)commitKeyboard();});
+ keyboardInput.addEventListener('beforeinput',e=>{
+ if(composing||e.isComposing)return;
+ if(e.inputType==='deleteContentBackward'){e.preventDefault();keyboardKey('Backspace');resetKeyboard();}
+ else if(e.inputType==='insertLineBreak'||e.inputType==='insertParagraph'){e.preventDefault();keyboardKey('Enter');resetKeyboard();}
+ });
+ const heldMouse=new Map();
+ let showMouseButtons=false,wheelY=null;
+ function resetWheel(){wheelY=null;wheelGrip.style.transform='translateY(0px)';}
+ let statsTimer=null,statsSample=null;
+ const post=(message)=>window.ReactNativeWebView.postMessage(JSON.stringify({...message,epoch}));
+ const clamp=(v)=>Math.max(0,Math.min(1,v));
+ let fillHeight=false;
+ let panAnimation=null,viewportRightInset=0,viewportLeftInset=0,viewportBottomInset=0;
+ let cursorNeedsEntry=true,manualViewMoved=false,followRest=null;
+ // Insets guide centering and pan limits without clipping the full-screen
+ // video surface or adding an opaque strip beside the Dynamic Island.
+ const viewportLeft=()=>fillHeight?viewportLeftInset:0;
+ const viewportWidth=()=>Math.max(1,stage.clientWidth-viewportLeft()-(fillHeight?viewportRightInset:0));
+ const layout=()=>{const r=transform(viewportWidth(),stage.clientHeight,dw,dh,zoom,fx,fy,fillHeight);
+ return {...r,x:(viewportLeft()+viewportWidth()/2)-fx*r.width,y:stage.clientHeight/2-fy*r.height};};
+ function panBounds(r){const vw=viewportWidth(),vh=stage.clientHeight;
+ // Grow extra resting travel continuously from zero at fit to 180 screen
+ // points at maximum zoom. Never count the unused space of a fitting axis.
+ const clearance=180*(Math.max(1,Math.min(5,zoom))-1)/4;
+ const axis=(viewport,content)=>content<=viewport
+ ? {min:(viewport-content)/2-clearance,max:(viewport-content)/2+clearance}
+ : {min:viewport-content-clearance,max:clearance};
+ const x=axis(vw,r.width),y=axis(vh,r.height);
+ const bounds={minX:viewportLeft()+x.min,maxX:viewportLeft()+x.max,minY:y.min,maxY:y.max};
+ // A camera position required to expose the cursor is a valid resting point,
+ // not elastic overshoot. Preserve it across the next pan/pinch handoff.
+ if(followRest){const restX=viewportLeft()+vw/2-followRest.fx*r.width,restY=vh/2-followRest.fy*r.height;
+ const weight=followRest.zoom>1?clamp((zoom-1)/(followRest.zoom-1)):1;
+ bounds.minX+=Math.min(0,restX-bounds.minX)*weight;bounds.maxX+=Math.max(0,restX-bounds.maxX)*weight;
+ bounds.minY+=Math.min(0,restY-bounds.minY)*weight;bounds.maxY+=Math.max(0,restY-bounds.maxY)*weight;}
+ return bounds;}
+ const bounded=(v,min,max)=>Math.max(min,Math.min(max,v));
+ // Convert displayed overshoot back to finger travel before the next delta,
+ // so reversing direction unwinds smoothly without an edge jump.
+ function rubber(v,min,max,inverse=false){const edge=bounded(v,min,max),d=v-edge;
+ const reach=40+10*(Math.max(1,Math.min(5,zoom))-1);
+ return edge+Math.sign(d)*(inverse?reach*Math.abs(d)/Math.max(1,reach-Math.abs(d)):reach*Math.abs(d)/(reach+Math.abs(d)));}
+ function place(x,y,r){fx=((viewportLeft()+viewportWidth()/2)-x)/r.width;fy=(stage.clientHeight/2-y)/r.height;}
+ function cursorViewport(){
+ const hotX=remoteCursor?.hotX??9,hotY=remoteCursor?.hotY??9;
+ const w=remoteCursor?.width??18,h=remoteCursor?.height??18;
+ const left=viewportLeft(),right=left+viewportWidth(),bottom=Math.max(1,stage.clientHeight-viewportBottomInset);
+ // Keep the entire cursor, including its hotspot offset, clear of chrome.
+ const minX=Math.min(right-1,left+8+hotX),minY=Math.min(bottom-1,8+hotY);
+ return {minX,maxX:Math.max(minX,right-8-(w-hotX)),minY,maxY:Math.max(minY,bottom-8-(h-hotY))};
+ }
+ function moveTouchpad(dx,dy){
+ stopPanAnimation();const r=layout(),v=cursorViewport();
+ if(cursorNeedsEntry){
+ // Re-enter at the nearest visible edge; do not pull a manually positioned
+ // desktop back to the old off-screen cursor before applying this movement.
+ cx=clamp((bounded(r.x+cx*r.width,v.minX,v.maxX)-r.x)/r.width);
+ cy=clamp((bounded(r.y+cy*r.height,v.minY,v.maxY)-r.y)/r.height);
+ cursorNeedsEntry=false;
+ }
+ cx=clamp(cx+dx/r.width);cy=clamp(cy+dy/r.height);
+ const x=r.x+cx*r.width,y=r.y+cy*r.height;
+ if(zoom>1||r.width>viewportWidth()||r.height>stage.clientHeight-viewportBottomInset){
+ place(r.x+bounded(x,v.minX,v.maxX)-x,r.y+bounded(y,v.minY,v.maxY)-y,r);
+ followRest={fx,fy,zoom};
+ }
+ manualViewMoved=false;
+ }
+ function stopPanAnimation(){if(panAnimation!==null)cancelAnimationFrame(panAnimation);panAnimation=null;}
+ function settlePan(){stopPanAnimation();
+ const r=layout(),b=panBounds(r),x=bounded(r.x,b.minX,b.maxX),y=bounded(r.y,b.minY,b.maxY);
+ if(x===r.x&&y===r.y)return;
+ if(reducedMotion.matches){place(x,y,r);render();return;}
+ const started=performance.now();
+ const tick=now=>{const t=Math.min(1,(now-started)/280),ease=1-Math.pow(1-t,3);
+ place(r.x+(x-r.x)*ease,r.y+(y-r.y)*ease,r);render();
+ panAnimation=t<1?requestAnimationFrame(tick):null;};panAnimation=requestAnimationFrame(tick);
+ }
+ function render(){const r=layout();
+ const touchFeedback=control&&mode==='touch'&&touchCursorVisible;
+ const cursorX=mode==='touch'&&touchCursor?touchCursor.x:cx;
+ const cursorY=mode==='touch'&&touchCursor?touchCursor.y:cy;
+ cursor.style.transition=mode==='touch'&&!touchFeedback&&!reducedMotion.matches?'opacity 120ms ease-out':'none';for(const el of [image,video]){el.style.width=r.width+'px';el.style.height=r.height+'px';el.style.left=r.x+'px';el.style.top=r.y+'px';}if(remoteCursor){
+ cursor.style.width=remoteCursor.width+'px';cursor.style.height=remoteCursor.height+'px';
+ cursor.style.border='0';cursor.style.borderRadius='0';cursor.style.transform='none';
+ cursor.style.left=(r.x+cursorX*r.width-remoteCursor.hotX)+'px';cursor.style.top=(r.y+cursorY*r.height-remoteCursor.hotY)+'px';
+ cursor.style.display='block';
+ cursor.style.opacity=(mode==='touch'?touchFeedback:(remoteCursor.visible||(control&&mode==='pointer'&&localCursorAwake)))?'1':'0';
+ }else{
+ cursor.style.opacity=(mode==='touch'?!touchFeedback:false)?'0':'1';cursor.style.width='18px';cursor.style.height='18px';cursor.style.border='2px solid var(--foreground)';
+ cursor.style.borderRadius='50%';cursor.style.transform='translate(-50%,-50%)';
+ cursor.style.left=(r.x+cursorX*r.width)+'px';cursor.style.top=(r.y+cursorY*r.height)+'px';
+ cursor.style.display=control&&(mode==='pointer'||mode==='touch')?'block':'none';
+ }}
+ // Literal source is required: Hermes function.toString() yields bytecode.
+ function validCursor(v){
+ return !!v && typeof v==='object' && typeof v.visible==='boolean' &&
+ [v.x,v.y,v.width,v.height,v.hotX,v.hotY].every(Number.isFinite) &&
+ v.x>=0&&v.x<=1&&v.y>=0&&v.y<=1&&v.width>0&&v.width<=256&&v.height>0&&v.height<=256&&
+ v.hotX>=0&&v.hotX<=v.width&&v.hotY>=0&&v.hotY<=v.height&&
+ typeof v.png==='string'&&v.png.length<=65536&&/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png);
+ }
+ function receiveCursor(value){
+ if(value===null){if(remoteCursor){remoteCursor={...remoteCursor,visible:false};render();}return;}
+ if(!validCursor(value))return;
+ if(!remoteCursor||remoteCursor.png!==value.png)cursorImage.src='data:image/png;base64,'+value.png;
+ // Keep delayed host coordinates from pulling the local touchpad backwards.
+ if(!remoteCursor||!control||mode!=='pointer'||(!pointers.size&&performance.now()-lastLocalMove>200)){
+ cx=value.x;cy=value.y;
+ }
+ if(value.visible)localCursorAwake=false;
+ remoteCursor=value;render();
+ }
+ function resetCursor(){clearTimeout(touchCursorTimer);touchCursorVisible=false;touchCursor=null;localCursorAwake=false;remoteCursor=null;cursorImage.removeAttribute('src');render();}
+ function queue(event){if(!control)return;
+ // Remote visibility can remain hidden after synthetic mouse movement. Wake
+ // the local touchpad cursor until the host reports a visible cursor again.
+ if(event.kind==='move'&&mode==='pointer')localCursorAwake=true;
+ if(event.kind==='key'||event.kind==='text'){localCursorAwake=false;render();}
+ if(event.kind==='move'||event.kind==='button')lastLocalMove=performance.now();const tail=pending[pending.length-1];
+ if(event.kind==='move'&&tail?.kind==='move')pending[pending.length-1]=event;
+ // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the
+ // accumulated distance so a delayed ACK cannot replay a large scroll backlog.
+ else if(event.kind==='scroll'&&tail?.kind==='scroll'){tail.dx=Math.max(-2000,Math.min(2000,tail.dx+event.dx));tail.dy=Math.max(-2000,Math.min(2000,tail.dy+event.dy));}
+ else pending.push(event);
+ if(pending.length>64){pending=[{kind:'release'}];control=false;post({type:'inputOverflow'});}}
+ function flush(){if(!pending.length||sending)return;const events=pending.splice(0,64),sequence=++seq;if(dc&&dc.readyState==='open'&&dc.bufferedAmount<16384){dc.send(JSON.stringify({sequence,events}));}else{sending=true;post({type:'input',sequence,events});}}
+ setInterval(()=>{
+ // Hold displacement controls speed, even without further pointer moves.
+ // Skip missed ticks while awaiting ACK instead of building a scroll backlog.
+ if(wheelY?.moved&&!sending){const offset=Math.max(-24,Math.min(24,wheelY.y-wheelY.start));if(Math.abs(offset)>4)scrollMouse(Math.sign(offset)*(Math.abs(offset)-4)*1.5);}
+ flush();
+ },33);
+ function release(){clearTimeout(hold);if(gestureFrame!==null)cancelAnimationFrame(gestureFrame);gestureFrame=null;if(control){queue({kind:'release'});flush();}heldMouse.clear();resetWheel();updateMouseButtons();drag=false;pointers.clear();start=null;last=null;multi=null;}
+ function updateMouseButtons(){mouseButtons.style.display=showMouseButtons&&control?'block':'none';for(const [name,button] of [['left',0],['right',2]])document.getElementById('mouse-'+name).setAttribute('aria-pressed',String(heldMouse.has(button)));}
+ for(const [name,button] of [['left',0],['right',2]]){
+ const el=document.getElementById('mouse-'+name);
+ el.addEventListener('pointerdown',e=>{e.preventDefault();if(!control||!showMouseButtons||heldMouse.has(button))return;clearTimeout(hold);el.setPointerCapture(e.pointerId);heldMouse.set(button,e.pointerId);queue({kind:'button',button,down:true,x:cx,y:cy});flush();updateMouseButtons();});
+ const up=e=>{e.preventDefault();if(heldMouse.get(button)!==e.pointerId)return;heldMouse.delete(button);queue({kind:'button',button,down:false,x:cx,y:cy});flush();updateMouseButtons();};
+ el.addEventListener('pointerup',up);el.addEventListener('pointercancel',up);el.addEventListener('lostpointercapture',up);
+ el.addEventListener('click',e=>{if(e.detail===0&&control&&showMouseButtons){click(button);flush();}});
+ }
+ const scrollMouse=dy=>{if(control&&showMouseButtons&&Number.isFinite(dy)){queue({kind:'scroll',dx:0,dy:Math.max(-2000,Math.min(2000,dy))});}};
+ wheel.addEventListener('pointerdown',e=>{e.preventDefault();if(!control||!showMouseButtons||wheelY)return;wheel.setPointerCapture(e.pointerId);wheelY={id:e.pointerId,y:e.clientY,start:e.clientY,moved:false};});
+ // A small dead zone preserves middle clicks; displacement drives the timer.
+ wheel.addEventListener('pointermove',e=>{if(!wheelY||wheelY.id!==e.pointerId)return;e.preventDefault();wheelGrip.style.transform='translateY('+Math.max(-24,Math.min(24,e.clientY-wheelY.start))+'px)';wheelY.y=e.clientY;if(Math.abs(e.clientY-wheelY.start)>4)wheelY.moved=true;});
+ wheel.addEventListener('pointerup',e=>{if(!wheelY||wheelY.id!==e.pointerId)return;e.preventDefault();if(!wheelY.moved&&control&&showMouseButtons){click(1);flush();}resetWheel();});
+ const cancelWheel=e=>{if(wheelY?.id===e.pointerId)resetWheel();};
+ wheel.addEventListener('pointercancel',cancelWheel);wheel.addEventListener('lostpointercapture',cancelWheel);
+ wheel.addEventListener('click',e=>{if(e.detail===0&&control&&showMouseButtons){click(1);flush();}});
+ wheel.addEventListener('keydown',e=>{if(e.key==='ArrowUp'||e.key==='ArrowDown'){e.preventDefault();scrollMouse(e.key==='ArrowUp'?-120:120);}});
+ function insideDesktop(p){const r=layout();return p.x>=r.x&&p.x<=r.x+r.width&&p.y>=r.y&&p.y<=r.y+r.height;}
+ function point(p){const r=layout();return{x:clamp((p.x-r.x)/r.width),y:clamp((p.y-r.y)/r.height)};}
+ function click(button=0){if(control&&mode==='touch'){clearTimeout(touchCursorTimer);touchCursor={x:cx,y:cy};touchCursorVisible=true;render();touchCursorTimer=setTimeout(()=>{touchCursorVisible=false;render();},450);}queue({kind:'button',button,down:true,x:cx,y:cy});queue({kind:'button',button,down:false,x:cx,y:cy});}
+ function pan(dx,dy){manualViewMoved=true;cursorNeedsEntry=true;stopPanAnimation();const r=layout(),b=panBounds(r);place(rubber(rubber(r.x,b.minX,b.maxX,true)+dx,b.minX,b.maxX),rubber(rubber(r.y,b.minY,b.maxY,true)+dy,b.minY,b.maxY),r);render();}
+ function pair(){const [a,b]=[...pointers.values()];return{x:(a.x+b.x)/2,y:(a.y+b.y)/2,d:Math.hypot(a.x-b.x,a.y-b.y)};}
+ function movePair(){gestureFrame=null;if(pointers.size<2||!multi)return;const next=pair(),span=Math.abs(next.d-multi.d),travel=Math.hypot(next.x-multi.x,next.y-multi.y);
+ if(multi.kind!=='pinch'){
+ const pinchSlop=Math.max(6,Math.min(12,multi.d*.04));
+ if(span>=pinchSlop&&span>travel*.65){
+ // A parallel scroll may deliver its two pointer updates in different
+ // frames. Confirm separation briefly before taking over as a pinch.
+ if(!multi.candidate)multi.candidate={at:Date.now(),d:next.d,zoom,anchor:point(next)};
+ if(Date.now()-multi.candidate.at>=40){
+ if(multi.kind==='scroll'){multi.d=multi.candidate.d;multi.zoom=multi.candidate.zoom;multi.anchor=multi.candidate.anchor;}
+ multi.kind='pinch';multi.candidate=null;
+ }else{gestureFrame=requestAnimationFrame(movePair);return;}
+ }else{multi.candidate=null;if(!multi.kind&&travel>8&&travel>span)multi.kind='scroll';}
+ }
+ if(multi.kind==='pinch'){manualViewMoved=true;cursorNeedsEntry=true;zoom=Math.max(1,Math.min(5,multi.zoom*next.d/Math.max(1,multi.d)));const r=layout();fx=multi.anchor.x+((viewportLeft()+viewportWidth()/2)-next.x)/r.width;fy=multi.anchor.y+(stage.clientHeight/2-next.y)/r.height;const moved=layout(),b=panBounds(moved);place(rubber(moved.x,b.minX,b.maxX),rubber(moved.y,b.minY,b.maxY),moved);}
+ else if(multi.kind==='scroll'){const dx=next.x-multi.lastX,dy=next.y-multi.lastY;if(control&&mode!=='pan')queue({kind:'scroll',dx:Math.max(-2000,Math.min(2000,-dx)),dy:Math.max(-2000,Math.min(2000,-dy))});else pan(dx,dy);}
+ if(multi.kind){multi.lastX=next.x;multi.lastY=next.y;}render();
+ }
+ stage.addEventListener('pointerdown',e=>{
+ e.preventDefault();stopPanAnimation();stage.setPointerCapture(e.pointerId);pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
+ if(pointers.size===1){cursorNeedsEntry=true;start={x:e.clientX,y:e.clientY};last=start;moved=false;
+ hold=setTimeout(()=>{if(control&&mode!=='pan'&&!moved&&pointers.size===1&&!heldMouse.size&&(mode!=='touch'||insideDesktop(start))){if(mode==='touch'){const p=point(start);cx=p.x;cy=p.y;}queue({kind:'button',button:0,down:true,x:cx,y:cy});drag=true;}},400);
+ }else {clearTimeout(hold);if(drag)queue({kind:'release'});drag=false;start=null;const p=pair();multi={...p,lastX:p.x,lastY:p.y,zoom,anchor:point(p),kind:null};}
+ });
+ stage.addEventListener('pointermove',e=>{
+ if(!pointers.has(e.pointerId))return;e.preventDefault();pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
+ if(pointers.size>=2){if(gestureFrame===null)gestureFrame=requestAnimationFrame(movePair);return;}
+ if(!start||!last)return;const now={x:e.clientX,y:e.clientY},dx=now.x-last.x,dy=now.y-last.y;last=now;
+ if(Math.hypot(now.x-start.x,now.y-start.y)>6){moved=true;clearTimeout(hold);}
+ if(!control||mode==='pan'||(mode==='touch'&&!drag&&!heldMouse.size)){pan(dx,dy);return;}
+ if(mode==='pointer'){moveTouchpad(dx,dy);}else{const p=point(now);cx=p.x;cy=p.y;}
+ queue({kind:'move',x:cx,y:cy});render();
+ });
+ function up(e){if(!pointers.has(e.pointerId))return;clearTimeout(hold);
+ if(pointers.size>=2&&multi){
+ pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
+ if(gestureFrame!==null)cancelAnimationFrame(gestureFrame);
+ movePair();
+ if(gestureFrame!==null)cancelAnimationFrame(gestureFrame);gestureFrame=null;
+ }
+ pointers.delete(e.pointerId);
+ if(drag){queue({kind:'button',button:0,down:false,x:cx,y:cy});drag=false;}
+ else if(start&&!moved&&control&&mode!=='pan'&&!heldMouse.size&&e.type==='pointerup'&&(mode!=='touch'||insideDesktop({x:e.clientX,y:e.clientY}))){if(mode==='touch'){const p=point({x:e.clientX,y:e.clientY});cx=p.x;cy=p.y;}click();}
+ start=null;last=null;multi=null;render();if(!pointers.size&&manualViewMoved)settlePan();
+ }
+ stage.addEventListener('pointerup',up);stage.addEventListener('pointercancel',()=>{release();settlePan();});
+ document.addEventListener('contextmenu',e=>e.preventDefault());
+ // Scope selection suppression to the desktop surface, preserving the hidden
+ // textarea's native keyboard/IME editing and programmatic selection.
+ stage.addEventListener('selectstart',e=>e.preventDefault());
+ stage.addEventListener('dragstart',e=>e.preventDefault());
+ const normalizedKey=code=>/^(Shift|Control|Alt|Meta)Right$/.test(code)?code.replace(/Right$/,'Left'):code;
+ document.addEventListener('keydown',e=>{if(control&&validKeys.has(normalizedKey(e.code))){e.preventDefault();queue({kind:'key',code:normalizedKey(e.code),down:true});}});
+ document.addEventListener('keyup',e=>{if(control&&validKeys.has(normalizedKey(e.code))){e.preventDefault();queue({kind:'key',code:normalizedKey(e.code),down:false});}});
+ window.addEventListener('blur',()=>{release();settlePan();});new ResizeObserver(()=>{release();settlePan();render();}).observe(stage);
+ // Keep one bounded frame in this document only; never persist desktop pixels.
+ // Snapshot before detaching the track. A JPEG fallback already lives in image.
+ function retainFrame(){
+ if(video.style.display!=='block'||video.readyState<2||!video.videoWidth||!video.videoHeight)return;
+ const canvas=document.createElement('canvas');
+ try{const scale=Math.min(1,1280/Math.max(video.videoWidth,video.videoHeight));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){context.drawImage(video,0,0,canvas.width,canvas.height);image.src=canvas.toDataURL('image/jpeg',.7);}}catch{/* Keep the previous compatibility frame if WebKit cannot read video. */}finally{canvas.width=0;canvas.height=0;}
+ }
+ function closeRtc(preserveFrame=true){if(preserveFrame)retainFrame();generation++;clearInterval(statsTimer);statsTimer=null;statsSample=null;if(dc)dc.close();if(pc)pc.close();pc=null;dc=null;video.srcObject=null;video.style.display='none';image.style.display='block';if(!preserveFrame)image.removeAttribute('src');}
+ async function connect(){closeRtc();const g=generation;if(!window.RTCPeerConnection){post({type:'fallback'});return;}
+ try{const rtc=new RTCPeerConnection({iceServers:[{urls:'stun:stun.l.google.com:19302'}]});pc=rtc;dc=rtc.createDataChannel('input-v1');rtc.addTransceiver('video',{direction:'recvonly'});rtc.addTransceiver('audio',{direction:'recvonly'});
+ dc.onmessage=e=>{try{if(g!==generation||pc!==rtc)return;if(typeof e.data!=='string'||e.data.length>80000)return;const message=JSON.parse(e.data);if(message.type==='cursor')receiveCursor(message.cursor);if((video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video)&&message.type==='viewPing'&&typeof message.challenge==='string'&&message.challenge.length<=64&&dc?.readyState==='open')dc.send(message.challenge);}catch{}};
+ let readingStats=false;
+ statsTimer=setInterval(async()=>{
+ if(readingStats||g!==generation)return;readingStats=true;
+ try{const stats=await rtc.getStats();if(g!==generation||pc!==rtc)return;const result=networkStats(stats,statsSample);statsSample=result.sample;post({type:'network',transport:result.transport,bytesPerSecond:result.bytesPerSecond,latencyMs:result.latencyMs});}catch{/* Metrics must never interrupt the stream. */}finally{readingStats=false;}
+ },1000);
+ rtc.ontrack=e=>{if(g!==generation)return;video.srcObject=e.streams[0]||new MediaStream([e.track]);video.play().catch(()=>{});};
+ video.onplaying=()=>{if(g!==generation)return;video.style.display='block';image.style.display='none';post({type:'streaming'});post({type:'pipCapability',supported:!!(video.webkitSupportsPresentationMode?.('picture-in-picture')||document.pictureInPictureEnabled)});render();};
+ rtc.onconnectionstatechange=()=>{if(g===generation&&['failed','disconnected','closed'].includes(rtc.connectionState)){release();closeRtc();post({type:'fallback'});}};
+ await rtc.setLocalDescription(await rtc.createOffer());await new Promise(resolve=>{if(rtc.iceGatheringState==='complete')return resolve();const timer=setTimeout(resolve,3000);rtc.onicegatheringstatechange=()=>{if(rtc.iceGatheringState==='complete'){clearTimeout(timer);resolve();}};});
+ if(g===generation)post({type:'offer',sdp:rtc.localDescription.sdp});
+ setTimeout(()=>{if(g===generation&&rtc.connectionState!=='connected'){closeRtc();post({type:'fallback'});}},12000);
+ }catch{if(g===generation){closeRtc();post({type:'fallback'});}}
+ }
+ function reportPresentation(){post({type:'presentation',active:video.webkitPresentationMode==='picture-in-picture'||document.pictureInPictureElement===video});}
+ video.addEventListener('webkitpresentationmodechanged',reportPresentation);
+ video.addEventListener('enterpictureinpicture',reportPresentation);
+ video.addEventListener('leavepictureinpicture',reportPresentation);
+ function receive(event){let message;try{message=JSON.parse(event.data);}catch{return;}
+ switch(message.type){
+ case 'presentation':
+ try {
+ if(message.enabled){
+ release();showKeyboard(false);
+ if(video.webkitSupportsPresentationMode?.('picture-in-picture'))video.webkitSetPresentationMode('picture-in-picture');
+ else if(video.requestPictureInPicture)video.requestPictureInPicture().catch(()=>post({type:'presentationFailed'}));
+ else post({type:'presentationFailed'});
+ }else if(video.webkitSetPresentationMode)video.webkitSetPresentationMode('inline');
+ else if(document.pictureInPictureElement)document.exitPictureInPicture().catch(()=>{});
+ }catch{post({type:'presentationFailed'});}break;
+ case 'videoSettings':video.muted=!message.audio;connect();break;
+ case 'keyboard':showKeyboard(message.enabled===true);break;
+ case 'resume':if(video.srcObject)video.play().catch(()=>{});break;
+ case 'releaseInput':release();break;
+ case 'theme':if(/^#[0-9a-f]{3,8}$/i.test(message.surface)){document.body.style.background=message.surface;document.documentElement.style.setProperty('--surface',message.surface);}if(/^#[0-9a-f]{3,8}$/i.test(message.foreground)){cursor.style.borderColor=message.foreground;document.documentElement.style.setProperty('--foreground',message.foreground);}break;
+ case 'mouseButtons':if(Number.isFinite(message.bottomInset))viewportBottomInset=Math.max(0,Math.min(stage.clientHeight-1,message.bottomInset));if(Number.isFinite(message.leftInset)){const left=Math.max(0,Math.min(stage.clientWidth-1,message.leftInset));if(left!==viewportLeftInset){viewportLeftInset=left;settlePan();render();}}if(Number.isFinite(message.rightInset)){const inset=Math.max(0,Math.min(stage.clientWidth-1,message.rightInset));if(inset!==viewportRightInset){viewportRightInset=inset;settlePan();render();}}if(!message.enabled){for(const button of heldMouse.keys())queue({kind:'button',button,down:false,x:cx,y:cy});heldMouse.clear();resetWheel();flush();}for(const [edge,value] of [['bottom',message.bottomInset],['right',message.rightInset]])if(Number.isFinite(value)&&value>=0&&value<=4096)mouseButtons.style[edge]=value+'px';showMouseButtons=message.enabled===true;for(const name of ['left','right','wheel'])if(typeof message.labels?.[name]==='string')document.getElementById('mouse-'+name).setAttribute('aria-label',message.labels[name]);updateMouseButtons();break;
+ case 'init':followRest=null;cursorNeedsEntry=true;stopPanAnimation();resetCursor();control=false;release();pending=[];sending=false;seq=0;epoch=message.epoch;dw=message.width;dh=message.height;fillHeight=message.fillHeight===true;video.muted=!message.audio;render();connect();break;
+ case 'viewport':fillHeight=message.fillHeight===true;release();render();break;
+ case 'answer':if(pc){const current=pc;pc.setRemoteDescription({type:'answer',sdp:message.sdp}).catch(()=>{if(pc===current){closeRtc();post({type:'fallback'});}});}break;
+ case 'fallback':closeRtc();break;
+ case 'frame':{if('cursor' in message)receiveCursor(message.cursor);else resetCursor();const frameEpoch=epoch;image.onload=()=>{if(epoch===frameEpoch)post({type:'framePresented'});};image.src='data:image/jpeg;base64,'+message.jpeg;break;}
+ case 'control':release();control=message.enabled;if(!control)showKeyboard(false);pending=[];updateMouseButtons();render();break;
+ case 'mode':release();if(message.mode!=='pointer')followRest=null;settlePan();clearTimeout(touchCursorTimer);touchCursorVisible=false;mode=message.mode;render();break;
+ case 'fit':followRest=null;cursorNeedsEntry=true;manualViewMoved=false;stopPanAnimation();zoom=1;fx=.5;fy=.5;render();break;
+ case 'rightClick':click(2);break;
+ case 'events':for(const e of message.events)queue(e);flush();break;
+ case 'ack':if(message.epoch===epoch&&message.sequence===seq)sending=false;break;
+ case 'stop':showKeyboard(false);control=false;release();pending=[];sending=false;epoch=null;closeRtc(message.preserveFrame===true);updateMouseButtons();render();break;
+ }
+ }
+ window.addEventListener('message',receive);document.addEventListener('message',receive);render();post({type:'ready'});
+})();`;
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 107ed1ff58..5f7ef76a67 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -38,7 +38,7 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 82 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 142 | 121 | 744 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 142 | 121 | 747 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/globals.css | 145 | 72 | 288 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 41 | 0 | 71 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 46 | 0 | 59 |
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
new file mode 100644
index 0000000000..66c36d1d28
--- /dev/null
+++ b/docs/remote-desktop.md
@@ -0,0 +1,379 @@
+# Mobile remote desktop
+
+The device detail page opens the real desktop of the selected computer. On the
+computer, enable **Settings → Remote control → Allow remote desktop**, as well
+as device control. Screen recording and accessibility permissions are granted
+in the operating system. The phone automatically requests control on connection
+when the host supports input, using the existing permission and ownership checks.
+**Controls → View only** releases control and preserves that choice when reconnecting
+within this page. The computer always has a **Disconnect**
+button while being viewed or controlled.
+
+## Interaction
+
+- The fullscreen viewport has four tools: All windows, Desktop, Keyboard, and
+ Controls. Portrait places them at the bottom; landscape uses a narrow side rail.
+ Controls opens an overlay without resizing the picture. Titles, connection
+ details and gesture help stay in this panel. Rotation changes only the phone
+ viewport, never the computer's resolution. Portrait fits the full desktop;
+ landscape fills the viewport height without top/bottom bars. Any horizontal
+ overflow remains accessible by panning.
+- Controls groups rotation, audio, view-only and system picture in picture into
+ quick actions. Display settings contain frame rate, quality, actual computer
+ resolution and monitor selection. Touch and Trackpad use a segmented
+ selector, with a saved Show mouse buttons option. Disconnect stays visible in
+ a separate footer while settings scroll.
+- Trackpad mode moves the pointer relatively. Touch mode taps at an absolute
+ location. Hold then move to drag, including selections and window dragging.
+- Pinch zoom preserves the point under the two fingers. Two-finger gestures pan and zoom the picture; trackpad scrolling is also available through the virtual wheel. The normalized view
+ focus survives rotation and keyboard resizing.
+- The keyboard offers native text composition, modifier combinations, navigation
+ keys, and a full key strip. Desktop / All windows use operating system shortcuts.
+- Switching displays creates a new lease and retains the control/view-only choice.
+ Backgrounding normally releases the lease; explicit system picture in picture
+ retains viewing only. Returning to the foreground automatically reconnects. Network failures and viewer process loss also recover automatically,
+ with the last picture retained, a prominent connecting indicator and capped backoff on the existing heartbeat timer.
+ Portrait always has an icon-only Back button (a native SwiftUI glass button on
+ iOS 26+), which cancels recovery immediately. Landscape hides Back; Controls
+ still offers Disconnect. Explicit host
+ disconnect, revoked access and missing permissions stop automatic recovery.
+ Recovery only opens the selected peer and replaces this desktop lease; it never
+ restarts the shared relay or other peers' connections.
+
+## Transport and compatibility
+
+`device-link:remote-desktop:v1` is an additive business invoke channel inside the
+existing authenticated same-account protocol. The server protocol is unchanged.
+The optional `automaticReconnect` capability and `start.resume` flag let
+the host reject automatic recovery after an explicit local disconnect, including
+when the phone was offline. Older phones still use ordinary starts; newer phones
+retain manual connection when an older host cannot enforce this recovery boundary.
+Computers without this channel reject it and the phone asks for an upgrade. Screen
+data and signaling are never added to the generic broadcast allowlist.
+
+WebRTC carries a video track and an ordered input DataChannel. Capture runs in
+the existing, trusted main renderer, with exact Main-side host identity checks.
+The phone runs a dedicated trusted inline WebView document; the untrusted HTML
+preview's restrictions are unchanged. The mobile presentation module requests scene rotation and a playback audio session
+for system picture in picture. This requires a new native mobile build. Voice
+recording and ordinary audio retain their foreground-only runtime policy. The current direct-connection ICE configuration uses a public STUN
+server; there is no bundled TURN service.
+
+When WebRTC is unavailable or cannot connect, the phone uses an explicitly
+labeled compatibility mode: JPEG at at most 1280 pixels per dimension, at most
+180 KB before base64, one frame in flight, and no more than four capture requests
+per second. Images are transient and pass through the authenticated TLS relay.
+This mode trades frame rate and clarity for reachability. It is suitable for
+ordinary desktop work, not game streaming. A production TURN service is the
+follow-up needed for consistently smooth video across restrictive networks.
+
+## Authority and lifetime
+
+On macOS, enabling remote desktop automatically checks screen recording in the
+capturing Cindy process and accessibility in the actual input helper. It opens
+an in-app guide if either permission is missing or unconfirmed. The guide reuses
+Computer Use's interactive permission rows and fixed System Settings targets;
+it never treats CuaDriver's permissions as remote desktop permissions. The
+settings page and guide recheck automatically, including when focus returns.
+Closing the guide cancels any pending follow-up that would open System Settings.
+
+The phone shows separate permission states and can request this Cindy guide on
+the computer. This is a documented, narrow exception to the no-UI invoke rule:
+only the remote-desktop business handler accepts `permissions/check|guide`,
+after both local opt-ins and controller revocation checks. It accepts no URL,
+never changes the opt-ins, and never opens OS settings or grants OS permission
+from a remote request. Those actions require a button in the trusted local UI.
+The added capabilities field is optional for older desktops; without it the
+phone retains the text guidance and reconnect action. Permission recovery stays
+within remote desktop and never restarts shared device-link connections.
+
+Desktop authorization is a separate local default-off preference. The lease is
+bound to the relay-verified source peer and a random lease ID, and renewed every
+three seconds with a twelve-second expiry. Every input and completed capture is
+checked against current authorization. Local stop, revocation, relay loss, peer
+offline, display changes, and capture-host loss stop the lease. Stale operations
+cannot resurrect a stopped lease. Input sequence numbers prevent replay.
+
+The native helper holds actual down/up state and releases it on EOF/stop, with a
+watchdog for an unresponsive parent. Input batches and queues are bounded; a
+backpressure failure stops control rather than silently dropping key-up events.
+CUA Agent actions and human input share a process-local ownership guard. Other
+applications and separate Cindy processes are outside that guard.
+
+## Platform and verification limits
+
+macOS uses a signed Swift helper; Windows uses a Rust helper with Win32 SendInput.
+Forge builds and packages both through the existing tools signing paths. Linux
+currently offers viewing only. Neither helper bypasses OS security boundaries:
+Windows secure desktop/UAC and elevated applications can reject input, and
+macOS lock/login screens and protected surfaces are not guaranteed controllable.
+System audio and explicit clipboard transfers are supported when advertised by the host. Virtual displays and remote power-on are not included. The phone keyboard sends committed text directly; the computer keyboard supplies modifiers and special keys.
+
+Unit tests cover peer/lease isolation, expiry, revocation during asynchronous
+capture, start/stop races, input replay, human/Agent exclusion, portrait/landscape
+geometry, keyboard resize, inline viewer parsing, two-finger gestures, and reconnect.
+The related desktop, mobile, and device-link test suites pass. A disposable
+Chromium receiver verified live WebRTC video, ordered input, portrait/landscape
+resizing, and capture cleanup. The macOS helper was exercised against an isolated
+development window with Chinese/Emoji text, Command+A, and release on exit; the
+Windows helper passes a Windows-target compilation check.
+
+These checks do not replace end-to-end validation on an actual phone. First-run
+OS permission flows, real-device WebView RTC behavior, Windows input, packaged
+signing, light/dark phone rendering, and different network topologies still need
+device validation before release.
+
+## Display controls (2026-09-07)
+
+Operations provides Rotate, Sound, View only and system Picture in picture, with
+Display settings in a separate panel. Video settings are optional additions to
+`offer`: 30/60 fps, automatic bitrate or 2/8/20 Mbps ceilings, and desktop audio.
+These are encoder/capture targets, not guaranteed measured rates or lossless
+quality. Compatibility JPEG transport does not apply them; the UI reports that
+fallback. Old viewers keep the original 1920-pixel/30-fps capture bounds. New
+viewers only send settings when the host advertises `videoSettings`.
+
+System audio defaults on with the viewer preference saved locally, supported on Windows and macOS 14.2+, and selected by a
+single-use display capture grant tied to the current offer, lease and trusted
+main renderer. No microphone is captured. macOS packaging declares
+NSAudioCaptureUsageDescription; development launchers must also have the OS
+permission. Linux audio is not advertised.
+
+`displayModes` and `resolution` operate on the lease's display. macOS uses
+CoreGraphics mode enumeration and applies only an available mode ID for the
+current login session. The operation requires control and rechecks lease and
+authorization after native preparation. It changes the actual computer display,
+not just the encoded image. Geometry changes release capture/input; only this
+remote desktop reconnects with fresh dimensions. The shared relay and other
+peer links remain untouched. Windows/Linux display mode changes are currently
+unavailable and are not advertised.
+
+System PiP is offered only when WebKit reports support for this video and the
+native presentation module and host backgroundViewing capability are present.
+Entering releases control. A capture-renderer challenge/pong heartbeat renews
+only a view-only lease while the viewer reports actual system PiP presentation.
+Closing PiP, closing WebRTC, local disconnect, revocation and the ordinary finite
+lease timeout all terminate background viewing. This does not grant indefinite
+background control or extend the lifetime of unrelated device links.
+
+Validation for these additions: static compilation only; no interaction tests,
+network multi-peer tests or Light/Dark visual inspection, per the user's request.
+PiP/WebRTC background playback and audio permission behavior need device testing.
+
+## Locked-session capture (2026-09-07)
+
+The installed UU 4.35.0 bundle imports both ScreenCaptureKit and the legacy
+CoreGraphics display-stream API. Its launch agent declares LoginWindow and Aqua
+session types and it has a separate root daemon. This demonstrates that capture
+and session lifecycle are separate concerns; imports do not prove which backend
+UU selects while locked.
+
+Cindy now has a macOS native compatibility capture child for a logged-in user.
+If Chromium capture fails, times out, ends or mutes, its bounded JPEG frames feed
+a canvas video track on the existing WebRTC connection. Lock/unlock notifications
+discard cached pixels and release held input. Main validates the exact renderer,
+active lease and current generation before returning pixels. Stop, expiry and
+revocation kill capture; EOF and a five-second native watchdog also terminate it.
+No frame or typed password is saved and no public listening port is added.
+The fallback targets 15 fps and at most 1280 pixels on the longest edge; existing
+audio tracks may survive, but starting directly in fallback has no system audio.
+
+The legacy public API is runtime-resolved because SDK 15+ marks it unavailable.
+It may be absent or denied by macOS/TCC. A live probe on this macOS 27 machine
+found the missing condition: a sleeping display accepted stream creation/start
+but delivered no frames. Waking the display with IOPMAssertionDeclareUserActivity
+immediately delivered the actual password/lock screen while IOConsoleLocked
+remained true. The helper now performs that wake after checking capture access.
+The authenticated viewer lease holds Electron's prevent-display-sleep assertion
+and releases it on stop/expiry/revocation on all supported Electron platforms.
+The macOS JPEG compatibility transport uses the same native path.
+
+An explicit display-sleep → fixed-helper probe returned its first frame in
+874 ms with the OS still locked, and EOF terminated the helper with exit 0.
+This verifies capture on this Mac, not Windows/Linux or pre-login/FileVault
+support. System authentication is unchanged; no password is stored or supplied.
+
+A second failure was the unconditional display-metrics-changed teardown: display
+wake emitted that notification and ended a valid lease. Only bounds, scale or
+rotation changes on the selected monitor now end the lease; work-area changes
+and changes to other monitors do not invalidate whole-display input coordinates.
+
+End-to-end checks through two authenticated Cindy clients on this machine passed:
+JPEG capture followed by WebRTC decoded 160 frames in six seconds. A separate
+display-sleep → direct WebRTC connection (without a preliminary JPEG request)
+decoded 74 frames in six seconds; its received-video snapshot showed the actual
+system password/lock screen. Heartbeats remained successful. After disconnect,
+active lease was null, no capture child remained and PreventUserIdleDisplaySleep
+was zero. Desktop typecheck and native arm64/x86_64 compilation passed. These
+checks cover the current Mac's locked, already logged-in session, not the phone's
+cellular route or other operating systems. Display wake does not power on a
+shutdown computer or provide pre-boot FileVault access.
+
+Remaining platform adapters are explicitly separate:
+
+- macOS pre-login: a signed LoginWindow agent and authenticated system-service
+ lifecycle are still required; never run the whole Electron application as root.
+ An OS-approved install/uninstall flow must precede enabling that service.
+- Windows secure desktop: the SYSTEM broker and session worker are implemented
+ below; runtime validation on Windows is still required. [Microsoft documents LOCAL_SYSTEM access requirements](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutput1-duplicateoutput).
+- Linux: keep X11 and Wayland/compositor capabilities distinct. GNOME remote
+ assistance closes on lock, while GDM remote login is a separate service and
+ session type; it must not be presented as restoring the user's same desktop.
+ [GNOME's modes](https://github.com/GNOME/gnome-remote-desktop/blob/main/README.md).
+
+The macOS pre-login and Linux service adapters remain unimplemented. The remote business protocol and shared relay are unchanged. Recovery
+affects only this desktop lease/video track, not other connected peers.
+
+
+### Windows system service (implementation awaiting Windows runtime validation)
+
+Packaged Windows builds include a native SCM service, a Main-only Node-API pipe
+transport, a session-scoped SYSTEM GDI capture worker and the SendInput helper.
+The settings page installs/removes the service through Windows administrator
+consent. Only a protected all-users Program Files installation is eligible;
+per-user/development installations retain the ordinary desktop path.
+
+Authorization records a live process handle for the Cindy process explicitly
+approved through the elevated setup helper. Executable path alone is insufficient:
+plugin utility processes share Cindy.exe. The service starts on demand and exits when its approved Cindy process exits.
+Restarting Cindy or the service requires fresh administrator approval. This is a current limitation, not unattended
+post-reboot support. No authorization secrets or screenshots are persisted.
+
+The broker validates file/directory ownership, writable ACLs, reparse points,
+SCM identity, peer PIDs and active console session. It retains installation
+handles for its lifetime. Workers are fixed-purpose children in kill-on-close jobs
+with local-only, bounded, timed pipes. Uninstall/upgrade waits for the service to
+stop before removing binaries. Upgrade clears the authorization.
+
+Desktop transitions terminate the old input helper, including pending batches
+and long text input; Main then recovers only the remote desktop lease. Ctrl+Alt+Del
+is routed through service-side SendSAS impersonating the approved user's session.
+Windows policy decides whether software SAS is allowed; Cindy never changes it.
+Capture follows the input desktop and validates the selected monitor's geometry.
+The GDI compatibility stream is capped at a 1280-pixel long edge and 180 KB JPEG.
+
+Validation available on macOS: Windows-target Rust compilation checks and Desktop
+TypeScript checking. Still required on Windows 10/11: signed package linking and
+installation, administrator consent/cancellation, lock/unlock, UAC, policy-enabled
+SAS, mixed-DPI displays, worker cleanup, upgrade/uninstall, and plugin rejection.
+Windows display-mode changes and pre-login/unattended post-reboot control are not
+implemented. Linux remains deferred. Do not present this as fully validated
+Windows support or advertise high-frame-rate secure capture.
+
+
+### Keyboard clipboard actions
+
+The keyboard's leading clipboard button opens two actions in both phone and
+computer keyboard modes: **Copy to phone** reads the focused desktop application's
+selected text, or existing computer clipboard text when the selection is empty; **Paste from phone** writes phone clipboard text to the computer
+and sends its platform paste shortcut. Transfers are explicit, text-only and
+limited to 16,384 UTF-16 code units; oversized content is rejected, not truncated.
+
+Copy uses macOS Accessibility selected text or Windows UI Automation TextPattern
+selection. If an application does not expose its selection, copy fails explicitly.
+A confirmed empty selection falls back to the computer clipboard, as explicitly
+requested by the user. Permission failures, unsupported selection APIs, protected
+fields and oversized selections do not trigger fallback. Clipboard fallback reads
+check the change counter before and after reading; concurrent changes fail rather
+than returning an inconsistent value. Secure/locked desktop selection
+and password fields are not advertised as clipboard sources. Native selection
+output stays in memory; helper/JSON errors are sanitized before returning across
+the device link. Paste uses Command+V on macOS and Control+V on Windows.
+
+The optional `clipboardText` capability and `clipboard` operation are additive on
+the existing remote-desktop business channel. Old desktops show an upgrade hint;
+no relay/server protocol changes are required. Both operations require the current
+peer-bound controlling lease, reject concurrent transfers, and check revocation
+again after asynchronous native work. The phone also discards results after its
+lease changes or it leaves the foreground. No clipboard listeners, background
+synchronization, history, logs containing text, or disk persistence are added.
+
+TypeScript and native compilation checks cover this implementation. Keyboard/menu
+interaction, application-specific selection support, and physical-phone transfer
+have not been exercised; manual verification remains with the user.
+
+
+### Portable clipboard content
+
+New peers advertise optional `clipboardContent`; legacy `clipboardText` and its
+16,384-character limit remain unchanged. New iOS native builds read and write a
+single pasteboard item atomically, preserving available plain text, HTML, RTF,
+HTTP(S) URL and a PNG image representation. JPEG/HEIC still images are converted
+to PNG without a lossy transport compression step. Electron writes all supported
+representations together before Command/Control+V. Selected computer text still
+takes precedence over the computer clipboard; confirmed non-text controls may
+fall back to clipboard content, but protected/failed/stale selection reads do not.
+
+Clipboard JSON is transferred sequentially in 64 Ki-character chunks, at most
+32 Mi-characters total (native iOS additionally bounds UTF-8 bytes). Images are
+limited to 64 million pixels. Each transfer is peer/lease/control-generation
+bound, lives only in memory, expires after 60 seconds, and is discarded on
+control changes or disconnect. Commit consumes its transfer before pasting and
+is never automatically retried. No transport/global frame limits are changed.
+Mobile builds lacking the new native API retain the original text route and
+request an upgrade for images.
+
+This is **not arbitrary-format or file synchronization**. File references,
+multiple iOS pasteboard items, multiple macOS pasteboard items, unsupported-only
+content and animated UIKit image representations are rejected. App-private
+formats accompanying a portable representation are not transmitted. HTML/RTF
+references to external assets are not downloaded or inlined. Files need a
+separate byte-transfer and owned-file lifetime implementation; remote paths must
+never be pasted as if they were local files.
+
+Validation: mobile/desktop TypeScript checks, iOS device compilation, macOS
+helper typecheck and Windows cross-compilation check. No actual clipboard content
+was read and no physical-device or Windows application paste was exercised.
+
+### macOS local cursor overlay
+
+Optional `cursorOverlay` on capabilities, offer and compatibility-frame requests
+negotiates cursor-free capture; omitted flags retain the original protocol.
+The macOS helper reads the global NSCursor image/hotspot and the public legacy
+CGCursorIsVisible symbol, with normalized position within the selected display.
+No cursor-hiding call is applied to the user's physical desktop.
+
+Current Electron does not advertise the cursor media constraint. The negotiated
+path therefore uses native cursor-free video (up to 4096 pixels on the long edge,
+selected 30/60 fps as capture caps). It retains Chromium system audio when requested.
+A bounded JPEG intermediate is encoded into the existing WebRTC stream; unusually
+detailed frames reduce quality/size to fit the 1 MB native-frame limit. Actual
+frame rate depends on capture, decode and network costs; 30/60 is not a measured
+delivery-rate guarantee.
+
+Cursor PNG/dimensions/hotspot/visibility are validated and travel on the existing
+lease-bound frame response and input-v1 data channel. Only the latest cursor is
+retained; congested cursor updates are skipped. On the phone the cursor keeps
+its source colors, moves immediately with touchpad input, and accepts host
+position corrections only outside active touchpad movement. Late messages from
+old RTC generations are discarded. Hidden cursors are not drawn. Unsupported
+cursor images fall back to the existing position indicator without killing video.
+Both Light and Dark use the source raster rather than tinting it.
+
+Checked: desktop/mobile types, native compilation, a bounded read-only native
+capture returning cursor geometry/raster metadata. Real phone gestures,
+application-by-application cursor transitions and sustained frame rate remain
+for manual verification.
+
+
+## Clipboard and connection handoff
+
+The keyboard clipboard menu offers Copy to phone and Paste from phone. Copy
+requests the selected content first, falling back to the existing computer
+clipboard. Transfers support text, HTML, RTF, URLs and PNG images through bounded,
+sequential chunks, with a blocking progress overlay. Arbitrary files and private
+application clipboard formats are not supported. Transfer buffers are discarded
+on completion, cancellation and lease termination; uncertain paste responses are
+never automatically retried. Native clipboard access requires a new iOS build.
+
+Only one viewer lease is active. A second viewer sees a busy state and can
+explicitly take over when the host advertises `connectionTakeover`. Ordinary
+starts never evict an existing viewer. Takeover stops the old lease and input;
+the former viewer cannot automatically reconnect with `resume` to evict the new
+viewer. Older hosts retain the busy message without a takeover action.
+
+Brief iOS inactive transitions (such as an interrupted Home gesture) retain the
+connection. Actual backgrounding releases control unless system PiP is active.
+Reconnection retains the last picture but disables input until a fresh lease is
+ready. Touch/trackpad, mouse-button visibility and audio preferences are saved
+locally. Landscape hides the network status overlay to preserve picture space.
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index bb9af9db05..33cfffb14c 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -363,6 +363,30 @@ dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值
已确定禁用:`开发版(仅当英文含 Dev)`(zh-CN)、`開発版(仅当英文含 Dev)`(ja)、`개발판(仅当英文含 Dev)`(ko)
+### Remote desktop
+
+同账号手机查看和操作电脑真实桌面,独立于 Cindy 内部设备控制授权。
+
+### Lock screen control
+
+Windows 远程桌面设置中的系统服务授权能力;不表示支持开机前解密或无人登录。
+
+### Native resolution
+
+Remote display mode reported as native by the host OS; distinct from current and recommended. Compact option badge: Native / 原生.
+
+### Picture in picture
+
+Remote desktop display controls; resolution changes the host display, small window uses system picture in picture.
+
+### Computer resolution
+
+Remote desktop display controls; resolution changes the host display, small window uses system picture in picture.
+
+### Take over connection
+
+Explicit user action that replaces the current remote desktop viewer; never used for automatic recovery.
+
### Activity Monitor
独立窗口/兼容页签,展示本机进程 CPU/内存并可终止 Agent 进程。不可叫「任务管理器」——Session→任务 已 decided,会被读成管理左侧任务列表。不叫「用量」——会和 token / 账号 Usage→用量 混淆(#3183)。「资源监视器」是窗口标题,看的是本机资源占用,不是输入监控;输入监控权限仍用「监听权限」。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 1d28b4cc84..eb41d8ec6c 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -13,6 +13,30 @@
"desktop:settings.help.qnaFeedbackBodyTemplate"
],
"terms": [
+ {
+ "id": "remote-desktop-lock-screen-control",
+ "status": "proposed",
+ "en": "Lock screen control",
+ "translations": {
+ "zh-CN": "锁屏控制",
+ "zh-TW": "鎖定畫面控制",
+ "ja": "ロック画面の操作",
+ "ko": "잠금 화면 제어"
+ },
+ "note": "Windows 远程桌面设置中的系统服务授权能力;不表示支持开机前解密或无人登录。"
+ },
+ {
+ "id": "remote-desktop",
+ "status": "proposed",
+ "en": "Remote desktop",
+ "translations": {
+ "zh-CN": "远程桌面",
+ "zh-TW": "遠端桌面",
+ "ja": "リモートデスクトップ",
+ "ko": "원격 데스크톱"
+ },
+ "note": "同账号手机查看和操作电脑真实桌面,独立于 Cindy 内部设备控制授权。"
+ },
{
"id": "cindy-ai-free-tier",
"status": "proposed",
@@ -1940,6 +1964,54 @@
"ko": "Doubao"
},
"note": "模型显示品牌采用官方中文名称,版本号和变体原样保留;仅用于展示与搜索,不改模型 ID 或用户保存的名称。"
+ },
+ {
+ "id": "remote-desktop-resolution",
+ "status": "proposed",
+ "en": "Computer resolution",
+ "translations": {
+ "zh-CN": "电脑分辨率",
+ "zh-TW": "電腦解析度",
+ "ja": "パソコンの解像度",
+ "ko": "컴퓨터 해상도"
+ },
+ "note": "Remote desktop display controls; resolution changes the host display, small window uses system picture in picture."
+ },
+ {
+ "id": "remote-desktop-pip",
+ "status": "proposed",
+ "en": "Picture in picture",
+ "translations": {
+ "zh-CN": "小窗模式",
+ "zh-TW": "小窗模式",
+ "ja": "ピクチャインピクチャ",
+ "ko": "화면 속 화면"
+ },
+ "note": "Remote desktop display controls; resolution changes the host display, small window uses system picture in picture."
+ },
+ {
+ "id": "remote-desktop-native-resolution",
+ "status": "proposed",
+ "en": "Native resolution",
+ "translations": {
+ "zh-CN": "原生分辨率",
+ "zh-TW": "原生解析度",
+ "ja": "ネイティブ解像度",
+ "ko": "기본 해상도"
+ },
+ "note": "Remote display mode reported as native by the host OS; distinct from current and recommended. Compact option badge: Native / 原生."
+ },
+ {
+ "id": "remote-desktop-takeover",
+ "status": "proposed",
+ "en": "Take over connection",
+ "translations": {
+ "zh-CN": "接管连接",
+ "zh-TW": "接管連線",
+ "ja": "接続を引き継ぐ",
+ "ko": "연결 넘겨받기"
+ },
+ "note": "Explicit user action that replaces the current remote desktop viewer; never used for automatic recovery."
}
]
}
diff --git a/packages/device-link/src/__tests__/remoteDesktop.test.ts b/packages/device-link/src/__tests__/remoteDesktop.test.ts
new file mode 100644
index 0000000000..9000e69540
--- /dev/null
+++ b/packages/device-link/src/__tests__/remoteDesktop.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+import {
+ isDesktopInput,
+ parseRemoteDesktopRequest,
+ REMOTE_DESKTOP_CHANNEL,
+ isDesktopPermission,
+} from "../remoteDesktop";
+import { REMOTE_INVOKE_ALLOWLIST, PUSH_FORWARD_ALLOWLIST } from "../allowlist";
+describe("remote desktop wire boundary", () => {
+ it("accepts old starts and validates the optional recovery flag", () => {
+ expect(parseRemoteDesktopRequest({ op: "start", displayId: "1" })).toEqual({
+ op: "start",
+ displayId: "1",
+ });
+ expect(
+ parseRemoteDesktopRequest({
+ op: "start",
+ displayId: "1",
+ resume: true,
+ }),
+ ).toEqual({ op: "start", displayId: "1", resume: true });
+ for (const resume of ["", 1, null])
+ expect(() =>
+ parseRemoteDesktopRequest({ op: "start", displayId: "1", resume }),
+ ).toThrow("INVALID_REQUEST");
+ });
+ it("limits permission actions to status and the dedicated guide", () => {
+ expect(
+ parseRemoteDesktopRequest({ op: "permissions", action: "guide" }),
+ ).toEqual({ op: "permissions", action: "guide" });
+ expect(() =>
+ parseRemoteDesktopRequest({ op: "permissions", action: "openExternal" }),
+ ).toThrow();
+ expect(isDesktopPermission("accessibility")).toBe(true);
+ expect(isDesktopPermission("https://example.com")).toBe(false);
+ expect(isDesktopPermission("fullDiskAccess")).toBe(false);
+ });
+ it("adds only a business invoke channel, never a broadcast", () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has(REMOTE_DESKTOP_CHANNEL)).toBe(true);
+ expect(PUSH_FORWARD_ALLOWLIST.has(REMOTE_DESKTOP_CHANNEL)).toBe(false);
+ });
+ it.each([
+ { kind: "move", x: NaN, y: 0 },
+ { kind: "move", x: -1, y: 0 },
+ { kind: "button", x: 0, y: 0, button: 5, down: true },
+ { kind: "key", code: "shell", down: true },
+ { kind: "text", text: "a".repeat(4097) },
+ { kind: "scroll", dx: 1, dy: Infinity },
+ ])("rejects malformed input %j", (value) => {
+ expect(isDesktopInput(value)).toBe(false);
+ });
+ it("bounds batches, SDP, and sequence numbers", () => {
+ expect(() =>
+ parseRemoteDesktopRequest({
+ op: "input",
+ lease: "a",
+ sequence: -1,
+ events: [],
+ }),
+ ).toThrow();
+ expect(() =>
+ parseRemoteDesktopRequest({
+ op: "input",
+ lease: "a",
+ sequence: 1,
+ events: Array(65).fill({ kind: "release" }),
+ }),
+ ).toThrow();
+ expect(() =>
+ parseRemoteDesktopRequest({
+ op: "offer",
+ lease: "a",
+ sdp: "x".repeat(64001),
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index a10dc97dfc..1ae324fcd8 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -17,6 +17,11 @@
*
* 双层校验:控制端发送前(快速失败)+ 被控端执行前(权威)。
* 新增 channel 不进表即天然不可远程调用(代码保证确定性)。
+ *
+ * 远程桌面专用例外: device-link:remote-desktop:v1 的 permissions/guide 只能
+ * 显示 Cindy 自己的权限引导,需同账号鉴权、远控与远程桌面两个本机 opt-in、未撤销。
+ * 不接受 URL、不直接打开系统设置/请求 OS 授权、不修改开关;系统权限按钮仅本机可信
+ * Renderer 可调用。它由业务 dispatch 拦截,绝不放行通用 UI / shell IPC。
*/
import { SESSION_ACTIVITY_CHANNEL, SESSION_SYNC_CHANNEL } from './topics.js';
import {
@@ -560,6 +565,7 @@ export const REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS: ReadonlySet<string> = new Se
/** 远程可调用的 invoke channel 全集(被控端 dispatch 前的权威校验依据) */
export const REMOTE_INVOKE_ALLOWLIST: ReadonlySet<string> = new Set([
+ 'device-link:remote-desktop:v1',
...CORE_INVOKE_CHANNELS,
...EXTENDED_INVOKE_CHANNELS,
]);
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 219c4afc2a..05ff178312 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -15,3 +15,6 @@ export * from './topics.js';
export * from './attachmentOssRef.js';
export * from './contactsSyncProtocol.js';
export * from './remoteResources.js';
+export * from './remoteDesktop.js';
+export * from './remoteClipboard.js';
+export * from './remoteCursor.js';
diff --git a/packages/device-link/src/remoteClipboard.ts b/packages/device-link/src/remoteClipboard.ts
new file mode 100644
index 0000000000..d89faefff3
--- /dev/null
+++ b/packages/device-link/src/remoteClipboard.ts
@@ -0,0 +1,44 @@
+/** Portable representations of one clipboard item. No remote paths or private formats. */
+export interface RemoteClipboardContent {
+ text?: string;
+ html?: string;
+ rtf?: string;
+ url?: string;
+ png?: string;
+}
+export const CLIPBOARD_CHUNK_CHARS = 64 * 1024;
+export const CLIPBOARD_MAX_CHARS = 32 * 1024 * 1024;
+export type ClipboardContentRequest =
+ | { op: "clipboardContent"; lease: string; action: "copy" }
+ | { op: "clipboardContent"; lease: string; action: "begin"; length: number }
+ | { op: "clipboardContent"; lease: string; action: "read"; id: string; offset: number }
+ | { op: "clipboardContent"; lease: string; action: "write"; id: string; offset: number; data: string }
+ | { op: "clipboardContent"; lease: string; action: "commit" | "cancel"; id: string };
+
+export function parseClipboardContentRequest(v: Record<string, unknown>, lease: string): ClipboardContentRequest {
+ const op = "clipboardContent";
+ if (v.action === "copy") return { op, lease, action: v.action };
+ if (v.action === "begin" && Number.isSafeInteger(v.length) && Number(v.length) > 0 && Number(v.length) <= CLIPBOARD_MAX_CHARS)
+ return { op, lease, action: v.action, length: Number(v.length) };
+ if (typeof v.id !== "string" || !/^[a-f0-9-]{36}$/.test(v.id)) throw new Error("INVALID_REQUEST");
+ if (v.action === "commit" || v.action === "cancel") return { op, lease, action: v.action, id: v.id };
+ if (!Number.isSafeInteger(v.offset) || Number(v.offset) < 0 || Number(v.offset) >= CLIPBOARD_MAX_CHARS) throw new Error("INVALID_REQUEST");
+ if (v.action === "read") return { op, lease, action: v.action, id: v.id, offset: Number(v.offset) };
+ if (v.action === "write" && typeof v.data === "string" && v.data.length > 0 && v.data.length <= CLIPBOARD_CHUNK_CHARS)
+ return { op, lease, action: v.action, id: v.id, offset: Number(v.offset), data: v.data };
+ throw new Error("INVALID_REQUEST");
+}
+export function parseClipboardContent(json: string): RemoteClipboardContent {
+ if (json.length > CLIPBOARD_MAX_CHARS) throw new Error("CLIPBOARD_TOO_LONG");
+ let value: unknown;
+ try { value = JSON.parse(json); } catch { throw new Error("CLIPBOARD_UNSUPPORTED"); }
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("CLIPBOARD_UNSUPPORTED");
+ const v = value as Record<string, unknown>;
+ if (!Object.keys(v).length || Object.entries(v).some(([k, x]) =>
+ !["text", "html", "rtf", "url", "png"].includes(k) || typeof x !== "string" || !x))
+ throw new Error("CLIPBOARD_UNSUPPORTED");
+ if (v.url && (typeof v.url !== "string" || !/^https?:\/\//i.test(v.url))) throw new Error("CLIPBOARD_UNSUPPORTED");
+ if (v.png && (typeof v.png !== "string" || !/^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png) || v.png.length % 4 !== 0))
+ throw new Error("CLIPBOARD_UNSUPPORTED");
+ return v as RemoteClipboardContent;
+}
diff --git a/packages/device-link/src/remoteCursor.ts b/packages/device-link/src/remoteCursor.ts
new file mode 100644
index 0000000000..1a23410388
--- /dev/null
+++ b/packages/device-link/src/remoteCursor.ts
@@ -0,0 +1,23 @@
+/** Bounded raster cursor data, never markup or a remote URL. Sizes/hotspot in desktop points. */
+export interface RemoteDesktopCursor {
+ visible: boolean;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ hotX: number;
+ hotY: number;
+ png: string;
+}
+export interface RemoteDesktopCursorFrame { jpeg: string; cursor: RemoteDesktopCursor | null }
+export function isRemoteDesktopCursor(value: unknown): value is RemoteDesktopCursor {
+ if (!value || typeof value !== "object") return false;
+ const v = value as RemoteDesktopCursor;
+ return typeof v.visible === "boolean" &&
+ [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&
+ v.x >= 0 && v.x <= 1 && v.y >= 0 && v.y <= 1 &&
+ v.width > 0 && v.width <= 256 && v.height > 0 && v.height <= 256 &&
+ v.hotX >= 0 && v.hotX <= v.width && v.hotY >= 0 && v.hotY <= v.height &&
+ typeof v.png === "string" && v.png.length <= 65536 &&
+ /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png);
+}
diff --git a/packages/device-link/src/remoteDesktop.ts b/packages/device-link/src/remoteDesktop.ts
new file mode 100644
index 0000000000..c241eae0d2
--- /dev/null
+++ b/packages/device-link/src/remoteDesktop.ts
@@ -0,0 +1,264 @@
+import { parseClipboardContentRequest, type ClipboardContentRequest } from "./remoteClipboard";
+/** Additive, same-account business channel. Never broadcast screen data or input. */
+export const REMOTE_DESKTOP_CHANNEL = "device-link:remote-desktop:v1";
+export const REMOTE_DESKTOP_LEASE_MS = 12_000;
+export const REMOTE_DESKTOP_MAX_FRAME_BYTES = 180_000;
+
+export const REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS = 16_384;
+
+export type DesktopInput =
+ | { kind: "move"; x: number; y: number }
+ | { kind: "button"; button: 0 | 1 | 2; down: boolean; x: number; y: number }
+ | { kind: "scroll"; dx: number; dy: number }
+ | { kind: "key"; code: string; down: boolean }
+ | { kind: "text"; text: string }
+ | { kind: "release" };
+
+export const DESKTOP_KEY_CODES = [
+ ..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map((key) => `Key${key}`),
+ ..."0123456789".split("").map((key) => `Digit${key}`),
+ ...Array.from({ length: 12 }, (_, i) => `F${i + 1}`),
+ "Enter",
+ "Escape",
+ "Tab",
+ "Space",
+ "Backspace",
+ "Delete",
+ "Insert",
+ "Home",
+ "End",
+ "PageUp",
+ "PageDown",
+ "ArrowUp",
+ "ArrowDown",
+ "ArrowLeft",
+ "ArrowRight",
+ "ShiftLeft",
+ "ControlLeft",
+ "AltLeft",
+ "MetaLeft",
+ "Minus",
+ "Equal",
+ "BracketLeft",
+ "BracketRight",
+ "Backslash",
+ "Semicolon",
+ "Quote",
+ "Backquote",
+ "Comma",
+ "Period",
+ "Slash",
+] as const;
+const codes = new Set<string>(DESKTOP_KEY_CODES);
+const unit = (v: unknown): v is number =>
+ typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
+const delta = (v: unknown): v is number =>
+ typeof v === "number" && Number.isFinite(v) && Math.abs(v) <= 2000;
+
+export function isDesktopInput(value: unknown): value is DesktopInput {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ const v = value as Record<string, unknown>;
+ switch (v.kind) {
+ case "release":
+ return true;
+ case "move":
+ return unit(v.x) && unit(v.y);
+ case "button":
+ return (
+ unit(v.x) &&
+ unit(v.y) &&
+ [0, 1, 2].includes(v.button as number) &&
+ typeof v.down === "boolean"
+ );
+ case "scroll":
+ return delta(v.dx) && delta(v.dy);
+ case "key":
+ return (
+ typeof v.code === "string" &&
+ codes.has(v.code) &&
+ typeof v.down === "boolean"
+ );
+ case "text":
+ return typeof v.text === "string" && v.text.length <= 4096;
+ default:
+ return false;
+ }
+}
+
+export interface RemoteDesktopVideoSettings {
+ fps: 30 | 60;
+ bitrate: 0 | 2_000_000 | 8_000_000 | 20_000_000;
+ audio: boolean;
+}
+export interface RemoteDesktopDisplayMode {
+ id: string;
+ width: number;
+ height: number;
+ current: boolean;
+ /** Reported by the host OS; absent on older hosts or when unknown. */
+ native?: boolean;
+}
+export interface RemoteDesktopDisplay {
+ id: string;
+ name: string;
+ width: number;
+ height: number;
+}
+export interface RemoteDesktopCapabilities {
+ version: 1;
+ enabled: boolean;
+ canControl: boolean;
+ platform: string;
+ displays: RemoteDesktopDisplay[];
+ /** Optional so older desktops retain their original connection behavior. */
+ permissions?: RemoteDesktopPermissions;
+ /** Supports resume and preserves explicit local disconnects during recovery. */
+ automaticReconnect?: boolean;
+ /** Explicit same-account replacement of the active viewer. */
+ connectionTakeover?: boolean;
+ videoSettings?: boolean;
+ systemAudio?: boolean;
+ displayModes?: boolean;
+ backgroundViewing?: boolean;
+ cursorOverlay?: boolean;
+ clipboardText?: boolean;
+ clipboardContent?: boolean;
+}
+export type DesktopPermission = "screenRecording" | "accessibility";
+export type DesktopPermissionStatus =
+ "granted" | "missing" | "unknown" | "notRequired";
+export interface RemoteDesktopPermissions {
+ screenRecording: DesktopPermissionStatus;
+ accessibility: DesktopPermissionStatus;
+}
+export function isDesktopPermission(
+ value: unknown,
+): value is DesktopPermission {
+ return value === "screenRecording" || value === "accessibility";
+}
+export function desktopPermissionReady(
+ status: DesktopPermissionStatus,
+): boolean {
+ return status === "granted" || status === "notRequired";
+}
+export interface RemoteDesktopLease {
+ lease: string;
+ display: RemoteDesktopDisplay;
+ controlling: boolean;
+}
+export type RemoteDesktopRequest =
+ | ClipboardContentRequest
+ | { op: "capabilities" }
+ | { op: "permissions"; action: "check" | "guide" }
+ | { op: "start"; displayId: string; resume?: boolean; takeover?: boolean }
+ | { op: "heartbeat" | "stop"; lease: string }
+ | { op: "frame"; lease: string; cursorOverlay?: boolean }
+ | { op: "control" | "presentation"; lease: string; enabled: boolean }
+ | { op: "input"; lease: string; sequence: number; events: DesktopInput[] }
+ | {
+ op: "offer";
+ lease: string;
+ sdp: string;
+ cursorOverlay?: boolean;
+ settings?: RemoteDesktopVideoSettings;
+ }
+ | { op: "clipboard"; lease: string; action: "copy" }
+ | { op: "clipboard"; lease: string; action: "paste"; text: string }
+ | { op: "displayModes"; lease: string }
+ | { op: "resolution"; lease: string; modeId: string };
+
+export function parseRemoteDesktopRequest(
+ value: unknown,
+): RemoteDesktopRequest {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ throw new Error("INVALID_REQUEST");
+ const v = value as Record<string, unknown>;
+ if (v.op === "capabilities") return { op: v.op };
+ if (v.op === "permissions" && (v.action === "check" || v.action === "guide"))
+ return { op: v.op, action: v.action };
+ if (
+ v.op === "start" &&
+ typeof v.displayId === "string" &&
+ v.displayId.length <= 128
+ ) {
+ if (v.resume !== undefined && typeof v.resume !== "boolean")
+ throw new Error("INVALID_REQUEST");
+ if (v.takeover !== undefined && typeof v.takeover !== "boolean") throw new Error("INVALID_REQUEST");
+ if (v.takeover === true && v.resume === true) throw new Error("INVALID_REQUEST");
+ return {
+ op: v.op,
+ displayId: v.displayId,
+ ...(v.takeover === true ? { takeover: true } : {}),
+ ...(typeof v.resume === "boolean" ? { resume: v.resume } : {}),
+ };
+ }
+ if (typeof v.lease !== "string" || v.lease.length > 128 || !v.lease)
+ throw new Error("INVALID_LEASE");
+ const lease = v.lease;
+ if (v.op === "clipboardContent") return parseClipboardContentRequest(v, lease);
+ if (v.op === "clipboard") {
+ if (v.action === "copy") return { op: v.op, lease, action: "copy" };
+ if (v.action === "paste" && typeof v.text === "string" && v.text.length > 0 && v.text.length <= REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS)
+ return { op: v.op, lease, action: "paste", text: v.text };
+ throw new Error("INVALID_REQUEST");
+ }
+ if (v.op === "frame") {
+ if (v.cursorOverlay !== undefined && typeof v.cursorOverlay !== "boolean") throw new Error("INVALID_REQUEST");
+ return { op: v.op, lease, ...(v.cursorOverlay === true ? { cursorOverlay: true } : {}) };
+ }
+ if (v.op === "heartbeat" || v.op === "stop")
+ return { op: v.op, lease };
+ if (
+ (v.op === "control" || v.op === "presentation") &&
+ typeof v.enabled === "boolean"
+ )
+ return { op: v.op, lease, enabled: v.enabled };
+ if (v.op === "displayModes") return { op: v.op, lease };
+ if (
+ v.op === "resolution" &&
+ typeof v.modeId === "string" &&
+ /^[0-9]{1,10}$/.test(v.modeId)
+ )
+ return { op: v.op, lease, modeId: v.modeId };
+ if (v.op === "offer" && typeof v.sdp === "string" && v.sdp.length <= 64_000) {
+ if (v.cursorOverlay !== undefined && typeof v.cursorOverlay !== "boolean") throw new Error("INVALID_REQUEST");
+ const overlay = v.cursorOverlay === true ? { cursorOverlay: true } : {};
+ if (v.settings === undefined) return { op: v.op, lease, sdp: v.sdp, ...overlay };
+ const settings = v.settings as RemoteDesktopVideoSettings;
+ if (
+ !settings ||
+ ![30, 60].includes(settings.fps) ||
+ ![0, 2_000_000, 8_000_000, 20_000_000].includes(settings.bitrate) ||
+ typeof settings.audio !== "boolean"
+ )
+ throw new Error("INVALID_REQUEST");
+ return {
+ op: v.op,
+ lease,
+ sdp: v.sdp,
+ ...overlay,
+ settings: {
+ fps: settings.fps,
+ bitrate: settings.bitrate,
+ audio: settings.audio,
+ },
+ };
+ }
+ if (
+ v.op === "input" &&
+ Number.isSafeInteger(v.sequence) &&
+ (v.sequence as number) >= 0 &&
+ Array.isArray(v.events) &&
+ v.events.length <= 64 &&
+ v.events.every(isDesktopInput) &&
+ JSON.stringify(v.events).length <= 16_384
+ ) {
+ return {
+ op: v.op,
+ lease,
+ sequence: v.sequence as number,
+ events: v.events,
+ };
+ }
+ throw new Error("INVALID_REQUEST");
+}
diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjs
index 376c3beb4e..79bf165f8e 100644
--- a/scripts/generate-third-party-notices.mjs
+++ b/scripts/generate-third-party-notices.mjs
@@ -33,6 +33,8 @@ const MOBILE_DIR = path.join(REPO_ROOT, "apps", "mobile");
const NOTICES_DIR = path.join(REPO_ROOT, "docs", "legal", "notices");
const SBOM_DIR = path.join(NOTICES_DIR, "sbom");
const CARGO_MANIFESTS = [
+ path.join(DESKTOP_DIR, "native", "remote-desktop", "windows-input", "Cargo.toml"),
+ path.join(DESKTOP_DIR, "native", "remote-desktop", "windows-host", "Cargo.toml"),
path.join(DESKTOP_DIR, "cindy-updater", "src-tauri", "Cargo.toml"),
path.join(
DESKTOP_DIR,