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。

fix(remote-desktop): 修复剪贴板误报并改为轻量提示

Dash58cd9bec39e3
diff --git a/apps/desktop/native/remote-desktop/linux-clipboard/main.c b/apps/desktop/native/remote-desktop/linux-clipboard/main.c
index bf337de2e7..1b88c74dca 100644
--- a/apps/desktop/native/remote-desktop/linux-clipboard/main.c
+++ b/apps/desktop/native/remote-desktop/linux-clipboard/main.c
@@ -10,6 +10,10 @@
#include <unistd.h>
#include <wayland-client.h>
+/* Keep in step with Desktop clipboardLimits.ts and the transport JSON bound. */
+#define IMAGE_BYTES (16 * 1024 * 1024)
+#define PAYLOAD_BYTES (32 * 1024 * 1024)
+
/* One portable clipboard offer, supplied through stdin, never argv or a file.
* No observation of clipboard contents. The compositor requests only offered
* MIME types; replacement or parent EOF destroys the in-memory offer. */
@@ -102,7 +106,7 @@ static int decode(const char *text, size_t size, unsigned char **out,
size_t *length) {
static const char alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- if (size % 4 || size > 11184812)
+ if (size % 4 || size > ((IMAGE_BYTES + 2) / 3) * 4)
return -1;
unsigned char *bytes = malloc(size / 4 * 3 + 1);
if (!bytes)
@@ -131,7 +135,7 @@ static int decode(const char *text, size_t size, unsigned char **out,
}
*out = bytes;
*length = n;
- return n <= 8388608 ? 0 : -1;
+ return n <= IMAGE_BYTES ? 0 : -1;
}
static int payload(const char *line) {
struct json_tokener *tok = json_tokener_new_ex(8);
@@ -187,7 +191,7 @@ static int payload(const char *line) {
int main(int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
alarm(5);
- char *line = malloc(16000002);
+ char *line = malloc(PAYLOAD_BYTES + 2);
if (!line)
return 1;
int status = 1;
@@ -195,7 +199,7 @@ int main(int argc, char **argv) {
struct wl_registry *registry = NULL;
struct zwlr_data_control_device_v1 *device = NULL;
struct zwlr_data_control_source_v1 *source = NULL;
- if (!fgets(line, 16000002, stdin) || !strchr(line, '\n') || payload(line))
+ if (!fgets(line, PAYLOAD_BYTES + 2, stdin) || !strchr(line, '\n') || payload(line))
goto done;
if (argc == 2 && !strcmp(argv[1], "--check")) {
status = 0;
diff --git a/apps/desktop/native/remote-desktop/linux-clipboard/test.mjs b/apps/desktop/native/remote-desktop/linux-clipboard/test.mjs
index 553e365109..c050ac9c4e 100644
--- a/apps/desktop/native/remote-desktop/linux-clipboard/test.mjs
+++ b/apps/desktop/native/remote-desktop/linux-clipboard/test.mjs
@@ -55,6 +55,12 @@ int main(void) {
assert(decode("Y!==",4,&bytes,&length)==-1);
assert(decode("A",1,&bytes,&length)==-1);
assert(decode("====",4,&bytes,&length)==-1);
+ size_t encoded=((IMAGE_BYTES+2)/3)*4;
+ char *large=malloc(encoded+1);assert(large);memset(large,'A',encoded);large[encoded]=0;
+ large[encoded-1]='=';large[encoded-2]='=';
+ assert(!decode(large,encoded,&bytes,&length) && length==IMAGE_BYTES);free(bytes);
+ large[encoded-2]='A';
+ assert(decode(large,encoded,&bytes,&length)==-1);free(bytes);free(large);
assert(payload("{\\\"text\\\":3}")==-1);
assert(payload("{}")==-1);
assert(!payload("{\\\"text\\\":\\\"test\\\",\\\"html\\\":\\\"<b>test</b>\\\",\\\"png\\\":\\\"YQ==\\\"}"));
diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts
index a254f3c466..8157acc787 100644
--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts
+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts
@@ -7,6 +7,41 @@ import {
import { DEFAULT_VIEWER_PREFERENCES } from '../../../shared/remoteDesktopViewer';
import { ViewerSafety } from '../safety';
+it.each([
+ ['CLIPBOARD_UNSUPPORTED', 'clipboardSyncSkipped'],
+ ['CLIPBOARD_TOO_LONG', 'clipboardSyncTooLarge'],
+] as const)(
+ 'distinguishes %s and clears its notice after a new empty snapshot',
+ async (code, notice) => {
+ const { safety, sync } = syncFixture();
+ let version = '1';
+ let error = code as string;
+ const json = '{"text":"remote"}';
+ const options: Parameters<ViewerSafety['tick']>[0] = {
+ ...sync,
+ caps: { ...sync.caps, clipboardInline: true },
+ clipboard: {
+ version: async () => version,
+ read: async () => {
+ throw new Error(error);
+ },
+ write: vi.fn(),
+ },
+ request: (async (message: RemoteDesktopRequest) => {
+ if (message.op === 'clipboardVersion') return { version: '1' };
+ if (message.op === 'clipboardContent') return { data: json, length: json.length };
+ return { enabled: true };
+ }) as Parameters<ViewerSafety['tick']>[0]['request'],
+ };
+ expect((await safety.tick(options)).notice).toBeNull();
+ version = '2';
+ expect((await safety.tick(options)).notice).toBe(notice);
+ version = '3';
+ error = 'CLIPBOARD_EMPTY';
+ expect((await safety.tick(options)).notice).toBeNull();
+ },
+);
+
function fixture() {
const safety = new ViewerSafety();
const request = vi.fn(async () => ({ enabled: true })) as any;
@@ -218,7 +253,7 @@ it('a copy mid-read keeps the status; other failures back off to 5s at most and
}
});
-it('a permission failure still waits for an explicit retry', async () => {
+it('waits after permission denial, then checks again when the user returns or copies', async () => {
const { safety, sync } = syncFixture();
const tick = vi
.spyOn(ClipboardSync.prototype, 'tick')
@@ -226,9 +261,11 @@ it('a permission failure still waits for an explicit retry', async () => {
.mockResolvedValue(undefined);
try {
expect((await safety.tick(sync)).notice).toBe('clipboardSyncPermission');
- safety.wake();
expect((await safety.tick(sync)).notice).toBe('clipboardSyncPermission');
expect(tick).toHaveBeenCalledOnce();
+ safety.wake();
+ expect((await safety.tick(sync)).notice).toBeNull();
+ expect(tick).toHaveBeenCalledTimes(2);
} finally {
tick.mockRestore();
}
diff --git a/apps/desktop/src/main/remote-desktop-viewer/safety.ts b/apps/desktop/src/main/remote-desktop-viewer/safety.ts
index 577e39836e..4ff10d63ea 100644
--- a/apps/desktop/src/main/remote-desktop-viewer/safety.ts
+++ b/apps/desktop/src/main/remote-desktop-viewer/safety.ts
@@ -27,7 +27,7 @@ export interface ViewerClipboardFailure {
code: string;
/** Status key for the viewer window; null keeps whatever is shown. */
notice: string | null;
- /** Milliseconds until the next attempt; null waits for an explicit retry. */
+ /** Milliseconds until the next attempt; null waits for focus or a copy/paste wakeup. */
delay: number | null;
/** Settles by itself (locked computer, a copy mid-read); never grows the backoff. */
transient: boolean;
@@ -70,9 +70,8 @@ export class ViewerSafety {
idle(): Promise<void> {
return this.settled;
}
- /** Regained focus or a copy/paste: retry now, unless sync waits for a permission. */
+ /** User returned or copied/pasted: permissions may have changed in Settings. */
wake(): void {
- if (this.retryAt === Infinity) return;
this.retryAt = 0;
this.failures = 0;
}
@@ -218,11 +217,21 @@ export class ViewerSafety {
readLocal: () => local(options.clipboard!.read(current)),
writeLocal: (json, version) => local(options.clipboard!.write(json, version, current)),
localReadCache: this.localReadCache,
- trace: (stage) => {
+ trace: (stage, code) => {
if (!valid()) return;
if (stage === 'content-skipped')
- this.notices.set('clipboardSync', 'clipboardSyncSkipped');
- else if (['phone-to-computer-complete', 'computer-to-phone-complete'].includes(stage))
+ this.notices.set(
+ 'clipboardSync',
+ code === 'CLIPBOARD_TOO_LONG' ? 'clipboardSyncTooLarge' : 'clipboardSyncSkipped',
+ );
+ else if (
+ [
+ 'phone-to-computer-complete',
+ 'computer-to-phone-complete',
+ 'unchanged-content',
+ 'content-empty',
+ ].includes(stage)
+ )
this.notices.delete('clipboardSync');
},
digest: (json) => {
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts
index 7f75c660a9..0a5c0c06d9 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts
@@ -79,13 +79,38 @@ it('retains pixel bounds on file-backed images', async () => {
const syncCopy = () =>
transferDesktopClipboardContent('copy', undefined, () => true, vi.fn(), { sync: true });
+it.each([
+ [3840, 2160],
+ [5120, 2880],
+ [6016, 3384],
+])('copies and pastes a %s x %s screenshot without resizing', async (width, height) => {
+ const bytes = Buffer.alloc(33);
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82]).copy(bytes);
+ bytes.writeUInt32BE(width, 16);
+ bytes.writeUInt32BE(height, 20);
+ const native = { ...image, getSize: () => ({ width, height }), toPNG: () => bytes };
+ mocks.clipboard.readImage.mockReturnValue(native);
+ mocks.decode.mockReturnValue(native);
+ const content = await syncCopy();
+ expect(content).toMatchObject({ png: bytes.toString('base64') });
+ await expect(
+ transferDesktopClipboardContent(
+ 'paste',
+ { png: bytes.toString('base64') },
+ () => true,
+ vi.fn(),
+ { sync: true },
+ ),
+ ).resolves.toEqual({ version: '1' });
+ expect(mocks.clipboard.write).toHaveBeenCalledWith({ image: native });
+});
it.each([copy, syncCopy])(
'rejects oversized native images before encoding in either copy mode',
async (read) => {
const encode = vi.fn();
mocks.clipboard.readImage.mockReturnValue({
...image,
- getSize: () => ({ width: 2001, height: 2000 }),
+ getSize: () => ({ width: 6001, height: 4000 }),
toPNG: encode,
});
await expect(read()).rejects.toThrow('CLIPBOARD_TOO_LONG');
@@ -93,7 +118,7 @@ it.each([copy, syncCopy])(
},
);
it('rejects an oversized encoded buffer before making a Base64 copy', async () => {
- const bytes = Buffer.alloc(8 * 1024 * 1024 + 1);
+ const bytes = Buffer.alloc(16 * 1024 * 1024 + 1);
const stringify = vi.spyOn(bytes, 'toString');
mocks.clipboard.readImage.mockReturnValue({ ...image, toPNG: () => bytes });
await expect(syncCopy()).rejects.toThrow('CLIPBOARD_TOO_LONG');
@@ -101,7 +126,7 @@ it('rejects an oversized encoded buffer before making a Base64 copy', async () =
});
it('accepts the exact pixel boundary and explicitly encodes at scale one', async () => {
const encode = vi.fn(() => png);
- const size = vi.fn(() => ({ width: 2000, height: 2000 }));
+ const size = vi.fn(() => ({ width: 6000, height: 4000 }));
mocks.clipboard.readImage.mockReturnValue({
...image,
getSize: size,
@@ -111,13 +136,13 @@ it('accepts the exact pixel boundary and explicitly encodes at scale one', async
expect(size).toHaveBeenCalledWith(1);
expect(encode).toHaveBeenCalledWith({ scaleFactor: 1 });
});
-it.each([0, 2001, 0xffffffff])(
+it.each([0, 6001, 0xffffffff])(
'refuses incoming invalid/oversized dimensions before native decode: %s',
async (width) => {
const bytes = Buffer.alloc(33);
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82]).copy(bytes);
bytes.writeUInt32BE(width, 16);
- bytes.writeUInt32BE(2000, 20);
+ bytes.writeUInt32BE(4000, 20);
await expect(
transferDesktopClipboardContent(
'paste',
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts
index 00b42b2e90..999e9bdd02 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts
@@ -7,6 +7,26 @@ vi.mock('node:child_process', () => ({ execFile: vi.fn(), spawn: h.spawn }));
vi.mock('node:util', () => ({ promisify: () => h.exec }));
vi.mock('node:fs', () => ({ accessSync: vi.fn(), constants: { X_OK: 1 } }));
import { readLinuxClipboardSnapshot, writeLinuxClipboard } from '../linuxClipboardNative';
+it.each([
+ [6016, 3384, true],
+ [6000, 4000, true],
+ [6001, 4000, false],
+] as const)('applies Desktop image bounds to Linux %s x %s', async (width, height, accepted) => {
+ const png = Buffer.alloc(33);
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(png);
+ png.writeUInt32BE(width, 16);
+ png.writeUInt32BE(height, 20);
+ h.exec.mockImplementation(async (_tool, args: string[]) => ({
+ stdout: args.includes('--list-types') ? Buffer.from('image/png\n') : png,
+ }));
+ if (accepted)
+ expect((await readLinuxClipboardSnapshot()).content.png).toBe(png.toString('base64'));
+ else await expect(readLinuxClipboardSnapshot()).rejects.toThrow('CLIPBOARD_TOO_LONG');
+});
+it('reports a Linux read buffer limit as size, not clipboard access failure', async () => {
+ h.exec.mockRejectedValue({ code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' });
+ await expect(readLinuxClipboardSnapshot()).rejects.toThrow('CLIPBOARD_TOO_LONG');
+});
beforeEach(() => {
h.exec.mockReset();
h.spawn.mockReset();
diff --git a/apps/desktop/src/main/remote-desktop/clipboard.ts b/apps/desktop/src/main/remote-desktop/clipboard.ts
index 85a934a39f..b969943560 100644
--- a/apps/desktop/src/main/remote-desktop/clipboard.ts
+++ b/apps/desktop/src/main/remote-desktop/clipboard.ts
@@ -14,8 +14,10 @@ import {
supportsLinuxClipboard,
} from './linuxClipboardNative';
-const IMAGE_BYTES = 8 * 1024 * 1024;
-const IMAGE_PIXELS = 4_000_000;
+import {
+ CLIPBOARD_IMAGE_BYTES as IMAGE_BYTES,
+ CLIPBOARD_IMAGE_PIXELS as IMAGE_PIXELS,
+} from './clipboardLimits';
function checkImageSize(width: number, height: number): void {
if (
diff --git a/apps/desktop/src/main/remote-desktop/clipboardLimits.ts b/apps/desktop/src/main/remote-desktop/clipboardLimits.ts
new file mode 100644
index 0000000000..74e7acf80d
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/clipboardLimits.ts
@@ -0,0 +1,4 @@
+// Covers common 4K/5K/6K screenshots without lifting the 32 Mi-character
+// transport limit. Bound decoded pixels before encoding/decoding allocation.
+export const CLIPBOARD_IMAGE_PIXELS = 24_000_000;
+export const CLIPBOARD_IMAGE_BYTES = 16 * 1024 * 1024;
diff --git a/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts b/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts
index 30591a25ca..307c78c149 100644
--- a/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts
+++ b/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts
@@ -7,6 +7,7 @@ import { accessSync, constants } from 'node:fs';
import path from 'node:path';
import type { RemoteClipboardContent } from '@cindy/device-link';
import { isLinuxDesktopUnlocked } from './linuxSessionLock';
+import { CLIPBOARD_IMAGE_BYTES, CLIPBOARD_IMAGE_PIXELS } from './clipboardLimits';
const exec = promisify(execFile);
export function supportsLinuxClipboard(): boolean {
@@ -38,6 +39,13 @@ async function read(args: string[], maxBuffer: number, checkLock = true): Promis
await assertUnlocked(checkLock);
return result.stdout;
} catch (error) {
+ if (
+ error &&
+ typeof error === 'object' &&
+ 'code' in error &&
+ error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'
+ )
+ throw new Error('CLIPBOARD_TOO_LONG');
// Empty selection is distinct from failed compositor access. Never propagate
// subprocess exceptions: they can include clipboard contents in stdout.
if (
@@ -87,7 +95,11 @@ export async function readLinuxClipboardSnapshot(
}
}
if (!primary && formats.includes('image/png')) {
- const png = await read(['--no-newline', '--type', 'image/png'], 8 * 1024 * 1024, checkLock);
+ const png = await read(
+ ['--no-newline', '--type', 'image/png'],
+ CLIPBOARD_IMAGE_BYTES,
+ checkLock,
+ );
if (
png.length < 33 ||
!png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
@@ -95,7 +107,8 @@ export async function readLinuxClipboardSnapshot(
throw new Error('CLIPBOARD_UNSUPPORTED');
const width = png.readUInt32BE(16),
height = png.readUInt32BE(20);
- if (!width || !height || width * height > 4000000) throw new Error('CLIPBOARD_TOO_LONG');
+ if (!width || !height || width > CLIPBOARD_IMAGE_PIXELS / height)
+ throw new Error('CLIPBOARD_TOO_LONG');
content.png = png.toString('base64');
}
return { formats, content };
diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
index 3f6917e17f..7cef178be0 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx
@@ -31,6 +31,7 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Switch } from '@/components/ui/switch';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Tip } from '@/components/ui/tooltip';
+import { toast, ToastContainer } from '@/components/ui/toast';
import {
fittedChoices,
ratioLabel,
@@ -87,6 +88,15 @@ export function RemoteDesktopViewerWindow() {
const generation = useRef(-1);
const latestState = useRef<ViewerSnapshot | null>(null);
const activePanel = useRef(settings);
+ const safetyNotice = state?.safety.notice;
+ const clipboardNotice = safetyNotice?.startsWith('clipboardSync') ? safetyNotice : null;
+ const persistentSafetyNotice = clipboardNotice ? null : safetyNotice;
+ useEffect(() => {
+ if (!clipboardNotice) return;
+ // Same status from idle polls does not reopen or prolong a notification.
+ const id = toast.info(t(`remoteDesktop.${clipboardNotice}`), { duration: 4000 });
+ return () => toast.dismiss(id);
+ }, [clipboardNotice, t]);
// Only the latest clipboard click reports; queued earlier transfers stay silent.
const clipboardAttempt = useRef(0);
activePanel.current = settings;
@@ -861,10 +871,10 @@ export function RemoteDesktopViewerWindow() {
<span className="sr-only" role="status">
{state?.safety.privacyActive ? t('remoteDesktop.privacyActive') : ''}
</span>
- {(notice || state?.safety.notice) && (
+ {(notice || persistentSafetyNotice) && (
<div className="remote-viewer-feedback" role="status">
- <span>{notice ?? t(`remoteDesktop.${state?.safety.notice}`)}</span>
- {state?.safety.notice && (
+ <span>{notice ?? t(`remoteDesktop.${persistentSafetyNotice}`)}</span>
+ {!notice && persistentSafetyNotice && (
<Button
variant="secondary"
onClick={() => void controller.current?.refreshSafety(true)}
@@ -883,6 +893,7 @@ export function RemoteDesktopViewerWindow() {
</div>
)}
</div>
+ <ToastContainer />
<ConfirmDialog
presentation="standard"
open={closeGeneration !== null}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx
index 0dfaa84833..7628594140 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx
+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx
@@ -4,6 +4,7 @@ import { afterEach, expect, it, onTestFinished, vi } from 'vitest';
import i18n from '@/i18n';
import { RemoteDesktopViewerWindow } from '../RemoteDesktopViewerWindow';
import type { ViewerSnapshot } from '../viewerController';
+import { getToastSnapshot, toast } from '@/lib/toast';
const lifecycle = vi.hoisted(() => ({
created: vi.fn(),
@@ -61,6 +62,91 @@ afterEach(() => {
vi.clearAllMocks();
});
+it('shows clipboard status as a transient toast without retry and keeps privacy failures visible', async () => {
+ await i18n.changeLanguage('zh-CN');
+ Object.assign(window, {
+ electronAPI: {
+ remoteDesktopViewer: {
+ onActive: () => () => {},
+ onLocale: () => () => {},
+ onCloseRequested: () => () => {},
+ state: async () => ({ generation: 1 }),
+ rendererReady: async () => {},
+ presentationReady: async () => {},
+ inputFocus: async () => {},
+ },
+ },
+ });
+ render(<RemoteDesktopViewerWindow />);
+ await act(async () => {});
+ vi.useFakeTimers();
+ const snapshot: ViewerSnapshot = {
+ target: { deviceId: 'host', name: 'Mac' },
+ status: 'live',
+ error: null,
+ ready: true,
+ controlling: true,
+ controlPending: false,
+ closing: false,
+ displayId: 'one',
+ transport: 'direct',
+ latency: null,
+ receiveRate: null,
+ settings: { fps: 30, quality: 'auto', audio: false },
+ caps: null,
+ preferences: {
+ audio: true,
+ privacyScreen: false,
+ hostMute: false,
+ clipboardSync: true,
+ lockOnExit: false,
+ },
+ safety: { privacyActive: false, notice: 'clipboardSyncSkipped', clipboardProgress: null },
+ credential: null,
+ credentialBusy: false,
+ credentialNotice: null,
+ fittedDisplay: null,
+ };
+ try {
+ act(() => lifecycle.update?.(snapshot));
+ const text = i18n.t('remoteDesktop.clipboardSyncSkipped');
+ expect(screen.getByText(text)).toBeDefined();
+ expect(screen.queryByRole('button', { name: i18n.t('remoteDesktop.retry') })).toBeNull();
+ expect(document.querySelector('.remote-viewer-feedback')).toBeNull();
+ expect(getToastSnapshot()).toHaveLength(1);
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ act(() => lifecycle.update?.({ ...snapshot }));
+ await act(async () => vi.advanceTimersByTimeAsync(1400));
+ expect(screen.queryByText(text)).toBeNull();
+ act(() => lifecycle.update?.({ ...snapshot }));
+ expect(getToastSnapshot()).toHaveLength(0);
+
+ // A distinct size failure gets its own short notice; recovery removes it early.
+ act(() =>
+ lifecycle.update?.({
+ ...snapshot,
+ safety: { ...snapshot.safety, notice: 'clipboardSyncTooLarge' },
+ }),
+ );
+ expect(screen.getByText(i18n.t('remoteDesktop.clipboardSyncTooLarge'))).toBeDefined();
+ act(() => lifecycle.update?.({ ...snapshot, safety: { ...snapshot.safety, notice: null } }));
+ await act(async () => vi.advanceTimersByTimeAsync(400));
+ expect(getToastSnapshot()).toHaveLength(0);
+
+ act(() =>
+ lifecycle.update?.({ ...snapshot, safety: { ...snapshot.safety, notice: 'privacyFailed' } }),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(5000));
+ expect(screen.getByRole('button', { name: i18n.t('remoteDesktop.retry') })).toBeDefined();
+ expect(document.querySelector('.remote-viewer-feedback')).not.toBeNull();
+ } finally {
+ cleanup();
+ toast.dismissAll();
+ await vi.advanceTimersByTimeAsync(400);
+ vi.useRealTimers();
+ }
+});
+
it('confirms toolbar and native exits, keeps cancellation connected, and discards stale confirmations', async () => {
await i18n.changeLanguage('zh-CN');
const close = vi.fn(async () => {});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5edbcb9fff..f10fcacd6d 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -779,8 +779,9 @@
"clipboardSync": "Clipboard sync",
"clipboardSyncConflict": "Both clipboards changed. Both copies were kept. Copy again on either device to sync.",
"clipboardSyncFailed": "Sync temporarily failed. Retrying automatically; your setting stays on.",
- "clipboardSyncSkipped": "This content could not be synced and was skipped. Check paste access, or copy text or an image to try again.",
- "clipboardSyncPermission": "Sync is paused. Allow paste access, then retry. Your setting stays on.",
+ "clipboardSyncSkipped": "This format is not supported for clipboard sync and was skipped.",
+ "clipboardSyncTooLarge": "Content exceeds the clipboard sync size limit and was skipped.",
+ "clipboardSyncPermission": "Clipboard sync needs paste access. Allow it, then return to this window to resume.",
"clipboardSyncWaiting": "The remote computer’s clipboard is not available right now (it may be locked). Sync resumes automatically.",
"lockingOnExit": "Locking computer…",
"lockOnExit": "Lock Computer on Exit",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a230fc44e8..c6a745494c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -769,8 +769,9 @@
"clipboardSync": "クリップボード同期",
"clipboardSyncConflict": "両方のクリップボードが変更されました。それぞれの内容は保持されています。どちらかのデバイスでもう一度コピーすると同期されます。",
"clipboardSyncFailed": "同期に一時的に失敗しました。自動で再試行します。設定はオンのままです。",
- "clipboardSyncSkipped": "この内容は同期できないためスキップしました。ペーストの許可を確認するか、テキストや画像をコピーして再試行してください。",
- "clipboardSyncPermission": "同期を一時停止しました。ペーストを許可してから再試行してください。設定はオンのままです。",
+ "clipboardSyncSkipped": "この形式はクリップボード同期に対応していないためスキップしました。",
+ "clipboardSyncTooLarge": "クリップボード同期のサイズ上限を超えたためスキップしました。",
+ "clipboardSyncPermission": "クリップボード同期にはペーストの許可が必要です。許可後、このウィンドウに戻ると再開します。",
"clipboardSyncWaiting": "リモートのパソコンのクリップボードに現在アクセスできません(ロック中の可能性があります)。自動で同期を再開します。",
"lockingOnExit": "コンピューターをロック中…",
"lockOnExit": "終了時にパソコンをロック",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ba90aa99a7..cffc6046d1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -769,8 +769,9 @@
"clipboardSync": "클립보드 동기화",
"clipboardSyncConflict": "양쪽 클립보드가 변경되어 각각의 내용을 유지했습니다. 어느 기기에서든 다시 복사하면 동기화됩니다.",
"clipboardSyncFailed": "동기화가 일시적으로 실패했습니다. 자동으로 재시도하며 설정은 켜진 상태로 유지됩니다.",
- "clipboardSyncSkipped": "현재 콘텐츠를 동기화할 수 없어 건너뛰었습니다. 붙여넣기 권한을 확인하거나 텍스트 또는 이미지를 복사한 후 다시 시도해 주세요.",
- "clipboardSyncPermission": "동기화가 일시 중지되었습니다. 붙여넣기를 허용한 후 다시 시도해 주세요. 설정은 켜진 상태로 유지됩니다.",
+ "clipboardSyncSkipped": "클립보드 동기화에서 지원하지 않는 형식이라 건너뛰었습니다.",
+ "clipboardSyncTooLarge": "클립보드 동기화 크기 제한을 초과하여 건너뛰었습니다.",
+ "clipboardSyncPermission": "클립보드 동기화에는 붙여넣기 권한이 필요합니다. 허용한 후 이 창으로 돌아오면 재개됩니다.",
"clipboardSyncWaiting": "원격 컴퓨터의 클립보드에 지금은 접근할 수 없습니다(잠겨 있을 수 있음). 자동으로 동기화를 재개합니다.",
"lockingOnExit": "컴퓨터를 잠그는 중…",
"lockOnExit": "종료 시 컴퓨터 잠금",
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 b7447cb62b..25a7a8280f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -769,8 +769,9 @@
"clipboardSync": "剪贴板同步",
"clipboardSyncConflict": "两端剪贴板都发生了变化,已分别保留。请在任一设备上重新复制以同步。",
"clipboardSyncFailed": "同步暂时失败,正在自动重试。开关保持开启。",
- "clipboardSyncSkipped": "当前内容无法同步,已跳过。请检查粘贴权限,或复制文字、图片后重试。",
- "clipboardSyncPermission": "同步已暂停,请允许粘贴权限后重试。开关保持开启。",
+ "clipboardSyncSkipped": "此格式暂不支持剪贴板同步,已跳过",
+ "clipboardSyncTooLarge": "内容超出剪贴板同步大小限制,已跳过",
+ "clipboardSyncPermission": "剪贴板同步需要粘贴权限,授权后回到窗口即可恢复",
"clipboardSyncWaiting": "远程电脑的剪贴板暂时无法访问(可能已锁屏),解锁后会自动继续同步。",
"lockingOnExit": "正在锁定电脑…",
"lockOnExit": "退出后锁定电脑",
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 0deed2e6d0..20ead856ea 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -769,8 +769,9 @@
"clipboardSync": "剪貼簿同步",
"clipboardSyncConflict": "兩端剪貼簿都發生了變更,已分別保留。請在任一裝置上重新複製以同步。",
"clipboardSyncFailed": "同步暫時失敗,正在自動重試。開關保持開啟。",
- "clipboardSyncSkipped": "目前內容無法同步,已略過。請檢查貼上權限,或複製文字、圖片後重試。",
- "clipboardSyncPermission": "同步已暫停,請允許貼上權限後重試。開關保持開啟。",
+ "clipboardSyncSkipped": "此格式暫不支援剪貼簿同步,已略過",
+ "clipboardSyncTooLarge": "內容超出剪貼簿同步大小限制,已略過",
+ "clipboardSyncPermission": "剪貼簿同步需要貼上權限,授權後回到視窗即可恢復",
"clipboardSyncWaiting": "遠端電腦的剪貼簿暫時無法存取(可能已鎖定螢幕),解鎖後會自動繼續同步。",
"lockingOnExit": "正在鎖定電腦…",
"lockOnExit": "退出後鎖定電腦",
diff --git a/apps/mobile/src/remote-desktop/clipboardSync.test.ts b/apps/mobile/src/remote-desktop/clipboardSync.test.ts
index 02a2a71438..cdc4f24561 100644
--- a/apps/mobile/src/remote-desktop/clipboardSync.test.ts
+++ b/apps/mobile/src/remote-desktop/clipboardSync.test.ts
@@ -113,7 +113,9 @@ describe("automatic clipboard synchronization", () => {
await engine.tick();
await engine.tick();
expect(h.deps.readLocal).toHaveBeenCalledTimes(1);
- expect(trace).toHaveBeenCalledWith("content-skipped");
+ expect(
+ trace.mock.calls.some(([stage]) => stage === "content-skipped"),
+ ).toBe(false);
h.local("2");
await engine.tick();
expect(
@@ -445,7 +447,10 @@ it("an unreadable local item next to a new computer copy is a conflict; the next
);
h.local("2");
await expect(engine.tick()).resolves.toBeUndefined();
- expect(trace).toHaveBeenLastCalledWith("content-skipped");
+ expect(trace).toHaveBeenLastCalledWith(
+ "content-skipped",
+ "CLIPBOARD_UNSUPPORTED",
+ );
// Unreadable local item and a new computer copy in the same interval.
vi.mocked(h.deps.readLocal).mockRejectedValueOnce(
new Error("CLIPBOARD_UNSUPPORTED"),
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index d6c96b7c54..bb4e54948b 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -84,6 +84,14 @@ preserve both clipboards, and the next copy chooses the source. A successful
transfer restores ordinary content deduplication. Contents stay in Main/native code and do not cross the viewer
Renderer bridge.
+Connecting establishes both clipboard baselines silently, including empty,
+unsupported or oversized existing items. Empty later snapshots do not erase
+the other clipboard or compete with a real copy. Desktop clipboard sync notices
+use the shared transient toast (4 seconds, no retry action); unchanged status
+polls do not reopen it. Unsupported formats and size limits have distinct copy.
+Permission denials pause background attempts, but focus and copy/paste wakeups
+check again so returning after granting access resumes without a retry button.
+
The settings panel also supports host privacy screen, host mute, lock-on-exit and
macOS-to-macOS automatic unlock. Non-secret preferences are scoped to the local
account and target computer; only explicit overrides are stored. Host effects
@@ -1121,11 +1129,14 @@ processes once they are over one hour old. Filenames include the process ID and
start time, so current-process preparation survives long suspensions and module
recreation without an active-file registry.
-Desktop manual copy, automatic reads and write verification share a 4 million
-pixel check before native PNG encoding. PNG buffers over 8 MiB are rejected before
+Desktop manual copy, automatic reads and write verification share a 24 million
+pixel check before native PNG encoding, covering common 4K/5K/6K screenshots.
+PNG buffers over 16 MiB are rejected before
Base64/hash copies. Incoming PNGs have encoded-length, byte and dimension checks
before native decoding. The pixel limit bounds encoding work; Electron still
allocates the PNG buffer before its byte length can be checked.
+Linux uses the same Desktop limits. Transport framing remains unchanged; older
+Desktop and Mobile peers keep their own smaller limits and may decline an image.
### Opt-in Mobile clipboard synchronization
diff --git a/packages/device-link/src/__tests__/clipboardSync.test.ts b/packages/device-link/src/__tests__/clipboardSync.test.ts
new file mode 100644
index 0000000000..1a30eaadfb
--- /dev/null
+++ b/packages/device-link/src/__tests__/clipboardSync.test.ts
@@ -0,0 +1,124 @@
+import { expect, it, vi } from "vitest";
+import { ClipboardSync, type ClipboardSyncDeps } from "../clipboardSync";
+
+function fixture() {
+ const local = { version: 1, json: '{"text":"local"}', error: "" };
+ const remote = { version: 1, json: '{"text":"remote"}', error: "" };
+ const trace = vi.fn();
+ const write = vi.fn(async (json: string, version: string) => {
+ expect(version).toBe(String(local.version));
+ Object.assign(local, { json, error: "" });
+ return String(++local.version);
+ });
+ const request = vi.fn(
+ async (message: Parameters<ClipboardSyncDeps["request"]>[0]) => {
+ if (message.op === "clipboardVersion")
+ return { version: String(remote.version) };
+ if (message.op !== "clipboardContent")
+ throw new Error("UNEXPECTED_REQUEST");
+ if (message.action === "copy") {
+ if (remote.error) throw new Error(remote.error);
+ return { data: remote.json, length: remote.json.length };
+ }
+ if (message.action === "paste") {
+ expect(message.version).toBe(String(remote.version));
+ Object.assign(remote, { json: message.data, error: "" });
+ return { version: String(++remote.version) };
+ }
+ throw new Error("UNEXPECTED_REQUEST");
+ },
+ );
+ const read = vi.fn(async () => {
+ if (local.error) throw new Error(local.error);
+ return local.json;
+ });
+ const engine = new ClipboardSync({
+ lease: "lease",
+ inline: true,
+ current: () => true,
+ digest: (json) => json,
+ trace,
+ localVersion: async () => String(local.version),
+ readLocal: read,
+ writeLocal: write,
+ request: request as ClipboardSyncDeps["request"],
+ });
+ return { engine, local, remote, trace, write, read, request };
+}
+
+it.each(["CLIPBOARD_EMPTY", "CLIPBOARD_UNSUPPORTED", "CLIPBOARD_TOO_LONG"])(
+ "silently establishes both initial %s baselines, then syncs a new copy",
+ async (code) => {
+ const h = fixture();
+ h.local.error = h.remote.error = code;
+ await h.engine.tick();
+ await h.engine.tick();
+ expect(
+ h.trace.mock.calls.some(([stage]) => stage === "content-skipped"),
+ ).toBe(false);
+ expect(h.read).toHaveBeenCalledTimes(1);
+ expect(h.write).not.toHaveBeenCalled();
+ h.local.version++;
+ h.local.error = "";
+ await h.engine.tick();
+ expect(h.remote.json).toBe(h.local.json);
+ expect(h.trace).toHaveBeenLastCalledWith("phone-to-computer-complete");
+ },
+);
+
+it.each(["local", "remote"] as const)(
+ "an empty %s snapshot neither clears the other clipboard nor blocks its next copy",
+ async (side) => {
+ const h = fixture();
+ await h.engine.tick();
+ h[side].version++;
+ h[side].error = "CLIPBOARD_EMPTY";
+ await h.engine.tick();
+ expect(h.trace).toHaveBeenLastCalledWith("unchanged-content");
+ expect(h.write).not.toHaveBeenCalled();
+ expect(
+ h.request.mock.calls.some(
+ ([m]) => m.op === "clipboardContent" && m.action === "paste",
+ ),
+ ).toBe(false);
+ // Another empty version alongside a real copy is still not a conflict.
+ h[side].version++;
+ const other = side === "local" ? "remote" : "local";
+ h[other].version++;
+ h[other].json = '{"text":"new copy"}';
+ await h.engine.tick();
+ expect(h.local.json).toBe(h.remote.json);
+ expect(h[side].error).toBe("");
+ },
+);
+
+it.each(["CLIPBOARD_UNSUPPORTED", "CLIPBOARD_TOO_LONG"])(
+ "reports the specific %s code once per changed snapshot",
+ async (code) => {
+ const h = fixture();
+ await h.engine.tick();
+ h.local.version++;
+ h.local.error = code;
+ await h.engine.tick();
+ expect(h.trace).toHaveBeenLastCalledWith("content-skipped", code);
+ h.trace.mockClear();
+ await h.engine.tick();
+ expect(h.trace).not.toHaveBeenCalled();
+ },
+);
+
+it("does not accept an empty remote read whose version changed during the read", async () => {
+ const h = fixture();
+ await h.engine.tick();
+ h.remote.version++;
+ const request = h.request.getMockImplementation()!;
+ h.request.mockImplementation(async (message) => {
+ if (message.op === "clipboardContent" && message.action === "copy") {
+ h.remote.version++;
+ throw new Error("CLIPBOARD_EMPTY");
+ }
+ return request(message);
+ });
+ await expect(h.engine.tick()).rejects.toThrow("CLIPBOARD_CHANGED");
+ expect(h.write).not.toHaveBeenCalled();
+});
diff --git a/packages/device-link/src/clipboardSync.ts b/packages/device-link/src/clipboardSync.ts
index cc2e2692df..1e219f5b0d 100644
--- a/packages/device-link/src/clipboardSync.ts
+++ b/packages/device-link/src/clipboardSync.ts
@@ -28,7 +28,8 @@ export interface ClipboardSyncDeps {
current(): boolean;
inline?: boolean;
localReadCache?: LocalClipboardReadCache;
- trace?(stage: string): void;
+ /** Diagnostic codes only, never clipboard contents. */
+ trace?(stage: string, code?: string): void;
}
export interface ClipboardSyncBaseline {
local: string;
@@ -242,7 +243,7 @@ export class ClipboardSync {
digest = (await this.readLocal(local)).digest;
} catch (error) {
if (!skippableContent(error)) throw error;
- this.deps.trace?.("content-skipped");
+ // Connecting only establishes a baseline; no transfer was skipped.
if ((await this.deps.localVersion()) !== local)
throw new Error("CLIPBOARD_CHANGED");
}
@@ -254,7 +255,7 @@ export class ClipboardSync {
remoteDigest = (await this.readRemote(remote)).digest;
} catch (error) {
if (!skippableContent(error)) throw error;
- this.deps.trace?.("content-skipped");
+ // Existing unsupported/empty content is normal when connecting.
if ((await this.remoteVersion()) !== remote)
throw new Error("CLIPBOARD_CHANGED");
}
@@ -273,28 +274,52 @@ export class ClipboardSync {
let localChanged = local !== this.baseline.local;
let remoteChanged = remote !== this.baseline.remote;
if (!localChanged && !remoteChanged) return;
+ const empty = (error: unknown): undefined => {
+ if (clipboardSyncErrorCode(error) !== "CLIPBOARD_EMPTY") throw error;
+ return undefined;
+ };
const localContent = localChanged
- ? await this.readLocal(local).then((content) => {
- readLocalDigest = content.digest;
- return content;
- })
+ ? await this.readLocal(local)
+ .catch(empty)
+ .then((content) => {
+ if (!content) return undefined;
+ readLocalDigest = content.digest;
+ return content;
+ })
: undefined;
const remoteContent = remoteChanged
- ? await this.readRemote(remote).then((content) => {
- readRemoteDigest = content.digest;
- return content;
- })
+ ? await this.readRemote(remote)
+ .catch(empty)
+ .then((content) => {
+ if (!content) return undefined;
+ readRemoteDigest = content.digest;
+ return content;
+ })
: undefined;
this.check();
if ((await this.deps.localVersion()) !== local)
throw new Error("CLIPBOARD_CHANGED");
+ if (
+ remoteChanged &&
+ !remoteContent &&
+ (await this.remoteVersion()) !== remote
+ )
+ throw new Error("CLIPBOARD_CHANGED");
this.check();
+ // Empty is not a copy to propagate or a competing edit. A real copy on
+ // the other side may still sync; never erase it with an empty clipboard.
+ const localDigest = localChanged
+ ? localContent?.digest
+ : this.baseline.localDigest;
+ const remoteDigest = remoteChanged
+ ? remoteContent?.digest
+ : this.baseline.remoteDigest;
+ if (localChanged && !localContent) localChanged = false;
+ if (remoteChanged && !remoteContent) remoteChanged = false;
if (localContent && localContent.digest === this.baseline.localDigest)
localChanged = false;
if (remoteContent && remoteContent.digest === this.baseline.remoteDigest)
remoteChanged = false;
- const localDigest = localContent?.digest ?? this.baseline.localDigest;
- const remoteDigest = remoteContent?.digest ?? this.baseline.remoteDigest;
if (localDigest && localDigest === remoteDigest) {
localChanged = false;
remoteChanged = false;
@@ -369,11 +394,16 @@ export class ClipboardSync {
? this.baseline.remoteDigest
: readRemoteDigest,
});
- this.deps.trace?.("content-skipped");
+ const code = clipboardSyncErrorCode(error);
+ this.deps.trace?.(
+ code === "CLIPBOARD_EMPTY" ? "content-empty" : "content-skipped",
+ code,
+ );
// Both peers changed and one of them is unreadable: as with any
// simultaneous change, both copies are kept, but the user is told so
// instead of the readable copy silently never arriving.
- if (bothChanged) throw new Error("CLIPBOARD_CONFLICT");
+ if (bothChanged && code !== "CLIPBOARD_EMPTY")
+ throw new Error("CLIPBOARD_CONFLICT");
return;
}
throw error;