From c1e9d95eee0a22f54cd4a026990fc41e67888b94 Mon Sep 17 00:00:00 2001 From: cxykhaos <992308975@qq.com> Date: Wed, 2 Dec 2026 13:56:47 +0800 Subject: [PATCH 1/3] fix(display): offer native 2K resolution scaled to fit a window --- changes/window-native-resolution.json | 9 ++++ frontend/package.json | 2 +- frontend/scripts/test-display-presets.mjs | 60 +++++++++++++++++++++++ frontend/src/App.tsx | 3 ++ frontend/src/components/CreateWizard.tsx | 10 ++-- frontend/src/components/SettingsModal.tsx | 8 +-- frontend/src/i18n/domains/settings.gen.ts | 2 + frontend/src/i18n/keys.gen.ts | 1 + frontend/src/lib/format.ts | 16 ++++++ internal/host/display_stats_test.go | 7 +++ locales/en-US/settings.json | 1 + locales/zh-CN/settings.json | 1 + 12 files changed, 112 insertions(+), 8 deletions(-) create mode 100644 changes/window-native-resolution.json create mode 100644 frontend/scripts/test-display-presets.mjs diff --git a/changes/window-native-resolution.json b/changes/window-native-resolution.json new file mode 100644 index 0000000..2dd56f1 --- /dev/null +++ b/changes/window-native-resolution.json @@ -0,0 +1,9 @@ +{ + "group": "fixes", + "order": 0, + "authors": [ + "cxykhaos" + ], + "zh": "在支持固定显示模式的运行时中,创建和设置虚拟机时可在窗口模式选择目标显示器的原生分辨率,并缩放以适应窗口。", + "en": "Allow the target display’s native resolution in windowed mode when creating or configuring a VM with a fixed-display-mode runtime, scaling it to fit the window." +} diff --git a/frontend/package.json b/frontend/package.json index 93ce7b7..ad59e16 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "vite", - "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-tasks.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs", + "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs", "typecheck": "tsc --noEmit", "bundle": "vite build && node scripts/check-ui-contract.mjs", "build": "tsc --noEmit && pnpm run bundle", diff --git a/frontend/scripts/test-display-presets.mjs b/frontend/scripts/test-display-presets.mjs new file mode 100644 index 0000000..4c4ef3b --- /dev/null +++ b/frontend/scripts/test-display-presets.mjs @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { loadTestModule } from './load-test-module.mjs' + +const { windowDisplayPresets, recommendedDisplayPresets, recommendedResolution } = + await loadTestModule(`export * from './lib/format'`) + +function profile(width, height) { + return { + primary_display: { width, height, scale_pct: 125 }, + display_presets: [ + { resolution: '1920x1080', label: '1920 × 1080', hidpi: false, recommended: true }, + { resolution: '1600x900', label: '1600 × 900', hidpi: false }, + ], + } +} + +for (const [width, height] of [[2560, 1440], [2560, 1600]]) { + test(`fixed-mode runtime offers native ${width}x${height} in a window without changing fit recommendations`, () => { + const host = profile(width, height) + const before = structuredClone(host) + const fit = recommendedDisplayPresets(host) + assert.strictEqual(windowDisplayPresets(host, false), fit) + const options = windowDisplayPresets(host, true) + assert.deepEqual(options.slice(0, fit.length), fit) + assert.deepEqual(options.at(-1), { + resolution: `${width}x${height}`, label: `${width} × ${height}`, hidpi: false, scaleToFit: true, + }) + assert.equal(options.filter((p) => p.recommended).length, 1) + assert.equal(recommendedResolution(host), '1920x1080') + assert.deepEqual(host, before) + }) +} + +test('an existing native preset is not duplicated or relabeled', () => { + const host = profile(2560, 1440) + host.display_presets.push({ resolution: '2560x1440', label: '2560 × 1440', hidpi: false }) + assert.strictEqual(windowDisplayPresets(host, true), host.display_presets) +}) + +test('missing or invalid target geometry keeps fit-only presets', () => { + for (const display of [undefined, { width: 0, height: 1440 }, { width: 2560, height: -1 }, { width: 1920, height: 1080 }]) { + const host = { ...profile(2560, 1440), primary_display: display } + assert.strictEqual(windowDisplayPresets(host, true), host.display_presets) + } +}) + +test('native guest HiDPI metadata is preserved when scaling into a window', () => { + const host = { ...profile(3840, 2160), fullscreen_hidpi: true } + const preset = windowDisplayPresets(host, true).at(-1) + assert.equal(preset.hidpi, true) + assert.equal(preset.scaleToFit, true) +}) + +test('the effective target profile determines the added window resolution', () => { + const primary = profile(3840, 2160) + const target = { ...primary, primary_display: { width: 2560, height: 1600, scale_pct: 150 } } + assert.equal(windowDisplayPresets(target, true).at(-1).resolution, '2560x1600') + assert.equal(windowDisplayPresets(primary, true).at(-1).resolution, '3840x2160') +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index bd29262..00f72fe 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -342,6 +342,7 @@ export const App: React.FC = () => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] + const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime const canSuspend = state?.can_suspend ?? false @@ -1318,6 +1319,7 @@ export const App: React.FC = () => { { setShowWizard(false); setWizardDraft(null) }} @@ -1334,6 +1336,7 @@ export const App: React.FC = () => { driverID={selectedVM?.driver_id ?? ''} stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)} host={state.host} + fixedModeSupported={fixedModeSupported} optimizations={state.optimizations} running={effectiveState === 'running'} onCopy={copy} diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 275f6a5..6abb19c 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -23,7 +23,7 @@ import { hidpiLooksLike, hostDisplayAdvice, hostDisplayDesc, - recommendedDisplayPresets, + windowDisplayPresets, recommendedMemoryGB, recommendedResolution, shortGPUName, @@ -49,6 +49,7 @@ export interface WizardDraft { interface Props { locale: Locale host: HostReport + fixedModeSupported?: boolean tasks?: Task[] draft?: WizardDraft | null onClose: () => void @@ -75,7 +76,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] -export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, onClose, onSubmit }) => { +export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [step, setStep] = useState(draft?.step ?? 1) // Once the user has reached the review step, keep validating so step markers stay current. @@ -562,13 +563,14 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, label={tr('resolution')} value={opts.resolution} onChange={(resolution) => set({ resolution })} - options={(opts.borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host)).map((p: FullscreenDisplayPreset) => ({ + options={(opts.borderless ? fullscreenDisplayPresets(host) : windowDisplayPresets(host, fixedModeSupported)).map((p: FullscreenDisplayPreset) => ({ value: p.resolution, label: p.label, detail: [ p.hidpi ? `${tr('hidpiPresetBadge')} · ${hidpiLooksLike(p.resolution, tr) ?? ''}` : '', p.scaleBadge ?? '', p.native ? tr('resNativeBadge') : '', + p.scaleToFit ? tr('resScaleToFitWindow') : '', p.recommended ? tr('recommendedBadge') : '', ].filter(Boolean).join(' · ') || undefined, }))} @@ -627,7 +629,7 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => { - const list = borderless ? fullscreenDisplayPresets(host) : recommendedDisplayPresets(host) + const list = borderless ? fullscreenDisplayPresets(host) : windowDisplayPresets(host, fixedModeSupported) const keep = list.some((p) => p.resolution === opts.resolution) const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution set(keep ? { borderless } : { borderless, resolution: fallback }) diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index de9c470..07a12f9 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -22,7 +22,7 @@ import { hidpiLooksLike, hostDisplayAdvice, hostDisplayDesc, - recommendedDisplayPresets, + windowDisplayPresets, recommendedMemoryGB, recommendedResolution, shortGPUName, @@ -168,6 +168,7 @@ interface Props { driverID: string stats?: VMStats | null host: HostReport + fixedModeSupported?: boolean optimizations?: Optimization[] running: boolean onCopy?: (text: string) => void @@ -181,7 +182,7 @@ interface Props { onSaved: () => void } -export const SettingsModal: React.FC = ({ locale, detail, driverID, stats, host, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => { +export const SettingsModal: React.FC = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const irqOpt = findOptimization(optimizations, 'kernel_irqchip') const base = useMemo(() => baseline(detail, host), [detail, host]) @@ -294,7 +295,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats hidpi_advice: displayStatus.hidpi_advice, recommended_resolution: undefined, } : host, [host, displayStatus, activeTargetDisplay]) - const presets = recommendedDisplayPresets(displayProfile) + const presets = windowDisplayPresets(displayProfile, fixedModeSupported) const fsPresets = fullscreenDisplayPresets(displayProfile) const activePresets: FullscreenDisplayPreset[] = form.borderless ? fsPresets : presets const presetHit = activePresets.some((p) => same('resolution', p.resolution, form.resolution)) @@ -1155,6 +1156,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats p.hidpi ? tr('hidpiPresetBadge') : '', p.scaleBadge ?? '', p.native ? tr('resNativeBadge') : '', + p.scaleToFit ? tr('resScaleToFitWindow') : '', p.recommended ? tr('recommendedBadge') : '', ].filter(Boolean), })), diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index dd6bd27..942a034 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -399,6 +399,7 @@ export const settingsZh: Record = { "resFullscreen": "全屏", "resInvalid": "格式为 宽x高,例如 2560x1600", "resNativeBadge": "原生", + "resScaleToFitWindow": "缩放以适应窗口", "resetAll": "全部还原", "resetField": "还原为当前值", "runtimeDelete": "删除运行时", @@ -886,6 +887,7 @@ export const settingsEn: Record = { "resFullscreen": "Full screen", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", "resNativeBadge": "Native", + "resScaleToFitWindow": "Scale to fit window", "resetAll": "Revert all", "resetField": "Revert to current value", "runtimeDelete": "Delete runtime", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 86798b1..f8e5484 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -774,6 +774,7 @@ export type I18nKey = | "resInvalid" | "resLooksLike" | "resNativeBadge" + | "resScaleToFitWindow" | "resetAll" | "resetField" | "resizeLogPanel" diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 5397d1c..9776609 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -307,6 +307,22 @@ export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] { export interface FullscreenDisplayPreset extends DisplayPreset { native?: boolean scaleBadge?: string + scaleToFit?: boolean +} + +/** Preserve fit recommendations; fixed-mode runtimes can scale native guest pixels into a window. */ +export function windowDisplayPresets(host: HostReport, fixedModeSupported: boolean): FullscreenDisplayPreset[] { + const presets = recommendedDisplayPresets(host) + const d = host.primary_display + if (!fixedModeSupported || !d || d.width < 2560 || d.height < 1440) return presets + const resolution = `${d.width}x${d.height}` + if (presets.some((p) => p.resolution === resolution)) return presets + return [...presets, { + resolution, + label: `${d.width} × ${d.height}`, + hidpi: !!host.fullscreen_hidpi, + scaleToFit: true, + }] } /** diff --git a/internal/host/display_stats_test.go b/internal/host/display_stats_test.go index f14430e..2323146 100644 --- a/internal/host/display_stats_test.go +++ b/internal/host/display_stats_test.go @@ -141,6 +141,8 @@ func TestRecommendDisplayPresets(t *testing.T) { func TestShouldUseFixedGuestMode(t *testing.T) { uhd := &DisplayInfo{Width: 3840, Height: 2160, ScalePct: 150, WorkWidth: 3840, WorkHeight: 2088, Primary: true} + qhd := &DisplayInfo{Width: 2560, Height: 1440, ScalePct: 125, WorkWidth: 2560, WorkHeight: 1380, Primary: true} + wqxga := &DisplayInfo{Width: 2560, Height: 1600, ScalePct: 150, WorkWidth: 2560, WorkHeight: 1528} cases := []struct { name string borderless bool @@ -152,6 +154,11 @@ func TestShouldUseFixedGuestMode(t *testing.T) { {"fullscreen 4K native stays 1:1", true, "3840x2160", uhd, false}, {"fullscreen 4K upscaled 1440p", true, "2560x1440", uhd, true}, {"windowed fits monitor", false, "3200x1800", uhd, false}, + {"windowed 1440p native exceeds work area", false, "2560x1440", qhd, true}, + {"windowed 1600p native exceeds work area", false, "2560x1600", wqxga, true}, + {"windowed 1440p fit stays ordinary", false, "1920x1080", qhd, false}, + {"fullscreen 1440p native stays 1:1", true, "2560x1440", qhd, false}, + {"windowed 1440p work area fallback", false, "2560x1440", &DisplayInfo{Width: 2560, Height: 1440, ScalePct: 125}, true}, {"windowed exceeds monitor supersampled", false, "5120x2880", uhd, true}, {"invalid resolution", true, "bad", uhd, false}, {"fullscreen unknown display", true, "5120x2880", nil, true}, diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index a3d434d..cc907d3 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -223,6 +223,7 @@ "resCustomSub": "Width × height", "resFullscreen": "Full screen", "resNativeBadge": "Native", + "resScaleToFitWindow": "Scale to fit window", "resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600", "driveShareTitle": "Windows drive sharing", "driveShareMaster": "Share Windows drives", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 7cff96f..59fca5e 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -223,6 +223,7 @@ "resCustomSub": "宽 × 高", "resFullscreen": "全屏", "resNativeBadge": "原生", + "resScaleToFitWindow": "缩放以适应窗口", "resInvalid": "格式为 宽x高,例如 2560x1600", "driveShareTitle": "Windows 盘符共享", "driveShareMaster": "共享 Windows 盘符", From 037047ea439face5e6967f0edf5b73eaa08727ac Mon Sep 17 00:00:00 2001 From: cxykhaos <992308975@qq.com> Date: Wed, 2 Dec 2026 22:08:50 +0800 Subject: [PATCH 2/3] fix(display): correct window HiDPI advice and fullscreen fallback --- frontend/scripts/test-display-presets.mjs | 41 ++++++++++++++++++++++- frontend/src/components/CreateWizard.tsx | 11 +++--- frontend/src/components/SettingsModal.tsx | 5 +-- frontend/src/lib/format.ts | 11 ++++-- 4 files changed, 59 insertions(+), 9 deletions(-) diff --git a/frontend/scripts/test-display-presets.mjs b/frontend/scripts/test-display-presets.mjs index 4c4ef3b..1c21cc3 100644 --- a/frontend/scripts/test-display-presets.mjs +++ b/frontend/scripts/test-display-presets.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { loadTestModule } from './load-test-module.mjs' -const { windowDisplayPresets, recommendedDisplayPresets, recommendedResolution } = +const { windowDisplayPresets, fullscreenDisplayPresets, recommendedDisplayPresets, recommendedResolution, hostDisplayAdvice, canKeepDisplayPreset } = await loadTestModule(`export * from './lib/format'`) function profile(width, height) { @@ -52,6 +52,45 @@ test('native guest HiDPI metadata is preserved when scaling into a window', () = assert.equal(preset.scaleToFit, true) }) +test('window HiDPI presets suppress only the contradictory fullscreen advice', () => { + const host = { ...profile(2560, 1600), fullscreen_hidpi: true, hidpi_advice: 'fullscreen' } + const tr = (key) => key + assert.equal(hostDisplayAdvice(host, tr, windowDisplayPresets(host, false)), 'hidpiTipFullscreen') + assert.equal(hostDisplayAdvice(host, tr, windowDisplayPresets(host, true)), undefined) + assert.equal(hostDisplayAdvice({ ...host, hidpi_advice: 'scale' }, tr, windowDisplayPresets(host, true)), 'hidpiTipScale') + assert.equal(hostDisplayAdvice({ ...host, hidpi_advice: 'unavailable' }, tr, windowDisplayPresets(host, true)), 'hidpiTipUnavailable') +}) + +test('fullscreen round trips return to fit presets instead of implicitly opting into scaling', () => { + for (const fixedModeSupported of [false, true]) { + const host = profile(2560, 1440) + const windows = windowDisplayPresets(host, fixedModeSupported) + const full = fullscreenDisplayPresets(host) + const switchMode = (resolution, borderless) => { + const list = borderless ? full : windows + return list.some((p) => canKeepDisplayPreset(p, resolution, borderless)) + ? resolution + : list.find((p) => p.recommended)?.resolution ?? list[0].resolution + } + const native = switchMode('1920x1080', true) + assert.equal(native, '2560x1440') + assert.equal(switchMode(native, false), '1920x1080') + assert.equal(switchMode('1600x900', false), '1600x900') + } + const native = windowDisplayPresets(profile(2560, 1440), true).at(-1) + assert.equal(native.scaleToFit, true) // Still available for explicit window-mode selection. + assert.equal(canKeepDisplayPreset(native, '2560 × 1440', true), true) + assert.equal(canKeepDisplayPreset(native, '2560 × 1440', false), false) +}) + +test('new scaled window presets stay within the supported 5K bounds', () => { + for (const [width, height] of [[6016, 3384], [7680, 2160], [5120, 3202]]) { + const host = profile(width, height) + assert.strictEqual(windowDisplayPresets(host, true), host.display_presets) + } + assert.equal(windowDisplayPresets(profile(5120, 3200), true).at(-1).resolution, '5120x3200') +}) + test('the effective target profile determines the added window resolution', () => { const primary = profile(3840, 2160) const target = { ...primary, primary_display: { width: 2560, height: 1600, scale_pct: 150 } } diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 6abb19c..c767747 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -18,6 +18,7 @@ import { memorySafeLimitGB, parseMemoryGB, recommendedCPUs, + canKeepDisplayPreset, fullscreenDisplayPresets, FullscreenDisplayPreset, hidpiLooksLike, @@ -129,6 +130,8 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported start: true, }) const set = (patch: Partial) => setOpts((o) => ({ ...o, ...patch })) + const windowPresets = windowDisplayPresets(host, fixedModeSupported) + const fullscreenPresets = fullscreenDisplayPresets(host) const buildPayload = (): CreateOpts => { const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' } @@ -556,14 +559,14 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported title={tr('resolution')} disabled={opts.graphics !== 'reims-vgpu'} reason={tr('gpuSvgaReason')} - desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr) : undefined].filter(Boolean).join(' · ') || undefined} + desc={[hostDisplayDesc(host, tr), !opts.borderless ? hostDisplayAdvice(host, tr, windowPresets) : undefined].filter(Boolean).join(' · ') || undefined} control={ set({ resolution })} - options={(opts.borderless ? fullscreenDisplayPresets(host) : windowDisplayPresets(host, fixedModeSupported)).map((p: FullscreenDisplayPreset) => ({ + options={(opts.borderless ? fullscreenPresets : windowPresets).map((p: FullscreenDisplayPreset) => ({ value: p.resolution, label: p.label, detail: [ @@ -629,8 +632,8 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported label={tr('fullscreenLaunch')} checked={!!opts.borderless} onChange={(borderless) => { - const list = borderless ? fullscreenDisplayPresets(host) : windowDisplayPresets(host, fixedModeSupported) - const keep = list.some((p) => p.resolution === opts.resolution) + const list = borderless ? fullscreenPresets : windowPresets + const keep = list.some((p) => canKeepDisplayPreset(p, opts.resolution, borderless)) const fallback = list.find((p) => p.recommended)?.resolution ?? list[0]?.resolution ?? opts.resolution set(keep ? { borderless } : { borderless, resolution: fallback }) }} diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 07a12f9..70304f8 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -17,6 +17,7 @@ import { memorySafeLimitGB, parseMemoryGB, recommendedCPUs, + canKeepDisplayPreset, fullscreenDisplayPresets, FullscreenDisplayPreset, hidpiLooksLike, @@ -985,11 +986,11 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const selectedGPUHint = gpuCompatHint(locale, selectedGPU) const vgpu = form.graphics !== 'vmware-svga' const targetDisp = activeTargetDisplay - const hidpiAdvice = hostDisplayAdvice(displayProfile, tr) + const hidpiAdvice = hostDisplayAdvice(displayProfile, tr, presets) const resValue = customRes ? CUSTOM : activePresets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution const toggleBorderless = (borderless: boolean) => { const targetPresets = borderless ? fsPresets : presets - if (!customRes && !targetPresets.some((p) => same('resolution', p.resolution, form.resolution))) { + if (!customRes && !targetPresets.some((p) => canKeepDisplayPreset(p, form.resolution, borderless))) { const nextRes = borderless ? (targetDisp && targetDisp.width > 0 && targetDisp.height > 0 ? `${targetDisp.width}x${targetDisp.height}` diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 9776609..f708dc5 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -280,7 +280,8 @@ export function hostDisplayDesc( // How to get a HiDPI (sharp-text) macOS desktop when no window size gives // one on this screen; undefined when one does. -export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined { +export function hostDisplayAdvice(host: HostReport, tr: Tr, windowPresets: DisplayPreset[] = recommendedDisplayPresets(host)): string | undefined { + if (host.hidpi_advice === 'fullscreen' && windowPresets.some((p) => p.hidpi)) return undefined const tip: Record = { fullscreen: 'hidpiTipFullscreen', scale: 'hidpiTipScale', @@ -310,11 +311,17 @@ export interface FullscreenDisplayPreset extends DisplayPreset { scaleToFit?: boolean } +/** Scaling into a window is opt-in, not an automatic fullscreen-to-window fallback. */ +export function canKeepDisplayPreset(preset: FullscreenDisplayPreset, resolution: string | undefined, borderless: boolean): boolean { + const normalize = (value: string) => value.trim().toLowerCase().replace(/\s+/g, '').replace('×', 'x') + return resolution !== undefined && normalize(preset.resolution) === normalize(resolution) && (borderless || !preset.scaleToFit) +} + /** Preserve fit recommendations; fixed-mode runtimes can scale native guest pixels into a window. */ export function windowDisplayPresets(host: HostReport, fixedModeSupported: boolean): FullscreenDisplayPreset[] { const presets = recommendedDisplayPresets(host) const d = host.primary_display - if (!fixedModeSupported || !d || d.width < 2560 || d.height < 1440) return presets + if (!fixedModeSupported || !d || d.width < 2560 || d.height < 1440 || d.width > 5120 || d.height > 3200) return presets const resolution = `${d.width}x${d.height}` if (presets.some((p) => p.resolution === resolution)) return presets return [...presets, { From e6b46ae67a7f50cc2d671c11fc4dd3e076789675 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 22:25:22 +0800 Subject: [PATCH 3/3] ci: distinguish PR review readiness from CI status --- .github/scripts/pr-review-language.mjs | 34 +++++--- .github/scripts/pr-review.mjs | 116 +++++++++++++++++-------- .github/scripts/pr-review.test.mjs | 99 ++++++++++++++++----- docs/pr-review-guidelines.md | 4 +- 4 files changed, 178 insertions(+), 75 deletions(-) diff --git a/.github/scripts/pr-review-language.mjs b/.github/scripts/pr-review-language.mjs index 7fe990d..ca1ea5d 100644 --- a/.github/scripts/pr-review-language.mjs +++ b/.github/scripts/pr-review-language.mjs @@ -9,21 +9,26 @@ export const english = { upgrade: "Upgrade compatibility", ui: "UI consistency", implementation: "Duplication and simplification", - tests: "Test evidence for this PR commit", + tests: "CI for this PR commit", ciRun: "CI run", ciPassed: "Passed", - ciFailed: "Not passed", + ciFailed: "Failed", + ciNoPass: "No passing result", + ciActionRequired: "CI needs manual action.", ciPending: "Pending", ciMissing: "No CI run found for this commit.", - pending: "Still to verify", + pending: "Required manual checks", recommendation: "Merge recommendation", merge: "Ready to merge", changes: "Revise and review again", - verify: "Verify before merging", + verify: "Verify the key scenarios first", + inspect: "Review the remaining changes", + awaitCI: "No code blockers found. Awaiting CI.", decline: "Hold this PR", conflict: "GitHub detected merge conflicts. Resolve them and request another review.", - mainMoved: "The default branch moved during review. Review against the new commit.", - ciRequired: "Wait for passing CI and evidence of key tests.", + mainMoved: "The default branch moved during this review.", + ciRequired: "This commit has no passing CI result yet.", + fixCI: "Resolve the CI failure before merging.", fixFindings: "Address the actionable findings below before merging.", pendingRequired: "Run the key checks listed above.", incomplete: "Review the remaining changes before merging.", @@ -44,21 +49,26 @@ export const chinese = { upgrade: "旧版本、数据与配置升级", ui: "界面规范与风格", implementation: "实现精简与重复逻辑", - tests: "当前 PR 提交的实测记录", + tests: "当前 PR 提交的 CI", ciRun: "CI 运行记录", ciPassed: "通过", - ciFailed: "未通过", + ciFailed: "失败", + ciNoPass: "无通过结果", + ciActionRequired: "CI 需要人工处理。", ciPending: "尚未完成", ciMissing: "未找到对应提交的 CI 记录。", - pending: "待实测", + pending: "合并前必做实测", recommendation: "合并建议", merge: "可以合并", changes: "修改后再审", - verify: "待实测后再决定", + verify: "先验证关键场景", + inspect: "先审完剩余改动", + awaitCI: "代码未见阻塞,等待 CI", decline: "暂不合并", conflict: "GitHub 检测到合并冲突,解决后重新审核。", - mainMoved: "主线已更新,请对照新的主线提交重新审核。", - ciRequired: "等待对应提交的 CI 和关键测试记录。", + mainMoved: "审核期间主线有更新。", + ciRequired: "当前提交还没有 CI 通过记录。", + fixCI: "合并前处理 CI 失败项。", fixFindings: "合并前处理下方有证据的实质问题。", pendingRequired: "完成上面列出的关键流程实测。", incomplete: "本次只覆盖部分差异,合并前补齐审查。", diff --git a/.github/scripts/pr-review.mjs b/.github/scripts/pr-review.mjs index 6eabb73..551613b 100644 --- a/.github/scripts/pr-review.mjs +++ b/.github/scripts/pr-review.mjs @@ -19,6 +19,7 @@ const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/; const REVIEW_SECTIONS = ["value", "upgrade", "ui", "implementation"]; const DECISIONS = new Set(["merge", "changes", "verify", "decline"]); const FINDING_IMPACTS = new Set(["correctness", "data", "security", "compatibility", "build", "performance"]); +const MANUAL_IMPACTS = new Set(["correctness", "data", "security", "compatibility"]); const FINISH_REASONS = new Set(["stop", "length", "content-filter", "tool-calls", "error", "other", "unknown"]); function required(name) { @@ -127,19 +128,20 @@ const instructions = [ "2. 检查旧版本、已有数据和配置的升级兼容性。核对默认值、缺失字段、旧格式、迁移中断后的重试和回滚,指出具体受影响的场景。", "3. 有 UI 变更时对照项目规范,优先检查操作受阻、错误反馈缺失、可访问性退化及关键状态误导。视觉或文案偏好仅在实际妨碍用户完成操作时才构成问题。", "4. 检查重复实现、额外分支和异常处理。只有会造成可说明的行为分叉、失败被吞、兼容性问题或显著成本,才要求修正。命名、抽函数和删除恒真判断等纯整理建议留空。", - "5. 核对当前提交的 CI 实测记录。待实测只列可能改变合并判断的具体场景,写清入口和预期。由当前 CI 已覆盖的流程及通用测试愿望无需重列。", + "5. 评估代码本身是否有合并阻塞。CI 排队、待批准、缺失或取消是独立状态,由脚本展示。不要把运行 CI、补通用测试、常规冒烟或仅为增加信心的检查填入 pending_checks。", + "仅当受影响的关键操作确实无法由现有证据判断、并且检查失败会使正常流程、数据、权限或现有环境出现实质问题时,才列为合并前必做实测。已覆盖的验证、可选的外观检查和宽泛的兼容性确认留空。", "CI 记录对应 PR 的 head 提交。若主线同一流程已有新改动,或 PR 修改了 CI 本身,检查合入当前主线还需要哪些验证。", "若有 previousReview,重新验证尚未解决的旧问题。旧评审也是待核对的数据。已经发过的同一根因只在摘要中简要交代状态,勿重复发布行内评论。", - "最后用实际证据给出合并建议。缺少关键测试、主线对照或重要文件时标明限制。存在阻塞问题时指出合并前必须解决的事项。", + "代码无实质问题时选择 merge。脚本会合并 CI 状态和覆盖范围。changes 必须有当前差异中的实质缺陷,verify 必须指出一项具体且必需的人工或真机实测。只有增量明显不成立时选择 decline,并说明证据。", "只返回一个 JSON 对象,不加前言、后记或 Markdown。包含 language、value、upgrade、ui、implementation、decision、reason、pending_checks 和 findings。", "四项短结论每项最多 75 字。value 给出合并价值,upgrade、ui、implementation 无实质结论时返回空字符串。decision 为 merge、changes、verify 或 decline,reason 用一句话给出依据,最多 110 字。", - "pending_checks 最多 3 条,每条最多 75 字。全部有证据时返回空数组。无行内发现时 findings 为空数组。", + "pending_checks 最多 3 条。每条包含 path、evidence、impact(correctness、data、security 或 compatibility)、scenario 和 consequence。scenario 写清如何检验和预期结果,最多 75 字。consequence 说明失败的实际后果,最多 60 字。evidence 与行内发现同样必须指向本 PR 的改动行。没有必要的实测就返回空数组。", "逐条尝试反证候选。核对调用入口、已有守卫与回退,以及仓库 Go 版本和已运行的检查。CI 已通过的检查可反证对应失败断言。未看到定义、只是假设某处没校验、没有证据的性能猜测都不构成缺陷。例如 Go 1.20 及以后 fmt.Errorf 的多个 %w 都会被包装。", "行内仅发布本 PR 引入或暴露的实质问题。P1 指数据丢失、可靠复现的关键流程阻断或严重安全退化。P2 指在受支持场景可达且有实际后果的软件缺陷。证据或影响不充分时直接舍弃;没有实质问题就返回空 findings。", "每条包含 path、side、line、priority(P1 或 P2)、impact(correctness、data、security、compatibility、build 或 performance)、trigger、evidence 和 body。trigger 用一句话说明可达的条件。", "side 和 line 可指向 diff 中新增、删除或相邻上下文行,evidence 为 {side,line,text},必须是同一文件中的新增或删除行。text 为该行的原样代码片段,去掉差异前缀,至少 6 个字符,无 Markdown。", "每个根因一条,按实际影响降序排列,最多 3 条。body 每条最多 130 字,说明触发条件、实际后果及最小修法,使用纯文本,不提供可执行的攻击步骤。", - "如果差异为空,如实说明覆盖限制并选择 verify。", + "如果差异为空,如实说明覆盖限制,保留空 pending_checks。", "结果语言为英语或简体中文时省略 labels。其他语言须返回 labels 对象,沿用下列键,将各值翻译为结果语言。保持短标签简洁。", JSON.stringify(english), ].join("\n"); @@ -248,7 +250,7 @@ async function reviewDiffs(context, includeDesignGuidelines) { || typeof decoded.language !== "string" || !/^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i.test(decoded.language) || !DECISIONS.has(decoded.decision) || typeof decoded.reason !== "string" || !decoded.reason.trim() - || !Array.isArray(decoded.pending_checks) || !decoded.pending_checks.every((check) => typeof check === "string") + || !Array.isArray(decoded.pending_checks) || !Array.isArray(decoded.findings)) throw new Error("LLM review is missing the assessment or merge recommendation"); return decoded; } @@ -288,6 +290,13 @@ function plainMarkdown(value) { .replace(/[\\`*_~<>&[\]#!|]/g, "\\$&"); } +function hasChangedEvidence(anchors, evidence) { + if (!Number.isSafeInteger(evidence?.line) || typeof evidence.text !== "string") return false; + const source = anchors?.get(evidence.side + ":" + evidence.line); + const excerpt = evidence.text.trim(); + return source?.changed && excerpt.length >= 6 && source.text.includes(excerpt); +} + export function inlineComments(findings, locations) { const comments = []; const seen = new Set(); @@ -297,11 +306,8 @@ export function inlineComments(findings, locations) { || typeof finding.trigger !== "string" || !finding.trigger.trim() || typeof finding.body !== "string" || !finding.body.trim()) continue; const anchors = locations.get(finding.path); - const evidence = finding.evidence; - const source = anchors?.get(evidence?.side + ":" + evidence?.line); - const excerpt = typeof evidence?.text === "string" ? evidence.text.trim() : ""; if (!Number.isSafeInteger(finding.line) || !anchors?.has(finding.side + ":" + finding.line) - || !Number.isSafeInteger(evidence?.line) || !source?.changed || excerpt.length < 6 || !source.text.includes(excerpt)) continue; + || !hasChangedEvidence(anchors, finding.evidence)) continue; const { path, side, line } = finding; const key = JSON.stringify([path, side, line]); if (seen.has(key)) continue; @@ -394,7 +400,7 @@ async function listChangedFiles(github, path) { return files.slice(0, MAX_FILES); } -async function waitForCI(github, repoPath, pull, number, { skipCI = false } = {}) { +export async function waitForCI(github, repoPath, pull, number, { skipCI = false, wait = true } = {}) { if (pull.base.ref !== pull.base.repo.default_branch || !pull.head.repo) return { status: "unavailable" }; const startedAt = Date.now(); const deadline = startedAt + CI_WAIT_MS; @@ -417,13 +423,17 @@ async function waitForCI(github, repoPath, pull, number, { skipCI = false } = {} } const now = Date.now(); const remaining = deadline - now; - if (remaining <= 0 || pull.mergeable === false || (!run && (skipCI || now >= appearDeadline))) { + if (!wait || remaining <= 0 || pull.mergeable === false || (!run && (skipCI || now >= appearDeadline))) { return { status: run?.status ?? "unavailable", id: run?.id, attempt: run?.run_attempt, url: run?.html_url }; } await delay(Math.min(20_000, remaining)); } } +function reviewMarker(revision, mainSha, ci) { + return MARKER_PREFIX + [revision, mainSha, ci.id ?? "none", ci.attempt ?? "none", ci.conclusion ?? ci.status].join(":") + " -->"; +} + async function mainlineContext(github, repoPath, pull, files) { const branch = pull.base.repo.default_branch; const refPath = repoPath + "/git/ref/heads/" + encodeURIComponent(branch); @@ -453,49 +463,59 @@ async function mainlineContext(github, repoPath, pull, files) { }; } -export function reviewSummary(copy, assessment, ci, incomplete, mainMoved, mergeable, hasFindings = false) { +export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, hasFindings, locations }) { const lines = []; for (const key of REVIEW_SECTIONS) { if (!assessment[key].trim()) continue; lines.push("- **" + copy[key] + "** " + plainMarkdown(shortText(assessment[key], 75))); } - const ciStatus = ci.status === "completed" ? (ci.conclusion === "success" ? copy.ciPassed : copy.ciFailed + " (`" + ci.conclusion + "`)") - : ci.id ? copy.ciPending : copy.ciMissing; + const ciPassed = ci.status === "completed" && ci.conclusion === "success"; + const ciFailed = ci.status === "completed" && ["failure", "timed_out"].includes(ci.conclusion); + const ciNeedsAction = ci.conclusion === "action_required" || ci.status === "action_required"; + let ciStatus = ci.id ? copy.ciPending : copy.ciMissing; + if (ciNeedsAction) ciStatus = copy.ciActionRequired; + else if (ciPassed) ciStatus = copy.ciPassed; + else if (ci.status === "completed") ciStatus = (ciFailed ? copy.ciFailed : copy.ciNoPass) + " (`" + ci.conclusion + "`)"; lines.push("\n**" + copy.tests + "** " + ciStatus + (ci.url ? " · [" + copy.ciRun + "](" + ci.url + ")" : "")); for (const step of ci.steps ?? []) { lines.push("- " + plainMarkdown(step.name) + " · " + plainMarkdown(step.conclusion ?? "—")); } - const pending = assessment.pending_checks.map((check) => check.trim()).filter(Boolean).slice(0, MAX_PENDING_CHECKS); + const pending = assessment.pending_checks.filter((check) => MANUAL_IMPACTS.has(check?.impact) + && typeof check.scenario === "string" && check.scenario.trim() + && typeof check.consequence === "string" && check.consequence.trim() + && hasChangedEvidence(locations.get(check.path), check.evidence)).slice(0, MAX_PENDING_CHECKS); if (pending.length) { lines.push("\n**" + copy.pending + "**"); - for (const check of pending) lines.push("- " + plainMarkdown(shortText(check, 75))); + for (const check of pending) { + lines.push("- " + plainMarkdown(shortText(check.scenario, 75)) + " · " + plainMarkdown(shortText(check.consequence, 60))); + } } - let decision = assessment.decision; - let reason = plainMarkdown(shortText(assessment.reason, 110)); - const hasTestEvidence = ci.conclusion === "success" && ci.steps?.some((step) => step.conclusion === "success"); - const actualCIFailure = ci.status === "completed" && ["failure", "timed_out"].includes(ci.conclusion); + let decision = "merge"; + let reason = copy.noFindings; if (mergeable === false) { decision = "changes"; reason = copy.conflict; - } else if (actualCIFailure) { + } else if (ciFailed) { decision = "changes"; - reason = copy.ciRequired; - } else if (decision === "merge" && hasFindings) { + reason = copy.fixCI; + } else if (hasFindings) { decision = "changes"; reason = copy.fixFindings; - } else if (decision === "changes" && !hasFindings) { + } else if (assessment.decision === "decline") { + decision = "decline"; + reason = plainMarkdown(shortText(assessment.reason, 110)); + } else if (pending.length) { decision = "verify"; - reason = copy.noFindings; - } - if (decision === "merge" && (incomplete || mainMoved || !hasTestEvidence || pending.length)) { - decision = "verify"; - if (mainMoved) reason = copy.mainMoved; - else if (!hasTestEvidence) reason = copy.ciRequired; - else if (pending.length) reason = copy.pendingRequired; - else reason = copy.incomplete; + reason = copy.pendingRequired; + } else if (incomplete) { + decision = "inspect"; + reason = copy.incomplete; + } else if (!ciPassed) { + decision = "awaitCI"; + reason = copy.ciRequired; } lines.push("\n**" + copy.recommendation + " · " + copy[decision] + "** " + reason); return lines.join("\n"); @@ -536,8 +556,7 @@ export async function run() { waitForCI(github, repoPath, pull, number, { skipCI: hasSkipCIToken(headCommitMessage) }), ]); const mainline = await mainlineContext(github, repoPath, pull, files); - const marker = MARKER_PREFIX + [revision, mainline.sha, ci.id ?? "none", - ci.attempt ?? "none", ci.conclusion ?? ci.status].join(":") + " -->"; + const marker = reviewMarker(revision, mainline.sha, ci); const history = await fetchReviewHistory(github, repoPath, path, pull.head.sha, marker); if (history.alreadyReviewed) { console.log("This PR revision has already been reviewed"); @@ -577,6 +596,22 @@ export async function run() { const coverage = copy.scope + " " + diffs.length + "/" + pull.changed_files + (partial ? " (" + partial + " " + copy.partial + ")" : ""); const result = comments.length ? copy.inline + " · " + comments.length : diffs.length ? "" : copy.noDiff; + let finalCI = ci; + if (ci.conclusion !== "success") { + try { + finalCI = await waitForCI(github, repoPath, pull, number, { wait: false }); + } catch (error) { + console.warn("Could not refresh CI: " + error.message); + } + } + const finalMarker = reviewMarker(revision, mainline.sha, finalCI); + if (finalMarker !== marker) { + const { alreadyReviewed } = await fetchReviewHistory(github, repoPath, path, pull.head.sha, finalMarker); + if (alreadyReviewed) { + console.log("This PR revision has already been reviewed with the latest CI result"); + return; + } + } const latestPR = await currentPR(); if (!latestPR) { console.log("PR changed while the model was reviewing it"); @@ -587,10 +622,15 @@ export async function run() { const mainCoverage = mainline.comparisonUnavailable ? copy.comparisonUnavailable : mainline.overlappingFiles > mainline.overlappingDiffs.length || mainline.partialOverlaps || mainline.fileListMayBeTruncated ? copy.comparisonPartial : ""; - const summary = marker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage - + (mainCoverage ? " · " + mainCoverage : "") - + "\n\n" + reviewSummary(copy, assessment, ci, !diffs.length || diffs.length < pull.changed_files || partial > 0 - || Boolean(mainCoverage), mainMoved, latestPR.mergeable, comments.length > 0); + const scopeNotes = [mainCoverage, mainMoved ? copy.mainMoved : ""].filter(Boolean); + const assessmentSummary = reviewSummary(copy, assessment, finalCI, { + incomplete: !diffs.length || diffs.length < pull.changed_files || partial > 0, + mergeable: latestPR.mergeable, + hasFindings: comments.length > 0, + locations, + }); + const summary = finalMarker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage + + (scopeNotes.length ? " · " + scopeNotes.join(" ") : "") + "\n\n" + assessmentSummary; const review = { event: "COMMENT", commit_id: pull.head.sha, diff --git a/.github/scripts/pr-review.test.mjs b/.github/scripts/pr-review.test.mjs index d01ec99..762dead 100644 --- a/.github/scripts/pr-review.test.mjs +++ b/.github/scripts/pr-review.test.mjs @@ -9,6 +9,7 @@ import { reviewSummary, selectDiffs, shouldSkipAutoReview, + waitForCI, } from "./pr-review.mjs"; test("hasSkipCIToken recognizes standard skip tokens case-insensitively", () => { @@ -125,38 +126,88 @@ test("extractPreviousReview returns latest bot review with stripped marker and c assert.deepEqual(prev.changedFilesSincePreviousReview, ["internal/app/a.go"]); }); -test("reviewSummary overrides merge recommendation on conflicts or missing CI", () => { - const assessment = { - value: "good", - upgrade: "safe", - ui: "ok", - implementation: "clean", - decision: "merge", - reason: "looks ready", - pending_checks: [], +const mergeAssessment = { + value: "Adds a needed feature", upgrade: "", ui: "", implementation: "", decision: "merge", + reason: "The change is ready", pending_checks: [], +}; +const passingCI = { status: "completed", conclusion: "success", steps: [{ name: "CI tests", conclusion: "success" }] }; +const fullReview = { mergeable: true, incomplete: false, hasFindings: false, locations: new Map() }; + +test("the final CI refresh does one lookup and can pick up a passing rerun", async () => { + const pull = { + base: { ref: "main", repo: { default_branch: "main" } }, + head: { sha: "head", ref: "feature", repo: { full_name: "fork/Reims-Go" } }, }; - const conflictText = reviewSummary(chinese, assessment, { status: "completed", conclusion: "success", steps: [{ name: "CI tests", conclusion: "success" }] }, false, false, false); - assert.match(conflictText, /修改后再审/); - const noCIText = reviewSummary(chinese, assessment, { status: "unavailable" }, false, false, true); - assert.match(noCIText, /待实测后再决定/); + const run = { id: 100, run_attempt: 2, head_sha: "head", head_branch: "feature", head_repository: pull.head.repo, pull_requests: [] }; + let calls = 0; + const queued = await waitForCI(async () => { + calls++; + return { data: { workflow_runs: [{ ...run, status: "queued" }] } }; + }, "/repos/test/Reims-Go", pull, 42, { wait: false }); + assert.equal(queued.status, "queued"); + assert.equal(calls, 1); + + const passed = await waitForCI(async (route) => route.endsWith("/100/attempts/2/jobs") + ? { data: { jobs: [{ name: "verify", conclusion: "success", steps: passingCI.steps }] } } + : { data: { workflow_runs: [{ ...run, status: "completed", conclusion: "success" }] } }, + "/repos/test/Reims-Go", pull, 42, { wait: false }); + assert.equal(passed.conclusion, "success"); + assert.equal(passed.attempt, 2); + assert.match(reviewSummary(chinese, mergeAssessment, passed, fullReview), /可以合并/); +}); + +test("reviewSummary distinguishes CI awaiting action, waiting and failure", () => { + const approval = reviewSummary(chinese, mergeAssessment, { status: "completed", conclusion: "action_required", id: 1 }, fullReview); + assert.match(approval, /CI 需要人工处理/); + assert.match(approval, /代码未见阻塞,等待 CI/); + assert.doesNotMatch(approval, /失败|必做实测|先验证关键场景/); + + for (const ci of [{ status: "unavailable" }, { status: "queued", id: 1 }, { status: "completed", conclusion: "cancelled", id: 1 }]) { + const waiting = reviewSummary(chinese, mergeAssessment, ci, fullReview); + assert.match(waiting, /代码未见阻塞,等待 CI/); + assert.doesNotMatch(waiting, /修改后再审|先验证关键场景/); + } + const failed = reviewSummary(chinese, mergeAssessment, { ...passingCI, conclusion: "failure" }, fullReview); + assert.match(failed, /修改后再审/); + assert.match(failed, /处理 CI 失败项/); }); test("reviewSummary only recommends fixes for verified findings or CI failures and omits empty sections", () => { - const assessment = { - value: "Adds a needed feature", upgrade: "", ui: "", implementation: "", decision: "changes", - reason: "Refactor the redundant guard", pending_checks: [], - }; - const ci = { status: "completed", conclusion: "success", steps: [{ name: "CI tests", conclusion: "success" }] }; - const clean = reviewSummary(chinese, assessment, ci, false, false, true); - assert.match(clean, /待实测后再决定/); + const assessment = { ...mergeAssessment, decision: "changes", reason: "Refactor the redundant guard" }; + const clean = reviewSummary(chinese, assessment, passingCI, fullReview); + assert.match(clean, /可以合并/); assert.doesNotMatch(clean, /修改后再审/); assert.doesNotMatch(clean, /Refactor|界面规范与风格|实现精简与重复逻辑/); - const issue = reviewSummary(chinese, { ...assessment, decision: "merge" }, ci, false, false, true, true); + const issue = reviewSummary(chinese, mergeAssessment, passingCI, { ...fullReview, hasFindings: true }); assert.match(issue, /修改后再审/); assert.match(issue, /实质问题/); - const failed = reviewSummary(chinese, assessment, { ...ci, conclusion: "failure" }, false, false, true); - assert.match(failed, /修改后再审/); - assert.doesNotMatch(failed, /Refactor/); + const conflict = reviewSummary(chinese, mergeAssessment, passingCI, { ...fullReview, mergeable: false }); + assert.match(conflict, /修改后再审.*合并冲突/); + const partial = reviewSummary(chinese, mergeAssessment, passingCI, { ...fullReview, incomplete: true }); + assert.match(partial, /先审完剩余改动/); + assert.doesNotMatch(partial, /先验证关键场景/); +}); + +test("reviewSummary reserves pre-merge manual checks for supported risks in changed code", () => { + const context = { ...fullReview, locations: new Map([["disk.go", diffAnchors("@@ -1 +1,2 @@\n existing guard\n+replaceDisk()")]]) }; + const disk = { + path: "disk.go", evidence: { side: "RIGHT", line: 2, text: "replaceDisk()" }, impact: "data", + scenario: "Force a host write failure and verify the old disk reopens.", consequence: "Data becomes inaccessible after a failed rollback.", + }; + const assessment = { ...mergeAssessment, decision: "verify", reason: "Retest everything", pending_checks: [ + "Re-run CI and check small-window styling.", + { ...disk, impact: "style", scenario: "Check label width." }, + { ...disk, path: "unknown.go", scenario: "Unrelated host test." }, + { ...disk, evidence: { side: "RIGHT", line: 1, text: "existing guard" }, scenario: "Verify an unchanged guard." }, + ] }; + const clear = reviewSummary(chinese, assessment, passingCI, context); + assert.match(clear, /可以合并/); + assert.doesNotMatch(clear, /合并前必做实测|先验证关键场景|Retest everything/); + const blocked = reviewSummary(chinese, { ...assessment, pending_checks: [...assessment.pending_checks, disk] }, passingCI, context); + assert.match(blocked, /合并前必做实测/); + assert.match(blocked, /Force a host write failure.*Data becomes inaccessible/); + assert.match(blocked, /先验证关键场景/); + assert.doesNotMatch(blocked, /Re-run CI|label width|Unrelated host test|unchanged guard/); }); diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md index 3ef9d82..b2cfe2b 100644 --- a/docs/pr-review-guidelines.md +++ b/docs/pr-review-guidelines.md @@ -58,7 +58,9 @@ 自动审核先对照最新主线判断合并价值与功能完整性,再检查升级兼容性、UI 和实现是否会引入实质回归。行内意见需要指明可达的触发条件、实际影响及对应改动行。格式、命名和单纯的重构建议不发布为行内问题。复审会核对上一轮问题的解决状态,避免重复发布同一根因。 -审核附上当前 PR 提交的 CI 记录、会影响合并判断的待实测场景和合并建议。回复优先跟随作者在 PR 正文中实际使用的语言,其次参考标题,无法判断时使用英文。工作流在未检测到 CI 运行时最多等待约一分钟,检测到运行后最多等待约四分钟。CI 的现有 Go、前端、桌面构建及 WebView2 冒烟步骤提供实测证据,宿主机、升级和运行时场景以各自实际覆盖为准。 +审核附上当前 PR 提交的 CI 记录、合并前必做实测和合并建议。CI 排队、需要人工处理或缺少通过记录时,代码无实质问题的结论为「代码未见阻塞,等待 CI」。只有当前差异支持且失败会产生实质影响的场景才列为合并前必做实测。PR 差异覆盖不全时提示补齐审查。主线对照的范围限制单独标注。 + +回复优先跟随作者在 PR 正文中实际使用的语言,其次参考标题,无法判断时使用英文。工作流在未检测到 CI 运行时最多等待约一分钟,检测到运行后最多等待约四分钟。CI 尚未通过时,工作流在发布前刷新一次状态。CI 的现有 Go、前端、桌面构建及 WebView2 冒烟步骤提供实测证据,宿主机、升级和运行时场景以各自实际覆盖为准。 在目标仓库的 **Settings → Secrets and variables → Actions** 配置以下项目。