diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 4e455c1037..dcb1c7ed76 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -21,6 +21,7 @@ import { ChecksRow, IssuesRow, MergeRow, ReviewRow, RowParts, ThreadGlyph, type import { formatAgo } from './format.ts' import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' +import type { ForgeChangeRequestCardActionsProps } from './slots.ts' import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' import css from './ForgeTab.module.css' @@ -47,6 +48,8 @@ export interface ChangeRequestActions extends OverviewActions { readonly readChecks?: ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined /** Open the changes view of the change request. */ readonly viewChanges?: ((entry: ForgePanelChangeRequest) => void) | undefined + /** Draw the icon buttons plugins add to the card's head through `forge.change-request.card.actions`. */ + readonly renderActions?: ((owner: ForgeChangeRequestCardActionsProps) => ReactNode) | undefined } /** Props of one change request card. */ @@ -395,6 +398,7 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc )} + {actions.renderActions?.({ url: entry.url, ref: entry.ref, headSha: snapshot?.headSha ?? null, state: snapshot?.state ?? null })} + : } + + }> + {lensRun.run.code === 'forgePanel/lens-stale' ? t('filterLens.stale', { lens: chosenChoice.title }) + : lensRun.run.code === 'forgePanel/lens-interrupted' ? t('filterLens.interrupted', { lens: chosenChoice.title }) + : t('filterLens.failed', { lens: chosenChoice.title, message: lensRun.run.message })} + + )} {data?.kind === 'change' && data.viewed?.kind === 'failed' && ( {t('retry')}}> {t('viewed.readFailed', { message: data.viewed.message })} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index fc25c20ebc..93eaa3e409 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -29,6 +29,7 @@ import { FileLabel } from './FileLabel.tsx' import type { ForgePanelKey, NS } from './locales.ts' import type { ViewedState } from './viewed-files.ts' import type { SectionReach } from './section-reach.ts' +import type { SourcedAnnotation } from './annotations.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -65,6 +66,12 @@ export interface DiffFileHandlers { readonly nextThread: (path: string) => void /** Tells each expanded section when it comes within reach of the scrollport, which draws its lines. */ readonly reach: SectionReach + /** Draw the content of one line annotation through its source's `forge.diff.line.annotation` entry. */ + readonly annotation: (path: string, item: SourcedAnnotation) => ReactNode + /** Draw the plugin rows of a file's menu through `forge.changes.file.menu`. */ + readonly fileMenu: (file: ForgeDiffFile, dismiss: () => void) => ReactNode + /** Show the hunks the chosen lens folds in a file. */ + readonly unfold: (path: string) => void } /** Props of one file section. */ @@ -103,6 +110,12 @@ export interface DiffFileProps { readonly threads?: FileThreads | undefined /** Whether the section draws its lines at once, as the target of a thread jump, whose card must exist to be centered. */ readonly drawNow?: boolean | undefined + /** Line annotations of the file in stacking order, or undefined for none; the view keeps their identity. */ + readonly annotations?: readonly SourcedAnnotation[] | undefined + /** Most annotations the file shows, the rest counted below them, or undefined to show none while the limit is unknown. */ + readonly annotationLimit?: number | undefined + /** Indexes of the hunks the chosen lens folds with the lens's title, or undefined for none; the view keeps their identity. */ + readonly folded?: { readonly hunks: ReadonlySet; readonly lens: string } | undefined /** Actions shared by every section of the view. */ readonly handlers: DiffFileHandlers /** Forge panel copy. */ @@ -135,6 +148,7 @@ type SideSpans = ReadonlyMap | undefined /** A segment ready to draw: collapsed lines, or rows with the tokens of each side. */ type Prepared = | { readonly kind: 'gap'; readonly index: number; readonly count: number | null } + | { readonly kind: 'folded'; readonly hunks: readonly number[] } | { readonly kind: 'rows'; readonly rows: readonly DiffRow[]; readonly old: SideSpans; readonly new: SideSpans } /** Highlight one side of a run of rows as one fragment, so tokens spanning lines keep their state. */ @@ -180,13 +194,66 @@ function rangeKey(item: ReviewSelection): string { return `${item.comment.side}${item.comment.startLine}-${item.comment.endLine}` } +/** A file's annotations as it shows them: on lines, on the whole file, written on an earlier change, and how many the limit leaves out. */ +interface FileAnnotations { + readonly lines: readonly SourcedAnnotation[] + readonly file: readonly SourcedAnnotation[] + readonly outdated: readonly SourcedAnnotation[] + readonly hidden: number +} + +const NO_ANNOTATIONS: FileAnnotations = { lines: [], file: [], outdated: [], hidden: 0 } + +/** Group the first `limit` annotations of a file by where they show; none show while the limit is unknown. */ +function groupAnnotations( + file: ForgeDiffFile, items: readonly SourcedAnnotation[] | undefined, limit: number | undefined, +): FileAnnotations { + if (items === undefined || items.length === 0 || limit === undefined) return NO_ANNOTATIONS + const lines: SourcedAnnotation[] = [] + const whole: SourcedAnnotation[] = [] + const outdated: SourcedAnnotation[] = [] + for (const item of items.slice(0, limit)) { + const { place, digest } = item.annotation + if (digest !== undefined && digest !== file.digest) outdated.push(item) + else if (place === 'file') whole.push(item) + else lines.push(item) + } + return { lines, file: whole, outdated, hidden: Math.max(0, items.length - limit) } +} + +/** Whether a line of one side falls in one of the hunks. */ +function inHunks(file: ForgeDiffFile, hunks: readonly number[], side: 'L' | 'R', line: number): boolean { + return hunks.some((index) => { + const hunk = file.hunks[index] + /* v8 ignore next -- folded indexes name hunks of the file */ + if (hunk === undefined) return false + const start = side === 'L' ? hunk.oldStart : hunk.newStart + return line >= start && line < start + (side === 'L' ? hunk.oldLines : hunk.newLines) + }) +} + +/** The saved comments and plugin annotations the lines of a file place. */ +interface LinesNotes { + readonly comments: FileReviewState + readonly annotations: readonly SourcedAnnotation[] +} + +/** One annotation's frame, which holds the content its source's slot entry draws. */ +function Annotation({ path, item, handlers }: { + readonly path: string + readonly item: SourcedAnnotation + readonly handlers: DiffFileHandlers +}): ReactNode { + return
{handlers.annotation(path, item)}
+} + function pairKind(pair: SplitRow): 'context' | 'change' { return pair.left !== null && pair.left.kind === 'context' ? 'context' : 'change' } /** The hunks of one file with their collapsed and expanded unchanged lines. */ -function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, threads, t }: Pick & { readonly comments: FileReviewState }): ReactNode { +function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, threads, folded, annotations, t }: Pick & LinesNotes): ReactNode { const lines = typeof text === 'object' ? text : undefined const columns = split && file.additions > 0 && file.deletions > 0 const singleSide = file.status === 'added' ? 'R' : file.status === 'deleted' ? 'L' : null @@ -194,6 +261,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme for (const hunk of file.hunks) maximum = Math.max(maximum, hunk.oldStart + hunk.oldLines - 1, hunk.newStart + hunk.newLines - 1) const style: CSSProperties & { '--forge-number-width': string } = { '--forge-number-width': `calc(${Math.max(2, String(maximum).length)}ch + 12px)` } const highlighter = useCodeHighlighter(languageForPath(file.path)) + const foldLens = folded === undefined ? '' : folded.lens const [selection, setSelection] = useState(null) // Mirrors `selection` for the release of a hover-plus drag, whose listener outlives the render that chose the range. const chosen = useRef(null) @@ -271,9 +339,10 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme window.removeEventListener('pointercancel', finish) } }, [selecting, nativeSelection]) - const prepared = useMemo(() => segmentsOf(file, lines, open).map((segment): Prepared => segment.kind === 'gap' + const prepared = useMemo(() => segmentsOf(file, lines, open, folded?.hunks).map((segment): Prepared => segment.kind !== 'rows' ? segment - : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), [file, lines, open, highlighter]) + : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), + [file, lines, open, folded, highlighter]) // Returns whether the range was accepted; a range across hunks or outside them keeps the previous selection. const choose = (side: 'L' | 'R', line: number, extend: boolean): boolean => { /* v8 ignore next -- the line buttons and hover pluses that choose a range draw only with review actions */ @@ -366,6 +435,16 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme const unplaced = new Set(threads === undefined ? [] : threads.lines.map(item => ({ ...item, actions: threads.actions }))) const threadCard = (item: LineThread & { readonly actions: ThreadActions }): ReactNode => + // Plugin annotations follow the host threads on the row of their last line, or the collapsed or folded lines that hold it. + const unplacedNotes = new Set(annotations) + const annotationOf = (item: SourcedAnnotation): ReactNode => + + const lastLine = (item: SourcedAnnotation): { readonly side: 'L' | 'R'; readonly line: number } => { + const place = item.annotation.place + /* v8 ignore next -- only line annotations reach the lines */ + if (place === 'file') return { side: 'R', line: 0 } + return { side: place.side, line: place.endLine } + } // The editors, the saved comments, then the host threads whose ranges end on this side's line. const commentsAt = (side: 'L' | 'R', line: number | null): ReactNode[] => { const nodes: ReactNode[] = [] @@ -388,6 +467,12 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme nodes.push(threadCard(item)) unplaced.delete(item) } + for (const item of unplacedNotes) { + const at = lastLine(item) + if (at.side !== side || at.line !== line) continue + nodes.push(annotationOf(item)) + unplacedNotes.delete(item) + } return nodes } const editorOf = (item: ReviewSelection, actions: ReviewActions): ReactNode => @@ -418,6 +503,30 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme rows.push(threadCard(item)) unplaced.delete(item) } + for (const item of unplacedNotes) { + const at = lastLine(item) + if (gapOf(file, at.side, at.line) !== segment.index) continue + rows.push(annotationOf(item)) + unplacedNotes.delete(item) + } + } else if (segment.kind === 'folded') { + rows.push() + for (const item of unplaced) { + if (!inHunks(file, segment.hunks, item.place.side, item.place.endLine)) continue + rows.push(threadCard(item)) + unplaced.delete(item) + } + for (const item of unplacedNotes) { + const place = lastLine(item) + if (!inHunks(file, segment.hunks, place.side, place.line)) continue + rows.push(annotationOf(item)) + unplacedNotes.delete(item) + } } else if (columns) { for (const [index, pair] of splitRows(segment.rows).entries()) { rows.push(
) - const lineThreads = threads?.lines.map(item => ) + const lineThreads = <> + {threads?.lines.map(item => + )} + {notes.lines.map(item => )} + if (file.binary) return <>

{t('diff.binary')}

{records}{lineThreads} if (file.oversized) return <>

{t('diff.fileTooLarge')}

{records}{lineThreads} if (file.hunks.length === 0) return <>{records}{lineThreads} @@ -490,16 +603,27 @@ function Content(props: DiffFileProps): ReactNode { {records}{lineThreads} ) } - return + return } /** Host threads on the whole file, the lines, then the host threads that later commits made outdated. */ function Body(props: DiffFileProps): ReactNode { - const { threads, t } = props + const { file, threads, handlers, t } = props + const notes = groupAnnotations(file, props.annotations, props.annotationLimit) + const frame = (item: SourcedAnnotation): ReactNode => + return <> {threads?.file.map(thread => )} - + {notes.file.map(frame)} + {threads !== undefined && } + {notes.outdated.length > 0 && ( +
+
{t('annotation.outdated', { count: String(notes.outdated.length) })}
+ {notes.outdated.map(frame)} +
+ )} + {notes.hidden > 0 &&

{t('annotation.hidden', { count: String(notes.hidden) })}

} } @@ -543,6 +667,7 @@ function FileMenu({ name, file, handlers, t }: { {t(action.label)} ))} + {menuOpen &&
{handlers.fileMenu(file, () => { setMenuOpen(false) })}
} ) } diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx index 20eec63c19..a636d40cc9 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx @@ -4,7 +4,8 @@ import { useEffect, useState, type ReactNode } from 'react' import { Button, IconBranchOutlineRegular, IconCopyOutlineRegular, IconFolderCloseRegular, IconWarningTriangleOutlineRegular, StateDot, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from './slots.ts' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' @@ -68,6 +69,7 @@ export interface ForgeTabInjected { /** Full props of the tab body. */ export type ForgeTabProps = Pick, 'useTabInfo' | 'sessionId'> + & Pick, 'renderSlot'> & InjectFace & PropsLocale @@ -167,7 +169,7 @@ function SignIn({ state, copyText, t }: { export function ForgeTab({ useTabInfo, sessionId, usePanel, useHost, useLocale, reconnect, refresh, remove, markReady, merge, readChecks, restore, rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, copyPath, - reportVisible, createChangeRequest, t, + reportVisible, createChangeRequest, renderSlot, t, }: ForgeTabProps): ReactNode { const snapshot = usePanel(current => current) const home = useHost(facts => facts.home) @@ -200,6 +202,7 @@ export function ForgeTab({ openLink, copyLink: copyText, retry: startRefresh, remove, markReady, merge, readChecks, rerunChecks, requestReviews, reviewerCandidates, updateBranch, viewChanges: (entry) => { viewChanges({ kind: 'change', url: entry.url }) }, + renderActions: owner => renderSlot('forge.change-request.card.actions', owner), } const local = state.local !== null && state.local.files.length > 0 ? state.local : null const expanded = chosen ?? defaultExpanded(state.changeRequests) diff --git a/packages/experimental/client-ui-forge/src/client/LensFilter.module.css b/packages/experimental/client-ui-forge/src/client/LensFilter.module.css new file mode 100644 index 0000000000..848cea6332 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/LensFilter.module.css @@ -0,0 +1,87 @@ +/* The filter lens menu trigger, which shares the toolbar trigger's geometry and turns tinted while a lens is chosen. */ + +.trigger { + display: inline-flex; + flex: none; + align-items: center; + gap: 4px; + max-width: 220px; + height: 28px; + padding: 0 6px 0 8px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-secondary); + font: inherit; + white-space: nowrap; + cursor: pointer; +} + +.trigger[aria-expanded='true'] { + background: var(--dsw-alias-interactive-bg-hover); +} + +.trigger[data-active] { + background: var(--dsw-alias-state-business-tertiary); + color: var(--dsw-alias-state-business-primary); +} + +@media (hover: hover) { + .trigger:not([data-active]):hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.trigger:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -1px; +} + +.label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.count { + flex: none; + font-size: 12px; + opacity: 0.8; +} + +.spin { + flex: none; + animation: lens-spin 0.9s linear infinite; +} + +@media (prefers-reduced-motion: reduce) { + .spin { + animation: none; + } +} + +@keyframes lens-spin { + to { + transform: rotate(360deg); + } +} + +.row { + display: flex; + align-items: center; + gap: 16px; + width: 100%; +} + +.rowLabel { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.rowCount { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; +} diff --git a/packages/experimental/client-ui-forge/src/client/LensFilter.tsx b/packages/experimental/client-ui-forge/src/client/LensFilter.tsx new file mode 100644 index 0000000000..7269ae9bf4 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/LensFilter.tsx @@ -0,0 +1,105 @@ +/** The changes toolbar's filter lens menu: the Host's lenses with the files each keeps among the shown files. */ + +import { useState, type ReactNode } from 'react' +import { IconChevronDownOutlineRegular, IconLayersOutlineRegular, IconLoadingOutlineRegular, Menu, type MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { LensRun } from './lens-filter.ts' +import type { NS } from './locales.ts' +import css from './LensFilter.module.css' + +/** One lens the view offers. */ +export interface LensChoice { + /** Identity of the Host lens. */ + readonly id: string + /** Title in the current language, or the identity when no Client plugin describes it. */ + readonly title: string + /** Files the lens keeps among the shown files, or null before it ran for them. */ + readonly count: number | null +} + +/** Menu row identity of choosing no lens. */ +export const NO_LENS = 'lens:none' + +/** + * Menu row identity of choosing a lens. + * @param id - the lens identity. + * @returns the row identity. + */ +export function lensRowId(id: string): string { + return `lens:${id}` +} + +/** + * Read the lens a menu row chooses. + * @param row - a row identity. + * @returns the lens identity, null for no lens, or undefined for a row that chooses no lens. + */ +export function lensOfRow(row: string): string | null | undefined { + if (row === NO_LENS) return null + return row.startsWith('lens:') ? row.slice('lens:'.length) : undefined +} + +/** + * The rows that choose a lens: a heading, No lens, and each lens with its count. + * @param lenses - the lenses offered. + * @param t - forge panel copy. + * @returns the menu entries. + */ +export function lensEntries(lenses: readonly LensChoice[], t: PropsLocale['t']): MenuEntry[] { + return [ + { type: 'label', id: 'lens:heading', text: t('filterLens.heading') }, + { id: NO_LENS, label: t('filterLens.none') }, + ...lenses.map((lens): MenuEntry => ({ + id: lensRowId(lens.id), + label: {lens.title}{lens.count ?? '—'}, + })), + ] +} + +/** + * Render the lens menu button: Lens while none is chosen; the chosen lens's title, tinted, with the files it keeps, or + * its progress while it runs. + * @param props - the offered lenses, the chosen one, its run, the choose action, whether the owning tab is visible, and copy. + * @returns the trigger with its portalled menu. + */ +export function LensFilterMenu({ lenses, chosen, run, choose, visible, t }: PropsLocale & { + readonly lenses: readonly LensChoice[] + readonly chosen: LensChoice | null + readonly run: LensRun + readonly choose: (lens: string | null) => void + readonly visible: boolean +}): ReactNode { + const [open, setOpen] = useState(false) + let status: ReactNode = null + if (run.kind === 'running') { + status = <> + + {run.done !== null && run.total !== null && {t('filterLens.progress', { done: String(run.done), total: String(run.total) })}} + + } else if (chosen?.count !== null && chosen?.count !== undefined) { + status = {chosen.count} + } + return ( + { setOpen(false) }} + onSelect={(row) => { + setOpen(false) + const lens = lensOfRow(row) + /* v8 ignore next -- the menu offers only rows that choose a lens */ + if (lens === undefined) return + choose(lens) + }} + anchor={( + + )} /> + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 694dc51bea..bb9589f05d 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -7,6 +7,7 @@ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ReviewQueue } from './review-queue.ts' import { reviewRange, type ReviewSelection, type ReviewSource } from './review.ts' import type { NS } from './locales.ts' +import type { ForgeCommentActionsProps } from './slots.ts' import css from './ReviewComposer.module.css' /** Actions supplied by the owning changes tab. */ @@ -29,6 +30,8 @@ export interface ReviewActions { readonly publish?: (selection: ReviewSelection) => Promise /** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */ readonly queue?: (selection: ReviewSelection) => Promise + /** Draw the buttons plugins add to the form through `forge.diff.comment.actions`. */ + readonly renderActions?: (owner: Omit) => ReactNode } /** @@ -115,6 +118,15 @@ export function ReviewComposer({ selection, actions, close, visible = true, t }: if (actions.addToInput(selected)) { actions.onQuoted?.(selected); close() } else setError(t('review.inputFailed')) }}>{t('review.addToInput')} + {actions.renderActions?.({ + selection: { + path: selection.comment.path, side: selection.comment.side, + startLine: selection.comment.startLine, endLine: selection.comment.endLine, + }, + empty, + busy, + send: (deliver) => { void send(async () => await deliver(body.current)) }, + })} {visible && actions.queue !== undefined && { void send(actions.queue) }} menuLabel={t('review.githubActions')} diff --git a/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx b/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx index 4ba29ee705..6ccc1239a3 100644 --- a/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/ViewOptionsMenu.tsx @@ -6,6 +6,7 @@ import { IconEllipsisOutlineRegular, Menu, Tooltip, type MenuEntry } from '@deep import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { NS } from './locales.ts' import { foldOf } from './toolbar-fold.ts' +import { lensEntries, lensOfRow, NO_LENS, type LensChoice } from './LensFilter.tsx' import css from './ChangesTab.module.css' /** Toolbar state and actions the menu repeats. */ @@ -23,11 +24,16 @@ export interface ViewOptions { readonly hideTests: boolean | undefined readonly toggleTests: () => void readonly refresh: () => void + /** Lenses the menu offers while the lens menu folds, empty while a lens is chosen and its menu stays in the row. */ + readonly lenses: readonly LensChoice[] + readonly chooseLens: (lens: string | null) => void + /** Draw the `MenuItemButton` rows of plugin toolbar entries, which fold first; `close` closes the menu. */ + readonly plugins: (close: () => void) => ReactNode } /** * Render the More button and its menu, which lists the controls of the toolbar's fold level when it opens (see - * `observeToolbarFold`); the toolbar's styles hide the button while nothing folds. + * `observeToolbarFold`), then the rows of plugin toolbar entries; the toolbar's styles hide the button while nothing folds. * @param props - the toolbar state and actions, whether the owning tab is visible, and copy. * @returns the button and its portalled menu. */ @@ -45,10 +51,17 @@ export function ViewOptionsMenu({ options, visible, t }: PropsLocale { id: 'wrap', label: t('diff.wrapAria') }, ) if (fold >= 2 && options.hideTests !== undefined) entries.push({ type: 'separator', id: 'tests-separator' }, { id: 'tests', label: t('tests.hide') }) + if (fold >= 2 && options.lenses.length > 0) entries.push({ type: 'separator', id: 'lens-separator' }, ...lensEntries(options.lenses, t)) if (fold >= 3) entries.push({ type: 'separator', id: 'refresh-separator' }, { id: 'refresh', label: t('diff.refresh') }) } - const selected = [options.split && 'split', options.wrap && 'wrap', options.hideTests === true && 'tests'].filter(item => item !== false) + const selected = [options.split && 'split', options.wrap && 'wrap', options.hideTests === true && 'tests', options.lenses.length > 0 && NO_LENS] + .filter(item => item !== false) const run = (id: string): void => { + const lens = lensOfRow(id) + if (lens !== undefined) { + options.chooseLens(lens) + return + } switch (id) { case 'expansion': options.toggleExpansion(); break case 'split': options.toggleSplit(); break @@ -74,6 +87,8 @@ export function ViewOptionsMenu({ options, visible, t }: PropsLocale - )} /> + )}> + {fold !== null &&
{options.plugins(() => { setFold(null) })}
} +
) } diff --git a/packages/experimental/client-ui-forge/src/client/annotations.ts b/packages/experimental/client-ui-forge/src/client/annotations.ts new file mode 100644 index 0000000000..6fc9d36462 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/annotations.ts @@ -0,0 +1,105 @@ +/** + * Line annotations of one changes view: every source's annotations merged by path, and where each one shows in a + * file's lines. + */ + +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { ChangesTarget } from './changes-address.ts' +import type { ForgeAnnotationSource, ForgeLineAnnotation } from './changes-service.ts' + +/** One annotation with the source that draws it. */ +export interface SourcedAnnotation { + /** Identity of the source, the key of its `forge.diff.line.annotation` entry. */ + readonly source: string + readonly annotation: ForgeLineAnnotation +} + +/** Annotations of one view by path, in source order and then each source's order. */ +export type ViewAnnotations = ReadonlyMap + +const EMPTY: ViewAnnotations = new Map() + +/** Whether two lists hold the same annotations of the same sources at the same versions in the same order. */ +function sameList(a: readonly SourcedAnnotation[], b: readonly SourcedAnnotation[]): boolean { + return a.length === b.length && a.every((item, index) => { + const other = b[index] + return other !== undefined && item.source === other.source && item.annotation.key === other.annotation.key + && item.annotation.version === other.annotation.version + }) +} + +/** + * The merged annotations of one view. It observes each registered source while a reader subscribes, starting with + * the first reader and stopping after the last; a file whose annotations did not change keeps its list, so its section + * does not draw again. + */ +export class AnnotationView implements HostObservable { + private snapshot: ViewAnnotations = EMPTY + private readonly listeners = new Set<() => void>() + /** The followed sources in stacking order, each with its observable for this view and its unsubscribe. */ + private followed: readonly { readonly source: ForgeAnnotationSource; readonly values: ReturnType; readonly stop: () => void }[] = [] + private stopSources: (() => void) | undefined + + /** + * @param sources - the registered sources. + * @param target - the view's Session and source. + */ + constructor(private readonly sources: HostObservable, private readonly target: ChangesTarget) {} + + readonly getSnapshot = (): ViewAnnotations => this.snapshot + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + if (this.listeners.size === 1) { + this.stopSources = this.sources.subscribe(() => { this.sync() }) + this.sync() + } + return () => { + this.listeners.delete(listener) + if (this.listeners.size > 0) return + this.stopSources?.() + this.stopSources = undefined + for (const entry of this.followed) entry.stop() + this.followed = [] + } + } + + /** Follow the sources registered now, observing each new one once and releasing each withdrawn one, then merge. */ + private sync(): void { + const next = this.sources.getSnapshot().map(source => this.followed.find(entry => entry.source === source) ?? this.follow(source)) + for (const entry of this.followed) { + if (!next.includes(entry)) entry.stop() + } + this.followed = next + this.merge() + } + + private follow(source: ForgeAnnotationSource): (typeof this.followed)[number] { + const values = source.observe(this.target) + return { source, values, stop: values.subscribe(() => { this.merge() }) } + } + + private merge(): void { + const lists = new Map() + for (const { source, values } of this.followed) { + for (const [path, annotations] of values.getSnapshot()) { + const list = lists.get(path) ?? [] + for (const annotation of annotations) list.push({ source: source.id, annotation }) + if (list.length > 0) lists.set(path, list) + } + } + let changed = lists.size !== this.snapshot.size + const next = new Map() + for (const [path, list] of lists) { + const previous = this.snapshot.get(path) + if (previous !== undefined && sameList(previous, list)) next.set(path, previous) + else { + next.set(path, list) + changed = true + } + } + if (!changed) return + this.snapshot = next + for (const listener of [...this.listeners]) listener() + } +} diff --git a/packages/experimental/client-ui-forge/src/client/changes-address.ts b/packages/experimental/client-ui-forge/src/client/changes-address.ts index de9c62bda3..7c15d499c5 100644 --- a/packages/experimental/client-ui-forge/src/client/changes-address.ts +++ b/packages/experimental/client-ui-forge/src/client/changes-address.ts @@ -39,11 +39,13 @@ export interface ChangesTarget { export interface ChangesParams { /** File to scroll to, by its path in the diff. */ readonly path?: string + /** Identity of the filter lens to choose. */ + readonly lens?: string } declare module '@deepseek-ai/dsh-client-ui-sidebar-right/client' { interface SidebarRightResourceParamsMap { - /** The file a changes tab scrolls to. */ + /** The file a changes tab scrolls to and the lens it chooses. */ 'forge-changes': ChangesParams } } diff --git a/packages/experimental/client-ui-forge/src/client/changes-service.ts b/packages/experimental/client-ui-forge/src/client/changes-service.ts new file mode 100644 index 0000000000..fa3f1f6735 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/changes-service.ts @@ -0,0 +1,173 @@ +/** + * The changes view's face for other Client plugins, which the forge panel provides as `ctx.forgeChanges`: the + * changes tab's addresses and kinds, opening a view, the titles of Host lenses, and line annotation sources. + */ + +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ForgeExtensionState, ForgeLensId } from '../types.ts' +import { changesAddress, parseChangesAddress, type ChangesParams, type ChangesTarget } from './changes-address.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** The changes view's face for other Client plugins. */ + forgeChanges: ForgeChangesService + } +} + +/** The title of a filter lens a Host plugin registers, which a Client plugin describes. */ +export interface ForgeLensDescription { + /** Identity of the Host lens. */ + readonly id: ForgeLensId + /** Title in the current language, read whenever the view draws. */ + readonly title: () => string + /** Position among the lenses, lower first; equal positions keep registration order. Default 0. */ + readonly order?: number +} + +/** Where one line annotation sits in a file of a changes view. */ +export interface ForgeLineAnnotation { + /** Identity within its source, stable across updates; it keys the drawn entry. */ + readonly key: string + /** Inclusive 1-based lines on the old (`L`) or new (`R`) side, or `file` for the whole file. */ + readonly place: { readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } | 'file' + /** Digest of the file change it was written on; a file whose `digest` differs shows it in its outdated section. */ + readonly digest?: string + /** Changes whenever the entry should draw again; equal keys and versions keep the drawn entry's props. */ + readonly version: string | number +} + +/** A Client plugin's line annotations, drawn through its `forge.diff.line.annotation` entry. */ +export interface ForgeAnnotationSource { + /** Unique source identity, also the key of its `forge.diff.line.annotation` entry. */ + readonly id: string + /** Position among sources in one stack, lower first; equal positions keep registration order. Default 0. */ + readonly order?: number + /** + * Observe the annotations of one view, by path. The changes view calls it once per view and source registration; + * the source republishes through the same observable whenever the annotations change. + * @param target - the view's Session and source. + * @returns annotations by repository-relative path. + */ + observe(target: ChangesTarget): HostObservable> +} + +/** What the service needs from the right sidebar. */ +export interface ForgeChangesSidebar { + /** Session whose sidebar shows, or undefined without one. */ + readonly mounted: () => SessionId | undefined + /** Open a resource address in the shown Session's sidebar. */ + readonly openResource: (address: string, params: ChangesParams | undefined) => void +} + +/** The position of an ordered entry, 0 without an `order`. */ +function positionOf(entry: { readonly order?: number }): number { + return entry.order ?? 0 +} + +/** Entries kept by identity in registration order, published sorted by `order`. */ +class OrderedEntries implements HostObservable { + private entries: readonly T[] = [] + private readonly listeners = new Set<() => void>() + + constructor(private readonly what: string) {} + + readonly getSnapshot = (): readonly T[] => this.entries + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + return () => { this.listeners.delete(listener) } + } + + add(entry: T): () => void { + if (this.entries.some(item => item.id === entry.id)) throw new Error(`forge-panel: a ${this.what} "${entry.id}" is already registered`) + // A stable sort keeps registration order among equal positions. + this.publish([...this.entries, entry].sort((a, b) => positionOf(a) - positionOf(b))) + return () => { this.publish(this.entries.filter(item => item !== entry)) } + } + + private publish(next: readonly T[]): void { + if (next.length === this.entries.length && next.every((item, index) => item === this.entries[index])) return + this.entries = next + for (const listener of [...this.listeners]) listener() + } +} + +/** + * The changes view's face for other Client plugins. Registrations return their disposer, which the registering plugin + * holds in its own `ctx.effect` so a registration lives exactly as long as that plugin. + */ +export class ForgeChangesService { + /** Titles of Host lenses in display order. */ + readonly lenses: HostObservable + /** Annotation sources in stacking order. */ + readonly annotationSources: HostObservable + private readonly lensEntries = new OrderedEntries('lens description') + private readonly sourceEntries = new OrderedEntries('annotation source') + + /** + * @param sidebar - the right sidebar's open path. + * @param extensions - the Host's registered lenses and annotation limit, or null before the Host reports them. + * @param kinds - tab kinds of the changes view and the change request panel. + */ + constructor( + private readonly sidebar: ForgeChangesSidebar, + readonly extensions: HostObservable, + readonly kinds: { readonly changes: string; readonly panel: string }, + ) { + this.lenses = this.lensEntries + this.annotationSources = this.sourceEntries + } + + /** + * Mint the address of a changes view. + * @param target - Session and source. + * @returns the `dsh-resource://forge-changes/…` address. + */ + address(target: ChangesTarget): string { + return changesAddress(target) + } + + /** + * Read the Session and source back out of a changes address. + * @param address - a resource address. + * @returns the target, or undefined for an address the forge panel did not mint. + */ + parse(address: string): ChangesTarget | undefined { + return parseChangesAddress(address) + } + + /** + * Open or reveal a changes view in the shown Session's right sidebar, scrolled to `params.path` with the lens + * `params.lens` chosen. + * @param target - Session and source; the Session must be the one the sidebar shows. + * @param params - file to scroll to and lens to choose. + * @throws when `target.sessionId` is not the Session the sidebar shows. + */ + open(target: ChangesTarget, params?: ChangesParams): void { + if (this.sidebar.mounted() !== target.sessionId) { + throw new Error(`forge-panel: Session ${target.sessionId} is not the Session the sidebar shows`) + } + this.sidebar.openResource(changesAddress(target), params) + } + + /** + * Describe the title of a Host lens. A lens the Host registers without a description shows its identity. + * @param description - the lens identity, title, and position. + * @returns the disposer that withdraws the description. + * @throws when another description holds the identity. + */ + describeLens(description: ForgeLensDescription): () => void { + return this.lensEntries.add(description) + } + + /** + * Register a line annotation source; its `forge.diff.line.annotation` entry, keyed by `source.id`, draws each one. + * @param source - the source. + * @returns the disposer that withdraws the source and its annotations. + * @throws when another source holds the identity. + */ + registerAnnotations(source: ForgeAnnotationSource): () => void { + return this.sourceEntries.add(source) + } +} diff --git a/packages/experimental/client-ui-forge/src/client/changes-store.ts b/packages/experimental/client-ui-forge/src/client/changes-store.ts index ff05303e7d..d7aff92d0b 100644 --- a/packages/experimental/client-ui-forge/src/client/changes-store.ts +++ b/packages/experimental/client-ui-forge/src/client/changes-store.ts @@ -22,6 +22,8 @@ export interface ChangesTabState { commits: ForgeCommitRange | null /** Review layer whose files show. */ lens: ChangesLens + /** Identity of the Host filter lens that keeps some of the shown files, or null for none. */ + filterLens: string | null /** Whether files of the `test` layer hide from the file tree and the diff. */ hideTests: boolean /** Whether deletions and additions show in two columns. */ @@ -50,6 +52,7 @@ type ChangesActions = { based: (draft: ChangesState, tabId: string, base: ForgeBaseBranch | null) => void committed: (draft: ChangesState, tabId: string, commits: ForgeCommitRange | null) => void lensed: (draft: ChangesState, tabId: string, lens: ChangesLens) => void + filtered: (draft: ChangesState, tabId: string, lens: string | null) => void toggledTests: (draft: ChangesState, tabId: string) => void toggledSplit: (draft: ChangesState, tabId: string) => void toggledWrap: (draft: ChangesState, tabId: string) => void @@ -67,7 +70,7 @@ export function createChangesStore(): EngineStoreHandle { const tab = d.byTab[tabId] if (tab === undefined) { - d.byTab[tabId] = { scope: 'branch', base: null, commits: null, lens: 'all', hideTests: false, split: true, wrap: true, navigated: revision } + d.byTab[tabId] = { + scope: 'branch', base: null, commits: null, lens: 'all', filterLens: null, hideTests: false, split: true, wrap: true, navigated: revision, + } } else tab.navigated = revision }, /** @@ -114,6 +119,13 @@ export function createChangesStore(): EngineStoreHandle { bucket(d, tabId).lens = lens }, + /** + * Choose the Host filter lens that keeps some of the shown files, or none. + * @param d - draft state. + * @param tabId - the tab being drawn. + * @param lens - the lens identity, or null for none. + */ + filtered: (d, tabId: string, lens: string | null) => { bucket(d, tabId).filterLens = lens }, /** * Hide or show the files of the `test` layer; hiding them leaves the `test` lens for every file. * @param d - draft state. diff --git a/packages/experimental/client-ui-forge/src/client/diff-rows.ts b/packages/experimental/client-ui-forge/src/client/diff-rows.ts index 3269793b54..f06984e058 100644 --- a/packages/experimental/client-ui-forge/src/client/diff-rows.ts +++ b/packages/experimental/client-ui-forge/src/client/diff-rows.ts @@ -33,6 +33,10 @@ export type DiffSegment = * `count` is null while the length of the file is unknown. */ | { readonly kind: 'gap'; readonly index: number; readonly count: number | null } + /** Consecutive hunks a filter lens folds, drawn as one row that shows them, with the unchanged lines between them. */ + | { readonly kind: 'folded'; readonly hunks: readonly number[] } + +const NO_FOLDS: ReadonlySet = new Set() /** A line as drawn: without the carriage return of a CRLF line ending. */ function drawn(text: string): string { @@ -142,13 +146,17 @@ function endsNewSide(hunk: ForgeDiffHunk): boolean { * Unchanged lines before a hunk, between hunks, and after the last hunk * collapse into one gap each; an open gap draws its lines from `lines` once * they are known. The lines after the last hunk are unknown until `lines` - * arrives, unless the file is new, deleted, or its last hunk reaches its end. + * arrives, unless the file is new, deleted, or its last hunk reaches its end. Consecutive folded hunks draw as one + * folded segment that takes the unchanged lines between them too. * @param file - one file of a diff. * @param lines - the file's new side, which {@link matchesHunks} accepted, or undefined while it has not been read. * @param open - indexes of the gaps the user expanded. + * @param folded - indexes of the hunks a filter lens folds. * @returns the segments in file order. */ -export function segmentsOf(file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlySet): DiffSegment[] { +export function segmentsOf( + file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlySet, folded: ReadonlySet = NO_FOLDS, +): DiffSegment[] { const segments: DiffSegment[] = [] let rows: DiffRow[] = [] const flush = (): void => { @@ -168,9 +176,18 @@ export function segmentsOf(file: ForgeDiffFile, lines: readonly string[] | undef } let newEnd = 0 let oldEnd = 0 + let run: number[] | null = null for (const [index, hunk] of file.hunks.entries()) { - if (hunk.newStart - 1 > newEnd) gap(index, newEnd + 1, hunk.newStart - 1, hunk.oldStart - hunk.newStart) - rows.push(...hunkRows(hunk)) + if (run !== null && folded.has(index)) run.push(index) + else { + run = null + if (hunk.newStart - 1 > newEnd) gap(index, newEnd + 1, hunk.newStart - 1, hunk.oldStart - hunk.newStart) + if (folded.has(index)) { + flush() + run = [index] + segments.push({ kind: 'folded', hunks: run }) + } else rows.push(...hunkRows(hunk)) + } newEnd = hunk.newStart + hunk.newLines - 1 oldEnd = hunk.oldStart + hunk.oldLines - 1 } diff --git a/packages/experimental/client-ui-forge/src/client/index.ts b/packages/experimental/client-ui-forge/src/client/index.ts index 4e8c0e6fad..bacc765c1a 100644 --- a/packages/experimental/client-ui-forge/src/client/index.ts +++ b/packages/experimental/client-ui-forge/src/client/index.ts @@ -11,6 +11,13 @@ export { inject } from './mount.ts' export type { ForgePanelKey } from './locales.ts' export type { ChangeRequestActions, ChangeRequestCardProps } from './ChangeRequestCard.tsx' export type { ChangesParams, ChangesSource, ChangesTarget } from './changes-address.ts' +export type { + ForgeAnnotationSource, ForgeChangesService, ForgeChangesSidebar, ForgeLensDescription, ForgeLineAnnotation, +} from './changes-service.ts' +export type { + ForgeChangeRequestCardActionsProps, ForgeChangesFileMenuProps, ForgeChangesToolbarProps, ForgeCommentActionsProps, + ForgeLineAnnotationProps, +} from './slots.ts' export type { ChangesTabInjected, ChangesTabProps } from './ChangesTab.tsx' export type { ChangesTabTitleProps } from './ChangesTabTitle.tsx' export type { DiffFileAction, DiffFileProps, DiffFileText } from './DiffFile.tsx' diff --git a/packages/experimental/client-ui-forge/src/client/lens-filter.ts b/packages/experimental/client-ui-forge/src/client/lens-filter.ts new file mode 100644 index 0000000000..fc1c9b0a5d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/lens-filter.ts @@ -0,0 +1,122 @@ +/** A changes view's filter lens: the request to the Host, its progress and result, and which hunks it folds. */ + +import { useEffect, useState } from 'react' +import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' +import type { ForgeDiffHunk, ForgeLensFrame, ForgeLensKeep, ForgeLensRequest, ForgeLineRange } from '../types.ts' +import type { HostStream } from './source.ts' + +/** Where a lens request stands for the shown files. */ +export type LensRun = + /** No lens is chosen, or the files have not loaded. */ + | { readonly kind: 'idle' } + /** The lens runs; `done` and `total` are null before it reports progress. */ + | { readonly kind: 'running'; readonly done: number | null; readonly total: number | null } + /** The files the lens keeps, by path. */ + | { readonly kind: 'ready'; readonly files: Readonly> } + /** + * The request failed with a Remote error code and message, or with `forgePanel/lens-interrupted` and no message when the + * stream ended without a result, as after a lost connection. + */ + | { readonly kind: 'failed'; readonly code: string; readonly message: string } + +/** What a view knows when it asks for a lens. */ +export interface LensRunInput { + /** Whether the view is visible; a hidden view starts no request. */ + readonly visible: boolean + /** Identity of the chosen lens, or null for none. */ + readonly lens: string | null + /** The source of the shown files, or null before they load. */ + readonly source: ForgeLensRequest['source'] | null + /** `lensVersion` of the shown files, or null before they load. */ + readonly version: string | null + /** Changes on each retry. */ + readonly attempt: number + /** Open the Host's lens stream. */ + readonly open: (request: ForgeLensRequest, signal: AbortSignal) => HostStream +} + +/** The run of the chosen lens and the results already known for the shown files, by lens identity. */ +export interface LensRunState { + readonly run: LensRun + readonly results: LensResults +} + +const IDLE: LensRun = { kind: 'idle' } + +/** The files each lens keeps, by lens identity. */ +type LensResults = ReadonlyMap>> + +const NO_RESULTS: LensResults = new Map() + +/** + * Ask the Host for the chosen lens whenever the shown files, the lens, or the attempt change, keeping the results of + * every lens asked for the same files. A view that becomes hidden stops its request; a result already known is not + * asked for again. + * @param input - the view's lens, files, and stream opener. + * @returns the run and the known results. + */ +export function useLensRun(input: LensRunInput): LensRunState { + const { visible, lens, source, version, attempt, open } = input + const [kept, setKept] = useState<{ readonly version: string | null; readonly files: LensResults }>({ version: null, files: new Map() }) + const results = kept.version === version ? kept.files : NO_RESULTS + const [run, setRun] = useState<{ readonly key: string; readonly run: LensRun } | null>(null) + const key = lens === null || version === null ? null : `${version}\u0000${lens}\u0000${attempt}` + const known = lens === null ? undefined : results.get(lens) + useEffect(() => { + if (!visible || key === null || lens === null || source === null || version === null || known !== undefined) return + const controller = new AbortController() + const stream = open({ source, version, lens }, controller.signal) + setRun({ key, run: { kind: 'running', done: null, total: null } }) + void (async () => { + try { + for await (const frame of stream) { + if (controller.signal.aborted) return + if (frame.kind === 'progress') { + setRun({ key, run: { kind: 'running', done: frame.done, total: frame.total } }) + continue + } + setKept(previous => ({ + version, files: new Map(previous.version === version ? previous.files : []).set(lens, frame.files), + })) + return + } + if (!controller.signal.aborted) setRun({ key, run: { kind: 'failed', code: 'forgePanel/lens-interrupted', message: '' } }) + } catch (error) { + if (controller.signal.aborted) return + const failure = remoteErrorOf(error) + setRun({ key, run: { + kind: 'failed', code: failure?.code ?? 'forgePanel/lens-failed', + message: failure?.message ?? (error instanceof Error ? error.message : String(error)), + } }) + } + })() + return () => { + controller.abort() + stream.dispose() + } + }, [visible, key, lens, source, version, known, open]) + const shown: LensRun = key === null ? IDLE : known !== undefined ? { kind: 'ready', files: known } : run?.key === key ? run.run : IDLE + return { run: shown, results } +} + +/** Whether a hunk's lines on one side meet any of the ranges. */ +function meets(start: number, count: number, ranges: readonly ForgeLineRange[]): boolean { + const end = start + count - 1 + return count > 0 && ranges.some(range => range.start <= end && range.end >= start) +} + +/** + * The hunks of a kept file that touch none of the lens's lines on either side. + * @param hunks - the file's hunks. + * @param keep - what the lens keeps of the file. + * @returns the indexes of the hunks to fold, empty when the lens names no lines. + */ +export function foldedHunks(hunks: readonly ForgeDiffHunk[], keep: ForgeLensKeep): ReadonlySet { + const ranges = keep.ranges + if (ranges === undefined) return new Set() + const folded = new Set() + for (const [index, hunk] of hunks.entries()) { + if (!meets(hunk.oldStart, hunk.oldLines, ranges.old) && !meets(hunk.newStart, hunk.newLines, ranges.new)) folded.add(index) + } + return folded +} diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index bb31556a50..837f6568a1 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -233,6 +233,21 @@ export const zh = { 'lens.testHidden': '测试文件已隐藏', 'lens.menuAria': '分层透镜:{lens}', 'lens.empty': '没有要显示的文件', + 'filterLens.label': '透镜', + 'filterLens.aria': '筛选透镜', + 'filterLens.chosenAria': '筛选透镜:{lens}', + 'filterLens.heading': '筛选透镜', + 'filterLens.none': '不使用透镜', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': '清除透镜', + 'filterLens.failed': '透镜「{lens}」没有完成:{message}', + 'filterLens.stale': '变更已重新读取,刷新后再按「{lens}」筛选', + 'filterLens.removed': '透镜「{lens}」已移除', + 'filterLens.interrupted': '透镜「{lens}」的请求中断了', + 'filterLens.folded': '另有 {count} 处与「{lens}」无关的改动已折叠', + 'filterLens.unfold': '展开', + 'annotation.outdated': '写在较早改动上的注解 · {count}', + 'annotation.hidden': '此文件另有 {count} 条注解未显示', 'tests.hide': '隐藏测试文件', 'tests.hideHint': '不显示测试、快照、本地化文件、锁文件和生成的文件', 'viewed.label': '已审阅', @@ -665,6 +680,21 @@ export const en: Record = { 'lens.testHidden': 'Test files are hidden', 'lens.menuAria': 'Review layer: {lens}', 'lens.empty': 'No files to show', + 'filterLens.label': 'Lens', + 'filterLens.aria': 'Filter lens', + 'filterLens.chosenAria': 'Filter lens: {lens}', + 'filterLens.heading': 'Filter lenses', + 'filterLens.none': 'No lens', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Clear lens', + 'filterLens.failed': 'The lens “{lens}” did not finish: {message}', + 'filterLens.stale': 'The changes were read again; refresh to filter them by “{lens}”', + 'filterLens.removed': 'The lens “{lens}” was removed', + 'filterLens.interrupted': 'The lens “{lens}” stopped before it finished', + 'filterLens.folded': '{count} changes unrelated to “{lens}” folded', + 'filterLens.unfold': 'Show', + 'annotation.outdated': 'Annotations on an earlier change · {count}', + 'annotation.hidden': '{count} more annotations in this file are not shown', 'tests.hide': 'Hide test files', 'tests.hideHint': 'Hides tests, snapshots, locale files, lockfiles, and generated files', 'viewed.label': 'Viewed', @@ -1101,6 +1131,21 @@ export const ja: Record = { 'lens.testHidden': 'テストファイルは非表示です', 'lens.menuAria': 'レビューレイヤー:{lens}', 'lens.empty': '表示するファイルはありません', + 'filterLens.label': 'レンズ', + 'filterLens.aria': 'フィルターレンズ', + 'filterLens.chosenAria': 'フィルターレンズ: {lens}', + 'filterLens.heading': 'フィルターレンズ', + 'filterLens.none': 'レンズなし', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'レンズを解除', + 'filterLens.failed': 'レンズ「{lens}」が完了しませんでした: {message}', + 'filterLens.stale': '変更が再読み込みされました。更新してから「{lens}」で絞り込んでください', + 'filterLens.removed': 'レンズ「{lens}」は削除されました', + 'filterLens.interrupted': 'レンズ「{lens}」の要求が中断されました', + 'filterLens.folded': '「{lens}」に関係しない {count} 件の変更を折りたたみました', + 'filterLens.unfold': '表示', + 'annotation.outdated': '以前の変更への注釈 · {count}', + 'annotation.hidden': 'このファイルには表示されていない注釈がさらに {count} 件あります', 'tests.hide': 'テストファイルを非表示', 'tests.hideHint': 'テスト、スナップショット、ロケールファイル、ロックファイル、生成ファイルを表示しません', 'viewed.label': '確認済み', @@ -1530,6 +1575,21 @@ export const es: Record = { 'lens.testHidden': 'Los archivos de prueba están ocultos', 'lens.menuAria': 'Capa de revisión: {lens}', 'lens.empty': 'No hay archivos que mostrar', + 'filterLens.label': 'Lente', + 'filterLens.aria': 'Lente de filtro', + 'filterLens.chosenAria': 'Lente de filtro: {lens}', + 'filterLens.heading': 'Lentes de filtro', + 'filterLens.none': 'Sin lente', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Quitar lente', + 'filterLens.failed': 'La lente «{lens}» no terminó: {message}', + 'filterLens.stale': 'Los cambios se volvieron a leer; actualiza para filtrarlos por «{lens}»', + 'filterLens.removed': 'Se quitó la lente «{lens}»', + 'filterLens.interrupted': 'La lente «{lens}» se interrumpió antes de terminar', + 'filterLens.folded': '{count} cambios no relacionados con «{lens}» plegados', + 'filterLens.unfold': 'Mostrar', + 'annotation.outdated': 'Anotaciones sobre un cambio anterior · {count}', + 'annotation.hidden': 'Este archivo tiene {count} anotaciones más que no se muestran', 'tests.hide': 'Ocultar archivos de prueba', 'tests.hideHint': 'Oculta pruebas, instantáneas, archivos de idioma, archivos de bloqueo y archivos generados', 'viewed.label': 'Revisado', @@ -1959,6 +2019,21 @@ export const fr: Record = { 'lens.testHidden': 'Les fichiers de test sont masqués', 'lens.menuAria': 'Couche de revue : {lens}', 'lens.empty': 'Aucun fichier à afficher', + 'filterLens.label': 'Lentille', + 'filterLens.aria': 'Lentille de filtre', + 'filterLens.chosenAria': 'Lentille de filtre : {lens}', + 'filterLens.heading': 'Lentilles de filtre', + 'filterLens.none': 'Aucune lentille', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Retirer la lentille', + 'filterLens.failed': 'La lentille « {lens} » n’a pas abouti : {message}', + 'filterLens.stale': 'Les modifications ont été relues ; actualisez pour les filtrer par « {lens} »', + 'filterLens.removed': 'La lentille « {lens} » a été retirée', + 'filterLens.interrupted': 'La lentille « {lens} » s’est interrompue avant de finir', + 'filterLens.folded': '{count} modifications sans rapport avec « {lens} » repliées', + 'filterLens.unfold': 'Afficher', + 'annotation.outdated': 'Annotations sur une modification antérieure · {count}', + 'annotation.hidden': '{count} autres annotations de ce fichier ne sont pas affichées', 'tests.hide': 'Masquer les fichiers de test', 'tests.hideHint': 'Masque les tests, instantanés, fichiers de langue, fichiers de verrouillage et fichiers générés', 'viewed.label': 'Vu', @@ -2388,6 +2463,21 @@ export const de: Record = { 'lens.testHidden': 'Testdateien sind ausgeblendet', 'lens.menuAria': 'Prüfebene: {lens}', 'lens.empty': 'Keine Dateien anzuzeigen', + 'filterLens.label': 'Linse', + 'filterLens.aria': 'Filterlinse', + 'filterLens.chosenAria': 'Filterlinse: {lens}', + 'filterLens.heading': 'Filterlinsen', + 'filterLens.none': 'Keine Linse', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Linse entfernen', + 'filterLens.failed': 'Die Linse „{lens}“ wurde nicht fertig: {message}', + 'filterLens.stale': 'Die Änderungen wurden neu gelesen; aktualisieren, um nach „{lens}“ zu filtern', + 'filterLens.removed': 'Die Linse „{lens}“ wurde entfernt', + 'filterLens.interrupted': 'Die Linse „{lens}“ wurde vor dem Ende unterbrochen', + 'filterLens.folded': '{count} Änderungen ohne Bezug zu „{lens}“ eingeklappt', + 'filterLens.unfold': 'Anzeigen', + 'annotation.outdated': 'Anmerkungen zu einer früheren Änderung · {count}', + 'annotation.hidden': '{count} weitere Anmerkungen dieser Datei werden nicht angezeigt', 'tests.hide': 'Testdateien ausblenden', 'tests.hideHint': 'Blendet Tests, Snapshots, Sprachdateien, Lockfiles und generierte Dateien aus', 'viewed.label': 'Angesehen', @@ -2817,6 +2907,21 @@ export const ru: Record = { 'lens.testHidden': 'Тестовые файлы скрыты', 'lens.menuAria': 'Слой проверки: {lens}', 'lens.empty': 'Нет файлов для показа', + 'filterLens.label': 'Линза', + 'filterLens.aria': 'Линза-фильтр', + 'filterLens.chosenAria': 'Линза-фильтр: {lens}', + 'filterLens.heading': 'Линзы-фильтры', + 'filterLens.none': 'Без линзы', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Убрать линзу', + 'filterLens.failed': 'Линза «{lens}» не завершилась: {message}', + 'filterLens.stale': 'Изменения прочитаны заново; обновите, чтобы отфильтровать их по «{lens}»', + 'filterLens.removed': 'Линза «{lens}» удалена', + 'filterLens.interrupted': 'Линза «{lens}» прервалась, не завершившись', + 'filterLens.folded': 'Свёрнуто изменений, не связанных с «{lens}»: {count}', + 'filterLens.unfold': 'Показать', + 'annotation.outdated': 'Заметки к более раннему изменению · {count}', + 'annotation.hidden': 'Ещё заметок в этом файле не показано: {count}', 'tests.hide': 'Скрыть тестовые файлы', 'tests.hideHint': 'Скрывает тесты, снимки, файлы локализации, lock-файлы и сгенерированные файлы', 'viewed.label': 'Просмотрено', @@ -3246,6 +3351,21 @@ export const pt: Record = { 'lens.testHidden': 'Os arquivos de teste estão ocultos', 'lens.menuAria': 'Camada de revisão: {lens}', 'lens.empty': 'Nenhum arquivo para mostrar', + 'filterLens.label': 'Lente', + 'filterLens.aria': 'Lente de filtro', + 'filterLens.chosenAria': 'Lente de filtro: {lens}', + 'filterLens.heading': 'Lentes de filtro', + 'filterLens.none': 'Nenhuma lente', + 'filterLens.progress': '{done}/{total}', + 'filterLens.clear': 'Remover lente', + 'filterLens.failed': 'A lente “{lens}” não terminou: {message}', + 'filterLens.stale': 'As alterações foram lidas de novo; atualize para filtrá-las por “{lens}”', + 'filterLens.removed': 'A lente “{lens}” foi removida', + 'filterLens.interrupted': 'A lente “{lens}” parou antes de terminar', + 'filterLens.folded': '{count} alterações sem relação com “{lens}” recolhidas', + 'filterLens.unfold': 'Mostrar', + 'annotation.outdated': 'Anotações em uma alteração anterior · {count}', + 'annotation.hidden': 'Mais {count} anotações deste arquivo não são mostradas', 'tests.hide': 'Ocultar arquivos de teste', 'tests.hideHint': 'Oculta testes, snapshots, arquivos de idioma, arquivos de bloqueio e arquivos gerados', 'viewed.label': 'Revisado', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index d9304ea46a..84e4cc70ee 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -17,13 +17,18 @@ import type {} from '@deepseek-ai/dsh-experimental-client-ui-forge/remote' import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' -import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgePanelChangeRequest } from '../types.ts' +import type { + ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgePanelChangeRequest, +} from '../types.ts' +import { AnnotationView } from './annotations.ts' +import { ForgeChangesService } from './changes-service.ts' +import type {} from './slots.ts' import { ReviewQueue } from './review-queue.ts' import { ViewedFiles } from './viewed-files.ts' import { formatReviewComment, reviewQuoteSummary, type ReviewSelection } from './review.ts' import { formatThreadQuote, threadQuoteSummary } from './review-threads.ts' import { ActionToast } from './ActionToast.tsx' -import { CHANGES_ID, changesDefinition } from './changes-address.ts' +import { CHANGES_ID, CHANGES_KIND, changesDefinition, parseChangesAddress } from './changes-address.ts' import { createChangesStore } from './changes-store.ts' import { ChangesTab, type ChangesTabInjected } from './ChangesTab.tsx' import { ChangesTabTitle } from './ChangesTabTitle.tsx' @@ -72,6 +77,8 @@ interface SessionStores { readonly visibility: VisibilitySource readonly reviews: WeakMap readonly viewed: ViewedFiles + /** Plugin annotations of each changes view of the Session, by address. */ + readonly annotations: Map readonly release: () => void } @@ -116,13 +123,38 @@ function registerUi(ctx: Context): void { stores.delete(sessionId) }, 'forge-panel: release Session state') store = { - panel, visibility: createVisibilitySource(), reviews: new WeakMap(), viewed: new ViewedFiles(sessionId), + panel, visibility: createVisibilitySource(), reviews: new WeakMap(), viewed: new ViewedFiles(sessionId), annotations: new Map(), release: () => { void dispose() }, } stores.set(sessionId, store) } return store } + // The Host's lenses and annotation limit, streamed while any view reads them. + const extensionSource = createStreamSource({ + open: signal => ctx.remote.forgePanel.extensions(signal), + subscribeReset: listener => ctx.on('connection/reset', listener), + }, null, (_previous, frame) => frame) + ctx.effect(() => () => { extensionSource.close() }, 'forge-panel: extension stream') + const changes = new ForgeChangesService({ + mounted: () => ctx.sidebarRight.mounted.getSnapshot(), + openResource: (address, params) => { ctx.sidebarRight.openResource(address, params === undefined ? undefined : { params }) }, + }, { + getSnapshot: () => extensionSource.observable.getSnapshot().state, + subscribe: listener => extensionSource.observable.subscribe(listener), + }, { changes: CHANGES_KIND, panel: TAB_KIND }) + const withdrawChanges = ctx.reflect.provide('forgeChanges', changes) + ctx.effect(() => () => { void withdrawChanges() }, 'forge-panel: changes view face') + const annotationsOf = (store: SessionStores, address: string): AnnotationView => { + let view = store.annotations.get(address) + if (view === undefined) { + const target = parseChangesAddress(address) + if (target === undefined) throw new Error(`forge-panel: not a changes address "${address}"`) + view = new AnnotationView(changes.annotationSources, target) + store.annotations.set(address, view) + } + return view + } const settled = (result: RemoteResult, failure: ForgePanelKey, codes: Partial> = {}): boolean => { if (result.ok) return true notices.report(codes[result.error.code] ?? failure) @@ -271,7 +303,12 @@ function registerUi(ctx: Context): void { const changesFace = (sessionId: SessionId): ChangesTabInjected => { const store = storesOf(sessionId) return { - keyedHooks: { panel: visibility => visibility === 'visible' ? store.panel.hooks.panel : undefined }, + keyedHooks: { + panel: visibility => visibility === 'visible' ? store.panel.hooks.panel : undefined, + annotations: address => annotationsOf(store, address), + }, + hooks: { lenses: changes.lenses, extensions: extensionSource.observable }, + changesLens: (request, signal) => ctx.remote.forgePanel.changesLens(sessionId, request, signal), reconnect: store.panel.reconnect, localDiff: (scope, signal) => ctx.remote.forgePanel.localDiff(sessionId, scope, signal), diffBases: (query, signal) => ctx.remote.forgePanel.diffBases(sessionId, query, signal), @@ -356,6 +393,7 @@ function registerUi(ctx: Context): void { }), 'forge-panel: sidebar tab') ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID, locale: NS, inject: tabFace, + children: { 'forge.change-request.card.actions': { kind: 'list', scope: 'session' } }, }, ForgeTab)) ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID, locale: NS, @@ -363,6 +401,12 @@ function registerUi(ctx: Context): void { ctx.effect(() => ctx.sidebarRightTabs.register(changesDefinition(t)), 'forge-panel: changes tab') ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: CHANGES_ID, locale: NS, store: createChangesStore(), inject: changesFace, + children: { + 'forge.changes.toolbar': { kind: 'list', scope: 'session' }, + 'forge.changes.file.menu': { kind: 'list', scope: 'session' }, + 'forge.diff.line.annotation': { kind: 'keyed', scope: 'session' }, + 'forge.diff.comment.actions': { kind: 'list', scope: 'session' }, + }, }, ChangesTab)) ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: CHANGES_ID, locale: NS, diff --git a/packages/experimental/client-ui-forge/src/client/slots.ts b/packages/experimental/client-ui-forge/src/client/slots.ts new file mode 100644 index 0000000000..724463b03e --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/slots.ts @@ -0,0 +1,81 @@ +/** The forge panel's extension slots and the props their owners pass. */ + +import type { ChangeRequestRef, ChangeRequestState } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeLensFile } from '../types.ts' +import type { ChangesTarget } from './changes-address.ts' +import type { ForgeLineAnnotation } from './changes-service.ts' + +/** Owner props of `forge.changes.toolbar`. */ +export interface ForgeChangesToolbarProps { + /** The view the toolbar belongs to. */ + readonly target: ChangesTarget + /** `bar`: a 28px tool in the toolbar row; `menu`: `MenuItemButton` rows of the More menu a narrow toolbar folds entries into. */ + readonly form: 'bar' | 'menu' + /** Close the More menu after a row acted; a no-op in the toolbar row. */ + readonly close: () => void +} + +/** Owner props of `forge.changes.file.menu`. */ +export interface ForgeChangesFileMenuProps { + /** The view the file belongs to. */ + readonly target: ChangesTarget + /** The file whose menu opened. */ + readonly file: ForgeLensFile + /** Close the menu after a row acted. */ + readonly dismiss: () => void +} + +/** Owner props of `forge.diff.line.annotation`. */ +export interface ForgeLineAnnotationProps { + /** The view the annotation shows in. */ + readonly target: ChangesTarget + /** Repository-relative path of the annotated file. */ + readonly path: string + /** The annotation its source reported. */ + readonly annotation: ForgeLineAnnotation +} + +/** Owner props of `forge.diff.comment.actions`. */ +export interface ForgeCommentActionsProps { + /** The view the comment form belongs to. */ + readonly target: ChangesTarget + /** The lines the comment is on. */ + readonly selection: { readonly path: string; readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } + /** Whether the comment has no text, so actions stay disabled. */ + readonly empty: boolean + /** Whether a send runs, so actions stay disabled. */ + readonly busy: boolean + /** + * Hand the comment's text to `deliver`. The form shows itself busy until `deliver` settles, closes when it resolves + * to undefined, and keeps the text with the message it resolves to otherwise. + * @param deliver - receives the text. + */ + readonly send: (deliver: (body: string) => Promise) => void +} + +/** Owner props of `forge.change-request.card.actions`. */ +export interface ForgeChangeRequestCardActionsProps { + /** Binding URL of the change request. */ + readonly url: string + /** Parsed reference, or null when no provider serves the URL. */ + readonly ref: ChangeRequestRef | null + /** Head commit of the latest status, or null before one. */ + readonly headSha: string | null + /** Lifecycle state of the latest status, or null before one. */ + readonly state: ChangeRequestState | null +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** Tools a plugin adds to the changes toolbar, after its flexible space and before the thread list toggle. */ + 'forge.changes.toolbar': { kind: 'list'; scope: 'session'; owner: ForgeChangesToolbarProps } + /** Rows a plugin adds to a file's menu, below the built-in rows. */ + 'forge.changes.file.menu': { kind: 'list'; scope: 'session'; owner: ForgeChangesFileMenuProps } + /** The content of one line annotation, keyed by its source; the changes view draws the frame around it. */ + 'forge.diff.line.annotation': { kind: 'keyed'; scope: 'session'; owner: ForgeLineAnnotationProps } + /** Buttons a plugin adds to the line comment form, between Add to input and the code host actions. */ + 'forge.diff.comment.actions': { kind: 'list'; scope: 'session'; owner: ForgeCommentActionsProps } + /** Icon buttons a plugin adds to a change request card's head, before Open in browser. */ + 'forge.change-request.card.actions': { kind: 'list'; scope: 'session'; owner: ForgeChangeRequestCardActionsProps } + } +} diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 3a8fdc4ca5..83b1019c3b 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -1185,7 +1185,7 @@ export class ForgePanelController extends TypertRemoteService { const read = await this.commitFiles(ref, commits, signal) files = read.files newCommit = commits.to - oldCommit = async () => read.parent + oldCommit = () => Promise.resolve(read.parent) } return { key: JSON.stringify(['change', changeRequestKey(ref), newCommit, commits]), diff --git a/packages/experimental/client-ui-forge/src/lenses.ts b/packages/experimental/client-ui-forge/src/lenses.ts index fc2406182b..86977a6532 100644 --- a/packages/experimental/client-ui-forge/src/lenses.ts +++ b/packages/experimental/client-ui-forge/src/lenses.ts @@ -177,7 +177,7 @@ export async function runLens( progress: (done, total) => { if (!operation.aborted) progress(done, total) }, } const stopped = new Promise((_resolve, reject) => { - operation.addEventListener('abort', () => { reject(operation.reason) }, { once: true }) + operation.addEventListener('abort', () => { reject(new Error('the lens run stopped', { cause: operation.reason })) }, { once: true }) }) // The race observes `stopped`; this handler only keeps a later abort from rejecting unobserved. void stopped.catch(() => undefined) @@ -212,21 +212,22 @@ export async function* lensFrames( run: (progress: (done: number, total: number) => void) => Promise, ): AsyncIterable { // A box, so the reads below see what the progress callback writes. - const reports: { latest: { readonly done: number; readonly total: number } | null } = { latest: null } + const reports: { latest: { readonly done: number; readonly total: number } | null; finished: boolean } = { latest: null, finished: false } + // A function, so each check reads what the settlement wrote rather than the value the loop condition narrowed. + const finished = (): boolean => reports.finished let wake = Promise.withResolvers() - let finished = false const outcome = run((done, total) => { reports.latest = { done, total } wake.resolve() }) - const settled = outcome.then(() => { finished = true }, () => { finished = true }) - while (!finished) { + const settled = outcome.then(() => { reports.finished = true }, () => { reports.finished = true }) + while (!finished()) { const current = wake await Promise.race([current.promise, settled]) wake = Promise.withResolvers() const reported = reports.latest reports.latest = null - if (reported !== null && !finished) yield { kind: 'progress', done: reported.done, total: reported.total } + if (reported !== null && !finished()) yield { kind: 'progress', done: reported.done, total: reported.total } } yield { kind: 'result', files: await outcome } } diff --git a/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts b/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts index 5fda643a3f..ca192f0054 100644 --- a/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts @@ -60,7 +60,7 @@ describe('createChangesStore', () => { const store = createChangesStore().create() store.actions.navigated('tab-1', 1) expect(store.getSnapshot().byTab['tab-1']).toEqual({ - scope: 'branch', base: null, commits: null, lens: 'all', hideTests: false, split: true, wrap: true, navigated: 1, + scope: 'branch', base: null, commits: null, lens: 'all', filterLens: null, hideTests: false, split: true, wrap: true, navigated: 1, }) store.actions.scoped('tab-1', 'staged') store.actions.based('tab-1', { ref: 'refs/heads/topic', name: 'topic' }) @@ -68,10 +68,11 @@ describe('createChangesStore', () => { store.actions.toggledWrap('tab-1') store.actions.lensed('tab-1', 'interface') store.actions.toggledTests('tab-1') + store.actions.filtered('tab-1', 'fixture/exports') store.actions.navigated('tab-1', 2) expect(store.getSnapshot().byTab['tab-1']).toEqual({ - scope: 'staged', base: { ref: 'refs/heads/topic', name: 'topic' }, commits: null, lens: 'interface', hideTests: true, - split: false, wrap: false, navigated: 2, + scope: 'staged', base: { ref: 'refs/heads/topic', name: 'topic' }, commits: null, lens: 'interface', filterLens: 'fixture/exports', + hideTests: true, split: false, wrap: false, navigated: 2, }) store.actions.navigated('tab-2', 1) store.actions.forget('tab-1') diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 495ca88e83..4060435496 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -18,11 +18,16 @@ import { ViewedFiles } from '../src/client/viewed-files.ts' import { createChangesStore } from '../src/client/changes-store.ts' import { ChangesTab, type ChangesTabInjected, type ChangesTabProps } from '../src/client/ChangesTab.tsx' import { en, zh } from '../src/client/locales.ts' -import type { PanelSnapshot } from '../src/client/source.ts' +import type { HostStream, PanelSnapshot, StreamSnapshot } from '../src/client/source.ts' +import type { ForgeLensDescription } from '../src/client/changes-service.ts' +import type { ViewAnnotations } from '../src/client/annotations.ts' +import type { ForgeChangesToolbarProps } from '../src/client/slots.ts' +import { lensVersion } from '../src/lens-version.ts' import css from '../src/client/ChangesTab.module.css' import baseCss from '../src/client/BaseMenu.module.css' import type { - ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelChangeRequest, ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeExtensionState, ForgeLensId, ForgeLocalDiff, + ForgePanelChangeRequest, ForgePanelState, } from '../src/types.ts' import type { ChangeRequestKey, ForgeCommitList, ForgeReviewData, ForgeReviewId, ForgeReviewThread, ForgeReviewWriteResult, ForgeThreadId, @@ -186,12 +191,23 @@ function hookOf(instance: { subscribe: (listener: () => void) => () => void; } } +/** A Host stream that yields `frames`, then fails with `failure` when one is given. */ +function hostStream(frames: readonly F[], failure?: unknown): HostStream { + return { + dispose: vi.fn(), + async *[Symbol.asyncIterator]() { + for (const frame of frames) yield frame + if (failure !== undefined) throw failure + }, + } +} + /** Let the Remote reads the view awaits settle. */ async function settle(): Promise { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) }) } -type Faces = { -readonly [K in Exclude]: ReturnType> } +type Faces = { -readonly [K in Exclude]: ReturnType> } interface MountOptions { readonly translate?: typeof t @@ -204,6 +220,19 @@ interface MountOptions { readonly setup?: (faces: Faces) => void /** Viewed marks; each mount otherwise reads the Session's marks from browser storage. */ readonly viewedFiles?: ViewedFiles + /** The Host's lenses and annotation limit; null stands for facts not reported yet. */ + readonly extensions?: ForgeExtensionState | null + /** Lens titles Client plugins describe. */ + readonly lenses?: readonly ForgeLensDescription[] + /** Plugin annotations of the view by path, or null while the renderer has no source for the view. */ + readonly annotations?: ViewAnnotations | null +} + +/** One plugin slot the view drew: its name, the owner props, and the dispatch options. */ +interface SlotCall { + readonly key: string + readonly owner: unknown + readonly options: unknown } function mount(options: MountOptions = {}) { @@ -270,8 +299,27 @@ function mount(options: MountOptions = {}) { changeRequestReviewWrite: vi.fn(async () => ok({ ok: true })), createChangeRequest: vi.fn(), report: vi.fn(), + changesLens: vi.fn(() => hostStream([])), } options.setup?.(faces) + const extensions = createSnapshotStore>({ + state: options.extensions === undefined ? { lenses: [], maxAnnotationsPerFile: 100 } : options.extensions, disconnected: false, + }) + const lenses = createSnapshotStore(options.lenses ?? []) + const annotations = createSnapshotStore( + options.annotations === null ? undefined : options.annotations ?? new Map()) + const useAnnotationsOf = bindSnapshotSelector(annotations) + function useAnnotations(key: string): ViewAnnotations | undefined + function useAnnotations(key: string, select: (value: ViewAnnotations | undefined) => S): S + function useAnnotations(_key: string, select?: (value: ViewAnnotations | undefined) => S): S | ViewAnnotations | undefined { + return select === undefined ? useAnnotationsOf(value => value) : useAnnotationsOf(select) + } + const slotCalls: SlotCall[] = [] + // Records each plugin slot the view draws and draws nothing for it. + const renderSlot = ((key: string, owner: unknown, slotOptions?: unknown) => { + slotCalls.push({ key, owner, options: slotOptions }) + return null + }) as ChangesTabProps['renderSlot'] const viewedFiles = options.viewedFiles ?? new ViewedFiles(SESSION) const props: ChangesTabProps = { useTabInfo: () => ({ @@ -286,6 +334,10 @@ function mount(options: MountOptions = {}) { useStore: hookOf(store), actions: store.actions, usePanel, + useExtensions: bindSnapshotSelector(extensions), + useLenses: bindSnapshotSelector(lenses), + useAnnotations, + renderSlot, ...faces, viewedFiles, t: options.translate ?? t, @@ -298,7 +350,10 @@ function mount(options: MountOptions = {}) { return element } const paths = (): (string | null)[] => [...view.container.querySelectorAll('[data-forge-diff-file]')].map(element => element.getAttribute('data-forge-diff-file')) - return { view, panel, visibility, stops, navigation, store, aborter, tabActions, unbind, faces, viewedFiles, section, paths } + return { + view, panel, visibility, stops, navigation, store, aborter, tabActions, unbind, faces, viewedFiles, section, paths, extensions, lenses, + annotations, slotCalls, + } } /** Visible texts of the rows a section draws, in order. */ @@ -2477,3 +2532,121 @@ describe('ChangesTab review threads', () => { expect(card(m, 'on-row')).toBeNull() }) }) + +describe('ChangesTab extensions', () => { + const EXPORTS = 'fixture/exports' + const KEPT = { 'src/app.ts': { ranges: { old: [], new: [{ start: 3, end: 3 }] } }, 'src/new.ts': {}, 'docs/gone.txt': { ranges: { old: [], new: [] } } } + const describedLenses: readonly ForgeLensDescription[] = [{ id: EXPORTS as ForgeLensId, title: () => 'Exports' }] + const hosted: ForgeExtensionState = { lenses: ['lint/unused', EXPORTS], maxAnnotationsPerFile: 5 } + + it('offers the Host lenses by their descriptions and filters the files to those a chosen lens keeps, folding the hunks it is not about', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, setup: (faces) => { + faces.changesLens.mockReturnValueOnce(hostStream([{ kind: 'progress', done: 1, total: 6 }, { kind: 'result', files: KEPT }])) + } }) + await settle() + const trigger = m.view.getByRole('button', { name: 'Filter lens' }) + act(() => { trigger.click() }) + expect(within(document.body).getAllByRole('menuitem').map(row => row.textContent)).toEqual(['No lens', 'Exports—', 'lint/unused—']) + act(() => { within(document.body).getByRole('menuitem', { name: 'Exports—' }).click() }) + await settle() + expect(m.faces.changesLens.mock.calls[0]?.[0]).toEqual({ + source: { kind: 'local', scope: { kind: 'branch', base: null, commits: null } }, version: lensVersion(LOCAL.files), lens: EXPORTS, + }) + expect(m.paths()).toEqual(['docs/gone.txt', 'src/app.ts', 'src/new.ts']) + const chosen = m.view.getByRole('button', { name: 'Filter lens: Exports' }) + expect(chosen.textContent).toBe('Exports3') + expect(chosen.closest(`.${css.lensSlot}`)).not.toBeNull() + expect(m.view.getByRole('radiogroup', { name: 'Review layer' }).textContent).toBe('All3Interface0Implementation3Tests0') + const fold = m.section('src/app.ts').querySelector('[data-forge-lens-fold]') + expect(fold?.textContent).toBe('1 changes unrelated to “Exports” foldedShow') + act(() => { fold?.click() }) + expect(m.section('src/app.ts').querySelector('[data-forge-lens-fold]')).toBeNull() + expect(m.section('src/app.ts').querySelector('[data-old-line="11"]')).not.toBeNull() + act(() => { m.section('docs/gone.txt').querySelector('[data-forge-lens-fold]')?.click() }) + expect(m.section('docs/gone.txt').querySelector('[data-old-line="1"]')).not.toBeNull() + + act(() => { chosen.click() }) + act(() => { within(document.body).getByRole('menuitem', { name: 'No lens' }).click() }) + expect(m.paths()).toHaveLength(6) + expect(m.faces.changesLens).toHaveBeenCalledTimes(1) + }) + + it('chooses the lens a navigation names, and stops filtering with a notice once the Host withdraws it', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, params: { lens: EXPORTS }, setup: (faces) => { + faces.changesLens.mockReturnValue(hostStream([{ kind: 'result', files: KEPT }])) + } }) + await settle() + expect(m.paths()).toEqual(['docs/gone.txt', 'src/app.ts', 'src/new.ts']) + act(() => { m.extensions.set({ state: { ...hosted, lenses: ['lint/unused'] }, disconnected: false }) }) + expect(m.paths()).toHaveLength(6) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBeNull() + expect(m.faces.report).toHaveBeenCalledWith('filterLens.removed', { lens: 'Exports' }) + }) + + it('reports a failed lens with a retry and a clear, and a lens refused for files read again with a refresh', async () => { + const m = mount({ extensions: hosted, lenses: describedLenses, params: { lens: EXPORTS }, setup: (faces) => { + faces.changesLens + .mockReturnValueOnce(hostStream([], new RemoteError('forgePanel/lens-failed', 'the lens failed: parser crashed', {}))) + .mockReturnValueOnce(hostStream([], new RemoteError('forgePanel/lens-stale', 'read again', {}))) + .mockReturnValueOnce(hostStream([])) + } }) + await settle() + expect(m.view.getByText('The lens “Exports” did not finish: the lens failed: parser crashed')).toBeTruthy() + act(() => { m.view.getByRole('button', { name: 'Retry' }).click() }) + await settle() + expect(m.view.getByText('The changes were read again; refresh to filter them by “Exports”')).toBeTruthy() + const reads = m.faces.localDiff.mock.calls.length + act(() => { m.view.getAllByRole('button', { name: 'Refresh changes' }).at(-1)?.click() }) + await settle() + expect(m.faces.localDiff.mock.calls.length).toBeGreaterThan(reads) + expect(m.view.getByText('The lens “Exports” stopped before it finished')).toBeTruthy() + act(() => { m.view.getByRole('button', { name: 'Clear lens' }).click() }) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBeNull() + expect(m.view.queryByRole('button', { name: 'Clear lens' })).toBeNull() + }) + + it('draws the plugin slots of the toolbar, the More menu, the line annotations, the file menu, and the comment form', async () => { + const annotation = { key: 'n1', place: { side: 'R' as const, startLine: 4, endLine: 4 }, version: 1 } + const m = mount({ extensions: hosted, lenses: describedLenses, annotations: new Map([['src/app.ts', [{ source: 'notes', annotation }]]]) }) + await settle() + const target = { sessionId: SESSION, source: { kind: 'local' } } + const calls = (name: string): readonly SlotCall[] => m.slotCalls.filter(call => call.key === name) + const bar = calls('forge.changes.toolbar')[0]?.owner as ForgeChangesToolbarProps | undefined + expect(bar).toMatchObject({ target, form: 'bar' }) + // The row has no menu to close. + expect(() => { bar?.close() }).not.toThrow() + expect(calls('forge.diff.line.annotation')[0]).toEqual({ key: 'forge.diff.line.annotation', owner: { target, path: 'src/app.ts', annotation }, options: { entryKey: 'notes' } }) + expect(m.section('src/app.ts').querySelector('[data-forge-annotation="notes/n1"]')).not.toBeNull() + + act(() => { m.view.getByRole('button', { name: 'More view options' }).click() }) + expect(within(document.body).getAllByRole('menuitem').map(row => row.textContent)).toContain('Exports—') + expect(calls('forge.changes.toolbar').at(-1)?.owner).toMatchObject({ target, form: 'menu' }) + act(() => { within(document.body).getByRole('menuitem', { name: 'Exports—' }).click() }) + expect(m.store.getSnapshot().byTab[TAB]?.filterLens).toBe(EXPORTS) + + act(() => { within(m.section('src/app.ts')).getByRole('button', { name: 'More actions for app.ts' }).click() }) + expect(calls('forge.changes.file.menu')).toHaveLength(1) + expect(calls('forge.changes.file.menu')[0]?.owner).toMatchObject({ target, file: { path: 'src/app.ts' } }) + act(() => { within(m.section('src/app.ts')).getByRole('button', { name: 'Select line R4' }).click() }) + act(() => { within(m.section('src/app.ts')).getByRole('button', { name: 'Add comment' }).click() }) + expect(calls('forge.diff.comment.actions')[0]?.owner).toMatchObject({ target, selection: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4 } }) + }) +}) + +describe('ChangesTab extensions before the Host reports them', () => { + it('offers no lens and draws no annotations until the Host names its lenses and annotation limit', async () => { + const annotation = { key: 'n1', place: { side: 'R' as const, startLine: 4, endLine: 4 }, version: 1 } + const m = mount({ extensions: null, annotations: new Map([['src/app.ts', [{ source: 'notes', annotation }]]]) }) + await settle() + expect(m.view.queryByRole('button', { name: 'Filter lens' })).toBeNull() + expect(m.section('src/app.ts').querySelector('[data-forge-annotation]')).toBeNull() + expect(m.section('src/app.ts').querySelector('[data-forge-hidden-annotations]')).toBeNull() + }) + + it('draws no annotations while the renderer has no source for the view', async () => { + const m = mount({ annotations: null }) + await settle() + expect(m.paths()).toHaveLength(6) + expect(m.view.container.querySelector('[data-forge-annotation]')).toBeNull() + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts index 28c7ad748c..828cd18fb0 100644 --- a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts @@ -88,6 +88,8 @@ export interface EntryOptions { readonly origin?: BindingOrigin /** Snapshot an earlier poll returned, kept by a binding whose latest poll failed. */ readonly kept?: ChangeRequestSnapshot + /** Review changes announced for the change request; defaults to none. */ + readonly reviewRevision?: number } /** Binding of pull request `number` whose latest poll returned `status`, or that has not been polled yet. */ @@ -97,7 +99,7 @@ export function entry( options: EntryOptions = {}, ): ForgePanelChangeRequest { const key = `github:github.com/octo/demo#${number}` as ChangeRequestKey - const binding = { url: `https://github.com/octo/demo/pull/${number}`, origin: options.origin ?? 'created', ref: ref(number) } + const binding = { url: `https://github.com/octo/demo/pull/${number}`, origin: options.origin ?? 'created', ref: ref(number), reviewRevision: options.reviewRevision ?? 0 } if (status === null) return { ...binding, update: null, snapshot: null } if ('code' in status) return { ...binding, update: { key, fetchedAt: 1, failure: status }, snapshot: options.kept ?? null } return { ...binding, update: { key, fetchedAt: 1, snapshot: status }, snapshot: status } @@ -105,7 +107,7 @@ export function entry( /** Binding of a URL that no provider serves. */ export function unserved(url: string): ForgePanelChangeRequest { - return { url, origin: 'created', ref: null, update: null, snapshot: null } + return { url, origin: 'created', ref: null, update: null, snapshot: null, reviewRevision: 0 } } /** Checkout of `/work/repo` on `main`. */ diff --git a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx index efb64ee40b..5ed4ebb722 100644 --- a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx @@ -9,7 +9,12 @@ import { ReviewQueue } from '../src/client/review-queue.ts' import { SectionReach } from '../src/client/section-reach.ts' import { selectReviewLines } from '../src/client/review.ts' import type { ReviewActions } from '../src/client/ReviewComposer.tsx' +import type { ForgeCommentActionsProps } from '../src/client/slots.ts' import type { ForgeDiffFile } from '../src/types.ts' +import type { ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import type { SourcedAnnotation } from '../src/client/annotations.ts' +import type { FileThreads, ThreadActions } from '../src/client/ReviewThreads.tsx' +import { reviewThread } from './thread-fixtures.client.ts' const file: ForgeDiffFile = { path: 'a.txt', previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, layer: 'implementation', digest: 'digest', additions: 3, deletions: 2, hunks: [{ oldStart: 2, oldLines: 3, newStart: 2, newLines: 4, lines: [' same', '-old first', '-old last', '+new first', '+new last', '+'] }] } @@ -23,7 +28,7 @@ function mount(overrides: Partial = {}) { const review: ReviewActions = { source, addToInput, records, onQuoted: (item) => { records.recordAgent(item) } } const handlers = { toggle: vi.fn(), reveal: vi.fn(), expand: vi.fn(), view: vi.fn(), actions: () => [], section: vi.fn(), nextThread: vi.fn(), - reach: new SectionReach(), + reach: new SectionReach(), annotation: vi.fn(() => null), fileMenu: vi.fn(() => null), unfold: vi.fn(), } const props: DiffFileProps = { file, visible: true, expanded: true, large: false, revealed: false, text: undefined, open: new Set(), split: true, wrap: true, badge: '', tooltip: 'a.txt', @@ -342,3 +347,122 @@ it('labels the plus on the unified row that ends a right-side range', () => { expect(m.container.querySelector('[data-review-add="R4"]')).toBeNull() expect(m.container.querySelector('[data-review-add="R3"]')).not.toBeNull() }) + +/** A plugin annotation on a range of one side, the whole file, or a change it was written on. */ +function annotation(key: string, place: SourcedAnnotation['annotation']['place'], digest?: string): SourcedAnnotation { + return { source: 'notes', annotation: { key, place, version: 1, ...digest === undefined ? {} : { digest } } } +} + +/** File threads whose cards share inert actions. */ +function lineThreads(lines: FileThreads['lines']): FileThreads { + const actions: ThreadActions = { + author: null, addToInput: () => true, openLink: vi.fn(), readText: vi.fn(), inputFailed: vi.fn(), focused: null, writes: null, + } + return { lines, file: [], outdated: [], unresolved: lines.length, actions } +} + +/** The annotation frames a section draws, in order. */ +function frames(container: HTMLElement): (string | null)[] { + return [...container.querySelectorAll('[data-forge-annotation]')].map(element => element.getAttribute('data-forge-annotation')) +} + +it('draws plugin annotations after the comments of their last line, in the column of their side, through the handler', () => { + const m = mount({ annotationLimit: 10, annotations: [annotation('r4', { side: 'R', startLine: 3, endLine: 4 }), annotation('l3', { side: 'L', startLine: 3, endLine: 3 })] }) + const rendered = vi.mocked(m.props.handlers.annotation) + expect(rendered.mock.calls.map(([path, item]) => `${path}:${item.annotation.key}`)).toEqual(['a.txt:l3', 'a.txt:r4']) + const notes = m.container.querySelector('[data-forge-annotation="notes/l3"]')!.closest('[data-forge-notes]')! + expect([...notes.children].findIndex(cell => cell.querySelector('[data-forge-annotation]') !== null)).toBe(0) + const right = m.container.querySelector('[data-forge-annotation="notes/r4"]')!.closest('[data-forge-notes]')! + expect([...right.children].findIndex(cell => cell.querySelector('[data-forge-annotation]') !== null)).toBe(1) + + m.rerender() + expect(frames(m.container)).toEqual(['notes/l3', 'notes/r4']) +}) + +it('places annotations on the whole file first, on an earlier change in their own section, and counts those past the limit', () => { + const m = mount({ + annotationLimit: 3, + annotations: [ + annotation('file', 'file'), annotation('old', { side: 'R', startLine: 3, endLine: 3 }, 'other'), annotation('line', { side: 'R', startLine: 3, endLine: 3 }, 'digest'), + annotation('extra', { side: 'R', startLine: 4, endLine: 4 }), + ], + }) + expect(frames(m.container)).toEqual(['notes/file', 'notes/line', 'notes/old']) + expect(m.container.querySelector('[data-forge-outdated-annotations]')!.textContent).toContain('Annotations on an earlier change · 1') + expect(m.container.querySelector('[data-forge-hidden-annotations]')!.textContent).toBe('1 more annotations in this file are not shown') + m.rerender() + expect(frames(m.container)).toEqual([]) +}) + +it('places annotations in the collapsed lines that hold them and after the lines when no row shows them', () => { + const m = mount({ annotationLimit: 10, annotations: [annotation('gap', { side: 'R', startLine: 1, endLine: 1 }), annotation('later', { side: 'R', startLine: 40, endLine: 40 })] }) + const code = m.container.querySelector('[data-review]')! + const rows = [...code.children] + const gap = rows.findIndex(row => row.hasAttribute('data-forge-diff-gap')) + expect(rows[gap + 1]?.getAttribute('data-forge-annotation')).toBe('notes/gap') + expect(rows.at(-1)?.getAttribute('data-forge-annotation')).toBe('notes/later') + + // A new file has no lines after its hunk, so an annotation past them follows the lines. + const added: ForgeDiffFile = { ...file, status: 'added', deletions: 0, additions: 2, hunks: [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 2, lines: ['+a', '+b'] }] } + m.rerender() + expect([...m.container.querySelector('[data-review]')!.children].at(-1)?.getAttribute('data-forge-annotation')).toBe('notes/past') +}) + +it('folds the hunks a lens folds into one row that shows them, holding the threads and annotations on their lines', () => { + const two: ForgeDiffFile = { ...file, additions: 4, deletions: 3, hunks: [file.hunks[0]!, { oldStart: 10, oldLines: 1, newStart: 11, newLines: 2, lines: ['-o', '+n', '+m'] }] } + const thread = reviewThread({ path: 'a.txt' }) + const m = mount({ + file: two, folded: { hunks: new Set([1]), lens: 'Exports' }, annotationLimit: 10, + annotations: [ + annotation('left', { side: 'L', startLine: 10, endLine: 10 }), annotation('right', { side: 'R', startLine: 12, endLine: 12 }), + annotation('kept', { side: 'R', startLine: 3, endLine: 3 }), annotation('end', { side: 'R', startLine: 40, endLine: 40 }), + ], + threads: lineThreads([ + { thread, place: { kind: 'line', side: 'R', startLine: 11, endLine: 11 } }, + { thread: reviewThread({ path: 'a.txt', id: 'thread-end' as ForgeThreadId }), place: { kind: 'line', side: 'R', startLine: 40, endLine: 40 } }, + ]), + }) + const fold = m.container.querySelector('[data-forge-lens-fold]')! + expect(fold.getAttribute('data-forge-lens-fold')).toBe('1') + expect(fold.textContent).toBe('1 changes unrelated to “Exports” foldedShow') + const rows = [...m.container.querySelector('[data-review]')!.children] + const at = rows.indexOf(fold) + expect(rows[at + 1]?.hasAttribute('data-forge-thread')).toBe(true) + expect(rows.slice(at + 2, at + 4).map(row => row.getAttribute('data-forge-annotation'))).toEqual(['notes/left', 'notes/right']) + expect(m.container.querySelector('[data-old-line="10"]')).toBeNull() + fireEvent.click(fold) + expect(m.props.handlers.unfold).toHaveBeenCalledWith('a.txt') +}) + +it('draws line annotations after a note that replaces the lines and lists the plugin rows of the file menu', () => { + const m = mount({ file: { ...file, binary: true, hunks: [] }, annotationLimit: 10, annotations: [annotation('bin', { side: 'R', startLine: 1, endLine: 1 })] }) + expect(frames(m.container)).toEqual(['notes/bin']) + vi.mocked(m.props.handlers.fileMenu).mockImplementation((_file, dismiss) => ) + fireEvent.click(m.getByRole('button', { name: 'More actions for a.txt' })) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Pin a note' })) + expect(vi.mocked(m.props.handlers.fileMenu).mock.calls[0]?.[0]).toBe(m.props.file) + expect(within(document.body).queryByRole('menuitem', { name: 'Pin a note' })).toBeNull() +}) + +it('hands the comment text to a plugin action, keeping the form with the message it returns and closing it otherwise', async () => { + const owners: ForgeCommentActionsProps[] = [] + const deliver = vi.fn<(body: string) => Promise>().mockResolvedValueOnce('Not pinned').mockResolvedValueOnce(undefined) + const m = mount() + const review: ReviewActions = { + ...m.props.review!, + renderActions: (owner) => { + owners.push({ target: { sessionId: 's' as never, source: { kind: 'local' } }, ...owner }) + return + }, + } + m.rerender() + fireEvent.click(m.line('R4')) + fireEvent.click(m.getByRole('button', { name: 'Add comment' })) + expect(owners.at(-1)).toMatchObject({ selection: { path: 'a.txt', side: 'R', startLine: 4, endLine: 4 }, empty: true, busy: false }) + fireEvent.change(m.getByRole('textbox', { name: 'Leave a comment…' }), { target: { value: 'Pin me' } }) + await act(async () => { fireEvent.click(m.getByRole('button', { name: 'Pin' })) }) + expect(deliver).toHaveBeenCalledWith('Pin me') + expect(m.getByRole('alert').textContent).toBe('Not pinned') + await act(async () => { fireEvent.click(m.getByRole('button', { name: 'Pin' })) }) + expect(m.queryByRole('region', { name: 'Comment on R4' })).toBeNull() +}) diff --git a/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts b/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts index 2cea3656f7..78a1847959 100644 --- a/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/diff-rows.client.spec.ts @@ -82,7 +82,7 @@ describe('matchesHunks', () => { describe('segmentsOf', () => { it('collapses the lines before, between, and after the hunks, the last of unknown length', () => { - expect(segmentsOf(file(), undefined, new Set([0, 1])).map(segment => segment.kind === 'gap' ? segment : segment.rows.length)).toEqual([ + expect(segmentsOf(file(), undefined, new Set([0, 1])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ { kind: 'gap', index: 0, count: 2 }, 5, { kind: 'gap', index: 1, count: 4 }, @@ -105,7 +105,7 @@ describe('segmentsOf', () => { }) it('keeps unexpanded gaps collapsed once the new side is known, and counts the lines after the last hunk', () => { - expect(segmentsOf(file(), NEW_SIDE, new Set([1])).map(segment => segment.kind === 'gap' ? segment : segment.rows.length)).toEqual([ + expect(segmentsOf(file(), NEW_SIDE, new Set([1])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ { kind: 'gap', index: 0, count: 2 }, 11, { kind: 'gap', index: 2, count: 2 }, @@ -133,6 +133,26 @@ describe('segmentsOf', () => { expect(segmentsOf(oldEnding, undefined, new Set()).map(segment => segment.kind)).toEqual(['gap', 'rows', 'gap']) }) + it('draws consecutive folded hunks as one row that takes the lines between them, and the gap before a folded run', () => { + const three = file({ hunks: [...HUNKS, { oldStart: 13, oldLines: 1, newStart: 13, newLines: 1, lines: ['-u', '+t13'] }] }) + expect(segmentsOf(three, undefined, new Set(), new Set([1, 2])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ + { kind: 'gap', index: 0, count: 2 }, + 5, + { kind: 'gap', index: 1, count: 4 }, + { kind: 'folded', hunks: [1, 2] }, + { kind: 'gap', index: 3, count: null }, + ]) + expect(segmentsOf(three, undefined, new Set(), new Set([0, 2])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([ + { kind: 'gap', index: 0, count: 2 }, + { kind: 'folded', hunks: [0] }, + { kind: 'gap', index: 1, count: 4 }, + 2, + { kind: 'gap', index: 2, count: 1 }, + { kind: 'folded', hunks: [2] }, + { kind: 'gap', index: 3, count: null }, + ]) + }) + it('draws nothing for a file without hunks', () => { expect(segmentsOf(file({ status: 'renamed', previousPath: 'old.ts', hunks: [] }), undefined, new Set())).toEqual([]) }) diff --git a/packages/experimental/client-ui-forge/tests/extension-api.client.spec.tsx b/packages/experimental/client-ui-forge/tests/extension-api.client.spec.tsx new file mode 100644 index 0000000000..96829e5471 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/extension-api.client.spec.tsx @@ -0,0 +1,300 @@ +// @vitest-environment jsdom +/** The changes view's face for other Client plugins, the merged annotations of a view, and a view's lens run. */ +import { act, cleanup, fireEvent, render, renderHook, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { AnnotationView } from '../src/client/annotations.ts' +import { changesAddress, type ChangesTarget } from '../src/client/changes-address.ts' +import { + ForgeChangesService, type ForgeAnnotationSource, type ForgeLensDescription, type ForgeLineAnnotation, +} from '../src/client/changes-service.ts' +import { foldedHunks, useLensRun, type LensRunInput } from '../src/client/lens-filter.ts' +import { LensFilterMenu, lensOfRow, lensRowId, NO_LENS, type LensChoice } from '../src/client/LensFilter.tsx' +import { en } from '../src/client/locales.ts' +import type { HostStream } from '../src/client/source.ts' +import type { ForgeDiffHunk, ForgeExtensionState, ForgeLensFrame, ForgeLensId } from '../src/types.ts' + +afterEach(() => { cleanup(); vi.restoreAllMocks() }) + +const t = makeTranslate(en) +const SESSION = SessionId('s1') +const target: ChangesTarget = { sessionId: SESSION, source: { kind: 'change', url: 'https://github.com/octo/demo/pull/7' } } + +function service(mounted: SessionId | undefined = SESSION) { + const openResource = vi.fn() + const extensions = createSnapshotStore(null) + const forge = new ForgeChangesService({ mounted: () => mounted, openResource }, extensions, { changes: 'forge-changes', panel: 'forge-panel' }) + return { forge, openResource, extensions } +} + +function lens(id: string, order?: number): ForgeLensDescription { + return { id: id as ForgeLensId, title: () => id.toUpperCase(), ...order === undefined ? {} : { order } } +} + +/** A source whose annotations of every view a test sets. */ +function source(id: string, order?: number) { + const values = createSnapshotStore>(new Map()) + const observe = vi.fn((_target: ChangesTarget): HostObservable> => values) + const entry: ForgeAnnotationSource = { id, observe, ...order === undefined ? {} : { order } } + return { entry, values, observe } +} + +function note(key: string, line: number, version: string | number = 1): ForgeLineAnnotation { + return { key, place: { side: 'R', startLine: line, endLine: line }, version } +} + +describe('ForgeChangesService', () => { + it('mints and reads changes addresses and opens a view of the Session the sidebar shows', () => { + const { forge, openResource } = service() + const address = forge.address(target) + expect(address).toBe(changesAddress(target)) + expect(forge.parse(address)).toEqual(target) + expect(forge.parse('dsh-resource://other/x')).toBeUndefined() + expect(forge.kinds).toEqual({ changes: 'forge-changes', panel: 'forge-panel' }) + forge.open(target, { lens: 'fixture/exports' }) + forge.open(target) + expect(openResource.mock.calls).toEqual([[address, { lens: 'fixture/exports' }], [address, undefined]]) + expect(() => { service(SessionId('other')).forge.open(target) }).toThrow('forge-panel: Session s1 is not the Session the sidebar shows') + }) + + it('publishes lens descriptions by position, refuses a taken identity, and withdraws one when its plugin unloads', async () => { + const { forge } = service() + const changes = vi.fn() + forge.lenses.subscribe(changes) + const root = new Context() + const fiber = root.plugin({ apply(ctx: Context) { ctx.effect(() => forge.describeLens(lens('b', 1))) } }) + await fiber + const releaseA = forge.describeLens(lens('a', 1)) + forge.describeLens(lens('c')) + expect(forge.lenses.getSnapshot().map(item => item.id)).toEqual(['c', 'b', 'a']) + expect(() => forge.describeLens(lens('a'))).toThrow('forge-panel: a lens description "a" is already registered') + await fiber.dispose() + expect(forge.lenses.getSnapshot().map(item => item.id)).toEqual(['c', 'a']) + releaseA() + releaseA() + expect(forge.lenses.getSnapshot().map(item => item.id)).toEqual(['c']) + expect(changes).toHaveBeenCalledTimes(5) + }) + + it('registers annotation sources by position and withdraws one when its plugin unloads', async () => { + const { forge } = service() + const root = new Context() + const fiber = root.plugin({ apply(ctx: Context) { ctx.effect(() => forge.registerAnnotations(source('notes', 2).entry)) } }) + await fiber + forge.registerAnnotations(source('lint').entry) + expect(forge.annotationSources.getSnapshot().map(item => item.id)).toEqual(['lint', 'notes']) + expect(() => forge.registerAnnotations(source('lint').entry)).toThrow('forge-panel: a annotation source "lint" is already registered') + await fiber.dispose() + expect(forge.annotationSources.getSnapshot().map(item => item.id)).toEqual(['lint']) + }) +}) + +describe('AnnotationView', () => { + it('merges the sources by path in source order, observing them only while read', () => { + const { forge } = service() + const notes = source('notes', 1) + const lint = source('lint') + forge.registerAnnotations(notes.entry) + forge.registerAnnotations(lint.entry) + const view = new AnnotationView(forge.annotationSources, target) + expect(view.getSnapshot().size).toBe(0) + expect(notes.observe).not.toHaveBeenCalled() + + const listener = vi.fn() + const stop = view.subscribe(listener) + expect(notes.observe).toHaveBeenCalledWith(target) + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3)]]])) }) + act(() => { lint.values.set(new Map([['a.ts', [note('l1', 1)]], ['b.ts', [note('l2', 2)]], ['c.ts', []]])) }) + const merged = view.getSnapshot() + expect([...merged].map(([path, list]) => [path, list.map(item => `${item.source}:${item.annotation.key}`)])) + .toEqual([['a.ts', ['lint:l1', 'notes:n1']], ['b.ts', ['lint:l2']]]) + + // A file whose annotations did not change keeps its list. + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3)]], ['d.ts', [note('n2', 1)]]])) }) + expect(view.getSnapshot().get('b.ts')).toBe(merged.get('b.ts')) + expect(view.getSnapshot().get('a.ts')).toBe(merged.get('a.ts')) + const calls = listener.mock.calls.length + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3)]], ['d.ts', [note('n2', 1)]]])) }) + expect(listener).toHaveBeenCalledTimes(calls) + act(() => { notes.values.set(new Map([['a.ts', [note('n1', 3, 2)]], ['d.ts', [note('n2', 1)]]])) }) + expect(view.getSnapshot().get('a.ts')).not.toBe(merged.get('a.ts')) + + stop() + act(() => { notes.values.set(new Map()) }) + expect(view.getSnapshot().get('d.ts')).toHaveLength(1) + }) + + it('follows sources that register and withdraw while read', () => { + const { forge } = service() + const notes = source('notes') + notes.values.set(new Map([['a.ts', [note('n1', 3)]]])) + const view = new AnnotationView(forge.annotationSources, target) + const stopA = view.subscribe(() => {}) + const stopB = view.subscribe(() => {}) + const release = forge.registerAnnotations(notes.entry) + expect(view.getSnapshot().get('a.ts')).toHaveLength(1) + const lint = source('lint', 1) + lint.values.set(new Map([['a.ts', [note('l1', 2)]]])) + forge.registerAnnotations(lint.entry) + expect(view.getSnapshot().get('a.ts')?.map(item => item.source)).toEqual(['notes', 'lint']) + expect(notes.observe).toHaveBeenCalledTimes(1) + release() + expect(view.getSnapshot().get('a.ts')?.map(item => item.source)).toEqual(['lint']) + act(() => { notes.values.set(new Map([['b.ts', [note('n2', 1)]]])) }) + expect(view.getSnapshot().has('b.ts')).toBe(false) + stopA() + stopB() + }) +}) + +describe('foldedHunks', () => { + const hunk = (oldStart: number, oldLines: number, newStart: number, newLines: number): ForgeDiffHunk => + ({ oldStart, oldLines, newStart, newLines, lines: [] }) + const hunks = [hunk(1, 3, 1, 3), hunk(10, 0, 10, 2), hunk(20, 2, 22, 0)] + + it('folds the hunks that meet none of the lens lines on either side', () => { + expect([...foldedHunks(hunks, { ranges: { old: [], new: [{ start: 11, end: 11 }] } })]).toEqual([0, 2]) + expect([...foldedHunks(hunks, { ranges: { old: [{ start: 21, end: 30 }], new: [{ start: 3, end: 3 }] } })]).toEqual([1]) + expect([...foldedHunks(hunks, { ranges: { old: [{ start: 10, end: 10 }], new: [{ start: 22, end: 22 }] } })]).toEqual([0, 1, 2]) + expect(foldedHunks(hunks, {}).size).toBe(0) + }) +}) + +describe('useLensRun', () => { + function stream(frames: readonly ForgeLensFrame[], failure?: unknown, gate?: Promise): HostStream { + return { + dispose: vi.fn(), + async *[Symbol.asyncIterator]() { + for (const frame of frames) { + await gate + yield frame + } + await gate + if (failure !== undefined) throw failure + }, + } + } + const base: LensRunInput = { + visible: true, lens: 'fixture/exports', source: { kind: 'local', scope: { kind: 'unstaged' } }, version: 'v1', attempt: 0, + open: () => stream([]), + } + + it('reports progress, then keeps the result, which choosing the lens again reuses without asking', async () => { + const gate = Promise.withResolvers() + const open = vi.fn() + .mockReturnValueOnce(stream([{ kind: 'progress', done: 1, total: 2 }, { kind: 'result', files: { 'a.ts': {} } }], undefined, gate.promise)) + .mockReturnValueOnce(stream([{ kind: 'result', files: {} }])) + const initialProps: LensRunInput = { ...base, open } + const hook = renderHook((input: LensRunInput) => useLensRun(input), { initialProps }) + expect(hook.result.current.run).toEqual({ kind: 'running', done: null, total: null }) + expect(open.mock.calls[0]?.[0]).toEqual({ source: base.source, version: 'v1', lens: 'fixture/exports' }) + await act(async () => { gate.resolve(undefined); await gate.promise }) + await vi.waitFor(() => { expect(hook.result.current.run).toEqual({ kind: 'ready', files: { 'a.ts': {} } }) }) + + hook.rerender({ ...base, open, lens: 'other' }) + await vi.waitFor(() => { expect(hook.result.current.run).toEqual({ kind: 'ready', files: {} }) }) + hook.rerender({ ...base, open, lens: 'fixture/exports' }) + expect(hook.result.current.run).toEqual({ kind: 'ready', files: { 'a.ts': {} } }) + expect([...hook.result.current.results.keys()]).toEqual(['fixture/exports', 'other']) + expect(open).toHaveBeenCalledTimes(2) + + // Other files drop the kept results. + hook.rerender({ ...base, open: () => stream([]), version: 'v2' }) + expect(hook.result.current.results.size).toBe(0) + }) + + it('reports a Remote failure by its code, another failure as a lens failure, and asks nothing while hidden or without files', async () => { + const open = vi.fn() + .mockReturnValueOnce(stream([], new RemoteError('forgePanel/lens-stale', 'read again', {}))) + .mockReturnValueOnce(stream([], new Error('socket closed'))) + .mockReturnValueOnce(stream([], 'stream ended')) + const initialProps: LensRunInput = { ...base, open } + const hook = renderHook((input: LensRunInput) => useLensRun(input), { initialProps }) + await vi.waitFor(() => { expect(hook.result.current.run).toEqual({ kind: 'failed', code: 'forgePanel/lens-stale', message: 'read again' }) }) + hook.rerender({ ...base, open, attempt: 1 }) + await vi.waitFor(() => { + expect(hook.result.current.run).toEqual({ kind: 'failed', code: 'forgePanel/lens-failed', message: 'socket closed' }) + }) + hook.rerender({ ...base, open, attempt: 2 }) + await vi.waitFor(() => { + expect(hook.result.current.run).toEqual({ kind: 'failed', code: 'forgePanel/lens-failed', message: 'stream ended' }) + }) + hook.rerender({ ...base, open, attempt: 3, visible: false }) + hook.rerender({ ...base, open, attempt: 3, source: null }) + hook.rerender({ ...base, open, lens: null }) + expect(hook.result.current.run).toEqual({ kind: 'idle' }) + expect(open).toHaveBeenCalledTimes(3) + }) + + it('stops a request whose view hides or unmounts and ignores what it delivers afterwards', async () => { + const gate = Promise.withResolvers() + const opened = stream([{ kind: 'result', files: { 'a.ts': {} } }], new Error('late'), gate.promise) + const failing = stream([], new Error('late'), gate.promise) + const ending = stream([], undefined, gate.promise) + const open = vi.fn().mockReturnValueOnce(opened).mockReturnValueOnce(failing).mockReturnValueOnce(ending) + const initialProps: LensRunInput = { ...base, open } + const hook = renderHook((input: LensRunInput) => useLensRun(input), { initialProps }) + hook.rerender({ ...base, open, visible: false }) + expect(opened.dispose).toHaveBeenCalled() + hook.rerender({ ...base, open, attempt: 1 }) + hook.rerender({ ...base, open, attempt: 2 }) + hook.unmount() + await act(async () => { gate.resolve(undefined); await new Promise(resolve => setTimeout(resolve, 0)) }) + expect(failing.dispose).toHaveBeenCalled() + expect(ending.dispose).toHaveBeenCalled() + expect(hook.result.current.run).toEqual({ kind: 'running', done: null, total: null }) + }) +}) + +describe('LensFilterMenu', () => { + const lenses: readonly LensChoice[] = [{ id: 'fixture/exports', title: 'Exports', count: 3 }, { id: 'lint', title: 'Lint', count: null }] + + it('names the lens rows and reads them back', () => { + expect(lensRowId('lint')).toBe('lens:lint') + expect(lensOfRow(lensRowId('lint'))).toBe('lint') + expect(lensOfRow(NO_LENS)).toBeNull() + expect(lensOfRow('split')).toBeUndefined() + }) + + it('offers no lens and each lens with its count, and chooses one', () => { + const choose = vi.fn() + const view = render() + const trigger = view.getByRole('button', { name: 'Filter lens' }) + expect(trigger.textContent).toBe('Lens') + expect(trigger.hasAttribute('data-active')).toBe(false) + act(() => { trigger.click() }) + const menu = within(document.body) + expect(menu.getAllByRole('menuitem').map(row => row.textContent)).toEqual(['No lens', 'Exports3', 'Lint—']) + act(() => { menu.getByRole('menuitem', { name: 'Lint—' }).click() }) + expect(choose).toHaveBeenCalledWith('lint') + act(() => { trigger.click() }) + act(() => { menu.getByRole('menuitem', { name: 'No lens' }).click() }) + expect(choose).toHaveBeenLastCalledWith(null) + act(() => { trigger.click() }) + act(() => { fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }) }) + expect(document.body.querySelectorAll('[role="menuitem"]')).toHaveLength(0) + }) + + it('shows the chosen lens tinted with the files it keeps, its progress while it runs, and stays closed in a hidden tab', () => { + const view = render() + const trigger = view.getByRole('button', { name: 'Filter lens: Exports' }) + expect(trigger.hasAttribute('data-active')).toBe(true) + expect(trigger.textContent).toBe('Exports2/5') + view.rerender() + expect(trigger.textContent).toBe('Exports') + view.rerender() + expect(trigger.textContent).toBe('Exports3') + view.rerender() + expect(view.getByRole('button', { name: 'Filter lens: Lint' }).textContent).toBe('Lint') + act(() => { view.getByRole('button', { name: 'Filter lens: Lint' }).click() }) + expect(document.body.querySelectorAll('[role="menuitem"]')).toHaveLength(0) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx index 433f644b1b..ba6965ec5b 100644 --- a/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx @@ -66,6 +66,8 @@ function tab(state: ForgePanelState | null, options: { disconnected?: boolean; v const reportVisible = vi.fn<(visible: boolean) => void>() const createChangeRequest = vi.fn<() => void>() const openResource = vi.fn() + // Draws nothing for the card's plugin slot. + const renderSlot = (() => null) as ForgeTabProps['renderSlot'] const props: ForgeTabProps = { useTabInfo: () => tabInfo(useVisibility(current => current), openResource), sessionId: SESSION, @@ -73,7 +75,7 @@ function tab(state: ForgePanelState | null, options: { disconnected?: boolean; v useHost: bindSnapshotSelector(host), useLocale: bindSnapshotSelector(createSnapshotStore('en')), reconnect, refresh, remove, markReady, merge, readChecks, rerunChecks, requestReviews, reviewerCandidates, updateBranch, restore, - openLink, copyText, copyPath, reportVisible, createChangeRequest, t, + openLink, copyText, copyPath, reportVisible, createChangeRequest, renderSlot, t, } const view = render() return { diff --git a/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts b/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts index 8bb1b1216a..6f5a1298e8 100644 --- a/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts @@ -254,9 +254,9 @@ describe('forgePanel lenses over change requests', () => { '', ].join('\n') - async function bound(overrides: Partial<{ baseSha: string | undefined }> = { baseSha: BASE }): Promise { + async function bound(base: string | null = BASE): Promise { const opened = await open(await project()) - opened.provider.overrides.set(7, { headSha: HEAD, ...overrides }) + opened.provider.overrides.set(7, { headSha: HEAD, ...base === null ? {} : { baseSha: base } }) opened.provider.patches.set(7, PATCH) shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) const follower = follow(opened.ctx, opened.session) @@ -318,7 +318,7 @@ describe('forgePanel lenses over change requests', () => { }) it('fails reads of an old side the provider cannot locate and retries a failed merge base lookup', async () => { - const withoutBase = await bound({ baseSha: undefined }) + const withoutBase = await bound(null) await provideLens(withoutBase.ctx, exportsLens()) const { files } = await withoutBase.ctx.forgePanel.changeRequestDiff(withoutBase.session, pullUrl(7), null, signal) const request: ForgeLensRequest = { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/exports' } diff --git a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts index 5124c90ea3..bba6c628f0 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -39,7 +39,8 @@ import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFiel import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import type { - ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, + ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame, + ForgeLensRequest, ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, } from '../src/types.ts' import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts' @@ -145,6 +146,7 @@ async function base() { const remote = new Remote() const streams: ReturnType[] = [] const stateStreams: ReturnType>[] = [] + const extensionStreams: ReturnType>[] = [] const forgePanel = { follow: vi.fn((_sessionId: SessionId, signal: AbortSignal) => { const handle = stream(signal) @@ -156,6 +158,12 @@ async function base() { stateStreams.push(handle) return handle }), + extensions: vi.fn((signal: AbortSignal) => { + const handle = stream(signal) + extensionStreams.push(handle) + return handle + }), + changesLens: vi.fn((_sessionId: SessionId, _request: ForgeLensRequest, signal: AbortSignal) => stream(signal)), worktreeCleanup: vi.fn(async (_sessionId: SessionId, _revision: number | null): Promise> => ({ ok: true, value: null })), track: vi.fn(async (_sessionId: SessionId, _url: string): Promise> => OK), @@ -210,7 +218,8 @@ async function base() { const unregisterTab = vi.fn() const sidebarRightTabs = { register: vi.fn((_type: SidebarRightTabDefinition) => unregisterTab) } ctx.provide('sidebarRightTabs', sidebarRightTabs) - const sidebarRight = { openTab: vi.fn(), toggleExpanded: vi.fn(), hide: vi.fn(), + const sidebarRight = { openTab: vi.fn(), toggleExpanded: vi.fn(), hide: vi.fn(), openResource: vi.fn(), + mounted: { getSnapshot: vi.fn((): SessionId | undefined => S1), subscribe: () => () => {} }, tabsIn: vi.fn(() => [{ id: 'forge-tab' as TabId, kind: TAB_KIND }]) } const scopes = new Map>() const sessions = { scope: vi.fn<(id: SessionId) => Context | undefined>((id) => { @@ -240,7 +249,8 @@ async function base() { }, } as never, () => null) return { - ctx, remote, unmount, streams, stateStreams, forgePanel, sidebarRightTabs, unregisterTab, sidebarRight, sessions, scopes, worktreeForm, + ctx, remote, unmount, streams, stateStreams, extensionStreams, forgePanel, sidebarRightTabs, unregisterTab, sidebarRight, sessions, + scopes, worktreeForm, } } @@ -386,6 +396,59 @@ describe('mountForgePanel registration', () => { }) }) +describe('mountForgePanel extension API', () => { + it('provides the changes view face, which opens a view in the shown Session and is withdrawn on unload', async () => { + const f = await fixture() + const forgeChanges = f.ctx.get('forgeChanges') + assert(forgeChanges !== undefined) + expect(forgeChanges.kinds).toEqual({ changes: CHANGES_KIND, panel: TAB_KIND }) + const target = { sessionId: S1, source: { kind: 'local' } } as const + forgeChanges.open(target, { path: 'src/a.ts' }) + expect(f.sidebarRight.openResource).toHaveBeenCalledWith(forgeChanges.address(target), { params: { path: 'src/a.ts' } }) + forgeChanges.open(target) + expect(f.sidebarRight.openResource).toHaveBeenLastCalledWith(forgeChanges.address(target), undefined) + await f.dispose() + await settle() + expect(f.ctx.get('forgeChanges')).toBeUndefined() + }) + + it('streams the Host lenses to the changes view while it reads them, opens lens requests, and keeps one annotation view per address', async () => { + const f = await fixture() + const face = f.changes(S1) + const seen = vi.fn() + const stop = face.hooks.extensions.subscribe(seen) + expect(face.hooks.extensions.getSnapshot().state).toBeNull() + f.extensionStreams[0]?.push({ lenses: ['fixture/exports'], maxAnnotationsPerFile: 4 }) + await settle() + expect(face.hooks.extensions.getSnapshot().state).toEqual({ lenses: ['fixture/exports'], maxAnnotationsPerFile: 4 }) + const forgeChanges = f.ctx.get('forgeChanges') + assert(forgeChanges !== undefined) + const relay = vi.fn() + const unrelay = forgeChanges.extensions.subscribe(relay) + f.extensionStreams[0]?.push({ lenses: [], maxAnnotationsPerFile: 4 }) + await settle() + expect(forgeChanges.extensions.getSnapshot()).toEqual({ lenses: [], maxAnnotationsPerFile: 4 }) + expect(relay).toHaveBeenCalled() + unrelay() + stop() + expect(face.hooks.lenses).toBe(forgeChanges.lenses) + + const request: ForgeLensRequest = { source: { kind: 'local', scope: { kind: 'unstaged' } }, version: 'v', lens: 'fixture/exports' } + face.changesLens(request, new AbortController().signal) + expect(f.forgePanel.changesLens).toHaveBeenCalledWith(S1, request, expect.any(AbortSignal)) + + const address = forgeChanges.address({ sessionId: S1, source: { kind: 'local' } }) + const view = face.keyedHooks.annotations(address) + expect(face.keyedHooks.annotations(address)).toBe(view) + expect(face.keyedHooks.annotations(forgeChanges.address({ sessionId: S1, source: { kind: 'change', url: 'https://github.com/octo/demo/pull/7' } }))) + .not.toBe(view) + expect(() => face.keyedHooks.annotations('dsh-resource://forge-changes/s1/remote')).toThrow('forge-panel: not a changes address') + + await f.dispose() + expect(f.extensionStreams[0]?.disposed).toHaveBeenCalled() + }) +}) + describe('mountForgePanel Session list', () => { it('shares one change request state stream among every Session row and hover card while any of them reads it', async () => { const f = await fixture() diff --git a/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx b/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx index 2267d73380..3e26ebfc59 100644 --- a/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/view-options.client.spec.tsx @@ -15,7 +15,7 @@ afterEach(() => { function mount(overrides: Partial = {}, visible = true, fold?: string) { const options: ViewOptions = { anyExpanded: false, hasFiles: true, toggleExpansion: vi.fn(), split: true, toggleSplit: vi.fn(), wrap: false, toggleWrap: vi.fn(), - hideTests: true, toggleTests: vi.fn(), refresh: vi.fn(), ...overrides, + hideTests: true, toggleTests: vi.fn(), refresh: vi.fn(), lenses: [], chooseLens: vi.fn(), plugins: vi.fn(() => null), ...overrides, } const view = render(
) const trigger = within(view.container).getByRole('button', { name: en['diff.moreOptions'] }) @@ -73,3 +73,16 @@ it('toggles test files from the menu', () => { fireEvent.click(m.view.getByRole('menuitem', { name: en['tests.hide'] })) expect(m.options.toggleTests).toHaveBeenCalledTimes(1) }) + +it('lists the lenses with the test switch at level 2, chooses one, and draws the plugin rows that close the menu', () => { + const chooseLens = vi.fn() + const plugins = vi.fn((close: () => void) => ) + const m = mount({ lenses: [{ id: 'fixture/exports', title: 'Exports', count: 1 }], chooseLens, plugins }, true, '2') + fireEvent.click(m.trigger) + expect(m.rows()).toEqual(['Expand all files', 'Side by side', 'Wrap lines', 'Hide test files', 'No lens', 'Exports1', 'Notes 2']) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Exports1' })) + expect(chooseLens).toHaveBeenCalledWith('fixture/exports') + fireEvent.click(m.trigger) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Notes 2' })) + expect(m.rows()).toEqual([]) +})