Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 4 additions & 17 deletions packages/web-ui/src/platform/browserCapabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
requestBrowserServerPath,
} from './browserDialogs';
import {listenForColorSchemeChanges, prefersDarkColorScheme} from './systemColorScheme';
import {readWebClipboardText, writeWebClipboardHtml, writeWebClipboardText} from './webClipboard';

function browserCapabilityNegotiation(serverFileBrowser: boolean): PlatformCapabilityNegotiation {
return createPlatformCapabilityNegotiation('browser', {
Expand Down Expand Up @@ -208,37 +209,23 @@ export class BrowserPlatformCapabilities implements PlatformCapabilities {

async readClipboard(): Promise<string> {
try {
if (!navigator.clipboard?.readText) {
throw new DOMException('Clipboard access is unavailable', 'NotAllowedError');
}
return await navigator.clipboard.readText();
return await readWebClipboardText();
} catch (error) {
throw new PlatformCapabilityPermissionError('readClipboard', 'browser', error);
}
}

async writeClipboard(text: string): Promise<void> {
try {
if (!navigator.clipboard?.writeText) {
throw new DOMException('Clipboard access is unavailable', 'NotAllowedError');
}
await navigator.clipboard.writeText(text);
await writeWebClipboardText(text);
} catch (error) {
throw new PlatformCapabilityPermissionError('writeClipboard', 'browser', error);
}
}

async writeClipboardHtml(html: string, altText: string): Promise<void> {
if (typeof ClipboardItem === 'undefined' || !navigator.clipboard?.write) {
return this.writeClipboard(altText);
}
try {
await navigator.clipboard.write([
new ClipboardItem({
'text/html': new Blob([html], {type: 'text/html'}),
'text/plain': new Blob([altText], {type: 'text/plain'}),
}),
]);
await writeWebClipboardHtml(html, altText);
} catch (error) {
throw new PlatformCapabilityPermissionError('writeClipboard', 'browser', error);
}
Expand Down
52 changes: 49 additions & 3 deletions packages/web-ui/src/platform/tauriCapabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
} from '@/utils/blob';
import {isLinuxDesktop} from '@/utils/systemTheme';
import {listenForColorSchemeChanges, prefersDarkColorScheme} from './systemColorScheme';
import {readWebClipboardText, writeWebClipboardHtml, writeWebClipboardText} from './webClipboard';

export interface TauriPlatformOperations {
chooseInputPath(options?: ChooseInputFileOptions): Promise<string | string[] | null>;
Expand Down Expand Up @@ -321,6 +322,7 @@ const selectedFileName = (reference: string): string => {
export class TauriPlatformCapabilities implements PlatformCapabilities {
readonly negotiation: PlatformCapabilityNegotiation;
private readonly operations: TauriPlatformOperations;
private pluginClipboardBroken = false;

constructor(
operations: TauriPlatformOperations = defaultTauriOperations,
Expand Down Expand Up @@ -438,17 +440,30 @@ export class TauriPlatformCapabilities implements PlatformCapabilities {

async readClipboard(): Promise<string> {
this.require('readClipboard');
return this.operations.readClipboardText();
// The plugin also rejects on an empty or non-text clipboard, where the webview reads ''.
return this.withWebClipboardFallback(
() => this.operations.readClipboardText(),
readWebClipboardText,
(text) => text !== '',
);
}

async writeClipboard(text: string): Promise<void> {
this.require('writeClipboard');
await this.operations.writeClipboardText(text);
await this.withWebClipboardFallback(
() => this.operations.writeClipboardText(text),
() => writeWebClipboardText(text),
() => true,
);
}

async writeClipboardHtml(html: string, altText: string): Promise<void> {
this.require('writeClipboard');
await this.operations.writeClipboardHtml(html, altText);
await this.withWebClipboardFallback(
() => this.operations.writeClipboardHtml(html, altText),
() => writeWebClipboardHtml(html, altText),
() => true,
);
}

async downloadFile(request: DownloadFileRequest): Promise<boolean> {
Expand Down Expand Up @@ -544,4 +559,35 @@ export class TauriPlatformCapabilities implements PlatformCapabilities {
private require(capability: keyof PlatformCapabilityNegotiation['capabilities']): void {
requirePlatformCapability(this.negotiation, capability);
}

/**
* The clipboard plugin (arboard) reaches Wayland only through the wlr/ext data-control
* protocols, which compositors such as Niri withhold from sandboxed (Flatpak) clients; arboard
* then falls back to X11 and fails after a timeout. The webview clipboard uses the window's own
* Wayland data device. The plugin stays the first choice because reading through the webview
* can make WebKitGTK ask for confirmation.
*
* Once the webview succeeds where the plugin failed and `provesPluginBroken` accepts the
* result, every later call skips the plugin for the lifetime of this window. When both fail,
* the webview error is thrown.
*/
private async withWebClipboardFallback<T>(
viaPlugin: () => Promise<T>,
viaWebview: () => Promise<T>,
provesPluginBroken: (result: T) => boolean,
): Promise<T> {
if (this.pluginClipboardBroken) return viaWebview();
let pluginError: unknown;
try {
return await viaPlugin();
} catch (error) {
pluginError = error;
}
const result = await viaWebview();
if (provesPluginBroken(result)) {
this.pluginClipboardBroken = true;
console.warn('Clipboard plugin failed, using the webview clipboard:', pluginError);
}
return result;
}
}
26 changes: 26 additions & 0 deletions packages/web-ui/src/platform/webClipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/** The webview's own clipboard (`navigator.clipboard`). Every function rejects with the raw error. */

const unavailable = () => new DOMException('Clipboard access is unavailable', 'NotAllowedError');

export async function readWebClipboardText(): Promise<string> {
if (!navigator.clipboard?.readText) throw unavailable();
return navigator.clipboard.readText();
}

export async function writeWebClipboardText(text: string): Promise<void> {
if (!navigator.clipboard?.writeText) throw unavailable();
await navigator.clipboard.writeText(text);
}

/** Writes HTML with a plain-text flavor, or only `altText` when `ClipboardItem` is unavailable. */
export async function writeWebClipboardHtml(html: string, altText: string): Promise<void> {
if (typeof ClipboardItem === 'undefined' || !navigator.clipboard?.write) {
return writeWebClipboardText(altText);
}
await navigator.clipboard.write([
new ClipboardItem({
'text/html': new Blob([html], {type: 'text/html'}),
'text/plain': new Blob([altText], {type: 'text/plain'}),
}),
]);
}
146 changes: 145 additions & 1 deletion packages/web-ui/tests/platform/tauriCapabilities.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {invoke} from '@tauri-apps/api/core';
import {describe, expect, it, vi} from 'vitest';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {createPlatformCapabilityNegotiation} from '@/platform/capabilities';
import {
TauriPlatformCapabilities,
Expand All @@ -14,6 +14,7 @@ const createOperations = (): TauriPlatformOperations => ({
showMessageDialog: vi.fn(),
readClipboardText: vi.fn(),
writeClipboardText: vi.fn(),
writeClipboardHtml: vi.fn(),
writeFileContents: vi.fn(),
readFileContents: vi.fn(),
openUrl: vi.fn(),
Expand Down Expand Up @@ -259,3 +260,146 @@ describe('TauriPlatformCapabilities host window integration', () => {
expect(capabilities.supports('openStorageLocation')).toBe(true);
});
});

describe('TauriPlatformCapabilities clipboard fallback', () => {
const pluginFailure = new Error('X11 server connection timed out');

const stubWebClipboard = (withClipboardItem = true) => {
const clipboard = {
readText: vi.fn().mockResolvedValue('from webview'),
writeText: vi.fn().mockResolvedValue(undefined),
write: vi.fn().mockResolvedValue(undefined),
};
vi.stubGlobal('navigator', {...navigator, clipboard});
vi.stubGlobal(
'ClipboardItem',
withClipboardItem
? class {
constructor(readonly items: Record<string, Blob>) {}
}
: undefined,
);
return clipboard;
};

const failingOperations = () => {
const operations = createOperations();
vi.mocked(operations.readClipboardText).mockRejectedValue(pluginFailure);
vi.mocked(operations.writeClipboardText).mockRejectedValue(pluginFailure);
vi.mocked(operations.writeClipboardHtml).mockRejectedValue(pluginFailure);
return operations;
};

afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});

it('leaves the webview clipboard untouched while the plugin works', async () => {
const clipboard = stubWebClipboard();
const operations = createOperations();
vi.mocked(operations.readClipboardText).mockResolvedValue('from plugin');
const capabilities = new TauriPlatformCapabilities(operations);

await expect(capabilities.readClipboard()).resolves.toBe('from plugin');
await capabilities.writeClipboard('SELECT 1');
await capabilities.writeClipboardHtml('<b>1</b>', '1');

expect(operations.writeClipboardText).toHaveBeenCalledWith('SELECT 1');
expect(operations.writeClipboardHtml).toHaveBeenCalledWith('<b>1</b>', '1');
expect(clipboard.readText).not.toHaveBeenCalled();
expect(clipboard.writeText).not.toHaveBeenCalled();
expect(clipboard.write).not.toHaveBeenCalled();
});

it('reads and writes text through the webview when the plugin fails', async () => {
const clipboard = stubWebClipboard();
vi.spyOn(console, 'warn').mockImplementation(() => {});
const capabilities = new TauriPlatformCapabilities(failingOperations());

await expect(capabilities.readClipboard()).resolves.toBe('from webview');
await capabilities.writeClipboard('SELECT 1');

expect(clipboard.writeText).toHaveBeenCalledWith('SELECT 1');
});

it('writes HTML and plain-text flavors through the webview when the plugin fails', async () => {
const clipboard = stubWebClipboard();
vi.spyOn(console, 'warn').mockImplementation(() => {});
const capabilities = new TauriPlatformCapabilities(failingOperations());

await capabilities.writeClipboardHtml('<b>1</b>', '1');

const [[item]] = clipboard.write.mock.calls[0] as [[{items: Record<string, Blob>}]];
await expect(item.items['text/html'].text()).resolves.toBe('<b>1</b>');
await expect(item.items['text/plain'].text()).resolves.toBe('1');
expect(clipboard.writeText).not.toHaveBeenCalled();
});

it('writes only the plain text when the webview has no ClipboardItem', async () => {
const clipboard = stubWebClipboard(false);
vi.spyOn(console, 'warn').mockImplementation(() => {});
const capabilities = new TauriPlatformCapabilities(failingOperations());

await capabilities.writeClipboardHtml('<b>1</b>', '1');

expect(clipboard.writeText).toHaveBeenCalledWith('1');
expect(clipboard.write).not.toHaveBeenCalled();
});

it('rejects with the webview error and keeps trying the plugin when both fail', async () => {
const clipboard = stubWebClipboard();
const webviewFailure = new DOMException('Denied', 'NotAllowedError');
clipboard.writeText.mockRejectedValue(webviewFailure);
const operations = failingOperations();
const capabilities = new TauriPlatformCapabilities(operations);

await expect(capabilities.writeClipboard('a')).rejects.toBe(webviewFailure);
await expect(capabilities.writeClipboard('b')).rejects.toBe(webviewFailure);

expect(operations.writeClipboardText).toHaveBeenCalledTimes(2);
});

it('skips the plugin for the session once a webview write succeeded', async () => {
const clipboard = stubWebClipboard();
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const operations = failingOperations();
const capabilities = new TauriPlatformCapabilities(operations);

await capabilities.writeClipboard('a');
await capabilities.writeClipboard('b');
await expect(capabilities.readClipboard()).resolves.toBe('from webview');

expect(operations.writeClipboardText).toHaveBeenCalledOnce();
expect(operations.readClipboardText).not.toHaveBeenCalled();
expect(clipboard.writeText).toHaveBeenNthCalledWith(2, 'b');
expect(warn).toHaveBeenCalledOnce();
expect(warn).toHaveBeenCalledWith(expect.any(String), pluginFailure);
});

it('keeps the plugin when a failed read meets an empty webview clipboard', async () => {
const clipboard = stubWebClipboard();
clipboard.readText.mockResolvedValue('');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const operations = failingOperations();
const capabilities = new TauriPlatformCapabilities(operations);

await expect(capabilities.readClipboard()).resolves.toBe('');
await capabilities.readClipboard();

expect(operations.readClipboardText).toHaveBeenCalledTimes(2);
expect(warn).not.toHaveBeenCalled();
});

it('skips the plugin once the webview read text the plugin could not', async () => {
stubWebClipboard();
vi.spyOn(console, 'warn').mockImplementation(() => {});
const operations = failingOperations();
const capabilities = new TauriPlatformCapabilities(operations);

await capabilities.readClipboard();
await capabilities.readClipboard();

expect(operations.readClipboardText).toHaveBeenCalledOnce();
});
});
41 changes: 41 additions & 0 deletions packages/web-ui/tests/platform/webClipboard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {afterEach, describe, expect, it, vi} from 'vitest';
import {
readWebClipboardText,
writeWebClipboardHtml,
writeWebClipboardText,
} from '@/platform/webClipboard';

describe('webClipboard', () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it('rejects with NotAllowedError when navigator.clipboard is missing', async () => {
vi.stubGlobal('navigator', {...navigator, clipboard: undefined});

await expect(readWebClipboardText()).rejects.toMatchObject({name: 'NotAllowedError'});
await expect(writeWebClipboardText('a')).rejects.toMatchObject({name: 'NotAllowedError'});
await expect(writeWebClipboardHtml('<b>a</b>', 'a')).rejects.toMatchObject({
name: 'NotAllowedError',
});
});

it('falls back to plain text when the clipboard cannot write items', async () => {
const clipboard = {writeText: vi.fn().mockResolvedValue(undefined)};
vi.stubGlobal('navigator', {...navigator, clipboard});

await writeWebClipboardHtml('<b>a</b>', 'a');

expect(clipboard.writeText).toHaveBeenCalledWith('a');
});

it('passes clipboard errors through unchanged', async () => {
const failure = new DOMException('Denied', 'NotAllowedError');
vi.stubGlobal('navigator', {
...navigator,
clipboard: {readText: vi.fn().mockRejectedValue(failure)},
});

await expect(readWebClipboardText()).rejects.toBe(failure);
});
});
Loading