feat(walkthrough): write walkthroughs in the reader's language

A guided explanation is only useful in a language the reader reads, so the
panel header gets a language picker alongside the model one, defaulting to
the interface language. Like the model, it is request state rather than a
setting: the language travels with the read and the generation, and the one
a walkthrough was written in is stored with it, so reopening a review
describes what is there instead of what a fresh one would be.

Only prose is translated. Hunk aliases resolve back to hunk ids and
icon/importance are validated against fixed English values, so a translated
one would be dropped by the normalizer — silently losing an anchor or a
style. Identifiers and paths stay as they appear in the code.

The language is part of the cache key, and a read now asks the cache for the
exact request it was given before falling back to the pointer. Without that
the panel answered a request to switch languages with the text it already
had, leaving the other language unused in the cache.

Alongside it:

- The answer budget is derived from the resolved model instead of a flat 24k.
  That number was the same for a 64k-context model and for one that admits to
  384k output tokens, and on the latter it was the only reason generation
  failed: the model spent the whole allowance reasoning and returned nothing.
  It is now min(96k, max(24k, a quarter of the context)) capped by the
  catalog's output limit, decided once so the input reserve and the request
  cannot drift apart.
- A read no longer offers Cancel. It is a few hundred milliseconds of git with
  nothing to cancel, and the button flickered on every model or language
  change. When the panel is showing a fallback, a banner names what is on
  screen versus what was asked for — only once the read has settled.
- The header keeps one 32px control height and drops its labels below 680px
  instead of squeezing them to two letters and an ellipsis.

Docs and module documentation updated in every locale.
This commit is contained in:
Bohdan Triapitsyn
2026-08-03 01:27:27 +03:00
parent e5799c0c67
commit 1d17cb87b3
39 changed files with 1027 additions and 81 deletions
@@ -27,6 +27,13 @@ interface ModelSelectorProps {
placeholder?: string;
tooltipsEnabled?: boolean;
dropdownPortalToBody?: boolean;
/**
* Drop the model name and the chevron, leaving the provider logo. For
* headers that run out of room before they run out of controls — the logo
* still says which provider is answering, which is the part a glance is
* usually after.
*/
compact?: boolean;
}
export const ModelSelector: React.FC<ModelSelectorProps> = ({
@@ -39,6 +46,7 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
placeholder,
tooltipsEnabled = true,
dropdownPortalToBody = false,
compact = false,
}) => {
const { t } = useI18n();
const { isReady, isUnavailable } = useOpenCodeReadiness();
@@ -169,26 +177,35 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
return (
<DropdownMenu open={isReady && isDropdownOpen} onOpenChange={isReady ? setIsDropdownOpen : undefined}>
<DropdownMenuTrigger asChild>
<div className={cn(
dropdownTriggerVariants({ size: 'sm' }),
'min-w-0 w-fit',
!isReady && 'opacity-60 cursor-not-allowed',
className,
)}>
<div
className={cn(
dropdownTriggerVariants({ size: 'sm' }),
'min-w-0 w-fit',
!isReady && 'opacity-60 cursor-not-allowed',
className,
)}
// The name is gone from the trigger, so it has to stay
// reachable somewhere.
title={compact && isReady ? triggerLabel : undefined}
>
{!isReady ? (
<>
<Icon name="loader-4" className="h-3.5 w-3.5 animate-spin text-muted-foreground flex-shrink-0" />
<span className="typography-ui-label font-normal whitespace-nowrap text-muted-foreground">
{isUnavailable ? t('common.unavailable') : t('common.loading')}
</span>
{!compact && (
<span className="typography-ui-label font-normal whitespace-nowrap text-muted-foreground">
{isUnavailable ? t('common.unavailable') : t('common.loading')}
</span>
)}
</>
) : (
<>
{providerId ? <ProviderLogo providerId={providerId} className="h-3.5 w-3.5 flex-shrink-0" /> : <Icon name="pencil-ai" className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />}
<span className="typography-ui-label min-w-0 flex-1 truncate text-left font-normal text-foreground">{triggerLabel}</span>
{!compact && (
<span className="typography-ui-label min-w-0 flex-1 truncate text-left font-normal text-foreground">{triggerLabel}</span>
)}
</>
)}
<Icon name="arrow-down-s" className="h-4 w-4 flex-shrink-0 text-muted-foreground/50" />
{!compact && <Icon name="arrow-down-s" className="h-4 w-4 flex-shrink-0 text-muted-foreground/50" />}
</div>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col" align="start" portalToBody={dropdownPortalToBody}>
@@ -10,7 +10,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useI18n } from '@/lib/i18n';
import { useI18n, type Locale } from '@/lib/i18n';
import { buildWalkthroughView } from '@/lib/walkthrough/model';
import type { WalkthroughSource, WalkthroughWorkingTreeScope } from '@/lib/walkthrough/types';
import { ModelSelector } from '@/components/sections/agents/ModelSelector';
@@ -54,8 +54,19 @@ const TOC_MIN_WIDTH = 180;
// than half the panel no matter how far the user drags.
const TOC_MAX_FRACTION = 0.5;
// Below this the header controls wrap onto a second row and the labels squeeze
// to two letters and an ellipsis, which reads as broken rather than dense. The
// controls drop their text instead: every one of them carries an icon that
// already identifies it.
//
// Every control in this row is 32px tall — `Button` size `sm` and the dropdown
// trigger's `default` size are both h-8, so this is the design system's form
// scale rather than a number picked here. Three heights in one row (28px
// pickers, 32px action, 36px arrows) read as misalignment, not hierarchy.
const HEADER_COMPACT_WIDTH = 680;
export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
const { t } = useI18n();
const { t, locale, locales, label } = useI18n();
const rootRef = useRef<HTMLDivElement | null>(null);
const [panelWidth, setPanelWidth] = useState(0);
@@ -76,6 +87,9 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
const [draggingToc, setDraggingToc] = useState(false);
const showToc = panelWidth === 0 || panelWidth >= TOC_MIN_PANEL_WIDTH;
// Zero means the observer has not reported yet; assume there is room rather
// than rendering a compact header for one frame on every open.
const compactHeader = panelWidth > 0 && panelWidth < HEADER_COMPACT_WIDTH;
// Clamped on read rather than on write: the panel can be resized after the
// width was stored, and a remembered 400px column must not swallow a narrow
// panel.
@@ -229,12 +243,28 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
const requestSource = useWalkthroughStore((state) => state.requestSource);
const selectModel = useWalkthroughStore((state) => state.selectModel);
const selectedModel = useWalkthroughStore((state) => state.getSelectedModel(directory, source));
const selectLanguage = useWalkthroughStore((state) => state.selectLanguage);
const selectedLanguage = useWalkthroughStore((state) => state.getSelectedLanguage(directory, source));
// Reloads on a model change too: whether this diff fits, and whether the
// model can produce structured output, are answers about a specific model.
// Explicit pick first, then the language the walkthrough on screen is
// actually written in, then the interface locale. The middle step matters for
// the same reason it does for the model: reopening a review should describe
// what is there, not what a fresh one would be.
const generatedLanguage = entry.result?.language;
const activeLanguage: Locale = (
selectedLanguage && locales.includes(selectedLanguage as Locale)
? (selectedLanguage as Locale)
: generatedLanguage && locales.includes(generatedLanguage as Locale)
? (generatedLanguage as Locale)
: locale
);
// Reloads on a model or language change: whether this diff fits, and whether
// the model can produce structured output, are answers about a specific
// request — and the language instruction is part of that request.
useEffect(() => {
void load(directory, source);
}, [directory, load, source, selectedModel]);
void load(directory, source, { language: activeLanguage });
}, [activeLanguage, directory, load, source, selectedModel]);
const view = useMemo(() => buildWalkthroughView(entry.result), [entry.result]);
@@ -278,6 +308,7 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
);
const [sourceMenuOpen, setSourceMenuOpen] = useState(false);
const [languageMenuOpen, setLanguageMenuOpen] = useState(false);
const sourceValue = source.kind === 'working-tree' ? source.scope : source.kind;
const sourceLabel = source.kind === 'branch'
? t('walkthrough.scope.branch')
@@ -331,7 +362,27 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
[modelsMetadata]
);
const isBusy = entry.status === 'loading' || entry.status === 'generating';
// Only generation is worth interrupting. A read is a few hundred milliseconds
// of git with nothing to cancel, and offering a Cancel button for it made the
// action flicker every time the model or language changed.
const isGeneratingEntry = entry.status === 'generating';
// What is on screen versus what is being asked for. A read that has settled
// is the only thing that can answer this: while one is in flight the panel is
// still showing the previous answer, and a banner claiming something is
// missing before we know would be the same flicker in another place.
const shownModel = entry.result?.model
? `${entry.result.model.providerID}/${entry.result.model.modelID}`
: undefined;
const shownLanguage = entry.result?.language;
const shownLocale = shownLanguage && locales.includes(shownLanguage as Locale)
? (shownLanguage as Locale)
: undefined;
const settled = entry.status === 'ready' && Boolean(view);
// An entry written before walkthroughs had a language carries none. Unknown
// is not the same as different, so it is not reported as missing.
const languageMissing = settled && Boolean(shownLocale) && shownLocale !== activeLanguage;
const modelMissing = settled && Boolean(shownModel) && Boolean(activeModel) && shownModel !== activeModel;
// The stage list outlives the work by a beat. Assembling takes milliseconds,
// so without this the result replaces the list before the last step is ever
@@ -371,9 +422,9 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
const handleGenerate = useCallback(
(force: boolean) => {
void generate(directory, source, { force });
void generate(directory, source, { force, language: activeLanguage });
},
[directory, generate, source]
[activeLanguage, directory, generate, source]
);
return (
@@ -383,7 +434,7 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring"
className="flex h-8 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring"
aria-label={t('walkthrough.scope.selectorAria')}
>
<span className="whitespace-nowrap">{sourceLabel}</span>
@@ -444,6 +495,47 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
</DropdownMenu>
<div className="ml-auto flex min-w-0 items-center gap-1">
{/* A walkthrough nobody can read is worth nothing, so the prose
language is a per-review choice like the model — defaulting to the
interface language, which is the best evidence of what the reader
reads. */}
<DropdownMenu open={languageMenuOpen} onOpenChange={setLanguageMenuOpen}>
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-8 min-w-0 flex-shrink items-center gap-1.5 rounded-md px-2 typography-ui-label text-muted-foreground outline-none hover:bg-interactive-hover hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
aria-label={t('walkthrough.language.selectorAria')}
title={compactHeader ? label(activeLanguage) : undefined}
>
<Icon name="global" className="size-4 flex-shrink-0 opacity-70" />
{!compactHeader && (
<>
<span className="truncate">{label(activeLanguage)}</span>
<Icon name="arrow-down-s" className="size-4 flex-shrink-0 opacity-60" />
</>
)}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuLabel className={SCOPE_GROUP_LABEL_CLASS}>
{t('walkthrough.language.menuLabel')}
</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={activeLanguage}
onValueChange={(value) => {
setLanguageMenuOpen(false);
selectLanguage(directory, source, value);
}}
>
{locales.map((value) => (
<DropdownMenuRadioItem key={value} value={value}>
{label(value)}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
{/* Choosing a roomier model for a risky change is a per-review call,
so this is panel state rather than a settings edit. */}
<ModelSelector
@@ -456,14 +548,15 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
isModelAllowed={isStructuredOutputCapable}
tooltipsEnabled={false}
dropdownPortalToBody
className="h-7 min-w-0 max-w-48"
compact={compactHeader}
className={cn('h-8 min-w-0', !compactHeader && 'max-w-48')}
/>
{view && (
<>
<Button
type="button"
variant="ghost"
size="icon"
size="sm"
aria-label={t('walkthrough.action.previous')}
onClick={() => step(-1)}
>
@@ -472,7 +565,7 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
<Button
type="button"
variant="ghost"
size="icon"
size="sm"
aria-label={t('walkthrough.action.next')}
onClick={() => step(1)}
>
@@ -481,9 +574,18 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
</>
)}
{isBusy ? (
<Button type="button" variant="outline" size="sm" onClick={() => cancel(directory, source)}>
{t('walkthrough.action.cancel')}
{isGeneratingEntry ? (
<Button
type="button"
variant="outline"
size="sm"
aria-label={compactHeader ? t('walkthrough.action.cancel') : undefined}
title={compactHeader ? t('walkthrough.action.cancel') : undefined}
onClick={() => cancel(directory, source)}
>
{compactHeader
? <Icon name="stop" className="size-3.5" />
: t('walkthrough.action.cancel')}
</Button>
) : (
<Button
@@ -491,10 +593,16 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
variant="outline"
size="sm"
className={WALKTHROUGH_ACTION_CLASS}
aria-label={compactHeader
? (view ? t('walkthrough.action.regenerate') : t('walkthrough.action.generate'))
: undefined}
title={compactHeader
? (view ? t('walkthrough.action.regenerate') : t('walkthrough.action.generate'))
: undefined}
onClick={() => handleGenerate(Boolean(view))}
>
<Icon name={view ? 'refresh' : 'route'} className="size-3.5" />
{view ? t('walkthrough.action.regenerate') : t('walkthrough.action.generate')}
{!compactHeader && (view ? t('walkthrough.action.regenerate') : t('walkthrough.action.generate'))}
</Button>
)}
</div>
@@ -516,6 +624,38 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
</div>
)}
{/* Switching the model or the language is a request for a walkthrough
that may not exist yet. Falling back to the last one is better than an
empty panel, but only if the panel says so — otherwise the picker
claims Ukrainian over English prose. */}
{(languageMissing || modelMissing) && (
<div className="flex shrink-0 items-center gap-2 border-b border-border/60 bg-[var(--status-info-background)] px-3 py-2">
<Icon name="information" className="size-4 shrink-0 text-[var(--status-info)]" />
<span className="typography-meta text-foreground">
{languageMissing && modelMissing
? t('walkthrough.missing.languageAndModel')
: languageMissing
? t('walkthrough.missing.language', {
requested: label(activeLanguage),
shown: label(shownLocale as Locale),
})
: t('walkthrough.missing.model', { model: activeModelId })}
</span>
<Button
type="button"
variant="ghost"
size="xs"
className="ml-auto"
// Not forced: if an entry for this exact request existed the banner
// would not be here, and a forced run would refuse the cache it may
// find on the way.
onClick={() => handleGenerate(false)}
>
{t('walkthrough.action.generate')}
</Button>
</div>
)}
{view?.isStale && entry.status !== 'generating' && (
<div className="flex shrink-0 items-center gap-2 border-b border-border/60 bg-status-warning/10 px-3 py-2">
<Icon name="error-warning" className="size-4 shrink-0 text-status-warning" />
@@ -529,7 +669,7 @@ export const WalkthroughView = ({ directory }: WalkthroughViewProps) => {
className="ml-auto"
// Clicking this again mid-flight would abort the running generation
// and start another — paying for the same answer twice.
disabled={isBusy}
disabled={isGeneratingEntry}
onClick={() => handleGenerate(true)}
>
{t('walkthrough.action.regenerate')}
+5
View File
@@ -1106,6 +1106,11 @@ export const dict = {
'walkthrough.scope.working': 'Unstaged',
'walkthrough.scope.branch': 'This branch',
'walkthrough.scope.selectorAria': 'Select what to review',
'walkthrough.language.menuLabel': 'Walkthrough language',
'walkthrough.missing.language': 'No walkthrough in {requested} yet — showing the one in {shown}.',
'walkthrough.missing.model': 'No walkthrough from {model} yet — showing the last one generated here.',
'walkthrough.missing.languageAndModel': 'No walkthrough in this language from this model yet — showing the last one generated here.',
'walkthrough.language.selectorAria': 'Select the walkthrough language',
'walkthrough.scope.pullRequest': 'PR #{number}',
'walkthrough.action.generate': 'Generate walkthrough',
'walkthrough.action.regenerate': 'Regenerate',
+5
View File
@@ -1107,6 +1107,11 @@ export const dict: Record<I18nKey, string> = {
"walkthrough.scope.working": "Sin preparar",
"walkthrough.scope.branch": "Esta rama",
"walkthrough.scope.selectorAria": "Elegir qué revisar",
"walkthrough.language.menuLabel": "Idioma del recorrido",
"walkthrough.missing.language": "Aún no hay un recorrido en {requested}: se muestra el de {shown}.",
"walkthrough.missing.model": "Aún no hay un recorrido de {model}: se muestra el último generado aquí.",
"walkthrough.missing.languageAndModel": "Aún no hay un recorrido en este idioma con este modelo: se muestra el último generado aquí.",
"walkthrough.language.selectorAria": "Elegir el idioma del recorrido",
"walkthrough.scope.pullRequest": "PR n.º {number}",
"walkthrough.action.generate": "Generar recorrido",
"walkthrough.action.regenerate": "Regenerar",
+5
View File
@@ -931,6 +931,11 @@ export const dict = {
'walkthrough.scope.working': 'Non indexées',
'walkthrough.scope.branch': 'Cette branche',
'walkthrough.scope.selectorAria': 'Choisir ce qui est examiné',
'walkthrough.language.menuLabel': 'Langue du parcours',
'walkthrough.missing.language': 'Pas encore de parcours en {requested} — voici celui en {shown}.',
'walkthrough.missing.model': 'Pas encore de parcours généré par {model} — voici le dernier généré ici.',
'walkthrough.missing.languageAndModel': 'Pas encore de parcours dans cette langue avec ce modèle — voici le dernier généré ici.',
'walkthrough.language.selectorAria': 'Choisir la langue du parcours',
'walkthrough.scope.pullRequest': 'PR n° {number}',
'walkthrough.action.generate': 'Générer le parcours',
'walkthrough.action.regenerate': 'Régénérer',
+5
View File
@@ -1103,6 +1103,11 @@ export const dict: Record<I18nKey, string> = {
'walkthrough.scope.working': '未ステージ',
'walkthrough.scope.branch': 'このブランチ',
'walkthrough.scope.selectorAria': 'レビュー対象を選択',
'walkthrough.language.menuLabel': 'ウォークスルーの言語',
'walkthrough.missing.language': '{requested}のウォークスルーはまだありません。{shown}のものを表示しています。',
'walkthrough.missing.model': '{model} が生成したウォークスルーはまだありません。ここで最後に生成されたものを表示しています。',
'walkthrough.missing.languageAndModel': 'この言語・このモデルのウォークスルーはまだありません。ここで最後に生成されたものを表示しています。',
'walkthrough.language.selectorAria': 'ウォークスルーの言語を選択',
'walkthrough.scope.pullRequest': 'PR #{number}',
'walkthrough.action.generate': 'ウォークスルーを生成',
'walkthrough.action.regenerate': '再生成',
+5
View File
@@ -1107,6 +1107,11 @@ export const dict: Record<I18nKey, string> = {
'walkthrough.scope.working': '스테이지 안 됨',
'walkthrough.scope.branch': '이 브랜치',
'walkthrough.scope.selectorAria': '리뷰 대상 선택',
'walkthrough.language.menuLabel': '워크스루 언어',
'walkthrough.missing.language': '{requested} 워크스루가 아직 없어 {shown} 워크스루를 표시합니다.',
'walkthrough.missing.model': '{model}(으)로 생성한 워크스루가 아직 없어 마지막으로 생성된 것을 표시합니다.',
'walkthrough.missing.languageAndModel': '이 언어와 이 모델로 생성한 워크스루가 아직 없어 마지막으로 생성된 것을 표시합니다.',
'walkthrough.language.selectorAria': '워크스루 언어 선택',
'walkthrough.scope.pullRequest': 'PR #{number}',
'walkthrough.action.generate': '워크스루 생성',
'walkthrough.action.regenerate': '다시 생성',
+5
View File
@@ -1419,6 +1419,11 @@ export const dict: Record<I18nKey, string> = {
'walkthrough.scope.working': 'Poza poczekalnią',
'walkthrough.scope.branch': 'Ta gałąź',
'walkthrough.scope.selectorAria': 'Wybierz, co przejrzeć',
'walkthrough.language.menuLabel': 'Język przewodnika',
'walkthrough.missing.language': 'Nie ma jeszcze przewodnika w języku {requested} — pokazujemy ten w języku {shown}.',
'walkthrough.missing.model': 'Nie ma jeszcze przewodnika od modelu {model} — pokazujemy ostatni wygenerowany tutaj.',
'walkthrough.missing.languageAndModel': 'Nie ma jeszcze przewodnika w tym języku od tego modelu — pokazujemy ostatni wygenerowany tutaj.',
'walkthrough.language.selectorAria': 'Wybierz język przewodnika',
'walkthrough.scope.pullRequest': 'PR #{number}',
'walkthrough.action.generate': 'Wygeneruj przewodnik',
'walkthrough.action.regenerate': 'Wygeneruj ponownie',
@@ -1107,6 +1107,11 @@ export const dict: Record<I18nKey, string> = {
"walkthrough.scope.working": "Fora do stage",
"walkthrough.scope.branch": "Este branch",
"walkthrough.scope.selectorAria": "Escolher o que revisar",
"walkthrough.language.menuLabel": "Idioma do percurso",
"walkthrough.missing.language": "Ainda não há um percurso em {requested} — exibindo o de {shown}.",
"walkthrough.missing.model": "Ainda não há um percurso gerado por {model} — exibindo o último gerado aqui.",
"walkthrough.missing.languageAndModel": "Ainda não há um percurso neste idioma com este modelo — exibindo o último gerado aqui.",
"walkthrough.language.selectorAria": "Escolher o idioma do percurso",
"walkthrough.scope.pullRequest": "PR nº {number}",
"walkthrough.action.generate": "Gerar percurso",
"walkthrough.action.regenerate": "Gerar novamente",
+5
View File
@@ -1107,6 +1107,11 @@ export const dict: Record<I18nKey, string> = {
"walkthrough.scope.working": "Поза індексом",
"walkthrough.scope.branch": "Ця гілка",
"walkthrough.scope.selectorAria": "Обрати, що розбирати",
"walkthrough.language.menuLabel": "Мова розбору",
"walkthrough.missing.language": "Розбору мовою {requested} ще немає — показано той, що мовою {shown}.",
"walkthrough.missing.model": "Розбору від {model} ще немає — показано останній згенерований тут.",
"walkthrough.missing.languageAndModel": "Розбору цією мовою від цієї моделі ще немає — показано останній згенерований тут.",
"walkthrough.language.selectorAria": "Обрати мову розбору",
"walkthrough.scope.pullRequest": "PR #{number}",
"walkthrough.action.generate": "Створити розбір",
"walkthrough.action.regenerate": "Створити заново",
@@ -1107,6 +1107,11 @@ export const dict: Record<I18nKey, string> = {
'walkthrough.scope.working': '未暂存',
'walkthrough.scope.branch': '当前分支',
'walkthrough.scope.selectorAria': '选择评审范围',
'walkthrough.language.menuLabel': '导读语言',
'walkthrough.missing.language': '尚无{requested}导读,当前显示的是{shown}版本。',
'walkthrough.missing.model': '尚无由 {model} 生成的导读,当前显示最近一次生成的版本。',
'walkthrough.missing.languageAndModel': '尚无使用该语言和该模型生成的导读,当前显示最近一次生成的版本。',
'walkthrough.language.selectorAria': '选择导读语言',
'walkthrough.scope.pullRequest': 'PR #{number}',
'walkthrough.action.generate': '生成导读',
'walkthrough.action.regenerate': '重新生成',
@@ -1119,6 +1119,11 @@ export const dict: Record<I18nKey, string> = {
'walkthrough.scope.working': '未暫存',
'walkthrough.scope.branch': '目前分支',
'walkthrough.scope.selectorAria': '選擇審閱範圍',
'walkthrough.language.menuLabel': '導讀語言',
'walkthrough.missing.language': '尚無{requested}導讀,目前顯示的是{shown}版本。',
'walkthrough.missing.model': '尚無由 {model} 產生的導讀,目前顯示最近一次產生的版本。',
'walkthrough.missing.languageAndModel': '尚無使用該語言與該模型產生的導讀,目前顯示最近一次產生的版本。',
'walkthrough.language.selectorAria': '選擇導讀語言',
'walkthrough.scope.pullRequest': 'PR #{number}',
'walkthrough.action.generate': '產生導讀',
'walkthrough.action.regenerate': '重新產生',
+4 -2
View File
@@ -31,13 +31,14 @@ const throwFromResponse = async (response: Response, fallback: string): Promise<
export async function fetchWalkthrough(
directory: string,
source: WalkthroughSource,
options: { model?: string; signal?: AbortSignal } = {}
options: { model?: string; language?: string; signal?: AbortSignal } = {}
): Promise<WalkthroughResult> {
const response = await runtimeFetch(BASE, {
query: {
directory,
source: JSON.stringify(source),
...(options.model ? { model: options.model } : {}),
...(options.language ? { language: options.language } : {}),
},
signal: options.signal,
});
@@ -50,7 +51,7 @@ export async function fetchWalkthrough(
export async function generateWalkthrough(
directory: string,
source: WalkthroughSource,
options: { force?: boolean; model?: string; signal?: AbortSignal } = {}
options: { force?: boolean; model?: string; language?: string; signal?: AbortSignal } = {}
): Promise<WalkthroughResult> {
const response = await runtimeFetch(`${BASE}/generate`, {
method: 'POST',
@@ -60,6 +61,7 @@ export async function generateWalkthrough(
source,
force: options.force === true,
...(options.model ? { model: options.model } : {}),
...(options.language ? { language: options.language } : {}),
}),
signal: options.signal,
});
+5
View File
@@ -62,6 +62,11 @@ export interface WalkthroughResult {
source: WalkthroughSource;
walkthrough: Walkthrough | null;
model?: WalkthroughModel;
/**
* Language the prose on screen is written in not necessarily the one being
* asked for now. Null for an entry written before the setting existed.
*/
language?: string | null;
generatedAt?: string;
fromCache?: boolean;
hunks: WalkthroughHunk[];
@@ -33,28 +33,35 @@ let generateCalls = 0;
let releaseGeneration: (() => void) | undefined;
let lastReadModel: string | undefined;
let lastGenerateModel: string | undefined;
let lastReadLanguage: string | undefined;
let lastGenerateLanguage: string | undefined;
mock.module('@/lib/walkthrough/api', () => ({
fetchWalkthrough: async (
_directory: string,
_source: WalkthroughSource,
options: { model?: string } = {},
options: { model?: string; language?: string } = {},
) => {
lastReadModel = options.model;
lastReadLanguage = options.language;
return readResult;
},
generateWalkthrough: async (
_directory: string,
_source: WalkthroughSource,
options: { model?: string } = {},
options: { model?: string; language?: string } = {},
) => {
generateCalls += 1;
lastGenerateModel = options.model;
lastGenerateLanguage = options.language;
return new Promise<WalkthroughResult>((resolve) => {
releaseGeneration = () => resolve(finished);
});
},
cancelWalkthroughGeneration: async () => {},
// The store imports this for its progress poller. Leaving it out of the mock
// makes the whole module fail to load, which reads as an unrelated crash.
fetchWalkthroughStage: async () => null,
}));
mock.module('@/lib/runtime-switch', () => ({ getRuntimeKey: () => 'local' }));
@@ -162,3 +169,57 @@ describe('useWalkthroughStore — model selection', () => {
.toBe('anthropic/claude-haiku-4-5');
});
});
describe('useWalkthroughStore — walkthrough language', () => {
beforeEach(() => {
useWalkthroughStore.getState().reset();
readResult = result();
generateCalls = 0;
lastReadLanguage = undefined;
lastGenerateLanguage = undefined;
});
afterEach(() => {
useWalkthroughStore.getState().reset();
});
// The read carries it too: readiness is an answer about a specific request,
// and the language instruction is part of that request.
test('sends the resolved language with both the read and the generation', async () => {
await useWalkthroughStore.getState().load('/repo', SOURCE, { language: 'uk' });
await flush();
expect(lastReadLanguage).toBe('uk');
void useWalkthroughStore.getState().generate('/repo', SOURCE, { language: 'uk' });
await flush();
expect(lastGenerateLanguage).toBe('uk');
releaseGeneration?.();
await flush();
});
test('keeps an explicit choice apart per source', () => {
const branch: WalkthroughSource = { kind: 'branch', baseRef: 'main', headRef: 'feature' };
useWalkthroughStore.getState().selectLanguage('/repo', SOURCE, 'ja');
expect(useWalkthroughStore.getState().getSelectedLanguage('/repo', branch)).toBe(undefined);
expect(useWalkthroughStore.getState().getSelectedLanguage('/repo', SOURCE)).toBe('ja');
});
test('clearing the choice returns to no explicit language', () => {
useWalkthroughStore.getState().selectLanguage('/repo', SOURCE, 'ja');
useWalkthroughStore.getState().selectLanguage('/repo', SOURCE, null);
expect(useWalkthroughStore.getState().getSelectedLanguage('/repo', SOURCE)).toBe(undefined);
});
test('a re-attach after a reload still names the language it would ask for', async () => {
readResult = result({ generating: true });
await useWalkthroughStore.getState().load('/repo', SOURCE, { language: 'pl' });
await flush();
expect(lastGenerateLanguage).toBe('pl');
releaseGeneration?.();
await flush();
});
});
Binary file not shown.