From fcbcff2ee0baaf84fe6ade476273449649ad060a Mon Sep 17 00:00:00 2001 From: Johnny Huynh <27847622+johnnyhuy@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:34:06 +0700 Subject: [PATCH] fix: report tool-card clipboard failures and stale copy feedback Co-authored-by: OpenAI Codex --- README.md | 2 + src/renderer/components/WorkbenchControls.tsx | 49 +++++++-- src/renderer/workbench.css | 12 ++ tests/e2e/tool-preview.test.ts | 49 +++++++++ tests/integration/ToolCard.test.tsx | 103 +++++++++++++++++- 5 files changed, 206 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 82205b1..2e1fccf 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,8 @@ The new-session view shows the selected root's branch and changed-file counts be Expanded tool cards show output first. Open Input or close Output independently, and copy either section while it is closed. These choices stay with each card while scrolling through the transcript; reopening the transcript resets them. +Each section reports when copying is in progress, succeeds or fails. A failed copy keeps a retry message beside its Copy button, including when the section is closed. Copy again to retry. New streamed text clears the previous copy feedback so Copied always refers to the current text. + Long tool output previews the first 2,000 characters. Use **Show end** to inspect the last 2,000 characters, including final errors, without expanding the whole result. The end preview follows new output while Pi works. **Show beginning** returns to the start, **Show more** opens the full text, and Copy keeps the complete output in every mode. Session history shows source/fork relationships and an entry tree with selected and archive-tip markers. Select a branch tip or an earlier entry to preview its parent chain. Resume at the archive tip continues in place; **Resume in new fork** continues a historical selection in a separate archive and preserves the source. **Fork from here** uses the selected entry. Pi 1.5.0 RPC does not expose arbitrary-entry navigation, so forks extract a native branch archive before launching Pi so even runtime startup writes preserve the source. Continuation requires an intact Pi v3 archive within the 16 MiB browsing limit. See [ADR 0013](docs/adr/0013-session-branch-selection.md) for runtime semantics and limits. diff --git a/src/renderer/components/WorkbenchControls.tsx b/src/renderer/components/WorkbenchControls.tsx index 55eaad7..6e90ab5 100644 --- a/src/renderer/components/WorkbenchControls.tsx +++ b/src/renderer/components/WorkbenchControls.tsx @@ -1,5 +1,6 @@ import { memo, + useEffect, useId, useRef, useState, @@ -318,17 +319,37 @@ export function diffLines(oldText: string, newText: string): DiffLine[] { } function useCopy(text: string) { - const [copied, setCopied] = useState(false); + const [status, setStatus] = useState<'idle' | 'copying' | 'copied' | 'failed'>('idle'); + const attempt = useRef(0); + const pending = useRef(false); + const timer = useRef | undefined>(undefined); + useEffect(() => { + setStatus('idle'); + pending.current = false; + return () => { + // A streamed update or recycled row invalidates outstanding feedback. + attempt.current++; + clearTimeout(timer.current); + }; + }, [text]); const copy = async () => { + if (pending.current) return; + const current = ++attempt.current; + pending.current = true; + clearTimeout(timer.current); + setStatus('copying'); try { await navigator.clipboard.writeText(text); - setCopied(true); - window.setTimeout(() => setCopied(false), 1500); + if (current !== attempt.current) return; + setStatus('copied'); + timer.current = setTimeout(() => setStatus('idle'), 1500); } catch { - setCopied(false); + if (current === attempt.current) setStatus('failed'); + } finally { + if (current === attempt.current) pending.current = false; } }; - return { copied, copy }; + return { status, copy }; } function ToolSection({ @@ -348,7 +369,14 @@ function ToolSection({ const [open, setOpen] = useState( () => expanded.get(stateKey) ?? title === 'Output', ); - const { copied, copy } = useCopy(text); + const { status, copy } = useCopy(text); + const feedback = status === 'failed' + ? `Could not copy ${title.toLowerCase()}. Try Copy again.` + : status === 'copied' + ? `${title} copied.` + : status === 'copying' + ? `Copying ${title.toLowerCase()}…` + : ''; return (
@@ -371,11 +399,18 @@ function ToolSection({ type="button" className="wb-tool-copy" aria-label={`Copy ${title.toLowerCase()}`} + aria-describedby={feedback ? `${id}-copy` : undefined} + disabled={status === 'copying'} onClick={() => void copy()} > - {copied ? 'Copied' : 'Copy'} + {status === 'copied' ? 'Copied' : status === 'copying' ? 'Copying…' : 'Copy'}
+ {feedback && ( +

+ {feedback} +

+ )}
); diff --git a/src/renderer/workbench.css b/src/renderer/workbench.css index d73fd0a..6c13d52 100644 --- a/src/renderer/workbench.css +++ b/src/renderer/workbench.css @@ -805,6 +805,18 @@ html[data-reduced-motion='true'] .wb-shell *::after { .wb-tool-toggle { margin: 0 12px 12px; } +.wb-tool-copy:disabled { + opacity: 0.6; + cursor: default; +} +.wb-tool-copy-feedback { + margin: 0; + padding: 0 12px 8px; + color: var(--muted); +} +.wb-tool-copy-feedback[role='alert'] { + color: var(--error); +} .wb-tool-preview-actions { display: flex; flex-wrap: wrap; diff --git a/tests/e2e/tool-preview.test.ts b/tests/e2e/tool-preview.test.ts index 1a5e08d..f58459c 100644 --- a/tests/e2e/tool-preview.test.ts +++ b/tests/e2e/tool-preview.test.ts @@ -223,4 +223,53 @@ describe('bounded tool previews in Electron', () => { expect(await text.evaluate((node) => node.scrollTop)).toBe(0); expect(errors).toEqual([]); }); + + it.each(['input', 'output'])('reports a denied %s copy while collapsed and retries using the real clipboard', async (section) => { + await resizeWindow(1280, 800); + await page.getByRole('tree', { name: 'Session archives', exact: true }) + .getByRole('treeitem', { name: /Inspect long bash input/ }).click(); + const card = page.locator('.wb-tool'); + if (await card.getAttribute('open') === null) await card.locator('summary').click(); + const title = section === 'input' ? 'Input' : 'Output'; + const toggle = card.getByRole('button', { name: `${title} details` }); + if (await toggle.getAttribute('aria-expanded') === 'true') await toggle.click(); + const button = card.getByRole('button', { name: `Copy ${section}` }); + await page.evaluate(() => { + Object.defineProperty(navigator.clipboard, 'writeText', { + configurable: true, + value: () => Promise.reject(new DOMException('Clipboard denied by test', 'NotAllowedError')), + }); + }); + try { + await button.focus(); + await page.keyboard.press('Enter'); + const feedback = card.getByRole('alert'); + await feedback.waitFor(); + expect(await feedback.textContent()).toBe(`Could not copy ${section}. Try Copy again.`); + expect(await toggle.getAttribute('aria-expanded')).toBe('false'); + expect(await button.isEnabled()).toBe(true); + const capture = async (name: string) => { + await feedback.scrollIntoViewIfNeeded(); + expect(await page.evaluate(() => document.body.scrollWidth <= innerWidth)).toBe(true); + const png = await page.screenshot({ scale: 'css' }); + await Promise.all([ + fs.writeFile(path.join(root, '.tmp/proof', name), png), + fs.writeFile(path.join(shots, name), png), + ]); + }; + await capture(`tool-copy-${section}-failed.png`); + await resizeWindow(900, 600); + await capture(`tool-copy-${section}-failed-narrow.png`); + } finally { + await page.evaluate(() => { Reflect.deleteProperty(navigator.clipboard, 'writeText'); }); + } + await button.click(); + await card.getByText(`${title} copied.`, { exact: true }).waitFor(); + expect(await card.getByRole('alert').count()).toBe(0); + expect(await app.evaluate(({ clipboard }) => clipboard.readText())).toBe( + section === 'input' ? 'bun run build' : failedOutput, + ); + expect(await toggle.getAttribute('aria-expanded')).toBe('false'); + expect(errors).toEqual([]); + }); }); diff --git a/tests/integration/ToolCard.test.tsx b/tests/integration/ToolCard.test.tsx index 61fe8bf..ff7a0aa 100644 --- a/tests/integration/ToolCard.test.tsx +++ b/tests/integration/ToolCard.test.tsx @@ -1,5 +1,5 @@ -import { describe, expect, it, beforeEach, vi } from 'vitest'; -import { render, cleanup, fireEvent } from '@testing-library/react'; +import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'; +import { act, render, cleanup, fireEvent } from '@testing-library/react'; import { TOOL_TEXT_PREVIEW_LIMIT, TranscriptRow } from '../../src/renderer/components/WorkbenchControls'; import type { Entry } from '../../src/renderer/timeline'; @@ -17,6 +17,105 @@ const toolEntry: Extract = { describe(' tool card', () => { beforeEach(() => cleanup()); + afterEach(() => vi.useRealTimers()); + + it.each(['input', 'output'] as const)('reports a failed %s copy while collapsed and allows retrying the complete text', async (section) => { + const writeText = vi.fn().mockRejectedValueOnce(new Error('Clipboard denied')).mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + const entry = { ...toolEntry, oldText: 'before', newText: 'after', output: 'x'.repeat(3000) }; + const { getByRole, queryByRole } = render( + , + ); + if (section === 'output') fireEvent.click(getByRole('button', { name: 'Output details' })); + const button = getByRole('button', { name: `Copy ${section}` }); + fireEvent.click(button); + await vi.waitFor(() => expect(getByRole('alert').textContent).toBe(`Could not copy ${section}. Try Copy again.`)); + expect(button).toHaveAccessibleDescription(`Could not copy ${section}. Try Copy again.`); + expect(button.closest('.wb-tool-section')?.querySelector('pre, .wb-tool-diff')).toBeNull(); + expect(button).toBeEnabled(); + fireEvent.click(button); + await vi.waitFor(() => expect(button.textContent).toBe('Copied')); + expect(queryByRole('alert')).toBeNull(); + expect(getByRole('status').textContent).toBe(`${section === 'input' ? 'Input' : 'Output'} copied.`); + expect(writeText.mock.calls.map(([text]) => text)).toEqual([entry[section], entry[section]]); + }); + + it('explains a missing clipboard API and keeps input feedback independent of output', async () => { + Object.defineProperty(navigator, 'clipboard', { value: undefined, configurable: true }); + const { getByRole, getByText } = render( + , + ); + fireEvent.click(getByRole('button', { name: 'Copy output' })); + await vi.waitFor(() => expect(getByRole('alert')).toBeTruthy()); + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + fireEvent.click(getByRole('button', { name: 'Copy input' })); + await vi.waitFor(() => expect(getByText('Input copied.')).toBeTruthy()); + expect(getByRole('alert').textContent).toContain('Could not copy output.'); + expect(writeText).toHaveBeenCalledExactlyOnceWith(toolEntry.input); + }); + + it('announces pending copying and prevents repeated writes until it settles', async () => { + let complete!: () => void; + const writeText = vi.fn(() => new Promise((resolve) => { complete = resolve; })); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + const { getByRole } = render( + , + ); + const button = getByRole('button', { name: 'Copy output' }); + fireEvent.click(button); + expect(button).toBeDisabled(); + expect(button.textContent).toBe('Copying…'); + expect(getByRole('status').textContent).toBe('Copying output…'); + fireEvent.click(button); + expect(writeText).toHaveBeenCalledTimes(1); + await act(async () => complete()); + expect(button).toBeEnabled(); + expect(button.textContent).toBe('Copied'); + }); + + it.each(['resolve', 'reject'])('ignores a superseded clipboard %s after streamed output changes', async (settlement) => { + let resolve!: () => void; + let reject!: (error: Error) => void; + const writeText = vi.fn() + .mockImplementationOnce(() => new Promise((done, fail) => { resolve = done; reject = fail; })) + .mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + const view = render(); + const button = view.getByRole('button', { name: 'Copy output' }); + fireEvent.click(button); + view.rerender(); + expect(button).toBeEnabled(); + expect(button.textContent).toBe('Copy'); + expect(view.queryByRole('status')).toBeNull(); + fireEvent.click(button); + await vi.waitFor(() => expect(button.textContent).toBe('Copied')); + await act(async () => settlement === 'resolve' ? resolve() : reject(new Error('Old failure'))); + expect(button.textContent).toBe('Copied'); + expect(view.queryByRole('alert')).toBeNull(); + expect(writeText.mock.calls.map(([text]) => text)).toEqual([toolEntry.output, 'New streamed text']); + }); + + it('clears previous feedback on text changes and cancels the previous success timeout', async () => { + vi.useFakeTimers(); + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + const expanded = new Map([[toolEntry.key, true]]); + const view = render(); + const button = view.getByRole('button', { name: 'Copy output' }); + await act(async () => { fireEvent.click(button); }); + expect(button.textContent).toBe('Copied'); + act(() => vi.advanceTimersByTime(1000)); + view.rerender(); + expect(button.textContent).toBe('Copy'); + expect(view.queryByRole('status')).toBeNull(); + await act(async () => { fireEvent.click(button); }); + act(() => vi.advanceTimersByTime(500)); + expect(button.textContent).toBe('Copied'); + act(() => vi.advanceTimersByTime(1000)); + expect(button.textContent).toBe('Copy'); + expect(view.queryByRole('status')).toBeNull(); + }); it('shows input and output as separate labelled sections when expanded', () => { const expanded = new Map([[toolEntry.key, true]]);