Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): restore scrolling capture without moving the pointer
Davida00172208ac7
diff --git a/apps/desktop/native/region-screenshot/macos-snapshot.swift b/apps/desktop/native/region-screenshot/macos-snapshot.swiftindex 89a7a727e4..5e890c5730 100644--- a/apps/desktop/native/region-screenshot/macos-snapshot.swift+++ b/apps/desktop/native/region-screenshot/macos-snapshot.swift@@ -30,6 +30,18 @@ let minSide: CGFloat = 4let maxSnapLayer = Int(CGWindowLevelForKey(.dockWindow))var elementDeadline: Date?+// Window-targeted posting needs both the window number and its coordinate+// stamp. Without the latter, Chromium silently drops the wheel event. Keep+// this optional SPI dynamically resolved: unsupported systems fail closed,+// never fall back to the HID tap (which moves the user's system pointer).+// CGPoint's two CGFloat fields use the same ABI as two Doubles on macOS.+typealias SetScrollWindowLocation = @convention(c) (CGEvent, Double, Double) -> Void+let setScrollWindowLocation: SetScrollWindowLocation? = {+ guard let framework = dlopen("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics", RTLD_LAZY | RTLD_LOCAL),+ let symbol = dlsym(framework, "CGEventSetWindowLocation") else { return nil }+ return unsafeBitCast(symbol, to: SetScrollWindowLocation.self)+}()+func emit(_ object: [String: Any]) {guard let data = try? JSONSerialization.data(withJSONObject: object),let line = String(data: data, encoding: .utf8)@@ -64,6 +76,30 @@ func onScreenWindows() -> [[String: Any]] {return result}+func scrollInputTarget(_ point: CGPoint) -> [String: Any]? {+ guard AXIsProcessTrusted() else { return nil }+ // A transparent, input-ignoring window can still be first in CGWindow order.+ // Resolve its receiving app through AX before choosing that app's front window.+ // Only retry our own overlay while WindowServer applies ignoresMouseEvents.+ let system = AXUIElementCreateSystemWide()+ AXUIElementSetMessagingTimeout(system, 0.05)+ var hitPid: pid_t = 0+ for attempt in 0..<11 {+ var hit: AXUIElement?+ AXUIElementCopyElementAtPosition(system, Float(point.x), Float(point.y), &hit)+ hitPid = 0+ if let hit = hit { AXUIElementGetPid(hit, &hitPid) }+ if hitPid != getppid() || attempt == 10 { break }+ usleep(10000)+ }+ guard hitPid > 0 else { return nil }+ return onScreenWindows().first { window in+ guard window["pid"] as? Int == Int(hitPid) else { return false }+ guard let rect = window["rect"] as? [Double] else { return false }+ return point.x >= rect[0] && point.x < rect[2] && point.y >= rect[1] && point.y < rect[3]+ }+}+func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {if let deadline = elementDeadline {let remaining = deadline.timeIntervalSinceNow@@ -144,9 +180,17 @@ while let line = readLine() {else { continue }let id = request["id"] ?? NSNull()switch request["op"] as? String {+ case "scroll-target":+ guard let x = (request["x"] as? NSNumber)?.doubleValue,+ let y = (request["y"] as? NSNumber)?.doubleValue, x.isFinite, y.isFinite,+ let target = scrollInputTarget(CGPoint(x: x, y: y))+ else { emit(["id": id, "ok": false]); continue }+ emit(["id": id, "hwnd": target["hwnd"]!, "pid": target["pid"]!])case "scroll":guard AXIsProcessTrusted(),+ let setScrollWindowLocation = setScrollWindowLocation,let pid = (request["pid"] as? NSNumber)?.int32Value,+ let windowId = (request["hwnd"] as? NSNumber)?.intValue,let x = (request["x"] as? NSNumber)?.doubleValue,let y = (request["y"] as? NSNumber)?.doubleValue,let delta = (request["delta"] as? NSNumber)?.int32Value,@@ -155,12 +199,22 @@ while let line = readLine() {let event = CGEvent(scrollWheelEvent2Source: source, units: .pixel, wheelCount: 1, wheel1: delta, wheel2: 0, wheel3: 0)else { emit(["id": id, "ok": false]); continue }let point = CGPoint(x: x, y: y)- var hit: AXUIElement?- AXUIElementCopyElementAtPosition(AXUIElementCreateSystemWide(), Float(x), Float(y), &hit)- var hitPid: pid_t = 0- if let hit = hit { AXUIElementGetPid(hit, &hitPid) }- guard hitPid == pid else { emit(["id": id, "ok": false]); continue }+ // Revalidate the same captured window on every step. Covering it with a+ // different input window stops scrolling instead of redirecting the event.+ guard let target = scrollInputTarget(point),+ target["hwnd"] as? Int == windowId, target["pid"] as? Int == Int(pid)+ else { emit(["id": id, "ok": false]); continue }event.location = point+ event.flags = []+ // CoreGraphics' windowNumber field (51) is not in the public Swift enum.+ // The coordinate stamp is screen-space, despite the SPI's name; routing+ // derives the receiving window's local point. Post exactly once to the+ // revalidated owner, without moving the cursor or changing focus.+ event.setIntegerValueField(CGEventField(rawValue: 51)!, value: Int64(windowId))+ event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(windowId))+ event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(windowId))+ event.setIntegerValueField(.eventTargetUnixProcessID, value: Int64(pid))+ setScrollWindowLocation(event, x, y)event.postToPid(pid)emit(["id": id, "ok": true])case "keys":diff --git a/apps/desktop/src/main/region-screenshot/__tests__/snapshotHost.test.ts b/apps/desktop/src/main/region-screenshot/__tests__/snapshotHost.test.tsindex 9a595b4700..cb522174de 100644--- a/apps/desktop/src/main/region-screenshot/__tests__/snapshotHost.test.ts+++ b/apps/desktop/src/main/region-screenshot/__tests__/snapshotHost.test.ts@@ -88,6 +88,26 @@ describe('snapshot helper failure isolation', () => {await expect(result).resolves.toEqual([{ handle: 5, pid: 9, rect: [0, 0, 20, 30] }]);});+ // Unit: resolving through a transparent overlay must not admit a new window+ // or reused handle outside the original capture. Existing tests only read lists.+ it('resolves scrolling only to a captured window containing the selection center', async () => {+ const overlay = { handle: 4, pid: 8, rect: [0, 0, 100, 100] as [number, number, number, number] };+ const source = { handle: 5, pid: 9, rect: [0, 0, 20, 30] as [number, number, number, number] };+ const candidates = [overlay, source];+ const valid = helper.scrollTarget(candidates, 10, 10);+ child.stdout.write(JSON.stringify({ id: 1, hwnd: 5, pid: 9 }) + '\n');+ await expect(valid).resolves.toEqual(source);+ const reused = helper.scrollTarget(candidates, 10, 10);+ child.stdout.write(JSON.stringify({ id: 2, hwnd: 5, pid: 10 }) + '\n');+ await expect(reused).resolves.toBeNull();+ const newWindow = helper.scrollTarget(candidates, 10, 10);+ child.stdout.write(JSON.stringify({ id: 3, hwnd: 6, pid: 9 }) + '\n');+ await expect(newWindow).resolves.toBeNull();+ const outside = helper.scrollTarget(candidates, 25, 10);+ child.stdout.write(JSON.stringify({ id: 4, hwnd: 5, pid: 9 }) + '\n');+ await expect(outside).resolves.toBeNull();+ });+// Unit: the production start entry on unsupported platforms must keep screen// capture optional, without attempting to spawn the Windows helper binary.it('does not start a native helper on an unsupported platform', async () => {diff --git a/apps/desktop/src/main/region-screenshot/__tests__/windows.test.ts b/apps/desktop/src/main/region-screenshot/__tests__/windows.test.tsindex 9fab80296a..6d7bb87fb0 100644--- a/apps/desktop/src/main/region-screenshot/__tests__/windows.test.ts+++ b/apps/desktop/src/main/region-screenshot/__tests__/windows.test.ts@@ -289,7 +289,10 @@ describe('screenshot window lifecycle', () => {// Auto scrolling operates on the source app: stale tokens must never trigger it,// and stopping while a frame is pending must prevent the next wheel event. tier: unit.- it('confines automatic scrolling to the owner and stops before a pending frame completes', async () => {+ // A transparent desktop overlay can precede the browser in CGWindow order.+ // Unit: resolve the real input window, and cancel a pending resolution on Stop.+ it.each(['darwin', 'win32'])('confines automatic scrolling to the owner on %s and stops pending input', async (platform) => {+ vi.stubGlobal('process', Object.create(process, { platform: { value: platform } }));const largeDisplay = { ...display, bounds: { x: 0, y: 0, width: 1280, height: 900 }, scaleFactor: 1 };mocks.screen.getAllDisplays.mockReturnValue([largeDisplay]);const overlay = pool.ensure(largeDisplay)!;@@ -300,13 +303,28 @@ describe('screenshot window lifecycle', () => {const source = { getSize: () => ({ width: 1280, height: 900 }), toBitmap: () => Buffer.alloc(1280 * 900 * 4), crop: () => crop } as unknown as NativeImage;const scroll = vi.fn(async () => true);const target = { handle: 99, pid: 1, rect: [0, 0, 1280, 900] as [number, number, number, number] };- const session = new RegionScreenshotSession({ pool, captures: [{ display: largeDisplay, image: source }], helper: { scroll } as unknown as SnapshotHelper, windows: [target], lastRegions: new Map(), onClosed: vi.fn(), onResult: vi.fn() });+ const scrollTarget = vi.fn(async () => target);+ const candidates = platform === 'darwin' ? [{ ...target, handle: 98, pid: 2 }, target] : [target];+ const session = new RegionScreenshotSession({ pool, captures: [{ display: largeDisplay, image: source }], helper: { scroll, scrollTarget } as unknown as SnapshotHelper, windows: candidates, lastRegions: new Map(), onClosed: vi.fn(), onResult: vi.fn() });await session.open();session.painted(owner, owner.mainFrame, session.token);session.startLive(owner, owner.mainFrame, session.token, 'scroll', { x: 100, y: 100, width: 400, height: 300 });expect(session.autoScroll(owner, owner.mainFrame, 'stale', true)).toBe(false);expect(session.autoScroll(owner, {} as Electron.WebFrameMain, session.token, true)).toBe(false);expect(session.autoScroll(owner, owner.mainFrame, session.token, true)).toBe(true);+ if (platform === 'darwin') {+ let resolveTarget!: (value: typeof target) => void;+ scrollTarget.mockImplementationOnce(() => new Promise(done => { resolveTarget = done; }));+ mocks.liveCapture.mockResolvedValueOnce(bitmap);+ const resolving = session.liveFrame(owner, owner.mainFrame, session.token, false);+ await vi.advanceTimersByTimeAsync(0);+ expect(session.autoScroll(owner, owner.mainFrame, session.token, false)).toBe(true);+ resolveTarget(target);+ expect((await resolving)?.autoScrolling).toBe(false);+ expect(scroll).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(200);+ expect(session.autoScroll(owner, owner.mainFrame, session.token, true)).toBe(true);+ }mocks.liveCapture.mockResolvedValueOnce(bitmap);expect((await session.liveFrame(owner, owner.mainFrame, session.token, false))?.autoScrolling).toBe(true);expect(scroll).toHaveBeenCalledExactlyOnceWith(target, 300, 250, -60);diff --git a/apps/desktop/src/main/region-screenshot/session.ts b/apps/desktop/src/main/region-screenshot/session.tsindex d69f5785e6..e362f0d3d0 100644--- a/apps/desktop/src/main/region-screenshot/session.ts+++ b/apps/desktop/src/main/region-screenshot/session.ts@@ -98,7 +98,7 @@ export class RegionScreenshotSession {private videoCapture: RegionVideoCapture | null = null;private recordingControls: RegionRect | null = null;private draggingControls = false;- private live: { member: Member; selection: RegionRect; mode: RegionCaptureMode; sampling: boolean; lastSample: number; editing: boolean; layout: ScrollCaptureLayout | null; automatic: boolean; target: SnapshotWindow | null; ignoring: boolean; previewHeight: number } | null = null;+ private live: { member: Member; selection: RegionRect; mode: RegionCaptureMode; sampling: boolean; lastSample: number; editing: boolean; layout: ScrollCaptureLayout | null; automatic: boolean; target: SnapshotWindow | null; targetResolved: boolean; ignoring: boolean; previewHeight: number } | null = null;private scrollPointerTimer: ReturnType<typeof setInterval> | null = null;private revealTimer: ReturnType<typeof setTimeout> | null = null;private releaseEscapeShortcut: (() => void) | null = null;@@ -332,7 +332,7 @@ export class RegionScreenshotSession {const center = { x: display.bounds.x + selection.x + selection.width / 2, y: display.bounds.y + selection.y + selection.height / 2 };const physical = process.platform === 'win32' ? screen.dipToScreenPoint(center) : center;const target = this.deps.windows.find(({ rect }) => physical.x >= rect[0] && physical.x < rect[2] && physical.y >= rect[1] && physical.y < rect[3]) ?? null;- this.live = { member, selection, mode: mode as RegionCaptureMode, sampling: false, lastSample: 0, editing: false, layout, automatic: false, target, ignoring: false, previewHeight: layout ? Math.min(layout.preview.height, Math.ceil(croppedSize.height * layout.preview.width / croppedSize.width)) : 0 };+ this.live = { member, selection, mode: mode as RegionCaptureMode, sampling: false, lastSample: 0, editing: false, layout, automatic: false, target, targetResolved: process.platform !== 'darwin', ignoring: false, previewHeight: layout ? Math.min(layout.preview.height, Math.ceil(croppedSize.height * layout.preview.width / croppedSize.width)) : 0 };for (const other of this.members.values()) {if (other === member) continue;hideScreenshotOverlay(other.overlay.window);@@ -438,9 +438,22 @@ export class RegionScreenshotSession {// Let native hit-testing see the source, including when Stop is hovered.member.overlay.window.setIgnoreMouseEvents(true, { forward: true });live.ignoring = true;- const ok = await this.deps.helper.scroll(live.target, Math.round(point.x), Math.round(point.y), -Math.max(1, Math.min(120, Math.floor(live.selection.height / 5))));- if (this.closed || this.live !== live || live.editing) return null;- if (!ok) live.automatic = false;+ if (!live.targetResolved) {+ const target = await this.deps.helper.scrollTarget(this.deps.windows, Math.round(point.x), Math.round(point.y));+ if (this.closed || this.live !== live || live.editing) return null;+ if (target) {+ live.target = target;+ live.targetResolved = true;+ } else {+ live.automatic = false;+ }+ }+ // Stop may arrive while the native input target is being resolved.+ if (live.automatic) {+ const ok = await this.deps.helper.scroll(live.target, Math.round(point.x), Math.round(point.y), -Math.max(1, Math.min(120, Math.floor(live.selection.height / 5))));+ if (this.closed || this.live !== live || live.editing) return null;+ if (!ok) live.automatic = false;+ }this.updateScrollHitTest();}const point = screen.getCursorScreenPoint();diff --git a/apps/desktop/src/main/region-screenshot/snapshotHost.ts b/apps/desktop/src/main/region-screenshot/snapshotHost.tsindex e8fcddba7c..0cc76155c1 100644--- a/apps/desktop/src/main/region-screenshot/snapshotHost.ts+++ b/apps/desktop/src/main/region-screenshot/snapshotHost.ts@@ -127,6 +127,13 @@ interface Pending {/** 一次截图会话内的识别程序进程。所有请求失败都返回空结果, 不抛错。 */export class SnapshotHelper {+ /** Resolve through input-transparent overlays, but only within the captured windows. */+ async scrollTarget(candidates: readonly SnapshotWindow[], x: number, y: number): Promise<SnapshotWindow | null> {+ const response = await this.request({ op: 'scroll-target', x, y });+ return candidates.find(({ handle, pid, rect }) => handle === response?.hwnd && pid === response?.pid+ && x >= rect[0] && x < rect[2] && y >= rect[1] && y < rect[3]) ?? null;+ }+/** One bounded wheel step in the captured window; never an arbitrary input bridge. */async scroll(window: SnapshotWindow, x: number, y: number, delta: number): Promise<boolean> {const response = await this.request({ op: 'scroll', hwnd: window.handle, pid: window.pid, x, y, delta });diff --git a/apps/desktop/src/renderer/features/region-screenshot/ScreenshotToolbar.tsx b/apps/desktop/src/renderer/features/region-screenshot/ScreenshotToolbar.tsxindex 78b3ba0f10..dbe90eadea 100644--- a/apps/desktop/src/renderer/features/region-screenshot/ScreenshotToolbar.tsx+++ b/apps/desktop/src/renderer/features/region-screenshot/ScreenshotToolbar.tsx@@ -243,7 +243,7 @@ export function ScreenshotModeBar(props: {<Divider /><div className="relative"><Button size="xs" variant="secondary" tone={props.aiMenuOpen ? 'default' : 'quiet'} disabled={!props.canAsk} aria-label={t('regionScreenshot.cindy')} aria-expanded={props.aiMenuOpen}- onMouseDown={(event) => event.preventDefault()} onClick={props.onToggleAiMenu}><Sparkles size={14} />Cindy</Button>+ onMouseDown={(event) => event.preventDefault()} onClick={props.onToggleAiMenu}><Sparkles size={14} className="text-[var(--warning-fg)]" />Cindy</Button>{props.aiMenuOpen && <div role="menu" className="absolute right-0 top-full z-10 mt-2 flex min-w-[168px] flex-col rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-1">{(['ask', 'translate', 'explain', 'extract'] as const).map((action) => {const Icon = AI_ICONS[action];diff --git a/apps/desktop/src/renderer/features/region-screenshot/ScrollCaptureOverlay.tsx b/apps/desktop/src/renderer/features/region-screenshot/ScrollCaptureOverlay.tsxindex 49a590b6a2..eae88f2efd 100644--- a/apps/desktop/src/renderer/features/region-screenshot/ScrollCaptureOverlay.tsx+++ b/apps/desktop/src/renderer/features/region-screenshot/ScrollCaptureOverlay.tsx@@ -8,6 +8,7 @@ import { ScrollCapture } from '../../../shared/scrollCapture';import type { RegionCaptureBegin } from '../../../shared/regionCapture';import type { RegionScreenshotBitmap } from '../../../shared/regionScreenshot';import { bitmapToImageData, type RegionScreenshotOverlayBridge } from './bridge';+import { SCREENSHOT_OVERLAY } from './screenshotColors';/** The selection stays over the source app; only its thumbnail/actions take input. */export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {@@ -28,7 +29,7 @@ export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {const previousHeight = useRef(begin.first.height);const reducedMotion = useReducedMotion();const followEdge = useRef<'start' | 'end'>('start');- const runtime = useRef({ active: true, finishing: false, capture: new ScrollCapture(begin.first), pending: null as Promise<void> | null, automatic: false, stillFrames: 0, unmatchedSince: 0, movingUntil: 0 });+ const runtime = useRef({ active: true, finishing: false, capture: new ScrollCapture(begin.first), pending: null as Promise<void> | null, automatic: false, automaticRevision: 0, stillFrames: 0, unmatchedSince: 0, movingUntil: 0 });const [height, setHeight] = useState(begin.first.height);const [automatic, setAutomatic] = useState(false);const [busy, setBusy] = useState(false);@@ -102,8 +103,12 @@ export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {async function changeAutomatic(enabled: boolean) {const state = runtime.current;if (state.finishing) return;+ const revision = ++state.automaticRevision;const accepted = await bridge.autoScroll(token, enabled);- if (!state.active || state.finishing) return;+ if (!state.active || state.finishing || revision !== state.automaticRevision) return;+ // Frames requested before this acknowledgement describe the previous switch+ // state, including frames requested while the command itself was in flight.+ state.automaticRevision++;state.automatic = accepted === true && enabled;state.stillFrames = 0;setAutomatic(state.automatic);@@ -112,9 +117,11 @@ export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {async function sample() {const state = runtime.current;+ const revision = state.automaticRevision;const frame = await bridge.liveFrame(token, false, panel.current?.clientHeight);if (!frame || !state.active || state.finishing) return;- if (state.automatic && frame.autoScrolling === false) {+ const currentAutomatic = state.automatic && revision === state.automaticRevision;+ if (currentAutomatic && frame.autoScrolling === false) {state.automatic = false; setAutomatic(false); setError('autoUnavailable');}const match = state.capture.add(frame.image);@@ -127,12 +134,12 @@ export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {state.unmatchedSince ||= performance.now();if (performance.now() - state.unmatchedSince > 1500) {if (state.capture.height > begin.first.height) setStatus('overlap');- if (state.automatic) await changeAutomatic(false);+ if (currentAutomatic && state.automatic) await changeAutomatic(false);}} else {state.unmatchedSince = 0;setStatus(match === 'limit' ? 'limit' : 'scrollHint');- if (state.automatic && (match === 'limit' || ++state.stillFrames >= 8)) await changeAutomatic(false);+ if (currentAutomatic && state.automatic && (match === 'limit' || ++state.stillFrames >= 8)) await changeAutomatic(false);}}@@ -190,7 +197,11 @@ export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {];const message = error === 'captureFailed' ? t('regionScreenshot.captureFailed') : t(`regionScreenshot.live.${error || status}`);return <div className="fixed inset-0 pointer-events-none select-none text-[var(--text-primary)]">- <div aria-hidden className="absolute border border-[var(--text-primary)]" style={{ left: begin.selection.x - 1, top: begin.selection.y - 1, width: begin.selection.width + 2, height: begin.selection.height + 2, boxShadow: '0 0 0 1px var(--surface-elevated)' }} />+ <div aria-hidden className="absolute" style={{+ left: begin.selection.x, top: begin.selection.y, width: begin.selection.width, height: begin.selection.height,+ outline: `1px solid ${SCREENSHOT_OVERLAY.edge}`,+ boxShadow: `0 0 0 1px ${SCREENSHOT_OVERLAY.edgeOuter}, 0 0 0 100000px ${SCREENSHOT_OVERLAY.shade}`,+ }} /><aside ref={panel} aria-label={t('regionScreenshot.live.preview')} className="absolute overflow-hidden pointer-events-auto" style={{ left: layout.preview.x, bottom: layout.viewport.height - layout.preview.y - layout.preview.height, width: layout.preview.width, height: initialPreviewHeight }}><div ref={preview} tabIndex={0} className="h-full w-full overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden" style={{ scrollbarWidth: 'none', overflowAnchor: 'none', scrollBehavior: 'auto' }} onWheel={() => { followGrowth.current = false; }} onScroll={() => {cancelAnimationFrame(scrollPaint.current);@@ -205,7 +216,7 @@ export function ScrollCaptureOverlay({ begin, token, bridge, onEdit }: {<div className="absolute flex items-center justify-center gap-1 rounded-lg border border-[var(--border-default)] bg-[var(--surface-elevated)] pointer-events-auto" style={{ left: layout.actions.x, top: layout.actions.y, width: layout.actions.width, height: layout.actions.height }}>{actions.map(({ key, label, Icon, run }) => <Tip key={key} text={label} side="top"><Button size="xs" variant={key === 'copy' ? 'cta' : 'secondary'} className="w-7 px-0" aria-label={label} disabled={busy} onClick={run}><Icon size={16} aria-hidden /></Button></Tip>)}</div>- <div className="absolute flex items-center justify-center rounded-lg border border-[var(--border-default)] bg-[var(--surface-elevated)] pointer-events-auto" style={{ left: layout.auto.x, top: layout.auto.y, width: layout.auto.width, height: layout.auto.height }}>+ <div className="absolute flex items-center justify-center pointer-events-auto" style={{ left: layout.auto.x, top: layout.auto.y, width: layout.auto.width, height: layout.auto.height }}><Tip text={t('regionScreenshot.live.scrollHint')} side="top"><Button size="sm" variant="secondary" disabled={busy} onClick={() => void changeAutomatic(!automatic)}>{t(`regionScreenshot.live.${automatic ? 'stopScroll' : 'autoScroll'}`)}</Button></Tip></div></div>;diff --git a/apps/desktop/src/renderer/features/region-screenshot/__tests__/screenshotRendering.test.tsx b/apps/desktop/src/renderer/features/region-screenshot/__tests__/screenshotRendering.test.tsxindex b226a439d5..3f422bcee5 100644--- a/apps/desktop/src/renderer/features/region-screenshot/__tests__/screenshotRendering.test.tsx+++ b/apps/desktop/src/renderer/features/region-screenshot/__tests__/screenshotRendering.test.tsx@@ -1,9 +1,12 @@// @vitest-environment jsdom-import { cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import { ScreenshotErrorBoundary } from '../ScreenshotErrorBoundary';import { Magnifier } from '../Magnifier';import { bitmapToImageData, imageDataToBitmap } from '../bridge';+import type { RegionScreenshotOverlayBridge } from '../bridge';+import type { RegionCaptureFrame } from '../../../../shared/regionCapture';+import { ScrollCaptureOverlay } from '../ScrollCaptureOverlay';vi.mock('@/lib/logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));@@ -14,9 +17,48 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => kdescribe('screenshot rendering recovery', () => {afterEach(() => {cleanup();+ vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals();});+ // 用户反馈点击自动滚动立刻提示已停止。已有渲染测试未覆盖开关与在途帧的竞态。+ // 最小输入:开启前发出的帧在开启成功后返回 false;下一帧的真实停止仍须显示。tier: unit。+ it('ignores a pre-start frame but reports a fresh automatic scrolling failure', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('ImageData', class {+ data: Uint8ClampedArray;+ constructor(readonly width: number, readonly height: number) {+ this.data = new Uint8ClampedArray(width * height * 4);+ }+ });+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({+ putImageData: vi.fn(), drawImage: vi.fn(),+ } as unknown as CanvasRenderingContext2D);+ const image = { width: 64, height: 64, data: new Uint8Array(64 * 64 * 4) };+ let resolveFrame!: (frame: RegionCaptureFrame) => void;+ const liveFrame = vi.fn(() => new Promise<RegionCaptureFrame>(resolve => { resolveFrame = resolve; }));+ const bridge = {+ liveFrame, autoScroll: vi.fn(async () => true), holdCapture: vi.fn(async () => {}),+ } as unknown as RegionScreenshotOverlayBridge;+ render(<ScrollCaptureOverlay token="capture" bridge={bridge} onEdit={vi.fn()} begin={{+ mode: 'scroll', first: image, selection: { x: 10, y: 10, width: 64, height: 64 },+ scrollLayout: {+ viewport: { width: 800, height: 600 }, preview: { x: 100, y: 10, width: 64, height: 128 },+ actions: { x: 100, y: 150, width: 128, height: 32 }, auto: { x: 10, y: 90, width: 128, height: 32 },+ },+ }} />);+ await act(() => vi.advanceTimersByTimeAsync(200));+ expect(liveFrame).toHaveBeenCalledTimes(1);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'regionScreenshot.live.autoScroll' })); });+ expect(screen.getByRole('button', { name: 'regionScreenshot.live.stopScroll' })).toBeTruthy();+ await act(async () => { resolveFrame({ image, autoScrolling: false, keys: null, cursor: null }); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('button', { name: 'regionScreenshot.live.stopScroll' })).toBeTruthy();+ await act(() => vi.advanceTimersByTimeAsync(200));+ await act(async () => { resolveFrame({ image, autoScrolling: false, keys: null, cursor: null }); });+ expect(screen.getByRole('alert').textContent).toBe('regionScreenshot.live.autoUnavailable');+ expect(screen.getByRole('button', { name: 'regionScreenshot.live.autoScroll' })).toBeTruthy();+ });// Unit: packed-pixel conversion must preserve alpha, immutable input and byte// views from IPC. Existing geometry/rendering tests do not inspect these bytes.it.each([0, 1])('round-trips screenshot pixels with byte offset %s', (offset) => {diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex dadfcd6ee7..888eb94c33 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -281,6 +281,7 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n> **Additional narrowly-scoped exceptions** (documented in their respective component specs, do NOT generalize as system semantic colors):>+> - **Screenshot toolbar Cindy icon** — the star icon before “Cindy” in Desktop's `ScreenshotModeBar` uses the existing gold foreground `--warning-fg` (`#F3A115` in Light and Dark; user decision 2026-10-28). Only this entry icon is gold; its label and button keep their standard theme colors and disabled treatment.> - **Mobile model-picker account quota bars** — owner-approved desktop parity (2026-10-23): `quotaBarWarn` marks remaining quota below 30% and above 10%; `quotaBarCrit` marks remaining quota at or below 10%. Both are quota-only semantic fills registered in §10, independent of the owner-crown and task-error roles. Normal quota remains neutral (`textSecondary`), and the track uses `surfaceChip`. iOS / Android share the real remaining proportion without a minimum fill width; 0% is empty. Keep the numerical percentage alongside the bar, so color is supplementary and never the only information. These colors do not apply to the account title, percentage text or row background.> - **Cindy Make source comparison** — the owner-approved source overview (2026-09-20, refined 2026-09-21) combines local main and the online target in one row, with personal below. Matching main hashes appear once in `--status-success`; differing hashes show the local value in `--text-secondary` → the verified online target in `--status-success`, with a `--text-tertiary` arrow. The online green identifies the official target even when local main is behind; difference counts remain explicit. Personal uses an icon-first label flush with the main row's left edge, without chip fill or inset padding: status icon, then `cindy-personal` with the localized status in parentheses, followed by the SHA and change count. The icon, name and parenthesized status inherit one color. Latest uses a check and `--status-success`; missing official updates use a download icon and the existing Light/Dark update foreground `--upgrade-banner-fg`; an inconclusive comparison uses a help icon and `--text-secondary`. The status stays visible; the shared hover/focus `Tip` may explain it further. This is informational, with no click action. During operations that replace the comparison, keep the name neutral and omit the status icon, suffix and tooltip. Personal-only changes do not invalidate latest; unavailable lookups never imply latest or an available update. Each source row wraps independently. Both modes use existing tokens; no other version surface inherits this treatment. Since 2026-10-01 (owner-approved plain-language Settings, [cindy-make-upstream.md](../cindy-make-upstream.md)), this hash comparison, the source path and its open/clear buttons sit inside the default-collapsed native `details` disclosure “Technical details (for developers)”; the visible overview is the plain-language `CindyMakeVersionSummary` (personal: official version + N changes; latest official: release/beta/dev label + included / not yet / can't confirm). The summary reuses the same verified comparison, the same check / download / help icons and `--status-success` / `--upgrade-banner-fg` / `--text-secondary` colors, shows no hash, branch or main, and is plain text because the technical comparison keeps the single live status region.> - **Shared-task mobile confirmations** — only the management page is full-screen. Remove, leave, close-current and close-all use compact confirmations. iOS retains `showConfirm` and the system Alert with supported Liquid Glass / older-system fallback. On 2026-09-20 the user rejected Android's default green-text system Alert: Android uses a centered content-height card, container radius 12, themed elevated surface, neutral outlined Cancel and pill-shaped solid danger action using `sharedTaskConfirmBackground/Foreground`. Reuse Mobile action primitives, minimum target 44, wrap actions when needed, and scroll long descriptions. Android Back cancels; the scrim does not dismiss. Cancellation preserves the task, page, tab and scroll position. An in-task guest exits directly from task details, without another management page. No native configuration changes or simulated iOS glass. Desktop retains the Plan B shared window.@@ -399,7 +400,7 @@ _Positioning note: the Display / Section Heading / Sub-heading rows are conceptu## 4. Component Stylings-**Desktop scrolling screenshot flow (owner correction, 2026-10-26).** Scrolling capture stays in the original screenshot overlay: the selected area passes input to the source app, while the available space beside it contains a width-scaled, scrollable preview and edit/save/cancel/finish icons. Do not add a separate capture toolbar or result page. Finish copies and closes; Edit returns the stitched image to the existing annotation toolbar. Preview scaling must not reduce export resolution. All control chrome follows the same Light/Dark tokens as the ordinary toolbar. The draggable screen-top mode bar contains Screenshot, Scrolling screenshot, Region recording, GIF and Cindy, and appears only on the currently operated display. Switching modes does not start capture; after selection an explicit start action begins scrolling/recording. The bottom toolbar contains only annotation and export tools. Manual scrolling supports both directions without duplicating previously captured content; automatic scrolling can be stopped. Static or briefly unmatched frames do not immediately show a failure notice; persistent failure preserves the captured content and stops automatic scrolling.+**Desktop scrolling screenshot flow (owner correction, 2026-10-26).** Scrolling capture stays in the original screenshot overlay: the selected area passes input to the source app, while the available space beside it contains a width-scaled, scrollable preview and edit/save/cancel/finish icons. During capture, the area outside the selection keeps the same dimming mask as region selection; the selected area remains clear and preview/actions appear above the mask (owner correction, 2026-10-28). Do not add a separate capture toolbar or result page. Finish copies and closes; Edit returns the stitched image to the existing annotation toolbar. Preview scaling must not reduce export resolution. All control chrome follows the same Light/Dark tokens as the ordinary toolbar. The draggable screen-top mode bar contains Screenshot, Scrolling screenshot, Region recording, GIF and Cindy, and appears only on the currently operated display. Switching modes does not start capture; after selection an explicit start action begins scrolling/recording. The bottom toolbar contains only annotation and export tools. Manual scrolling supports both directions without duplicating previously captured content; automatic scrolling can be stopped. Automatic scrolling must not move, lock, or repeatedly restore the system pointer; users can move freely and click Stop. Acceptance must include real pointer movement and button clicks, not only DOM automation (owner correction, 2026-10-28). The bottom automatic-scroll control has a single standard button face; its positioning wrapper has no background or border (owner correction, 2026-10-28). Static or briefly unmatched frames do not immediately show a failure notice; persistent failure preserves the captured content and stops automatic scrolling.**Screenshot chrome safe area (owner request, 2026-10-27).** The selection may cover the whole display, but every piece of screenshot chrome (mode bar, hint, size label, magnifier, annotation toolbar and style bar, scrolling preview and its actions, recording controls) stays inside the display's chrome area: the system work area (no menu bar, Dock or taskbar), with the macOS camera housing (notch) also excluded when the menu bar is hidden. Live controls fall back to the rest of the display only when the selection leaves no room inside it. On macOS, a two-finger trackpad swipe never zooms a pinned image (pinch zooms it continuously around the pointer); pinch in the editor zooms around the pointer; one swipe, including its momentum, changes the snap level by one step.