feat(forge-panel): open the changes view to Client plugins with lenses, annotations, and slots

Provide ctx.forgeChanges, which mints and reads changes addresses, opens a
view in the shown Session, takes the titles of Host lenses, and registers
line annotation sources. The changes toolbar gains a lens menu that keeps
the files a chosen Host lens keeps, folds the hunks it is not about, and
folds into the More menu at level 2 while no lens is chosen; failed,
refused, and interrupted runs show a notice with a retry and a clear.

Five slots open the view to plugins: forge.changes.toolbar,
forge.changes.file.menu, forge.diff.line.annotation (keyed by source),
forge.diff.comment.actions, and forge.change-request.card.actions.
Annotations stack after the comment form, the browser drafts, and the host
threads of their last line, in the column of their side; none draw before
a section comes within reach, and maxAnnotationsPerFile bounds a file.
This commit is contained in:
Yichen Jiang committed 2026-11-10 14:33:33 +08:00
1 parent 0692b893ea
commit b60e5985ab
31 files changed
+1991 -70

No files matched your search

@@ -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<ChangeRequestSnapshot>) | 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
</div>
)}
</div>
{actions.renderActions?.({ url: entry.url, ref: entry.ref, headSha: snapshot?.headSha ?? null, state: snapshot?.state ?? null })}
<Tooltip label={t('change.view')} side="top">
<button type="button" className={css.iconButton} aria-label={t('change.view')} onClick={() => { actions.openLink(url) }}>
<IconRightUpOutlineRegular size={14} />
@@ -157,6 +157,8 @@
.progressSlot,
.foldTests,
.foldPlugins,
.lensSlot,
.filesSlot {
display: inline-flex;
flex: none;
@@ -276,13 +278,15 @@
}
/* `observeToolbarFold` sets `data-fold` on the toolbar row to the shallowest level whose items fit on one line: level 1
folds the line totals, expansion, side by side, and wrapping into the More menu; level 2 the test switch, with the
progress label shortened to the bare count beside its ring; level 3 refresh. */
folds plugin tools, the line totals, expansion, side by side, and wrapping into the More menu; level 2 the test switch
and the lens menu while no lens is chosen, with the progress label shortened to the bare count beside its ring;
level 3 refresh. */
.more {
display: none;
}
.toolbarMain:is([data-fold='1'], [data-fold='2'], [data-fold='3']) .foldViews,
.toolbarMain:is([data-fold='1'], [data-fold='2'], [data-fold='3']) .foldPlugins,
.toolbarMain:is([data-fold='2'], [data-fold='3']) .foldTests,
.toolbarMain[data-fold='3'] .foldRefresh {
display: none;
@@ -982,3 +986,62 @@
font-size: 11px;
line-height: 16px;
}
/* One line annotation from a plugin: the frame of a thread card, whose content the plugin draws. */
.annotation {
box-sizing: border-box;
width: calc(100% - 20px);
max-width: 720px;
margin: 10px;
overflow: hidden;
border: 0.5px solid var(--dsw-alias-border-l3);
border-radius: var(--dsw-radius-md);
background: var(--dsw-alias-bg-layer-1);
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xs-13);
white-space: normal;
}
/* In a comment row's stack the stack's gap and padding space the frame. */
.noteStack > .annotation {
width: 100%;
margin: 0;
}
.outdatedAnnotations {
border-top: 0.5px solid var(--dsw-alias-border-l3);
font-family: var(--dsw-font-family);
}
.outdatedAnnotationsTitle {
padding: 8px 12px 0;
color: var(--dsw-alias-label-secondary);
font-size: 12px;
line-height: 18px;
}
/* Hunks a filter lens folds draw as one row like the collapsed unchanged lines, tinted to tell them apart. */
.lensFold {
background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 6%, var(--forge-fill));
color: var(--dsw-alias-label-secondary);
}
.lensFoldText {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.lensFoldAction {
flex: none;
color: var(--dsw-alias-state-business-primary);
}
/* A hairline above the first plugin row of a menu, drawn only when a plugin adds one. */
.menuPlugins:has([role='menuitem']) {
margin-top: 4px;
padding-top: 4px;
border-top: 0.5px solid var(--dsw-alias-border-l3);
}
@@ -22,15 +22,16 @@ import {
Menu, StateDot, Tooltip,
type MenuEntry,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
import type {
ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff,
ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState,
ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeExtensionState, ForgeLensFrame,
ForgeLensKeep, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState,
} from '../types.ts'
import { lensVersion } from '../lens-version.ts'
import type {
ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult,
ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest,
@@ -57,12 +58,17 @@ import { ChangeRequestGlyph } from './glyphs.tsx'
import type { ForgePanelKey, NS } from './locales.ts'
import { RefreshGlyph } from './RefreshGlyph.tsx'
import { ViewOptionsMenu } from './ViewOptionsMenu.tsx'
import type { ForgeLensDescription } from './changes-service.ts'
import type { SourcedAnnotation, ViewAnnotations } from './annotations.ts'
import { foldedHunks, useLensRun } from './lens-filter.ts'
import { LensFilterMenu, type LensChoice } from './LensFilter.tsx'
import type {} from './slots.ts'
import { observeToolbarFold } from './toolbar-fold.ts'
import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './ReviewThreads.tsx'
import { inFileOrder, type ThreadFilter } from './review-threads.ts'
import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts'
import { ThreadList } from './ThreadList.tsx'
import type { PanelSnapshot } from './source.ts'
import type { HostStream, PanelSnapshot, StreamSnapshot } from './source.ts'
import { numberOf, openChangeRequestOf, TONE_LABEL, toneOf } from './status.ts'
import css from './ChangesTab.module.css'
@@ -85,8 +91,21 @@ export interface ChangesTabInjected {
readonly reviewQueue: (tab: Pick<SidebarRightTabInfo['tab'], 'id' | 'signal'>) => ReviewQueue
/** Publish one comment or a completed review; never retries mutations. */
readonly submitReview: (url: string, request: ForgeReviewRequest) => Promise<RemoteResult<ForgeReviewResult>>
/** Panel source while visible; the renderer releases the subscription for an inactive key. */
readonly keyedHooks: { readonly panel: (visibility: string) => HostObservable<PanelSnapshot> | undefined }
/**
* Panel source while visible, which the renderer releases for an inactive key; and the plugin annotations of a view by
* its address, which the renderer binds as `useAnnotations`.
*/
readonly keyedHooks: {
readonly panel: (visibility: string) => HostObservable<PanelSnapshot> | undefined
readonly annotations: (address: string) => HostObservable<ViewAnnotations>
}
/** Lens titles Client plugins describe and the Host's lenses and annotation limit; bound as `useLenses` and `useExtensions`. */
readonly hooks: {
readonly lenses: HostObservable<readonly ForgeLensDescription[]>
readonly extensions: HostObservable<StreamSnapshot<ForgeExtensionState | null>>
}
/** Classify the shown files with a Host lens; `signal` aborts the stream. */
readonly changesLens: (request: ForgeLensRequest, signal: AbortSignal) => HostStream<ForgeLensFrame>
/** Open the panel stream again after it ended. */
readonly reconnect: () => void
/** Read the local changes of one scope; `signal` aborts the read. */
@@ -135,6 +154,8 @@ export interface ChangesTabInjected {
/** Full props of the changes tab body. */
export type ChangesTabProps =
Pick<PropsRuntime<'sidebar.right.pane.tab'>, 'useTabInfo' | 'sessionId'>
& Pick<PropsRenderSlots<'forge.changes.toolbar' | 'forge.changes.file.menu' | 'forge.diff.line.annotation' | 'forge.diff.comment.actions'>,
'renderSlot'>
& PropsStore<ReturnType<typeof createChangesStore>>
& InjectFace<ChangesTabInjected>
& PropsLocale<typeof NS>
@@ -189,6 +210,15 @@ const OPEN_LINES = 5000
const NO_GAPS: ReadonlySet<number> = new Set()
const NO_FOLDS: ReadonlyMap<string, { readonly hunks: ReadonlySet<number>; readonly lens: string }> = new Map()
const NO_PATHS: ReadonlySet<string> = new Set()
const NO_ANNOTATIONS: ViewAnnotations = new Map()
/** The toolbar row's close action, which has no menu to close. */
function noop(): void {}
const SCOPE_LABEL: Record<ScopeKind, ForgePanelKey> = {
branch: 'diff.scope.branch',
uncommitted: 'diff.scope.uncommitted',
@@ -311,9 +341,12 @@ function initiallyOpen(files: readonly ForgeDiffFile[], marks: ViewedMarks): Rea
return open
}
/** Whether a file shows under a lens while test files hide or not. */
function shownBy(file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean): boolean {
/** Whether a file shows under a layer while test files hide or not, and among the files a filter lens keeps when one applies. */
function shownBy(
file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean, kept: Readonly<Record<string, ForgeLensKeep>> | null = null,
): boolean {
return !(hideTests && file.layer === 'test') && (lens === 'all' || file.layer === lens)
&& (kept === null || Object.hasOwn(kept, file.path))
}
/** What a rename badge names: the old file name, or the old path when only the directory changed. */
@@ -485,7 +518,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale<typeof NS> & {
export function ChangesTab({
useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff,
changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, changeRequestViewed, setFileViewed,
openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t,
openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, useLenses, useExtensions,
useAnnotations, changesLens, renderSlot, t,
}: ChangesTabProps): ReactNode {
const { tab } = useTabInfo()
const { navigation, signal } = tab
@@ -585,6 +619,8 @@ export function ChangesTab({
useEffect(() => {
if (choices?.navigated === navigation.revision) return
actions.navigated(tab.id, navigation.revision)
const lensParam = navigation.params?.lens
if (lensParam !== undefined) actions.filtered(tab.id, lensParam)
const path = navigation.params?.path
if (path === undefined) return
setTreeState(value => ({ ...value, selected: path }))
@@ -682,9 +718,65 @@ export function ChangesTab({
const threadsToggle = useRef<HTMLButtonElement>(null)
const [focus, setFocus] = useState<ThreadFocus | null>(null)
const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data])
const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests])
// A Host filter lens keeps files only once its result for the shown files arrived; until then every file shows.
const extensions = useExtensions(current => current.state)
const descriptions = useLenses(current => current)
const hostLenses = extensions?.lenses ?? null
const chosenLens = choices?.filterLens ?? null
const activeLens = chosenLens !== null && hostLenses?.includes(chosenLens) === true ? chosenLens : null
const lensSource = useMemo((): ForgeLensRequest['source'] | null => data === null ? null
: data.kind === 'local' ? { kind: 'local', scope: data.scope } : { kind: 'change', url: data.url, commits: data.commits }, [data])
const filesVersion = useMemo(() => data === null ? null : lensVersion(data.files), [data])
const [lensAttempt, setLensAttempt] = useState(0)
const lensRun = useLensRun({
visible: tab.visible, lens: activeLens, source: lensSource, version: filesVersion, attempt: lensAttempt, open: changesLens,
})
const kept = lensRun.run.kind === 'ready' ? lensRun.run.files : null
const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests, kept)), [allFiles, lens, hideTests, kept])
const lensCounts = useMemo(() => Object.fromEntries(LENSES.map(item => [item,
allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record<ChangesLens, number>, [allFiles, hideTests])
allFiles.filter(file => shownBy(file, item, hideTests, kept)).length])) as Record<ChangesLens, number>, [allFiles, hideTests, kept])
const lensTitle = (id: string): string => {
const described = descriptions.find(item => item.id === id)
return described === undefined ? id : described.title()
}
// The described lenses come in their described order, then the lenses no Client plugin describes, by their identity.
const offered = hostLenses ?? []
const lensChoices: readonly LensChoice[] = [
...descriptions.filter(item => offered.includes(item.id)).map(item => item.id as string),
...offered.filter(id => !descriptions.some(item => item.id === id)),
].map((id) => {
const result = lensRun.results.get(id)
const count = result === undefined ? null : allFiles.filter(file => shownBy(file, lens, hideTests, result)).length
return { id, title: lensTitle(id), count }
})
const chosenChoice = lensChoices.find(item => item.id === activeLens) ?? null
// A lens the Host withdrew, as when its plugin unloaded, stops filtering; the reader is told once.
const withdrawn = chosenLens !== null && hostLenses !== null && !hostLenses.includes(chosenLens) ? chosenLens : null
useEffect(() => {
if (withdrawn === null) return
actions.filtered(tab.id, null)
report('filterLens.removed', { lens: live.current.lensTitle(withdrawn) })
}, [withdrawn, actions, tab.id, report])
const chooseLens = (next: string | null): void => { actions.filtered(tab.id, next) }
// The hunks each kept file folds stay folded until the reader shows them for that file; a new result folds again.
const [unfolded, setUnfolded] = useState<{ readonly kept: typeof kept; readonly paths: ReadonlySet<string> }>(
{ kept: null, paths: new Set() })
const shownPaths = unfolded.kept === kept ? unfolded.paths : NO_PATHS
const foldTitle = chosenChoice?.title ?? ''
const folds = useMemo(() => {
if (kept === null) return NO_FOLDS
const map = new Map<string, { readonly hunks: ReadonlySet<number>; readonly lens: string }>()
for (const file of allFiles) {
const keep = kept[file.path]
if (keep === undefined || shownPaths.has(file.path)) continue
const hunks = foldedHunks(file.hunks, keep)
if (hunks.size > 0) map.set(file.path, { hunks, lens: foldTitle })
}
return map
}, [allFiles, kept, shownPaths, foldTitle])
const annotations = useAnnotations(tab.contentId) ?? NO_ANNOTATIONS
// Annotations wait for the Host's limit.
const annotationLimit = extensions?.maxAnnotationsPerFile
const shownSource = useMemo(() => data === null ? null : reviewSourceOf(data), [data])
const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource)
const localMarks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey))
@@ -1010,7 +1102,8 @@ export function ChangesTab({
// an effect would hand them the previous diff's links. A render React discards leaves values derived from the same
// props and state, which the retried render assigns again.
const callbacks = {
data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, t,
data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, lensTitle,
renderSlot, kept, t,
}
const live = useRef(callbacks)
live.current = callbacks
@@ -1041,7 +1134,14 @@ export function ChangesTab({
},
nextThread: (path) => { live.current.nextThread(path) },
reach,
}), [reach])
annotation: (path, item: SourcedAnnotation) => live.current.renderSlot('forge.diff.line.annotation',
{ target, path, annotation: item.annotation }, { entryKey: item.source }),
fileMenu: (file, dismiss) => live.current.renderSlot('forge.changes.file.menu', { target, file, dismiss }),
unfold: (path) => {
const { kept: current } = live.current
setUnfolded(value => ({ kept: current, paths: new Set([...(value.kept === current ? value.paths : []), path]) }))
},
}), [reach, target])
const reviewStarted = pendingReview !== null
const publishingBlocked = reviewState.uncertain !== null
// Comments on a commit range or on local changes go to the input only; a whole change request also takes GitHub comments:
@@ -1053,6 +1153,7 @@ export function ChangesTab({
const fileReview = useMemo((): ReviewActions | undefined => shownSource === null ? undefined : {
source: shownSource,
addToInput: addReviewToInput,
renderActions: owner => live.current.renderSlot('forge.diff.comment.actions', { target, ...owner }),
records: queue, openLink, reviewStarted,
onQuoted: (selection) => { if (!queue.recordAgent(selection)) live.current.report('review.saveFailed') },
publishingBlocked,
@@ -1063,7 +1164,7 @@ export function ChangesTab({
url => queue.published(selection, url))
: Promise.resolve(live.current.t('review.stale')),
} : {},
}, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, queueable, single])
}, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, queueable, single, target])
let body: ReactNode
if (data === null) {
@@ -1121,6 +1222,9 @@ export function ChangesTab({
badge={badgeOf(file, data, t)}
tooltip={pathTooltipOf(file, t)}
threads={fileThreads.get(path)}
annotations={annotations.get(path)}
annotationLimit={annotationLimit}
folded={folds.get(path)}
drawNow={wanted !== null && wanted.center !== null && wanted.path === path}
viewed={viewedStateOf(marks, path, file.digest)}
viewedNote={host === null ? t('viewed.hint') : host.unavailable ? t('viewed.unavailable')
@@ -1193,7 +1297,14 @@ export function ChangesTab({
{allFiles.length > 0 && <span className={css.foldTests}>
<HideTestsSwitch hidden={hideTests} toggle={toggleTests} t={t} />
</span>}
{tab.visible && allFiles.length > 0 && lensChoices.length > 0 && (
// A chosen lens stays in the row, where it says what the files are filtered by.
<span className={activeLens === null ? css.foldTests : css.lensSlot}>
<LensFilterMenu lenses={lensChoices} chosen={chosenChoice} run={lensRun.run} choose={chooseLens} visible t={t} />
</span>
)}
<span className={css.spacer} data-fold-spacer="" />
<span className={css.foldPlugins}>{renderSlot('forge.changes.toolbar', { target, form: 'bar', close: noop })}</span>
{/* A truncated read keeps the list, whose footer says so, even when it kept no thread. */}
{review !== null && (review.threads.length > 0 || review.truncated) && (
<button ref={threadsToggle} type="button" className={css.threadsToggle} aria-pressed={threadList.open} data-forge-threads-toggle=""
@@ -1242,6 +1353,8 @@ export function ChangesTab({
<ViewOptionsMenu visible={tab.visible} options={{
anyExpanded, hasFiles: files.length > 0, toggleExpansion, split, toggleSplit, wrap, toggleWrap,
hideTests: allFiles.length > 0 ? hideTests : undefined, toggleTests, refresh,
lenses: allFiles.length > 0 && activeLens === null ? lensChoices : [], chooseLens,
plugins: close => renderSlot('forge.changes.toolbar', { target, form: 'menu', close }),
}} t={t} />
</span>
</div>
@@ -1257,6 +1370,18 @@ export function ChangesTab({
<Notice>{t('diff.stale', { count: data.localAhead })}</Notice>
)}
{data?.kind === 'local' && data.omitted > 0 && <Notice>{t('diff.omitted', { count: data.omitted })}</Notice>}
{lensRun.run.kind === 'failed' && chosenChoice !== null && (
<Notice action={<span className={css.noticeAction}>
{lensRun.run.code === 'forgePanel/lens-stale'
? <Button size="sm" variant="outline" onClick={refresh}>{t('diff.refresh')}</Button>
: <Button size="sm" variant="outline" onClick={() => { setLensAttempt(value => value + 1) }}>{t('retry')}</Button>}
<Button size="sm" variant="outline" onClick={() => { chooseLens(null) }}>{t('filterLens.clear')}</Button>
</span>}>
{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 })}
</Notice>
)}
{data?.kind === 'change' && data.viewed?.kind === 'failed' && (
<Notice action={<Button size="sm" variant="outline" className={css.noticeAction} onClick={refresh}>{t('retry')}</Button>}>
{t('viewed.readFailed', { message: data.viewed.message })}
@@ -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<typeof NS>['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<number>; 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<number, readonly HighlightSpan[]> | 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 <div className={css.annotation} data-forge-annotation={`${item.source}/${item.annotation.key}`}>{handlers.annotation(path, item)}</div>
}
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<DiffFileProps,
'file' | 'text' | 'open' | 'handlers' | 'split' | 'wrap' | 'review' | 'visible' | 'threads' | 't'> & { readonly comments: FileReviewState }): ReactNode {
function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, threads, folded, annotations, t }: Pick<DiffFileProps,
'file' | 'text' | 'open' | 'handlers' | 'split' | 'wrap' | 'review' | 'visible' | 'threads' | 'folded' | 't'> & 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<ReviewSelection | null>(null)
// Mirrors `selection` for the release of a hover-plus drag, whose listener outlives the render that chose the range.
const chosen = useRef<ReviewSelection | null>(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 =>
<ThreadCard key={`thread-${item.thread.id}`} thread={item.thread} place={item.place} actions={item.actions} t={t} />
// 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 =>
<Annotation key={`annotation-${item.source}-${item.annotation.key}`} path={file.path} item={item} handlers={handlers} />
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(<button key={`folded-${segment.hunks.join(',')}`} type="button" className={clsx(css.gap, css.lensFold)}
data-forge-lens-fold={segment.hunks.join(',')} onClick={() => { handlers.unfold(file.path) }}>
<IconChevronsUpDownOutlineRegular size={12} />
<span className={css.lensFoldText}>{t('filterLens.folded', { count: String(segment.hunks.length), lens: foldLens })}</span>
<span className={css.lensFoldAction}>{t('filterLens.unfold')}</span>
</button>)
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(<div key={`${at}-${index}`} className={css.pair} data-diff-pair={pairKind(pair)}
@@ -447,6 +556,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
}
}
for (const item of unplaced) rows.push(threadCard(item))
for (const item of unplacedNotes) rows.push(annotationOf(item))
return <div ref={root} className={css.code} style={style} data-single-side={singleSide ?? undefined} data-split={columns ? '' : undefined} data-wrap={wrap ? '' : undefined}
data-review={review === undefined ? undefined : ''}
data-native-side={nativeSide ?? undefined}
@@ -471,13 +581,16 @@ function drawsLines(file: ForgeDiffFile, large: boolean, revealed: boolean): boo
}
/** The file's lines or the note that replaces them, with its saved comments; host threads on lines follow when no lines show. */
function Content(props: DiffFileProps): ReactNode {
const { file, large, revealed, handlers, review, threads, t } = props
function Content(props: DiffFileProps & { readonly notes: FileAnnotations }): ReactNode {
const { file, large, revealed, handlers, review, threads, notes, t } = props
const comments = useFileReview(review, file.path)
const records = review === undefined ? null : comments.threads.map(thread => <ReviewThread key={thread.key} thread={thread}
actions={review} locked={comments.locked} outdated={!reviewMatches(thread.selection, review.source, file)} t={t} />)
const lineThreads = threads?.lines.map(item => <ThreadCard key={item.thread.id} thread={item.thread} place={item.place}
actions={threads.actions} t={t} />)
const lineThreads = <>
{threads?.lines.map(item =>
<ThreadCard key={item.thread.id} thread={item.thread} place={item.place} actions={threads.actions} t={t} />)}
{notes.lines.map(item => <Annotation key={`${item.source}-${item.annotation.key}`} path={file.path} item={item} handlers={handlers} />)}
</>
if (file.binary) return <><p className={css.fileNote}>{t('diff.binary')}</p>{records}{lineThreads}</>
if (file.oversized) return <><p className={css.fileNote}>{t('diff.fileTooLarge')}</p>{records}{lineThreads}</>
if (file.hunks.length === 0) return <>{records}{lineThreads}</>
@@ -490,16 +603,27 @@ function Content(props: DiffFileProps): ReactNode {
</button>{records}{lineThreads}</>
)
}
return <Lines {...props} comments={comments} />
return <Lines {...props} comments={comments} annotations={notes.lines} />
}
/** 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 =>
<Annotation key={`${item.source}-${item.annotation.key}`} path={file.path} item={item} handlers={handlers} />
return <>
{threads?.file.map(thread => <ThreadCard key={thread.id} thread={thread} place={{ kind: 'file' }} actions={threads.actions} t={t} />)}
<Content {...props} />
{notes.file.map(frame)}
<Content {...props} notes={notes} />
{threads !== undefined && <OutdatedThreads threads={threads.outdated} actions={threads.actions} t={t} />}
{notes.outdated.length > 0 && (
<div className={css.outdatedAnnotations} data-forge-outdated-annotations="">
<div className={css.outdatedAnnotationsTitle}>{t('annotation.outdated', { count: String(notes.outdated.length) })}</div>
{notes.outdated.map(frame)}
</div>
)}
{notes.hidden > 0 && <p className={css.fileNote} data-forge-hidden-annotations="">{t('annotation.hidden', { count: String(notes.hidden) })}</p>}
</>
}
@@ -543,6 +667,7 @@ function FileMenu({ name, file, handlers, t }: {
{t(action.label)}
</MenuItemButton>
))}
{menuOpen && <div className={css.menuPlugins}>{handlers.fileMenu(file, () => { setMenuOpen(false) })}</div>}
</Menu>
)
}
@@ -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<PropsRuntime<'sidebar.right.pane.tab'>, 'useTabInfo' | 'sessionId'>
& Pick<PropsRenderSlots<'forge.change-request.card.actions'>, 'renderSlot'>
& InjectFace<ForgeTabInjected>
& PropsLocale<typeof NS>
@@ -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)
@@ -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;
}
@@ -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<typeof NS>['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: <span className={css.row}><span className={css.rowLabel}>{lens.title}</span><span className={css.rowCount}>{lens.count ?? '—'}</span></span>,
})),
]
}
/**
* 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<typeof NS> & {
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 = <>
<IconLoadingOutlineRegular size={12} className={css.spin} />
{run.done !== null && run.total !== null && <span className={css.count}>{t('filterLens.progress', { done: String(run.done), total: String(run.total) })}</span>}
</>
} else if (chosen?.count !== null && chosen?.count !== undefined) {
status = <span className={css.count}>{chosen.count}</span>
}
return (
<Menu open={visible && open} portal dense align="start" autoFocus items={lensEntries(lenses, t)}
selectedId={chosen === null ? NO_LENS : lensRowId(chosen.id)}
onClose={() => { 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={(
<button type="button" className={css.trigger} aria-haspopup="menu" aria-expanded={visible && open}
aria-label={chosen === null ? t('filterLens.aria') : t('filterLens.chosenAria', { lens: chosen.title })}
data-active={chosen === null ? undefined : ''} data-forge-filter-lens={chosen?.id ?? ''}
onClick={() => { setOpen(value => !value) }}>
<IconLayersOutlineRegular size={14} />
<span className={css.label}>{chosen === null ? t('filterLens.label') : chosen.title}</span>
{status}
<IconChevronDownOutlineRegular size={12} />
</button>
)} />
)
}
@@ -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<string | undefined>
/** 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<string | undefined>
/** Draw the buttons plugins add to the form through `forge.diff.comment.actions`. */
readonly renderActions?: (owner: Omit<ForgeCommentActionsProps, 'target'>) => 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')}</Button>
{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 && <SplitAction disabled={busy || actions.publishingBlocked === true || empty}
label={t(busy ? 'review.publishing' : actions.reviewStarted === true ? 'review.queue' : 'review.startReview')}
run={() => { void send(actions.queue) }} menuLabel={t('review.githubActions')}
@@ -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<typeof NS>
{ 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<typeof NS>
<IconEllipsisOutlineRegular />
</button>
</Tooltip>
)} />
)}>
{fold !== null && <div className={css.menuPlugins}>{options.plugins(() => { setFold(null) })}</div>}
</Menu>
)
}
@@ -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<string, readonly SourcedAnnotation[]>
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<ViewAnnotations> {
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<ForgeAnnotationSource['observe']>; 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<readonly ForgeAnnotationSource[]>, 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<string, SourcedAnnotation[]>()
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<string, readonly SourcedAnnotation[]>()
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()
}
}
@@ -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
}
}
@@ -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<ReadonlyMap<string, readonly ForgeLineAnnotation[]>>
}
/** 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<T extends { readonly id: string; readonly order?: number }> implements HostObservable<readonly T[]> {
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<readonly ForgeLensDescription[]>
/** Annotation sources in stacking order. */
readonly annotationSources: HostObservable<readonly ForgeAnnotationSource[]>
private readonly lensEntries = new OrderedEntries<ForgeLensDescription>('lens description')
private readonly sourceEntries = new OrderedEntries<ForgeAnnotationSource>('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<ForgeExtensionState | null>,
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)
}
}
@@ -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<ChangesState, ChangesAct
actions: {
/**
* Apply a navigation; the first one seeds the `branch` scope with the automatic fork point, every commit and file,
* test files shown, two columns, and wrapped lines.
* no filter lens, test files shown, two columns, and wrapped lines.
* @param d - draft state.
* @param tabId - the tab being drawn.
* @param revision - the navigation revision being applied.
@@ -75,7 +78,9 @@ export function createChangesStore(): EngineStoreHandle<ChangesState, ChangesAct
navigated: (d, tabId: string, revision: number) => {
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<ChangesState, ChangesAct
* @param lens - every file, or one layer.
*/
lensed: (d, tabId: string, lens: ChangesLens) => { 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.
@@ -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<number> = 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<number>): DiffSegment[] {
export function segmentsOf(
file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlySet<number>, folded: ReadonlySet<number> = 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
}
@@ -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'
@@ -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<Record<string, ForgeLensKeep>> }
/**
* 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<ForgeLensFrame>
}
/** 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<string, Readonly<Record<string, ForgeLensKeep>>>
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<number> {
const ranges = keep.ranges
if (ranges === undefined) return new Set()
const folded = new Set<number>()
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
}
@@ -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<ForgePanelKey, string> = {
'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<ForgePanelKey, string> = {
'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<ForgePanelKey, string> = {
'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<ForgePanelKey, string> = {
'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<ForgePanelKey, string> = {
'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<ForgePanelKey, string> = {
'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<ForgePanelKey, string> = {
'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',
@@ -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<AbortSignal, ReviewQueue>
readonly viewed: ViewedFiles
/** Plugin annotations of each changes view of the Session, by address. */
readonly annotations: Map<string, AnnotationView>
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<ForgeExtensionState, ForgeExtensionState | null>({
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<unknown>, failure: ForgePanelKey, codes: Partial<Record<string, ForgePanelKey>> = {}): 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,
@@ -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<string | undefined>) => 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 }
}
}
@@ -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]),
@@ -177,7 +177,7 @@ export async function runLens(
progress: (done, total) => { if (!operation.aborted) progress(done, total) },
}
const stopped = new Promise<never>((_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<LensFiles>,
): AsyncIterable<ForgeLensFrame> {
// 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<void>()
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 }
}
@@ -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')
@@ -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<T>(instance: { subscribe: (listener: () => void) => () => void;
}
}
/** A Host stream that yields `frames`, then fails with `failure` when one is given. */
function hostStream<F>(frames: readonly F[], failure?: unknown): HostStream<F> {
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<void> {
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) })
}
type Faces = { -readonly [K in Exclude<keyof ChangesTabInjected, 'keyedHooks' | 'viewedFiles'>]: ReturnType<typeof vi.fn<ChangesTabInjected[K]>> }
type Faces = { -readonly [K in Exclude<keyof ChangesTabInjected, 'keyedHooks' | 'hooks' | 'viewedFiles'>]: ReturnType<typeof vi.fn<ChangesTabInjected[K]>> }
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<ChangesTabInjected['changeRequestReviewWrite']>(async () => ok<ForgeReviewWriteResult>({ ok: true })),
createChangeRequest: vi.fn<ChangesTabInjected['createChangeRequest']>(),
report: vi.fn<ChangesTabInjected['report']>(),
changesLens: vi.fn<ChangesTabInjected['changesLens']>(() => hostStream([])),
}
options.setup?.(faces)
const extensions = createSnapshotStore<StreamSnapshot<ForgeExtensionState | null>>({
state: options.extensions === undefined ? { lenses: [], maxAnnotationsPerFile: 100 } : options.extensions, disconnected: false,
})
const lenses = createSnapshotStore<readonly ForgeLensDescription[]>(options.lenses ?? [])
const annotations = createSnapshotStore<ViewAnnotations | undefined>(
options.annotations === null ? undefined : options.annotations ?? new Map())
const useAnnotationsOf = bindSnapshotSelector(annotations)
function useAnnotations(key: string): ViewAnnotations | undefined
function useAnnotations<S>(key: string, select: (value: ViewAnnotations | undefined) => S): S
function useAnnotations<S>(_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<HTMLElement>('[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<HTMLElement>('[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()
})
})
@@ -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`. */
@@ -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<DiffFileProps> = {}) {
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(<DiffFile {...m.props} split={false} />)
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(<DiffFile {...m.props} annotationLimit={undefined} />)
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(<DiffFile {...m.props} file={added} annotations={[annotation('past', { side: 'R', startLine: 9, endLine: 9 })]} />)
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<HTMLElement>('[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) => <button type="button" role="menuitem" onClick={dismiss}>Pin a note</button>)
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<string | undefined>>().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 <button type="button" disabled={owner.empty || owner.busy} onClick={() => { owner.send(deliver) }}>Pin</button>
},
}
m.rerender(<DiffFile {...m.props} review={review} />)
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()
})
@@ -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([])
})
@@ -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<ForgeExtensionState | null>(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<ReadonlyMap<string, readonly ForgeLineAnnotation[]>>(new Map())
const observe = vi.fn((_target: ChangesTarget): HostObservable<ReadonlyMap<string, readonly ForgeLineAnnotation[]>> => 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<unknown>): HostStream<ForgeLensFrame> {
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<undefined>()
const open = vi.fn<LensRunInput['open']>()
.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<LensRunInput['open']>()
.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<undefined>()
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<LensRunInput['open']>().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(<LensFilterMenu lenses={lenses} chosen={null} run={{ kind: 'idle' }} choose={choose} visible t={t} />)
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(<LensFilterMenu lenses={lenses} chosen={lenses[0] ?? null} run={{ kind: 'running', done: 2, total: 5 }}
choose={vi.fn()} visible t={t} />)
const trigger = view.getByRole('button', { name: 'Filter lens: Exports' })
expect(trigger.hasAttribute('data-active')).toBe(true)
expect(trigger.textContent).toBe('Exports2/5')
view.rerender(<LensFilterMenu lenses={lenses} chosen={lenses[0] ?? null} run={{ kind: 'running', done: null, total: null }}
choose={vi.fn()} visible t={t} />)
expect(trigger.textContent).toBe('Exports')
view.rerender(<LensFilterMenu lenses={lenses} chosen={lenses[0] ?? null} run={{ kind: 'ready', files: {} }} choose={vi.fn()} visible t={t} />)
expect(trigger.textContent).toBe('Exports3')
view.rerender(<LensFilterMenu lenses={lenses} chosen={lenses[1] ?? null} run={{ kind: 'failed', code: 'x', message: 'y' }}
choose={vi.fn()} visible={false} t={t} />)
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)
})
})
@@ -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<SidebarRightTabActions['openResource']>()
// 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<string>('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(<ForgeTab {...props} />)
return {
@@ -254,9 +254,9 @@ describe('forgePanel lenses over change requests', () => {
'',
].join('\n')
async function bound(overrides: Partial<{ baseSha: string | undefined }> = { baseSha: BASE }): Promise<Bench> {
async function bound(base: string | null = BASE): Promise<Bench> {
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' }
@@ -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<typeof stream>[] = []
const stateStreams: ReturnType<typeof stream<ForgeChangeRequestStatesFrame>>[] = []
const extensionStreams: ReturnType<typeof stream<ForgeExtensionState>>[] = []
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<ForgeExtensionState>(signal)
extensionStreams.push(handle)
return handle
}),
changesLens: vi.fn((_sessionId: SessionId, _request: ForgeLensRequest, signal: AbortSignal) => stream<ForgeLensFrame>(signal)),
worktreeCleanup: vi.fn(async (_sessionId: SessionId, _revision: number | null): Promise<RemoteResult<WorktreeCleanup | null>> =>
({ ok: true, value: null })),
track: vi.fn(async (_sessionId: SessionId, _url: string): Promise<RemoteResult<void>> => 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<SessionId, ReturnType<Context['plugin']>>()
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()
@@ -15,7 +15,7 @@ afterEach(() => {
function mount(overrides: Partial<ViewOptions> = {}, 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(<div data-fold={fold}><ViewOptionsMenu options={options} visible={visible} t={t} /></div>)
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) => <button type="button" role="menuitem" onClick={close}>Notes 2</button>)
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([])
})