From 853dcb032f725661698641ad17864bd3fa04419f Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 31 Oct 2026 11:12:03 +0800 Subject: [PATCH 1/3] fix(pet): keep desktop pet window resize requests in order The pet dock is anchored bottom-right, so a host window narrower than the dock clips the bubbles on the left. Each resize invoke runs as its own async task, so a stale smaller size could land after a newer larger one and leave the window too narrow until the layout changed again. Keep a single resize request in flight and coalesce the rest to the latest size, re-request the size when the viewport comes out shorter than the dock needs (display or DPI changes), and round the height up so physical-pixel conversion cannot shave a row. --- .../AgentCompanionDesktopPet.test.tsx | 24 ++++++ .../AgentCompanionDesktopPet.tsx | 45 ++++++++--- .../agentCompanionWindowResize.test.ts | 76 +++++++++++++++++++ .../agentCompanionWindowResize.ts | 66 ++++++++++++++++ 4 files changed, 201 insertions(+), 10 deletions(-) create mode 100644 src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.test.ts create mode 100644 src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.ts diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.test.tsx b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.test.tsx index 5af9815bf2..9b0b3d98e4 100644 --- a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.test.tsx +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.test.tsx @@ -445,6 +445,30 @@ describe('AgentCompanionDesktopPet', () => { expect(menu!.style.visibility).toBe('visible'); }); + it('re-requests the dock size when the host leaves the viewport too narrow', async () => { + pushActivity({ mood: 'working', tasks: [task()], sequence: 1, emittedAt: 1 }); + await act(async () => { + await Promise.resolve(); + }); + expect(invokeMock).toHaveBeenLastCalledWith('resize_agent_companion_desktop_pet', { + width: 288, + height: 102, + }); + invokeMock.mockClear(); + + // A full-size viewport needs nothing more. + act(() => { window.dispatchEvent(new Event('resize')); }); + expect(invokeMock).not.toHaveBeenCalledWith('resize_agent_companion_desktop_pet', expect.anything()); + + // The bottom-right anchored dock would be clipped on the left at this width. + vi.stubGlobal('innerWidth', 96); + act(() => { window.dispatchEvent(new Event('resize')); }); + expect(invokeMock).toHaveBeenLastCalledWith('resize_agent_companion_desktop_pet', { + width: 288, + height: 102, + }); + }); + it('does not resize the window for a context menu', async () => { pushActivity({ mood: 'working', tasks: [task()], sequence: 1, emittedAt: 1 }); // Let the bubble's own resize request settle before watching for new ones. diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx index 782ae6896b..2d2c1c89f2 100644 --- a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx @@ -20,6 +20,7 @@ import { isReducedMotionPreferred } from '@/shared/utils/motionPreference'; import { getPetLookDirection } from '@/infrastructure/config/services/agentCompanionPetSprite'; import { startAgentCompanionDrag } from '@/infrastructure/config/services/AgentCompanionDragService'; import { prepareAgentCompanionPointerDrag, type CompanionPointerDrag } from '@/infrastructure/config/services/AgentCompanionPointerDragService'; +import { createCompanionWindowResizer, isCompanionViewportShort } from './agentCompanionWindowResize'; import './AgentCompanionDesktopPet.scss'; const log = createLogger('AgentCompanionDesktopPet'); @@ -181,6 +182,10 @@ export const AgentCompanionDesktopPet: React.FC = () => { const [isSendingComposer, setIsSendingComposer] = useState(false); const [hoveredBubbleSessionId, setHoveredBubbleSessionId] = useState(null); const dockRef = useRef(null); + const windowResizer = useMemo(() => createCompanionWindowResizer( + size => api.invoke('resize_agent_companion_desktop_pet', { width: size.width, height: size.height }), + error => log.warn('Failed to resize Agent companion window', error), + ), []); const bubblesRef = useRef(null); const menuRef = useRef(null); const composerInputRef = useRef(null); @@ -465,23 +470,43 @@ export const AgentCompanionDesktopPet: React.FC = () => { activePetSize.width, Math.min(WINDOW_MAX_WIDTH, Math.ceil(measuredDockWidth)), ); + // Rounded up so converting to physical pixels cannot shave a row or column. + const nextWindowHeight = Math.ceil(nextHeight); - if (!Number.isFinite(nextWidth) || !Number.isFinite(nextHeight)) { + if (!Number.isFinite(nextWidth) || !Number.isFinite(nextWindowHeight)) { log.warn('Skipped invalid Agent companion window resize', { width: nextWidth, - height: nextHeight, + height: nextWindowHeight, }); return; } - void api.invoke('resize_agent_companion_desktop_pet', { - width: nextWidth, - height: nextHeight, - }) - .catch(error => { - log.warn('Failed to resize Agent companion window', error); - }); - }, [activePetSize.height, activePetSize.width, composingSessionId, visibleTasks]); + windowResizer.request({ width: nextWidth, height: nextWindowHeight }); + }, [activePetSize.height, activePetSize.width, composingSessionId, visibleTasks, windowResizer]); + + useEffect(() => { + // The host can change the window behind the dock's back (display or DPI + // changes, a request the platform did not apply). Ask again whenever the + // viewport comes out smaller than the dock needs; the host ignores requests + // that already match, so this cannot loop. + const reassertWindowSize = () => { + const target = windowResizer.target(); + if (target && isCompanionViewportShort( + { width: window.innerWidth, height: window.innerHeight }, + target, + )) { + log.debug('Re-requesting Agent companion window size', { + viewportWidth: window.innerWidth, + viewportHeight: window.innerHeight, + width: target.width, + height: target.height, + }); + windowResizer.request(target); + } + }; + window.addEventListener('resize', reassertWindowSize); + return () => window.removeEventListener('resize', reassertWindowSize); + }, [windowResizer]); useEffect(() => { if (IS_WINDOWS_WEBVIEW && !trackPetLook) { diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.test.ts b/src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.test.ts new file mode 100644 index 0000000000..7b2977d2b6 --- /dev/null +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + createCompanionWindowResizer, + isCompanionViewportShort, + type CompanionWindowSize, +} from './agentCompanionWindowResize'; + +function deferred() { + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + return { promise, resolve, reject }; +} + +async function flush() { + for (let index = 0; index < 5; index += 1) await Promise.resolve(); +} + +describe('createCompanionWindowResizer', () => { + it('keeps one request in flight and sends only the latest size afterwards', async () => { + const calls: Array<{ size: CompanionWindowSize; done: ReturnType }> = []; + const send = vi.fn((size: CompanionWindowSize) => { + const done = deferred(); + calls.push({ size, done }); + return done.promise; + }); + const resizer = createCompanionWindowResizer(send, vi.fn()); + + resizer.request({ width: 96, height: 110 }); + resizer.request({ width: 288, height: 110 }); + resizer.request({ width: 96, height: 110 }); + resizer.request({ width: 288, height: 120 }); + expect(send).toHaveBeenCalledTimes(1); + expect(resizer.target()).toEqual({ width: 288, height: 120 }); + + calls[0].done.resolve(); + await flush(); + // The stale intermediate sizes never reach the host, so none can land last. + expect(send.mock.calls.map(([size]) => size)).toEqual([ + { width: 96, height: 110 }, + { width: 288, height: 120 }, + ]); + + calls[1].done.resolve(); + await flush(); + resizer.request({ width: 96, height: 110 }); + expect(send).toHaveBeenCalledTimes(3); + }); + + it('keeps draining after a failed request', async () => { + const first = deferred(); + const send = vi.fn() + .mockReturnValueOnce(first.promise) + .mockResolvedValue(undefined); + const onError = vi.fn(); + const resizer = createCompanionWindowResizer(send, onError); + + resizer.request({ width: 96, height: 110 }); + resizer.request({ width: 288, height: 110 }); + first.reject(new Error('host busy')); + await flush(); + + expect(onError).toHaveBeenCalledTimes(1); + expect(send).toHaveBeenLastCalledWith({ width: 288, height: 110 }); + }); +}); + +describe('isCompanionViewportShort', () => { + it('ignores sub-pixel rounding but flags a viewport the dock overflows', () => { + const target = { width: 288, height: 110 }; + expect(isCompanionViewportShort({ width: 287.2, height: 109.6 }, target)).toBe(false); + expect(isCompanionViewportShort({ width: 300, height: 120 }, target)).toBe(false); + expect(isCompanionViewportShort({ width: 96, height: 110 }, target)).toBe(true); + expect(isCompanionViewportShort({ width: 288, height: 96 }, target)).toBe(true); + }); +}); diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.ts b/src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.ts new file mode 100644 index 0000000000..f5532fb494 --- /dev/null +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/agentCompanionWindowResize.ts @@ -0,0 +1,66 @@ +export interface CompanionWindowSize { + width: number; + height: number; +} + +export interface CompanionWindowResizer { + /** Requests a size; while a request is in flight only the latest one is kept. */ + request: (size: CompanionWindowSize) => void; + /** The size the dock last asked for, or null before the first request. */ + target: () => CompanionWindowSize | null; +} + +/** + * Serializes pet window resize IPC. + * + * Every invoke of an async Tauri command runs as its own task, so two requests + * sent back to back can reach the host in either order. A stale smaller size + * landing last leaves the window narrower than the bottom-right anchored dock, + * which clips the bubbles on the left. Keeping a single request in flight and + * coalescing the rest to the latest size makes the last request always win. + */ +export function createCompanionWindowResizer( + send: (size: CompanionWindowSize) => Promise, + onError: (error: unknown) => void, +): CompanionWindowResizer { + let target: CompanionWindowSize | null = null; + let pending: CompanionWindowSize | null = null; + let inFlight = false; + + const drain = async () => { + inFlight = true; + try { + while (pending) { + const next = pending; + pending = null; + try { + await send(next); + } catch (error) { + onError(error); + } + } + } finally { + inFlight = false; + } + }; + + return { + request: size => { + target = size; + pending = size; + if (!inFlight) void drain(); + }, + target: () => target, + }; +} + +/** + * True when the viewport is smaller than the requested size by more than the + * sub-pixel rounding fractional display scales introduce. + */ +export function isCompanionViewportShort( + viewport: CompanionWindowSize, + target: CompanionWindowSize, +): boolean { + return viewport.width + 1 < target.width || viewport.height + 1 < target.height; +} From 6f6b96fc202f137716bdeb9ee9c715aa4ba486a0 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 31 Oct 2026 11:12:03 +0800 Subject: [PATCH 2/3] fix(desktop): size the pet window by its inner bounds set_size applies the inner size, but the no-op check and the bottom-right anchoring compared against the outer size. Where the native frame adds pixels the request was skipped, leaving the viewport narrower than the dock. Compare and anchor on the inner size and include the frame when keeping the window inside the work area. Also re-clamp the pet into the work area after a display scale change: the platform keeps the physical origin while the physical size follows the new scale, which could push the pet past a screen edge until the next bubble-driven resize. The clamp math is now a pure function with tests. --- src/apps/desktop/src/appearance.rs | 134 +++++++++++++++++++++++++++-- 1 file changed, 129 insertions(+), 5 deletions(-) diff --git a/src/apps/desktop/src/appearance.rs b/src/apps/desktop/src/appearance.rs index 715c02e388..39b41582f5 100644 --- a/src/apps/desktop/src/appearance.rs +++ b/src/apps/desktop/src/appearance.rs @@ -83,7 +83,17 @@ fn clamp_agent_companion_window_position( let Some((area_position, area_size)) = work_area_for_agent_companion_window(app, window) else { return position; }; + clamp_to_agent_companion_work_area(position, size, area_position, area_size) +} +/// Keeps the whole outer window inside the work area, so neither the pet nor a +/// bubble beside it can sit past a screen edge. +fn clamp_to_agent_companion_work_area( + position: tauri::LogicalPosition, + size: tauri::LogicalSize, + area_position: tauri::LogicalPosition, + area_size: tauri::LogicalSize, +) -> tauri::LogicalPosition { let min_x = area_position.x + AGENT_COMPANION_WINDOW_EDGE_MARGIN; let min_y = area_position.y + AGENT_COMPANION_WINDOW_EDGE_MARGIN; let max_x = area_position.x + area_size.width - size.width - AGENT_COMPANION_WINDOW_EDGE_MARGIN; @@ -964,10 +974,26 @@ fn resize_agent_companion_window( AGENT_COMPANION_WINDOW_MAX_HEIGHT, ); let scale_factor = window.scale_factor().unwrap_or(1.0); - let size = agent_companion_window_effective_size(window); - if (size.width - width).abs() < 0.5 && (size.height - height).abs() < 0.5 { + // `set_size` sets the inner (webview) size, so compare and anchor against + // the inner size too. Comparing against the outer size skips requests on + // platforms where the native frame adds pixels, leaving the viewport + // narrower than the bottom-right anchored dock and clipping it on the left. + let fallback_size = agent_companion_window_effective_size(window); + let inner_size = window + .inner_size() + .ok() + .map(|size| size.to_logical::(scale_factor)) + .unwrap_or(fallback_size); + if (inner_size.width - width).abs() < 0.5 && (inner_size.height - height).abs() < 0.5 { return; } + let outer_size = window + .outer_size() + .ok() + .map(|size| size.to_logical::(scale_factor)) + .unwrap_or(inner_size); + let frame_width = (outer_size.width - inner_size.width).max(0.0); + let frame_height = (outer_size.height - inner_size.height).max(0.0); let old_position = window .outer_position() @@ -987,10 +1013,10 @@ fn resize_agent_companion_window( app, window, tauri::LogicalPosition::new( - position.x + size.width - width, - position.y + size.height - height, + position.x + inner_size.width - width, + position.y + inner_size.height - height, ), - tauri::LogicalSize::new(width, height), + tauri::LogicalSize::new(width + frame_width, height + frame_height), ); if let Err(e) = window.set_position(next_position) { warn!("Failed to position Agent companion window: {}", e); @@ -1000,6 +1026,54 @@ fn resize_agent_companion_window( } } +/// Pulls the pet back inside the work area after a display scale change. +/// +/// The platform keeps the physical origin while the window's physical size +/// follows the new scale, which can push the pet or a bubble past a screen edge. +/// Nothing else re-clamps it until the next bubble-driven resize. +fn reclamp_agent_companion_window(app: &tauri::AppHandle, window: &tauri::WebviewWindow) { + let scale_factor = window.scale_factor().unwrap_or(1.0); + let Ok(position) = window.outer_position() else { + return; + }; + let position = position.to_logical::(scale_factor); + let size = agent_companion_window_effective_size(window); + let next_position = clamp_agent_companion_window_position(app, window, position, size); + if (next_position.x - position.x).abs() < 0.5 && (next_position.y - position.y).abs() < 0.5 { + return; + } + if let Err(e) = window.set_position(next_position) { + warn!( + "Failed to keep Agent companion window inside the work area: {}", + e + ); + } else { + remember_agent_companion_window_position(next_position); + } +} + +fn watch_agent_companion_window_scale(app: &tauri::AppHandle, window: &tauri::WebviewWindow) { + let app = app.clone(); + window.on_window_event(move |event| { + if !matches!(event, tauri::WindowEvent::ScaleFactorChanged { .. }) { + return; + } + // Deferred: the platform applies its own DPI-adjusted bounds after this + // event returns, which would overwrite a position set from inside it. + let app_for_clamp = app.clone(); + if let Err(e) = app.run_on_main_thread(move || { + if let Some(window) = app_for_clamp.get_webview_window(AGENT_COMPANION_WINDOW_LABEL) { + reclamp_agent_companion_window(&app_for_clamp, &window); + } + }) { + warn!( + "Failed to schedule Agent companion window re-clamp after a scale change: {}", + e + ); + } + }); +} + /// Re-asserts the pet stacking hint after the native window is mapped. /// /// GTK applies keep-above on map, and a reused window may have been raised @@ -1112,6 +1186,7 @@ pub async fn show_agent_companion_desktop_pet(app: tauri::AppHandle) -> Result<( ); position_agent_companion_window(&app, &window); + watch_agent_companion_window_scale(&app, &window); let show_started_at = Instant::now(); window.show().map_err(|e| { @@ -1220,6 +1295,55 @@ pub async fn show_main_window(app: tauri::AppHandle) -> Result<(), String> { Ok(()) } +#[cfg(test)] +mod agent_companion_window_geometry_tests { + use super::{clamp_to_agent_companion_work_area, AGENT_COMPANION_WINDOW_EDGE_MARGIN}; + use tauri::{LogicalPosition, LogicalSize}; + + const MARGIN: f64 = AGENT_COMPANION_WINDOW_EDGE_MARGIN; + + fn clamp(x: f64, y: f64, width: f64, height: f64) -> (f64, f64) { + // A 2560x1440 work area to the right of a primary display, so negative + // and offset origins are both exercised by the other cases below. + let position = clamp_to_agent_companion_work_area( + LogicalPosition::new(x, y), + LogicalSize::new(width, height), + LogicalPosition::new(2560.0, 0.0), + LogicalSize::new(2560.0, 1400.0), + ); + (position.x, position.y) + } + + #[test] + fn keeps_a_window_that_already_fits() { + assert_eq!(clamp(3000.0, 600.0, 288.0, 110.0), (3000.0, 600.0)); + } + + #[test] + fn pulls_a_window_past_the_left_edge_back_inside() { + // A bubble growing the window leftward from a pet near the edge. + assert_eq!(clamp(2400.0, 600.0, 288.0, 110.0), (2560.0 + MARGIN, 600.0)); + } + + #[test] + fn keeps_the_right_and_bottom_edges_inside_including_the_frame() { + let (x, y) = clamp(5000.0, 2000.0, 290.0, 112.0); + assert_eq!(x, 2560.0 + 2560.0 - 290.0 - MARGIN); + assert_eq!(y, 1400.0 - 112.0 - MARGIN); + } + + #[test] + fn falls_back_to_the_work_area_origin_when_the_window_cannot_fit() { + let position = clamp_to_agent_companion_work_area( + LogicalPosition::new(-500.0, -500.0), + LogicalSize::new(360.0, 240.0), + LogicalPosition::new(-1280.0, 0.0), + LogicalSize::new(300.0, 200.0), + ); + assert_eq!((position.x, position.y), (-1280.0, 0.0)); + } +} + #[cfg(test)] mod development_frontend_tests { use super::development_frontend_url; From f7daa5074ab1bee06563a28a826d2a6a17598ea2 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 31 Oct 2026 11:12:03 +0800 Subject: [PATCH 3/3] fix(pet): fit oversized custom pets beside the bubble A bubble, gap, pet and edge buffer must fit in the 360px pet window; a custom spritesheet with large cells exceeded it, the host clamped the window and the bubble was clipped on the left every time. Add a petdexMaxSize box to the pet renderer that scales the native cell down while keeping its aspect ratio, and size the desktop pet within it. --- .../AgentCompanionDesktopPet.tsx | 10 ++++++++++ .../components/AgentCompanionPet.test.tsx | 20 +++++++++++++++++++ .../components/AgentCompanionPet.tsx | 17 ++++++++++++++-- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx index 2d2c1c89f2..d6613d6975 100644 --- a/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx +++ b/src/web-ui/src/app/components/AgentCompanionDesktopPet/AgentCompanionDesktopPet.tsx @@ -41,6 +41,15 @@ const WINDOW_EDGE_BUFFER = 4; * border gets clipped. */ const WINDOW_VERTICAL_BUFFER = 3; +/** + * Largest pet that still fits beside a bubble inside the host window. The dock + * is anchored bottom-right, so anything wider than the window is clipped on the + * left; oversized custom spritesheets are scaled down to this box instead. + */ +const PET_MAX_DISPLAY_SIZE = { + width: WINDOW_MAX_WIDTH - BUBBLE_WIDTH - WINDOW_HORIZONTAL_GAP - WINDOW_EDGE_BUFFER, + height: WINDOW_MAX_HEIGHT - WINDOW_VERTICAL_BUFFER * 2, +}; const POINTER_HOVER_POLL_INTERVAL_MS = 120; const PET_LOOK_HOLD_MS = 960; /** Clicks shorter/smaller than this use `show_main_window`; beyond it we start dragging. */ @@ -1205,6 +1214,7 @@ export const AgentCompanionDesktopPet: React.FC = () => { lookDirection={trackPetLook && !isDraggingPet ? lookDirection : null} nativePetdexSize petdexScale={PETDEX_DESKTOP_SCALE} + petdexMaxSize={PET_MAX_DISPLAY_SIZE} onPetFrameSizeChange={handlePetFrameSizeChange} className="openbitfun-agent-companion-window__pet" data-openbitfun-component="agent-companion-desktop-pet" data-openbitfun-part="pet"/> diff --git a/src/web-ui/src/flow_chat/components/AgentCompanionPet.test.tsx b/src/web-ui/src/flow_chat/components/AgentCompanionPet.test.tsx index c549fb7144..fb77358ae6 100644 --- a/src/web-ui/src/flow_chat/components/AgentCompanionPet.test.tsx +++ b/src/web-ui/src/flow_chat/components/AgentCompanionPet.test.tsx @@ -109,6 +109,26 @@ describe('pet sprite renderer', () => { expect(sprite().style.animation).not.toBe('none'); }); + it('scales an oversized native cell down into the max box, keeping its aspect ratio', async () => { + vi.stubGlobal('Image', class { + // v2 atlas with 512x512 cells: 256x256 at half scale, wider than the box. + naturalWidth = 8 * 512; + naturalHeight = 11 * 512; + onload: (() => void) | null = null; + set src(_value: string) { this.onload?.(); } + }); + const onSize = vi.fn(); + await act(async () => root.render()); + expect(onSize).toHaveBeenLastCalledWith({ width: 168, height: 168 }); + const petRoot = sprite().parentElement!; + expect(petRoot.style.getPropertyValue('--openbitfun-petdex-width')).toBe('168px'); + expect(petRoot.style.getPropertyValue('--openbitfun-petdex-height')).toBe('168px'); + + // A cell that already fits keeps the requested scale. + await act(async () => root.render()); + expect(onSize).toHaveBeenLastCalledWith({ width: 128, height: 128 }); + }); + it('shows look frames only during idle and restores the action under reduced motion', async () => { await act(async () => root.render()); expect(sprite().style.backgroundPositionY).toBe('100%'); diff --git a/src/web-ui/src/flow_chat/components/AgentCompanionPet.tsx b/src/web-ui/src/flow_chat/components/AgentCompanionPet.tsx index 64099db191..11c7dd2287 100644 --- a/src/web-ui/src/flow_chat/components/AgentCompanionPet.tsx +++ b/src/web-ui/src/flow_chat/components/AgentCompanionPet.tsx @@ -37,6 +37,8 @@ export interface AgentCompanionPetProps { pet?: AgentCompanionPetSelection | null; nativePetdexSize?: boolean; petdexScale?: number; + /** Fits the native petdex frame into this box, preserving its aspect ratio. */ + petdexMaxSize?: { width: number; height: number }; lookDirection?: number | null; action?: 'jumping' | 'waving' | 'failed' | null; dragDirection?: 'left' | 'right'; @@ -294,6 +296,7 @@ export const AgentCompanionPet: React.FC = ({ pet = null, nativePetdexSize = false, petdexScale = 1, + petdexMaxSize, lookDirection = null, action = null, dragDirection = 'left', @@ -309,6 +312,8 @@ export const AgentCompanionPet: React.FC = ({ const [failedPet, setFailedPet] = useState(null); const [reducedMotion, setReducedMotion] = useState(false); const [petFrameSize, setPetFrameSize] = useState<{ width: number; height: number } | null>(null); + const petdexMaxWidth = petdexMaxSize?.width; + const petdexMaxHeight = petdexMaxSize?.height; useEffect(() => { const media = window.matchMedia('(prefers-reduced-motion: reduce)'); const update = () => setReducedMotion(media.matches); @@ -356,7 +361,15 @@ export const AgentCompanionPet: React.FC = ({ return; } if (!nativePetdexSize) return; - const scale = Number.isFinite(petdexScale) && petdexScale > 0 ? petdexScale : 1; + const baseScale = Number.isFinite(petdexScale) && petdexScale > 0 ? petdexScale : 1; + const fitScale = (limit: number | undefined, size: number) => ( + limit !== undefined && Number.isFinite(limit) && limit > 0 ? limit / size : Infinity + ); + const scale = Math.min( + baseScale, + fitScale(petdexMaxWidth, frameSize.width), + fitScale(petdexMaxHeight, frameSize.height), + ); const nextSize = { width: Math.max(1, Math.round(frameSize.width * scale)), height: Math.max(1, Math.round(frameSize.height * scale)), @@ -375,7 +388,7 @@ export const AgentCompanionPet: React.FC = ({ return () => { cancelled = true; }; - }, [layout, nativePetdexSize, onPetFrameSizeChange, pet, petSrc, petdexScale]); + }, [layout, nativePetdexSize, onPetFrameSizeChange, pet, petSrc, petdexMaxHeight, petdexMaxWidth, petdexScale]); const [transitioning, setTransitioning] = useState(false); const prevMoodRef = useRef(mood);