Skip to content
Merged
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
49 changes: 42 additions & 7 deletions src/renderer/components/WorkbenchControls.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
memo,
useEffect,
useId,
useRef,
useState,
Expand Down Expand Up @@ -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<ReturnType<typeof setTimeout> | 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({
Expand All @@ -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 (
<div className="wb-tool-section">
<div className="wb-tool-section-head">
Expand All @@ -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'}
</button>
</div>
{feedback && (
<p id={`${id}-copy`} className="wb-tool-copy-feedback" role={status === 'failed' ? 'alert' : 'status'}>
{feedback}
</p>
)}
<div id={id} hidden={!open}>{open && children}</div>
</div>
);
Expand Down
12 changes: 12 additions & 0 deletions src/renderer/workbench.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
49 changes: 49 additions & 0 deletions tests/e2e/tool-preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
});
});
103 changes: 101 additions & 2 deletions tests/integration/ToolCard.test.tsx
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -17,6 +17,105 @@ const toolEntry: Extract<Entry, { kind: 'tool' }> = {

describe('<TranscriptRow> 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(
<TranscriptRow entry={entry} expanded={new Map([[entry.key, true]])} />,
);
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(
<TranscriptRow entry={toolEntry} expanded={new Map([[toolEntry.key, true]])} />,
);
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<void>((resolve) => { complete = resolve; }));
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
const { getByRole } = render(
<TranscriptRow entry={toolEntry} expanded={new Map([[toolEntry.key, true]])} />,
);
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<void>((done, fail) => { resolve = done; reject = fail; }))
.mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
const view = render(<TranscriptRow entry={toolEntry} expanded={new Map([[toolEntry.key, true]])} />);
const button = view.getByRole('button', { name: 'Copy output' });
fireEvent.click(button);
view.rerender(<TranscriptRow entry={{ ...toolEntry, output: 'New streamed text' }} expanded={new Map([[toolEntry.key, true]])} />);
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(<TranscriptRow entry={toolEntry} expanded={expanded} />);
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(<TranscriptRow entry={{ ...toolEntry, output: 'Updated result' }} expanded={expanded} />);
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<string, boolean>([[toolEntry.key, true]]);
Expand Down
Loading