Skip to content

Commit e99f6dc

Browse files
authored
fix(ui): surface onboarding and pairing clipboard failures (#118651)
* fix(ui): surface onboarding and pairing clipboard failures * fix(ui): keep translated clipboard labels after feedback resets
1 parent e1b1d4b commit e99f6dc

10 files changed

Lines changed: 276 additions & 78 deletions

File tree

‎ui/src/app/app-host-pairing-access.test.ts‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ type PairingSidebar = HTMLElement & {
1919

2020
type PairingAuth = { role: string; scopes?: string[] };
2121

22-
function createPairingShell(params: { auth: PairingAuth | null; connected?: boolean }) {
22+
function createPairingShell(params: {
23+
auth: PairingAuth | null;
24+
connected?: boolean;
25+
setupCode?: string;
26+
}) {
2327
const snapshot: ApplicationGatewaySnapshot = {
2428
client: { request: vi.fn(async () => ({})) } as unknown as GatewayBrowserClient,
2529
phase: params.connected === false ? "stopped" : "connected",
@@ -47,10 +51,17 @@ function createPairingShell(params: { auth: PairingAuth | null; connected?: bool
4751
approvalErrors: new Map(),
4852
approvalNowMs: 0,
4953
approvalBusy: false,
50-
devicePairSetupOpen: false,
54+
devicePairSetupOpen: Boolean(params.setupCode),
5155
devicePairSetupLoading: false,
5256
devicePairSetupError: null,
53-
devicePairSetup: null,
57+
devicePairSetup: params.setupCode
58+
? {
59+
setupCode: params.setupCode,
60+
gatewayUrl: "wss://gateway.example.test",
61+
auth: "token",
62+
urlSource: "test",
63+
}
64+
: null,
5465
devicePairSetupAccess: "full",
5566
devicePairPendingCount: 0,
5667
updateAvailable: null,
@@ -82,12 +93,14 @@ function createPairingShell(params: { auth: PairingAuth | null; connected?: bool
8293
return sidebar;
8394
};
8495

85-
return { snapshot, openDevicePairSetup, renderSidebar };
96+
return { snapshot, openDevicePairSetup, renderSidebar, container };
8697
}
8798

8899
afterEach(() => {
89100
document.body.replaceChildren();
101+
vi.unstubAllGlobals();
90102
vi.restoreAllMocks();
103+
Reflect.deleteProperty(document, "execCommand");
91104
});
92105

93106
describe("application shell pairing access", () => {
@@ -137,4 +150,40 @@ describe("application shell pairing access", () => {
137150

138151
expect(renderSidebar().canPairDevice).toBe(false);
139152
});
153+
154+
it("shows a visible accessible error when a mobile setup code cannot be copied", async () => {
155+
const writeText = vi.fn().mockRejectedValue(new DOMException("Clipboard access denied"));
156+
const execCommand = vi.fn(() => false);
157+
vi.stubGlobal("navigator", { clipboard: { writeText } });
158+
Object.defineProperty(document, "execCommand", { configurable: true, value: execCommand });
159+
const schedule = vi.spyOn(window, "setTimeout");
160+
const { container, renderSidebar } = createPairingShell({
161+
auth: { role: "operator", scopes: ["operator.pairing"] },
162+
setupCode: "pair-mobile-secret",
163+
});
164+
renderSidebar();
165+
const pairing = container.querySelector<HTMLElement>(".device-pair-setup");
166+
if (!pairing) {
167+
throw new Error("Expected the application shell to render its mobile pairing dialog");
168+
}
169+
document.body.append(pairing);
170+
const button = pairing.querySelector<HTMLButtonElement>(".device-pair-setup__actions button");
171+
172+
button?.click();
173+
174+
await vi.waitFor(() => expect(button?.textContent?.trim()).toBe("Copy failed"));
175+
expect(button?.getAttribute("aria-label")).toBe("Copy failed");
176+
expect(button?.querySelector("svg")).not.toBeNull();
177+
expect(writeText).toHaveBeenCalledWith("pair-mobile-secret");
178+
expect(execCommand).toHaveBeenCalledWith("copy");
179+
180+
const reset = schedule.mock.calls.find(([, delay]) => delay === 2_000)?.[0];
181+
if (typeof reset !== "function") {
182+
throw new Error("Expected the failed copy feedback to schedule its reset");
183+
}
184+
reset();
185+
186+
expect(button?.textContent?.trim()).toBe("Copy setup code");
187+
expect(button?.getAttribute("aria-label")).toBe("Copy setup code");
188+
});
140189
});

‎ui/src/app/app-shell-view.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import { icons } from "../components/icons.ts";
1010
import { renderSettingsSidebar } from "../components/settings-sidebar.ts";
1111
import type { ThemeModeChangeDetail } from "../components/theme-mode-toggle.ts";
1212
import { t } from "../i18n/index.ts";
13-
import { copyToClipboard } from "../lib/clipboard.ts";
1413
import { isGatewayMethodAdvertised } from "../lib/gateway-methods.ts";
1514
import { readSessionMethodAccess } from "../lib/session-method-access.ts";
1615
import { normalizeAgentId } from "../lib/sessions/session-key.ts";
@@ -489,7 +488,6 @@ export function renderApplicationShell(host: ShellViewHost) {
489488
onRefresh: () => void context.overlays.refreshDevicePairSetup(),
490489
onAccessChange: (access) => void context.overlays.setDevicePairSetupAccess(access),
491490
onClose: () => context.overlays.closeDevicePairSetup(),
492-
onCopy: (setupCode) => void copyToClipboard(setupCode),
493491
onManageDevices: () => {
494492
context.overlays.closeDevicePairSetup();
495493
host.navigate("nodes");

‎ui/src/components/connect-command.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
// Control UI component renders a copyable gateway connection command.
22
import { html } from "lit";
33
import { t } from "../i18n/index.ts";
4-
import { copyToClipboard } from "../lib/clipboard.ts";
54
import { renderCopyButton } from "./copy-button.ts";
65
import "./tooltip.ts";
76

8-
async function copyCommand(command: string) {
9-
await copyToClipboard(command);
7+
function copyCommand(event: Event) {
8+
(event.currentTarget as HTMLElement).querySelector<HTMLButtonElement>(".chat-copy-btn")?.click();
109
}
1110

1211
export function renderConnectCommand(command: string) {
@@ -18,18 +17,18 @@ export function renderConnectCommand(command: string) {
1817
role="button"
1918
tabindex="0"
2019
aria-label=${t("connection.help.copyCommandAria", { command })}
21-
@click=${async (event: Event) => {
20+
@click=${(event: Event) => {
2221
if ((event.target as HTMLElement | null)?.closest(".chat-copy-btn")) {
2322
return;
2423
}
25-
await copyCommand(command);
24+
copyCommand(event);
2625
}}
27-
@keydown=${async (event: KeyboardEvent) => {
26+
@keydown=${(event: KeyboardEvent) => {
2827
if (event.key !== "Enter" && event.key !== " ") {
2928
return;
3029
}
3130
event.preventDefault();
32-
await copyCommand(command);
31+
copyCommand(event);
3332
}}
3433
>
3534
<code>${command}</code>

‎ui/src/components/copy-button.ts‎

Lines changed: 49 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,54 @@ type CopyButtonOptions = {
2121

2222
function setButtonLabel(button: HTMLButtonElement, label: string) {
2323
button.setAttribute("aria-label", label);
24+
// Preserve Lit's marker nodes so a later locale change can rerender this label.
25+
const visibleLabel = button.querySelector("[data-copy-label]")?.lastChild;
26+
if (visibleLabel?.nodeType === Node.TEXT_NODE) {
27+
visibleLabel.nodeValue = label;
28+
}
29+
}
30+
31+
export async function handleCopyButton(event: Event, text: string, idleLabel: string) {
32+
const button = event.currentTarget as HTMLButtonElement | null;
33+
if (!button || button.dataset.copying === "1") {
34+
return;
35+
}
36+
37+
// Older reset timers must not replace feedback from a newer copy attempt.
38+
const attempt = String(Number(button.dataset.copyAttempt ?? "0") + 1);
39+
button.dataset.copyAttempt = attempt;
40+
button.dataset.copying = "1";
41+
button.setAttribute("aria-busy", "true");
42+
button.disabled = true;
43+
44+
const copied = await copyToClipboard(text);
45+
delete button.dataset.copying;
46+
button.removeAttribute("aria-busy");
47+
button.disabled = false;
48+
if (!button.isConnected || button.dataset.copyAttempt !== attempt) {
49+
return;
50+
}
51+
52+
const feedback = copied ? "copied" : "error";
53+
delete button.dataset[copied ? "error" : "copied"];
54+
button.dataset[feedback] = "1";
55+
const feedbackLabel = t(copied ? "common.copied" : "common.copyFailed");
56+
setButtonLabel(button, feedbackLabel);
57+
58+
const duration = copied ? COPIED_FOR_MS : ERROR_FOR_MS;
59+
window.setTimeout(() => {
60+
if (!button.isConnected || button.dataset.copyAttempt !== attempt) {
61+
return;
62+
}
63+
delete button.dataset[feedback];
64+
// A locale rerender can replace the idle label while feedback is still active.
65+
const renderedLabel =
66+
button.querySelector("[data-copy-label]")?.textContent ?? button.getAttribute("aria-label");
67+
setButtonLabel(
68+
button,
69+
renderedLabel && renderedLabel !== feedbackLabel ? renderedLabel : idleLabel,
70+
);
71+
}, duration);
2472
}
2573

2674
function createCopyButton(options: CopyButtonOptions): TemplateResult {
@@ -31,51 +79,7 @@ function createCopyButton(options: CopyButtonOptions): TemplateResult {
3179
class=${options.bare ? "chat-copy-btn" : "btn btn--xs chat-copy-btn"}
3280
type="button"
3381
aria-label=${idleLabel}
34-
@click=${async (e: Event) => {
35-
const btn = e.currentTarget as HTMLButtonElement | null;
36-
37-
if (!btn || btn.dataset.copying === "1") {
38-
return;
39-
}
40-
41-
btn.dataset.copying = "1";
42-
btn.setAttribute("aria-busy", "true");
43-
btn.disabled = true;
44-
45-
const copied = await copyToClipboard(options.text());
46-
if (!btn.isConnected) {
47-
return;
48-
}
49-
50-
delete btn.dataset.copying;
51-
btn.removeAttribute("aria-busy");
52-
btn.disabled = false;
53-
54-
if (!copied) {
55-
btn.dataset.error = "1";
56-
setButtonLabel(btn, t("common.copyFailed"));
57-
58-
window.setTimeout(() => {
59-
if (!btn.isConnected) {
60-
return;
61-
}
62-
delete btn.dataset.error;
63-
setButtonLabel(btn, idleLabel);
64-
}, ERROR_FOR_MS);
65-
return;
66-
}
67-
68-
btn.dataset.copied = "1";
69-
setButtonLabel(btn, t("common.copied"));
70-
71-
window.setTimeout(() => {
72-
if (!btn.isConnected) {
73-
return;
74-
}
75-
delete btn.dataset.copied;
76-
setButtonLabel(btn, idleLabel);
77-
}, COPIED_FOR_MS);
78-
}}
82+
@click=${(event: Event) => void handleCopyButton(event, options.text(), idleLabel)}
7983
>
8084
<span class="chat-copy-btn__icon" aria-hidden="true">
8185
<span class="chat-copy-btn__icon-copy">${icons.copy}</span>

‎ui/src/components/login-gate.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ afterEach(() => {
3939
document.body.replaceChildren();
4040
vi.unstubAllGlobals();
4141
vi.restoreAllMocks();
42+
Reflect.deleteProperty(document, "execCommand");
4243
});
4344

4445
describe("login gate failure recovery", () => {
@@ -99,4 +100,73 @@ describe("login gate failure recovery", () => {
99100
"Reconnect after the approval completes.",
100101
]);
101102
});
103+
104+
it.each(["click", "Enter", " ", "nested button"])(
105+
"surfaces denied gateway-command copying from the %s interaction",
106+
async (interaction) => {
107+
const writeText = vi.fn().mockRejectedValue(new DOMException("Clipboard access denied"));
108+
const execCommand = vi.fn(() => false);
109+
vi.stubGlobal("navigator", { clipboard: { writeText } });
110+
Object.defineProperty(document, "execCommand", { configurable: true, value: execCommand });
111+
const element = await mountFailure("WebSocket connection failed", null);
112+
const command = element.querySelector<HTMLElement>(".login-gate__command");
113+
const button = command?.querySelector<HTMLButtonElement>(".chat-copy-btn");
114+
115+
if (interaction === "nested button") {
116+
button?.click();
117+
} else if (interaction === "click") {
118+
command?.click();
119+
} else {
120+
command?.dispatchEvent(
121+
new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: interaction }),
122+
);
123+
}
124+
125+
await vi.waitFor(() => expect(button?.getAttribute("aria-label")).toBe("Copy failed"));
126+
expect(button?.dataset.error).toBe("1");
127+
expect(writeText).toHaveBeenCalledOnce();
128+
expect(execCommand).toHaveBeenCalledOnce();
129+
},
130+
);
131+
132+
it("keeps the latest command-copy feedback until its own reset", async () => {
133+
const writeText = vi
134+
.fn()
135+
.mockRejectedValueOnce(new DOMException("Clipboard access denied"))
136+
.mockResolvedValueOnce(undefined);
137+
const execCommand = vi.fn(() => false);
138+
vi.stubGlobal("navigator", { clipboard: { writeText } });
139+
Object.defineProperty(document, "execCommand", { configurable: true, value: execCommand });
140+
const schedule = vi.spyOn(window, "setTimeout");
141+
const element = await mountFailure("WebSocket connection failed", null);
142+
const command = element.querySelector<HTMLElement>(".login-gate__command");
143+
const button = command?.querySelector<HTMLButtonElement>(".chat-copy-btn");
144+
145+
command?.click();
146+
await vi.waitFor(() => expect(button?.getAttribute("aria-label")).toBe("Copy failed"));
147+
const failedReset = schedule.mock.calls.find(([, delay]) => delay === 2_000)?.[0];
148+
if (typeof failedReset !== "function") {
149+
throw new Error("Expected the failed copy feedback to schedule its reset");
150+
}
151+
152+
command?.click();
153+
await vi.waitFor(() => expect(button?.getAttribute("aria-label")).toBe("Copied!"));
154+
expect(button?.dataset.error).toBeUndefined();
155+
expect(button?.dataset.copied).toBe("1");
156+
157+
failedReset();
158+
expect(button?.getAttribute("aria-label")).toBe("Copied!");
159+
expect(button?.dataset.copied).toBe("1");
160+
161+
const successfulReset = schedule.mock.calls.find(([, delay]) => delay === 1_500)?.[0];
162+
if (typeof successfulReset !== "function") {
163+
throw new Error("Expected the successful copy feedback to schedule its reset");
164+
}
165+
successfulReset();
166+
167+
expect(button?.getAttribute("aria-label")).toBe("Copy command");
168+
expect(button?.dataset.copied).toBeUndefined();
169+
expect(writeText).toHaveBeenCalledTimes(2);
170+
expect(execCommand).toHaveBeenCalledOnce();
171+
});
102172
});

‎ui/src/components/wizard-step-controls.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { html, nothing, type TemplateResult } from "lit";
22
import type { WizardStep } from "../api/types.ts";
33
import { t } from "../i18n/index.ts";
4-
import { copyToClipboard } from "../lib/clipboard.ts";
4+
import { handleCopyButton } from "./copy-button.ts";
55
import { renderSensitiveInput } from "./sensitive-input.ts";
66
import "../styles/wizard-step-controls.css";
77

@@ -59,16 +59,17 @@ function renderDeviceCode(step: WizardStep) {
5959
if (!deviceCode) {
6060
return nothing;
6161
}
62+
const copyLabel = t("modelSetup.wizard.copy");
6263
return html`
6364
<div class="wizard-step__device-code">
6465
${deviceCode.message ? html`<div class="muted">${deviceCode.message}</div>` : nothing}
6566
<code>${deviceCode.code}</code>
6667
<button
6768
type="button"
6869
class="btn btn--sm"
69-
@click=${() => void copyToClipboard(deviceCode.code)}
70+
@click=${(event: Event) => void handleCopyButton(event, deviceCode.code, copyLabel)}
7071
>
71-
${t("modelSetup.wizard.copy")}
72+
<span data-copy-label>${copyLabel}</span>
7273
</button>
7374
${deviceCode.expiresInMinutes
7475
? html`<div class="muted">

0 commit comments

Comments
 (0)