diff --git a/CHANGELOG.md b/CHANGELOG.md index 31917f48..822d52a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to DreamCoder will be documented in this file. - **A cleaner desktop look.** All seven themes share one set of semantic colors, the conversation, sidebar and panels use one type scale (14px body text), and corners use one radius scale. The pages of the side panel (terminal, browser, files, changes) no longer draw their own frames; the terminal follows the light or dark theme, its project and branch sit in a row above the output with the clear and restart buttons, and the browser shows a loading bar under its address field. - **The Files tab previews a file beside the tree.** Clicking a file in the tree previews it in place instead of opening a tab; the tree's right-click menu can still open it in its own tab, and recent files and typed paths on the new-tab page select the file in the Files tab. A path bar above the preview holds an editor button with a menu of editors and file managers, a preview toggle for Markdown (which opens rendered), a line-wrap toggle (on by default) and a tree toggle; in a narrow panel the tree shows until you pick a file, then hides. Each part of the path has a menu (add to chat and copy path; folders can also open in an editor, the file manager or a terminal tab started there), shows its full path on hover, and is revealed in the tree when clicked. Right-clicking a file's content adds the file or the selection to the chat, copies its path or contents, and in source view comments on the clicked line or selects all. The file tree is built on `@pierre/trees`. `.bmp` and `.ico` files now preview as images. - **Changed files** have an open-file button and a menu on each row (add to chat, copy path, open file, open in an editor or the file manager). +- The card with a turn's changed files in the conversation starts as one line with the number of files, the lines added and removed and the undo button. Click the line to list the files, now in compact rows with the folder in a lighter color; a file's diff no longer repeats the file name above it. - **Line comments are lighter.** A comment icon appears beside the line number under the pointer in code and diffs; clicking the number opens a small box with the line label, where Enter adds the comment, Shift+Enter starts a new line and Escape cancels. An empty box closes when you click elsewhere. - **Skill details have an Overview and a Contents tab.** Overview shows the description and the other frontmatter fields, with the source, plugin, slash command, version, size and location beside them; Contents shows the skill's files in a tree beside a preview, where Markdown opens rendered and can switch to its source, images show as images, and binary or oversized files say they cannot be previewed instead of showing their bytes as text. The page no longer repeats the same facts in stat cards and metadata cards. - The "open project" button in the session header is a split button: the icon opens the project in the editor you used last, the arrow lists the other editors and file managers. diff --git a/desktop/src/components/README.md b/desktop/src/components/README.md index df1bbe82..77c5cb62 100644 --- a/desktop/src/components/README.md +++ b/desktop/src/components/README.md @@ -59,6 +59,7 @@ that only renames props or passes them through does not belong here. | `CardButton` | A button with the card surface, hover, disabled and focus styles; sizing and borders come from the caller | | `ViewerHeader` | The header of a full-screen page viewer: back button, title and actions, as the window's title row (drag region, title bar height on macOS) | | `SearchField` | Input Group, Input and lucide search/clear icons | +| `FilePathLabel` | A file path inside a row: the file name, then its folder in the subtle text color, truncated together; shared by the Changes tab and the turn change card in the conversation | | `SegmentedControl` | Single-selection Toggle Group | | `Dropdown` | Dropdown Menu radio items with optional descriptions, shared by settings selects and the workspace view switch | | `FormSelect` | Select with labelled triggers and empty application values encoded as nonempty Radix item values | @@ -71,7 +72,7 @@ that only renames props or passes them through does not belong here. | `ResponsivePopover` | Popover on desktop and bottom sheet on mobile | | `CopyButton` | Button, Tooltip and `useCopyAndNotify`, which wraps the clipboard helper with localized success and failure toasts | | `DirectoryPicker`, `RepositoryLaunchControls` | DreamCoder project/branch workflows using shared popovers, Command and controls | -| `PierreDiffSurface` | DreamCoder adapter around [`@pierre/diffs`](https://diffs.com), with token overrides in [`pierre.css`](shared/pierre.css) | +| `PierreDiffSurface` | DreamCoder adapter around [`@pierre/diffs`](https://diffs.com), with token overrides in [`pierre.css`](shared/pierre.css). Pierre's own file header is always off; the caller shows the file name | | `DreamCoderIcon` | DreamCoder brand artwork; not a general-purpose icon set | | `UpdateChecker` | Nonblocking persistent Sonner notification with Card, Button and Progress; updater state remains in the existing store | diff --git a/desktop/src/components/chat/CurrentTurnChangeCard.test.tsx b/desktop/src/components/chat/CurrentTurnChangeCard.test.tsx new file mode 100644 index 00000000..f637f760 --- /dev/null +++ b/desktop/src/components/chat/CurrentTurnChangeCard.test.tsx @@ -0,0 +1,148 @@ +import '@testing-library/jest-dom' +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { sessionsApi, type SessionTurnCheckpoint } from '../../api/sessions' +import { useSettingsStore } from '../../stores/settingsStore' +import { CurrentTurnChangeCard } from './CurrentTurnChangeCard' + +const checkpoint = (filesChanged: string[], insertions = 418, deletions = 0): SessionTurnCheckpoint => ({ + target: { targetUserMessageId: 'user-1', userMessageIndex: 0, userMessageCount: 1 }, + code: { available: true, filesChanged, insertions, deletions }, +}) + +const FILES = ['/repo/dc_artifacts/talk/slides/cover.html', '/repo/README.md', '/tmp/outside/notes.txt'] + +function renderCard(overrides: Partial[0]> = {}) { + const onUndo = vi.fn() + const view = render( + , + ) + return { onUndo, ...view } +} + +const card = () => screen.getByRole('region', { name: 'Turn changed files' }) +const summary = () => within(card()).getByRole('button', { name: /files changed/ }) +const fileRows = () => within(card()).queryAllByRole('button', { name: /^(Show|Hide) diff for / }) + +function stubViewport(mobile: boolean) { + vi.stubGlobal('matchMedia', (query: string) => ({ matches: mobile, media: query, addEventListener: vi.fn(), removeEventListener: vi.fn() })) +} + +describe('CurrentTurnChangeCard', () => { + beforeEach(() => { + stubViewport(false) + }) + + afterEach(() => { + cleanup() + useSettingsStore.setState(useSettingsStore.getInitialState(), true) + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('starts collapsed to one line with the number of files and the lines added and removed', () => { + renderCard() + expect(summary()).toHaveTextContent('3 files changed') + expect(summary()).toHaveTextContent('+418') + expect(summary()).toHaveTextContent('−0') + expect(summary()).toHaveAttribute('aria-expanded', 'false') + expect(fileRows()).toHaveLength(0) + expect(screen.queryByTestId('turn-change-files')).not.toBeInTheDocument() + }) + + it('lists the files when the line is clicked and hides them again on a second click', () => { + renderCard() + fireEvent.click(summary()) + expect(summary()).toHaveAttribute('aria-expanded', 'true') + expect(fileRows().map((row) => row.getAttribute('aria-label'))).toEqual([ + 'Show diff for dc_artifacts/talk/slides/cover.html', + 'Show diff for README.md', + 'Show diff for /tmp/outside/notes.txt', + ]) + fireEvent.click(summary()) + expect(fileRows()).toHaveLength(0) + }) + + it('keeps the undo button usable while collapsed, without opening the list', () => { + const { onUndo } = renderCard() + fireEvent.click(within(card()).getByRole('button', { name: 'Undo current turn changes' })) + expect(onUndo).toHaveBeenCalledOnce() + expect(fileRows()).toHaveLength(0) + expect(within(card()).getByRole('button', { name: 'Undo current turn changes' })).toHaveTextContent('Undo current turn') + }) + + it('shows the file name and, apart from it, the folder of each file', () => { + renderCard() + fireEvent.click(summary()) + const [nested, atRoot, outside] = fileRows() + expect(within(nested!).getByText('cover.html')).toBeInTheDocument() + expect(within(nested!).getByText('dc_artifacts/talk/slides')).toBeInTheDocument() + expect(within(nested!).getByText('cover.html')).not.toBe(within(nested!).getByText('dc_artifacts/talk/slides')) + expect(within(nested!).queryByText('dc_artifacts/talk/slides/cover.html')).not.toBeInTheDocument() + expect(within(atRoot!).getByText('README.md').parentElement?.children).toHaveLength(1) + expect(within(outside!).getByText('/tmp/outside')).toBeInTheDocument() + }) + + it('loads the diff of a file when its row is clicked', async () => { + const getDiff = vi.spyOn(sessionsApi, 'getTurnCheckpointDiff').mockResolvedValue({ state: 'unavailable', error: 'No diff for this file.' } as never) + renderCard() + fireEvent.click(summary()) + fireEvent.click(fileRows()[1]!) + expect(getDiff).toHaveBeenCalledWith('s1', 'user-1', '/repo/README.md', 0) + await waitFor(() => expect(within(card()).getByText('No diff for this file.')).toBeInTheDocument()) + expect(within(card()).getByRole('button', { name: 'Hide diff for README.md' })).toHaveAttribute('aria-expanded', 'true') + }) + + it('shows the changed lines of a file without repeating its name above them', async () => { + const diff = ['--- a/README.md', '+++ b/README.md', '@@ -1 +1 @@', '-old title', '+new title', ''].join('\n') + vi.spyOn(sessionsApi, 'getTurnCheckpointDiff').mockResolvedValue({ state: 'ok', diff } as never) + renderCard() + fireEvent.click(summary()) + fireEvent.click(fileRows()[1]!) + await waitFor(() => expect(card().querySelector('diffs-container')?.shadowRoot?.querySelector('[data-line-type="change-addition"]')).toBeTruthy()) + const surface = card().querySelector('diffs-container')!.shadowRoot! + expect(surface.textContent).toContain('new title') + expect(surface.querySelector('[data-diffs-header]')).toBeNull() + expect(surface.textContent).not.toContain('README.md') + }) + + it('names the undo of an earlier turn differently and shows that it is running', () => { + renderCard({ isLatest: false, isUndoing: true }) + const undo = within(card()).getByRole('button', { name: 'Rewind to before this turn' }) + expect(undo).toBeDisabled() + expect(undo).toHaveTextContent('Undoing...') + }) + + it('shows why an undo failed even while collapsed', () => { + renderCard({ error: 'The checkpoint is gone.' }) + expect(within(card()).getByText('The checkpoint is gone.')).toBeInTheDocument() + expect(fileRows()).toHaveLength(0) + }) + + it('shrinks the undo button to its icon on a phone, keeping its name', () => { + stubViewport(true) + renderCard() + const undo = within(card()).getByRole('button', { name: 'Undo current turn changes' }) + expect(undo).toHaveTextContent('') + expect(undo).toHaveAttribute('title', 'Undo current turn') + expect(summary()).toHaveTextContent('3 files changed') + }) + + it('uses the language of the app', () => { + useSettingsStore.setState({ locale: 'zh' }) + renderCard() + const region = screen.getByRole('region', { name: '轮次已更改文件' }) + expect(within(region).getByRole('button', { name: /3 个文件已更改/ })).toBeInTheDocument() + expect(within(region).getByRole('button', { name: '撤销当前轮次变更' })).toHaveTextContent('撤销当前轮次') + }) +}) diff --git a/desktop/src/components/chat/CurrentTurnChangeCard.tsx b/desktop/src/components/chat/CurrentTurnChangeCard.tsx index 61538f73..0c106a2c 100644 --- a/desktop/src/components/chat/CurrentTurnChangeCard.tsx +++ b/desktop/src/components/chat/CurrentTurnChangeCard.tsx @@ -1,8 +1,10 @@ -import { ChevronRight, Undo2 } from 'lucide-react' +import { ChevronDown, ChevronRight, FileCode, Undo2 } from 'lucide-react' import { Button } from '../shared/ui/button' -import { CardTitle, CardDescription } from '../shared/ui/card' +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../shared/ui/collapsible' +import { FilePathLabel } from '../shared/FilePathLabel' import { useCallback, useMemo, useState } from 'react' import { sessionsApi, type SessionTurnCheckpoint } from '../../api/sessions' +import { useMobileViewport } from '../../hooks/useMobileViewport' import { useTranslation } from '../../i18n' import { WorkspaceDiffSurface } from '../workspace/WorkspaceCodeSurface' @@ -39,6 +41,8 @@ export function CurrentTurnChangeCard({ onUndo, }: CurrentTurnChangeCardProps) { const t = useTranslation() + const isMobile = useMobileViewport() + const [open, setOpen] = useState(false) const [expandedPath, setExpandedPath] = useState(null) const [diffByPath, setDiffByPath] = useState>({}) @@ -97,9 +101,6 @@ export function CurrentTurnChangeCard({ const cardLabel = isLatest ? t('chat.turnChangesLatestCardLabel') : t('chat.turnChangesHistoricalCardLabel') - const subtitle = isLatest - ? t('chat.turnChangesLatestSubtitle') - : t('chat.turnChangesHistoricalSubtitle') const undoLabel = isLatest ? t('chat.turnChangesLatestUndo') : t('chat.turnChangesHistoricalUndo') @@ -108,93 +109,100 @@ export function CurrentTurnChangeCard({ : t('chat.turnChangesHistoricalUndoAria') return ( -
-
-
-
- +
+ +
- {subtitle} -
- -
-
- {files.map((fileEntry) => { - const isExpanded = expandedPath === fileEntry.apiPath - const diffState = diffByPath[fileEntry.apiPath] - return ( -
- - - {isExpanded && ( -
- {diffState?.loading ? ( -
- {t('chat.turnChangesDiffLoading')} -
- ) : diffState?.error ? ( -
- {diffState.error} -
- ) : diffState?.diff ? ( - - ) : ( -
- {t('chat.turnChangesDiffUnavailable')} -
+ +
+ {files.map((fileEntry) => { + const isExpanded = expandedPath === fileEntry.apiPath + const diffState = diffByPath[fileEntry.apiPath] + const Chevron = isExpanded ? ChevronDown : ChevronRight + return ( +
+
- )} -
- ) - })} -
+ > +
+ ) + })} +
+ {error && (
{error}
)} -
+ ) } diff --git a/desktop/src/components/chat/MessageList.test.tsx b/desktop/src/components/chat/MessageList.test.tsx index 61848293..02f5890f 100644 --- a/desktop/src/components/chat/MessageList.test.tsx +++ b/desktop/src/components/chat/MessageList.test.tsx @@ -45,6 +45,16 @@ function makeSessionState(overrides: Partial = {}): PerSessionS } } +async function showTurnChangeFiles() { + const cards = await screen.findAllByRole('region', { name: 'Turn changed files' }) + for (const card of cards) fireEvent.click(within(card).getByRole('button', { name: /files changed/ })) + return cards +} + +function changedFile(path: string, container: HTMLElement = document.body) { + return within(container).queryByRole('button', { name: `Show diff for ${path}` }) +} + function findTextNodeContaining(container: Element, text: string) { const walker = document.createTreeWalker(container, 4) let current = walker.nextNode() @@ -3149,11 +3159,11 @@ describe('MessageList nested tool calls', () => { render() - const cards = await screen.findAllByLabelText('Turn changed files') + const cards = await showTurnChangeFiles() expect(cards).toHaveLength(2) - expect(screen.getByText('src/first.ts')).toBeTruthy() - expect(screen.getByText('src/second.ts')).toBeTruthy() - expect(screen.queryByText('src/third.ts')).toBeNull() + expect(changedFile('src/first.ts')).toBeTruthy() + expect(changedFile('src/second.ts')).toBeTruthy() + expect(changedFile('src/third.ts')).toBeNull() }) it('expands a historical turn diff through the turn checkpoint diff API', async () => { @@ -3233,6 +3243,7 @@ describe('MessageList nested tool calls', () => { render() + await showTurnChangeFiles() fireEvent.click(await screen.findByRole('button', { name: 'Show diff for src/first.ts' })) const diffSurface = await screen.findByTestId('workspace-code') @@ -3302,6 +3313,7 @@ describe('MessageList nested tool calls', () => { render() + await showTurnChangeFiles() fireEvent.click(await screen.findByRole('button', { name: 'Show diff for src/first.ts' })) await screen.findByTestId('workspace-code') @@ -3367,7 +3379,7 @@ describe('MessageList nested tool calls', () => { render() - expect(await screen.findByText('src/live.ts')).toBeTruthy() + await showTurnChangeFiles() fireEvent.click(screen.getByRole('button', { name: 'Show diff for src/live.ts' })) await screen.findByTestId('workspace-code') expect(sessionsApi.getTurnCheckpointDiff).toHaveBeenCalledWith( @@ -3420,7 +3432,8 @@ describe('MessageList nested tool calls', () => { render() - expect(await screen.findByText('src/blank-response.ts')).toBeTruthy() + await showTurnChangeFiles() + expect(changedFile('src/blank-response.ts')).toBeTruthy() }) it('keeps historical turn change cards visible while the next turn is running', async () => { @@ -3465,7 +3478,8 @@ describe('MessageList nested tool calls', () => { render() - expect(await screen.findByText('src/first.ts')).toBeTruthy() + await showTurnChangeFiles() + expect(changedFile('src/first.ts')).toBeTruthy() act(() => { useChatStore.setState({ @@ -3479,7 +3493,7 @@ describe('MessageList nested tool calls', () => { }) await waitFor(() => { - expect(screen.getByText('src/first.ts')).toBeTruthy() + expect(changedFile('src/first.ts')).toBeTruthy() }) }) @@ -3588,7 +3602,7 @@ describe('MessageList nested tool calls', () => { render() - const historicalCard = (await screen.findAllByRole('region', { name: 'Turn changed files' })).find((card) => within(card).queryByText('src/first.ts')) + const historicalCard = (await showTurnChangeFiles()).find((card) => changedFile('src/first.ts', card)) expect(historicalCard).toBeTruthy() fireEvent.click( within(historicalCard as HTMLElement).getByRole('button', { @@ -3687,10 +3701,10 @@ describe('MessageList nested tool calls', () => { render() - const cards = await screen.findAllByLabelText('Turn changed files') + const cards = await showTurnChangeFiles() expect(cards).toHaveLength(1) - expect(screen.getByText('src/first.ts')).toBeTruthy() - expect(screen.queryByText('src/second.ts')).toBeNull() + expect(changedFile('src/first.ts')).toBeTruthy() + expect(changedFile('src/second.ts')).toBeNull() }) it('shows raw startup details under translated CLI startup errors', () => { diff --git a/desktop/src/components/shared/FilePathLabel.tsx b/desktop/src/components/shared/FilePathLabel.tsx new file mode 100644 index 00000000..b8b91de9 --- /dev/null +++ b/desktop/src/components/shared/FilePathLabel.tsx @@ -0,0 +1,11 @@ +import { getPathParts } from '../../lib/pathParts' + +export function FilePathLabel({ path }: { path: string }) { + const { name, dir } = getPathParts(path) + return ( + + {name} + {dir && {dir}} + + ) +} diff --git a/desktop/src/components/shared/PierreDiffSurface.tsx b/desktop/src/components/shared/PierreDiffSurface.tsx index 937862f3..2ede342c 100644 --- a/desktop/src/components/shared/PierreDiffSurface.tsx +++ b/desktop/src/components/shared/PierreDiffSurface.tsx @@ -12,11 +12,10 @@ import './pierre.css' type Props = Omit, 'options'> & { fileDiff: FileDiffMetadata theme: ThemeMode - hideFileHeader?: boolean onCommentLine?: (line: number) => void } -export function PierreDiffSurface({ fileDiff, theme, className, hideFileHeader = true, onCommentLine, ...props }: Props) { +export function PierreDiffSurface({ fileDiff, theme, className, onCommentLine, ...props }: Props) { const t = useTranslation() const commentButtonRef = useRef(null) const options = useMemo['options']>(() => ({ @@ -27,7 +26,7 @@ export function PierreDiffSurface({ fileDiff, theme, className, hideFileHeader = hunkSeparators: 'line-info', lineDiffType: 'word', overflow: 'scroll', - disableFileHeader: hideFileHeader, + disableFileHeader: true, onPostRender: onCommentLine ? (host, _, phase) => { if (phase === 'unmount') return for (const number of host.shadowRoot?.querySelectorAll('[data-column-number]') ?? []) { @@ -55,7 +54,7 @@ export function PierreDiffSurface({ fileDiff, theme, className, hideFileHeader = button.toggleAttribute('data-hidden', annotationSide !== 'additions') button.setAttribute('aria-label', t('workspace.commentLine', { line: lineNumber })) } : undefined, - }), [theme, hideFileHeader, onCommentLine, t]) + }), [theme, onCommentLine, t]) return ( { it('shows real line numbers and allows comments on added and context lines only', async () => { const onAddLineComment = vi.fn() render( - , + , ) expect(screen.queryByText('diff --git a/src/a.ts b/src/a.ts')).not.toBeInTheDocument() @@ -100,7 +100,7 @@ describe('WorkspaceDiffSurface', () => { }) it('offers a comment button in the diff gutter for new lines only', async () => { - render() + render() const shadow = document.querySelector('diffs-container')!.shadowRoot! await waitFor(() => expect(shadow.querySelector('[data-line-type="change-addition"]')).toBeTruthy()) const hover = (selector: string) => { diff --git a/desktop/src/components/workspace/WorkspaceCodeSurface.tsx b/desktop/src/components/workspace/WorkspaceCodeSurface.tsx index 4743b344..f0585f66 100644 --- a/desktop/src/components/workspace/WorkspaceCodeSurface.tsx +++ b/desktop/src/components/workspace/WorkspaceCodeSurface.tsx @@ -163,12 +163,11 @@ export function limitUnifiedDiff(value: string, lineLimit: number) { return lines.join('\n') + '\n' } -export function WorkspaceDiffSurface({ value, path, className = 'min-h-0 flex-1 overflow-auto', lineLimit = WORKSPACE_PREVIEW_LINE_LIMIT, hideFileHeaders = false, onAddLineComment, onAddSelection }: { +export function WorkspaceDiffSurface({ value, path, className = 'min-h-0 flex-1 overflow-auto', lineLimit = WORKSPACE_PREVIEW_LINE_LIMIT, onAddLineComment, onAddSelection }: { value: string path: string className?: string lineLimit?: number - hideFileHeaders?: boolean onAddLineComment?: (line: number, note: string, quote: string) => void onAddSelection?: (selection: WorkspaceTextSelection) => void }) { @@ -219,7 +218,7 @@ export function WorkspaceDiffSurface({ value, path, className = 'min-h-0 flex-1 const lineAnnotations = useMemo(() => activeCommentLine !== null ? [{ side: 'additions' as const, lineNumber: activeCommentLine }] : [], [activeCommentLine]) const content = diff.files.map((file, index) => ( - ( diff --git a/desktop/src/components/workspace/WorkspacePanel.tsx b/desktop/src/components/workspace/WorkspacePanel.tsx index ae76f121..c9c18018 100644 --- a/desktop/src/components/workspace/WorkspacePanel.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.tsx @@ -50,6 +50,8 @@ import { RenameSessionDialog } from '../layout/RenameSessionDialog' import { closeSideChat, detachSideChat, useStartSideChat } from '../../lib/sideChats' import { isDesktopRuntime } from '../../lib/desktopRuntime' import { SearchField } from '../shared/SearchField' +import { FilePathLabel } from '../shared/FilePathLabel' +import { getPathParts } from '../../lib/pathParts' import { useCopyAndNotify } from '../../hooks/useCopyAndNotify' import { useQuoteSelection } from '../../lib/selectionPopover' import { MarkdownRenderer } from '../markdown/MarkdownRenderer' @@ -398,12 +400,6 @@ function ImagePreview({ tab }: { tab: WorkspacePreviewEntry }) { ) } -function getPathParts(path: string) { - const segments = path.split('/').filter(Boolean) - const name = segments.pop() ?? path - return { name, dir: segments.join('/') } -} - function FileStatusLetter({ status }: { status: WorkspaceFileStatus }) { const meta = FILE_STATUS_META[status] return ( @@ -432,7 +428,6 @@ function ChangedFileItem({ children?: ReactNode }) { const t = useTranslation() - const { name, dir } = getPathParts(file.path) const Chevron = expanded ? ChevronDown : ChevronRight return (
@@ -447,10 +442,7 @@ function ChangedFileItem({ >