Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 129 additions & 5 deletions src/apps/desktop/src/appearance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f64>,
size: tauri::LogicalSize<f64>,
area_position: tauri::LogicalPosition<f64>,
area_size: tauri::LogicalSize<f64>,
) -> tauri::LogicalPosition<f64> {
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;
Expand Down Expand Up @@ -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::<f64>(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::<f64>(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()
Expand All @@ -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);
Expand All @@ -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::<f64>(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
Expand Down Expand Up @@ -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| {
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -40,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. */
Expand Down Expand Up @@ -181,6 +191,10 @@ export const AgentCompanionDesktopPet: React.FC = () => {
const [isSendingComposer, setIsSendingComposer] = useState(false);
const [hoveredBubbleSessionId, setHoveredBubbleSessionId] = useState<string | null>(null);
const dockRef = useRef<HTMLDivElement>(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<HTMLDivElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const composerInputRef = useRef<HTMLInputElement>(null);
Expand Down Expand Up @@ -465,23 +479,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) {
Expand Down Expand Up @@ -1180,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"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -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<void>((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<typeof deferred> }> = [];
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);
});
});
Loading
Loading