Skip to content

Commit d58edc0

Browse files
committed
fix(session-ui): handle unavailable clipboard APIs in copy actions
1 parent 20ec936 commit d58edc0

4 files changed

Lines changed: 141 additions & 35 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { expect, story } from "../../storybook/playwright/story"
2+
3+
for (const legacy of ["missing", "throws", "false", "success"] as const) {
4+
for (const modern of ["missing", "rejected", "success"] as const) {
5+
story(`copies tool errors: execCommand ${legacy}, navigator ${modern}`, async ({ mount, page }) => {
6+
const errors: string[] = []
7+
page.on("pageerror", (error) => errors.push(error.message))
8+
const root = await mount("components-tool-error-card--all")
9+
const card = root.locator('[data-kind="tool-error-card"]').first()
10+
if ((await card.getAttribute("data-open")) !== "true") {
11+
await card.locator('[data-slot="collapsible-trigger"]').click()
12+
}
13+
const button = card.getByRole("button", { name: "Copy error" })
14+
await expect(button).toBeVisible()
15+
const text = await card.locator('[data-slot="card-description"]').textContent()
16+
await page.evaluate(
17+
({ legacy, modern }) => {
18+
document.body.dataset.copyCalls = "[]"
19+
document.body.dataset.writeCalls = "[]"
20+
Object.defineProperty(document, "execCommand", {
21+
configurable: true,
22+
value:
23+
legacy === "missing"
24+
? undefined
25+
: (command: string) => {
26+
document.body.dataset.copyCalls = JSON.stringify([
27+
command,
28+
document.querySelector<HTMLTextAreaElement>("textarea[readonly]")?.value,
29+
])
30+
if (legacy === "throws") throw new Error("Legacy copy denied")
31+
return legacy === "success"
32+
},
33+
})
34+
Object.defineProperty(navigator, "clipboard", {
35+
configurable: true,
36+
value:
37+
modern === "missing"
38+
? undefined
39+
: {
40+
writeText: async (text: string) => {
41+
document.body.dataset.writeCalls = JSON.stringify([text])
42+
if (modern === "rejected") throw new Error("Clipboard denied")
43+
},
44+
},
45+
})
46+
},
47+
{ legacy, modern },
48+
)
49+
50+
await button.click()
51+
const success = legacy === "success" || modern === "success"
52+
await expect(card.getByRole("button", { name: success ? "Copied" : "Copy error", exact: true })).toBeVisible()
53+
expect(await page.locator("body").getAttribute("data-copy-calls")).toBe(
54+
JSON.stringify(legacy === "missing" ? [] : ["copy", text]),
55+
)
56+
expect(await page.locator("body").getAttribute("data-write-calls")).toBe(
57+
JSON.stringify(legacy === "success" || modern === "missing" ? [] : [text]),
58+
)
59+
await expect(page.locator("textarea[readonly]")).toHaveCount(0)
60+
expect(errors).toEqual([])
61+
})
62+
}
63+
}

‎packages/session-ui/src/components/clipboard.test.ts‎

Lines changed: 67 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -61,33 +61,71 @@ test("copies via execCommand when navigator.clipboard is missing", async () => {
6161
expect(execCommandCalls).toEqual([{ command: "copy", selected: "hello insecure origin" }])
6262
})
6363

64-
test("code-block copy button works without navigator.clipboard", async () => {
65-
hideClipboard()
66-
expect(navigator.clipboard).toBeUndefined()
67-
stubExecCommand(true)
64+
for (const legacy of ["missing", "throws", "false", "success"] as const) {
65+
for (const modern of ["missing", "rejected", "success"] as const) {
66+
test(`clipboard: execCommand ${legacy}, navigator ${modern}`, async () => {
67+
hideClipboard()
68+
const writes: string[] = []
69+
if (modern !== "missing") {
70+
Object.defineProperty(navigator, "clipboard", {
71+
configurable: true,
72+
value: {
73+
writeText: async (text: string) => {
74+
writes.push(text)
75+
if (modern === "rejected") throw new Error("Clipboard denied")
76+
},
77+
},
78+
})
79+
}
80+
stubExecCommand(legacy === "success")
81+
if (legacy === "missing") {
82+
Object.defineProperty(document, "execCommand", { configurable: true, value: undefined })
83+
}
84+
if (legacy === "throws") {
85+
document.execCommand = () => {
86+
throw new Error("Legacy copy denied")
87+
}
88+
}
6889

69-
const root = document.createElement("div")
70-
const wrapper = document.createElement("div")
71-
wrapper.setAttribute("data-component", "markdown-code")
72-
const pre = document.createElement("pre")
73-
const code = document.createElement("code")
74-
code.textContent = "const x = 1"
75-
pre.appendChild(code)
76-
const host = document.createElement("div")
77-
host.setAttribute("data-slot", "markdown-copy-button")
78-
const inner = document.createElement("button")
79-
inner.type = "button"
80-
host.appendChild(inner)
81-
wrapper.appendChild(pre)
82-
wrapper.appendChild(host)
83-
root.appendChild(wrapper)
84-
document.body.appendChild(root)
85-
86-
const cleanup = setupCodeCopy(root, () => ({ copy: "Copy", copied: "Copied" }))
87-
inner.dispatchEvent(new MouseEvent("click", { bubbles: true }))
88-
await new Promise((resolve) => setTimeout(resolve, 10))
89-
cleanup()
90-
91-
expect(execCommandCalls).toEqual([{ command: "copy", selected: "const x = 1" }])
92-
expect(host.getAttribute("data-copied")).toBe("true")
93-
})
90+
try {
91+
expect(await writeClipboard("copy me")).toBe(legacy === "success" || modern === "success")
92+
expect(writes).toEqual(legacy === "success" || modern === "missing" ? [] : ["copy me"])
93+
} finally {
94+
expect(document.querySelectorAll("textarea").length).toBe(0)
95+
}
96+
})
97+
}
98+
}
99+
100+
for (const succeeds of [true, false]) {
101+
test(`code-block copy button without navigator.clipboard: ${succeeds}`, async () => {
102+
hideClipboard()
103+
expect(navigator.clipboard).toBeUndefined()
104+
stubExecCommand(succeeds)
105+
106+
const root = document.createElement("div")
107+
const wrapper = document.createElement("div")
108+
wrapper.setAttribute("data-component", "markdown-code")
109+
const pre = document.createElement("pre")
110+
const code = document.createElement("code")
111+
code.textContent = "const x = 1"
112+
pre.appendChild(code)
113+
const host = document.createElement("div")
114+
host.setAttribute("data-slot", "markdown-copy-button")
115+
const inner = document.createElement("button")
116+
inner.type = "button"
117+
host.appendChild(inner)
118+
wrapper.appendChild(pre)
119+
wrapper.appendChild(host)
120+
root.appendChild(wrapper)
121+
document.body.appendChild(root)
122+
123+
const cleanup = setupCodeCopy(root, () => ({ copy: "Copy", copied: "Copied" }))
124+
inner.dispatchEvent(new MouseEvent("click", { bubbles: true }))
125+
await new Promise((resolve) => setTimeout(resolve, 10))
126+
cleanup()
127+
128+
expect(execCommandCalls).toEqual([{ command: "copy", selected: "const x = 1" }])
129+
expect(host.getAttribute("data-copied")).toBe(succeeds ? "true" : null)
130+
})
131+
}

‎packages/session-ui/src/components/clipboard.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
export async function writeClipboard(text: string): Promise<boolean> {
22
const body = typeof document === "undefined" ? undefined : document.body
3-
if (body) {
3+
if (body && typeof document.execCommand === "function") {
44
const textarea = document.createElement("textarea")
55
textarea.value = text
66
textarea.setAttribute("readonly", "")
77
textarea.style.position = "fixed"
88
textarea.style.opacity = "0"
99
textarea.style.pointerEvents = "none"
1010
body.appendChild(textarea)
11-
textarea.select()
12-
const copied = document.execCommand("copy")
13-
body.removeChild(textarea)
14-
if (copied) return true
11+
try {
12+
textarea.select()
13+
if (document.execCommand("copy")) return true
14+
} catch {
15+
// Legacy copying can be unavailable even when execCommand exists.
16+
} finally {
17+
textarea.remove()
18+
}
1519
}
1620

1721
const clipboard = typeof navigator === "undefined" ? undefined : navigator.clipboard

‎packages/session-ui/src/components/tool-error-card.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { Icon } from "@opencode/ui/icon"
66
import { IconButton } from "@opencode/ui/icon-button"
77
import { Tooltip } from "@opencode/ui/tooltip"
88
import { useI18n } from "@opencode/ui/context/i18n"
9+
import { writeClipboard } from "./clipboard"
910

1011
export interface ToolErrorCardProps extends Omit<ComponentProps<typeof Card>, "children" | "variant"> {
1112
tool: string
@@ -113,7 +114,7 @@ export function ToolErrorCard(props: ToolErrorCardProps) {
113114
const text = cleaned()
114115

115116
if (!text) return
116-
await navigator.clipboard.writeText(text)
117+
if (!(await writeClipboard(text))) return
117118
setState("copied", true)
118119
setTimeout(() => setState("copied", false), 2000)
119120
}

0 commit comments

Comments
 (0)