diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts index 506dcd0d177c5e..b0c45f5f37b656 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts @@ -28,6 +28,7 @@ import { ILogService } from '../../../../../platform/log/common/log.js'; import { IHostService } from '../../../../services/host/browser/host.js'; import { ChatPetJumpGameModel } from '../../common/chatPetJumpGame.js'; import { IChatModel } from '../../common/model/chatModel.js'; +import { getSubagentIsActive, IChatToolInvocation } from '../../common/chatService/chatService.js'; import { CHAT_PET_OPEN_ACHIEVEMENTS_COMMAND_ID, ChatPetAccessoryId, getChatPetAccessory, getChatPetAchievement } from '../chatPetAchievements.js'; import { CHAT_PET_DEFAULT_SCALE, ChatPetHorizontalAnchor, ChatPetHorizontalPosition, ChatPetVariant, IChatPetService } from '../chatPetService.js'; import { CHAT_PET_CHANGE_COLOR_COMMAND_ID, ChatPetColor, getChatPetBodyColor, getChatPetColoredSprite, getChatPetColorVariant, getChatPetEyeColor, setChatPetImageSource } from '../chatPetColors.js'; @@ -190,6 +191,19 @@ const SPEECHLESS_FRAME_DURATIONS = [400, 120, 1_000, 120, 1_080]; const WORRY_FRAME_DURATIONS = [600, 600]; const DIZZY_FRAME_DURATIONS = Array.from({ length: 8 }, () => 120); +/** Scaling factor for calculating the size of the subagent pets. */ +const SUBAGENT_PET_SCALE = 0.5; +/** Maximum number of subagent pets shown at once. */ +const SUBAGENT_PET_MAX_COUNT = 10; +/** Delay between subagent pet arrivals, in milliseconds. */ +const SUBAGENT_PET_ARRIVAL_DELAY = 120; +/** Maximum stacking height (CSS pixels) before subagent pets share space. */ +const SUBAGENT_PET_MAX_STACKING_HEIGHT = 500; +/** Tolerance for fractional pixels when checking subagent pet bounds. */ +const SUBAGENT_PET_BOUNDARY_EPSILON = 0.01; +/** Distance kept between subagent pets and the edges of their platform. */ +const SUBAGENT_PET_EDGE_INSET = 12; + interface ChatPetSpriteSource { readonly url: string; readonly frameWidth: number; @@ -219,6 +233,28 @@ interface ChatPetSpriteElement { redrawFrame?: () => void; } +/** Supplies shared appearance, geometry, and animation services to a subagent pet. */ +interface SubagentPetHost { + readonly layer: HTMLElement; + readonly overlay: HTMLElement; + readonly eyes: HTMLElement; + readonly onDidChangeAnimationVisibility: Event; + readonly enabled: boolean; + readonly motionReduced: boolean; + readonly variant: ChatPetVariant; + readonly color: ChatPetColor; + readonly accessory: ChatPetAccessoryId | undefined; + readonly scale: number; + readonly random: () => number; + isAnimationVisible(element: HTMLElement): boolean; + observeAnimationVisibility(element: HTMLElement): IDisposable; + getDragBounds(): DOMRect; + getMovementBounds(): DOMRect; + getLanding(size: number): { left: number; top: number }; + scheduleResize(): void; + startAnimation(source: ChatPetSpriteSource, sprite: ChatPetSpriteElement, animation: MutableDisposable, onComplete?: () => void, reverse?: boolean, onFrame?: (frameIndex: number) => void, renderFrame?: (context: CanvasRenderingContext2D, frameIndex: number) => boolean): void; +} + interface ChatPetPendingRender { readonly generation: number; readonly sprite: ChatPetSpriteElement; @@ -1289,8 +1325,263 @@ export class ChatPetHopController extends Disposable { } } +/** Returns the displayed size of a subagent pet at the given main pet scale. */ +function getSubagentPetSize(scale: number): number { + return CHAT_PET_DISPLAY_SIZE * SUBAGENT_PET_SCALE * scale; +} + +/** Owns the appearance, animation and lifecycle of one subagent pet. */ +class SubagentPet extends Disposable { + /** Overlay element positioned at the pet's landing coordinates. */ + readonly element: HTMLElement; + private readonly _canvas: HTMLCanvasElement; + private readonly _image: HTMLImageElement; + private readonly _eyes: HTMLElement; + private readonly _sprite: ChatPetSpriteElement; + /** Resources for the active pet or its disappearance effect. */ + private readonly _activity = this._register(new DisposableStore()); + private readonly _spriteAnimation = this._activity.add(new MutableDisposable()); + private readonly _fallAnimation = this._activity.add(new MutableDisposable()); + private readonly _accessoryListener = this._activity.add(new MutableDisposable()); + private readonly _respawnTimer = this._activity.add(new RunOnceScheduler(() => this._advanceRespawn(), RESPAWN_EFFECT_REDUCED_MOTION_DURATION)); + private readonly _blinkController: ChatPetBlinkController; + private _state: 'idle' | 'splat' = 'idle'; + /** Tracks relocation after the pet loses its supporting platform. */ + private _respawnPhase: 'none' | 'falling' | 'despawning' | 'respawning' = 'none'; + private _accessory: ReturnType | undefined; + private _accessoryImage: HTMLImageElement | undefined; + + /** Creates a pet at the given overlay-relative landing position. */ + constructor(private readonly _host: SubagentPetHost, private _left: number, private _top: number) { + super(); + const scale = SUBAGENT_PET_SCALE * _host.scale; + const size = getSubagentPetSize(_host.scale); + this.element = dom.append(_host.layer, dom.$('.chat-subagent-pet', { 'aria-hidden': 'true' })); + this._register(toDisposable(() => this.element.remove())); + this._register(_host.observeAnimationVisibility(this.element)); + this.element.style.left = `${this._left}px`; + this.element.style.top = `${this._top}px`; + this.element.style.transform = `scale(${scale})`; + const distance = Math.max(0, _host.overlay.getBoundingClientRect().top + this._top + size); + this._canvas = dom.append(this.element, dom.$('canvas.chat-subagent-pet-canvas')) as HTMLCanvasElement; + this._canvas.width = CHAT_PET_SOURCE_SIZE; + this._canvas.height = CHAT_PET_SOURCE_SIZE; + this._eyes = this.element.appendChild(_host.eyes.cloneNode(true)) as HTMLElement; + this._eyes.classList.remove('blink', 'blinking', 'bobbed'); + this._eyes.classList.add('tracking'); + for (const eye of this._eyes.children) { + (eye.firstElementChild as HTMLElement | null)?.style.removeProperty('transform'); + } + this._blinkController = this._activity.add(new ChatPetBlinkController(blinking => this._eyes.classList.toggle('blink', blinking), _host.random)); + this._activity.add(_host.onDidChangeAnimationVisibility(() => this.updateBlink())); + const firstPupil = this._eyes.firstElementChild?.firstElementChild; + if (firstPupil) { + this._activity.add(dom.addDisposableListener(firstPupil, 'animationend', event => { + if ((event as AnimationEvent).animationName === 'chat-pet-tall-eye-blink') { + this._blinkController.onAnimationComplete(); + } + })); + } + this.updateBlink(); + this._image = dom.append(this.element, dom.$('img.chat-pet-spritesheet')) as HTMLImageElement; + this._image.alt = ''; + this._sprite = { container: this.element, canvas: this._canvas, image: this._image, color: _host.color }; + this._updateAccessory(); + this._activity.add(dom.addDisposableListener(this._image, 'load', () => this._onImageLoad())); + this._setState('idle'); + if (!_host.motionReduced && distance > 0) { + this._animateFall(this._top - distance, this._top); + } + } + + get left(): number { return this._left; } + get top(): number { return this._top; } + + /** Updates the scale and overlay-relative top position. */ + setScale(scale: number, top: number): void { + this._top = top; + this.element.style.top = `${this._top}px`; + this.element.style.transform = `scale(${scale})`; + } + + /** Returns whether the pet is being relocated. */ + isRespawning(): boolean { return this._respawnPhase !== 'none'; } + + /** Enables blinking only while the idle pet is visible. */ + updateBlink(): void { + this._blinkController.setEnabled(this._respawnPhase === 'none' && this._state === 'idle' && this._host.enabled && !this._host.motionReduced && this._host.isAnimationVisible(this.element)); + } + + /** Applies changes to the shared color, motion, variant, and accessory. */ + updateAppearance(motionChanged: boolean, variantChanged: boolean, accessoryChanged: boolean): void { + this._sprite.color = this._host.color; + this._eyes.style.color = getChatPetEyeColor(this._host.color); + if (accessoryChanged) { + this._updateAccessory(); + } + if (motionChanged || variantChanged) { + if (this._host.motionReduced) { + this._fallAnimation.clear(); + if (this._respawnPhase === 'falling') { + this._respawnPhase = 'despawning'; + } + } + this._setState(this._host.motionReduced ? 'idle' : this._state); + } else { + this._sprite.redrawFrame?.(); + } + } + + /** Falls to an overlay-relative position, optionally starting relocation on landing. */ + fallTo(top: number, respawn = false): void { + const previousTop = this.element.getBoundingClientRect().top - this._host.overlay.getBoundingClientRect().top; + const animateFall = !this._host.motionReduced && top > previousTop; + this._respawnPhase = respawn ? (animateFall ? 'falling' : 'despawning') : 'none'; + this._fallAnimation.clear(); + this._top = top; + this.element.style.top = `${top}px`; + this._setState('idle'); + if (animateFall) { + this._animateFall(previousTop, top); + } + } + + /** Plays the disappearance effect and releases the pet when it completes. */ + despawn(onComplete: () => void): void { + this._activity.clear(); + this._image.remove(); + this._accessoryImage?.remove(); + this.element.classList.remove('chat-subagent-pet'); + this.element.classList.add('chat-subagent-pet-despawning'); + this._eyes.remove(); + const image = dom.append(this.element, dom.$('img.chat-pet-spritesheet')) as HTMLImageElement; + image.alt = ''; + const sources = getRespawnSpriteSources(this._host.variant); + const source = this._host.motionReduced ? sources.reducedMotion : sources.animated; + const animation = this._activity.add(new MutableDisposable()); + const sprite: ChatPetSpriteElement = { container: this.element, canvas: this._canvas, image, color: this._host.color }; + this._activity.add(dom.addDisposableListener(image, 'load', () => this._host.startAnimation(source, sprite, animation, onComplete, true))); + this._activity.add(dom.addDisposableListener(image, 'error', onComplete)); + const targetWindow = dom.getWindow(this.element); + const timer = targetWindow.setTimeout(onComplete, this._host.motionReduced ? RESPAWN_EFFECT_REDUCED_MOTION_DURATION : RESPAWN_EFFECT_DURATION); + this._activity.add(toDisposable(() => targetWindow.clearTimeout(timer))); + setChatPetImageSource(image, source.url); + } + + private _getSpriteSource(): ChatPetSpriteSource { + const sources = this._respawnPhase === 'despawning' || this._respawnPhase === 'respawning' + ? getRespawnSpriteSources(this._host.variant) : getChatPetSpriteSources(this._host.variant)[this._state]; + return this._host.motionReduced ? sources.reducedMotion : sources.animated; + } + + private _setState(state: 'idle' | 'splat'): void { + this._respawnTimer.cancel(); + this._spriteAnimation.clear(); + this._state = state; + this.updateBlink(); + if (this._host.motionReduced) { + this._eyes.classList.remove('bobbed'); + } + setChatPetImageSource(this._image, this._getSpriteSource().url); + } + + private _updateAccessory(): void { + this._accessory = this._host.accessory ? getChatPetAccessory(this._host.accessory) : undefined; + if (!this._accessory) { + this._accessoryListener.clear(); + this._accessoryImage?.remove(); + this._accessoryImage = undefined; + } else { + if (!this._accessoryImage) { + this._accessoryImage = dom.append(this.element, dom.$('img.chat-pet-spritesheet')) as HTMLImageElement; + this._accessoryImage.alt = ''; + this._accessoryListener.value = dom.addDisposableListener(this._accessoryImage, 'load', () => this._sprite.redrawFrame?.()); + } + setChatPetImageSource(this._accessoryImage, getChatPetAccessoryImageSource(this._accessory).url); + } + } + + private _onImageLoad(): void { + if (this._respawnPhase === 'despawning' || this._respawnPhase === 'respawning') { + this._eyes.classList.remove('tracking', 'bobbed'); + this._host.startAnimation(this._getSpriteSource(), this._sprite, this._spriteAnimation, () => this._advanceRespawn(), this._respawnPhase === 'despawning'); + // Relocation must finish even when its sprite is outside the viewport. + this._respawnTimer.schedule(this._host.motionReduced ? RESPAWN_EFFECT_REDUCED_MOTION_DURATION : RESPAWN_EFFECT_DURATION); + return; + } + if (this._state === 'splat' && this._host.motionReduced) { + this._setState('idle'); + return; + } + const source = this._getSpriteSource(); + this._eyes.classList.toggle('tracking', this._state === 'idle'); + this._host.startAnimation(source, this._sprite, this._spriteAnimation, this._state === 'splat' ? () => this._setState('idle') : undefined, false, frameIndex => { + this._eyes.classList.toggle('bobbed', this._state === 'idle' && !this._host.motionReduced && (source.accessoryRigFrame ?? frameIndex) >= 20); + }, (context, frameIndex) => { + if (this._accessoryImage?.complete && this._accessoryImage.naturalWidth > 0 && this._accessory) { + drawChatPetComposite(context, this._image, this._accessoryImage, frameIndex, source.accessoryRigFrame ?? frameIndex, source.frameWidth, source.frameHeight ?? CHAT_PET_SOURCE_SIZE, 'right', this._state, source.fixedOrientationDecorations, true, this._accessory.eyeAccessoryMirrorsWithFacing !== false, this._accessory.coversAntennae === true, this._sprite.color); + return true; + } + return false; + }); + } + + private _animateFall(from: number, to: number): void { + const fall = this.element.animate([{ top: `${from}px` }, { top: `${to}px` }], { duration: getChatPetFallDuration(to - from), easing: 'cubic-bezier(0.42, 0, 1, 1)' }); + this._fallAnimation.value = toDisposable(() => fall.cancel()); + fall.onfinish = () => { + this._fallAnimation.clear(); + if (this._respawnPhase === 'falling') { + this._respawnPhase = 'despawning'; + this._setState('idle'); + } else if (!this._host.motionReduced) { + this._setState('splat'); + } + }; + } + + /** Advances relocation from disappearance to reappearance and landing. */ + private _advanceRespawn(): void { + const size = getSubagentPetSize(this._host.scale); + if (this._respawnPhase === 'despawning') { + const overlay = this._host.overlay.getBoundingClientRect(); + const input = this._host.getDragBounds(); + this._respawnPhase = 'respawning'; + this._left = Math.max(input.left - overlay.left, Math.min(this._left, input.right - overlay.left - size)); + this._top = this._host.getMovementBounds().top - overlay.top; + this.element.style.left = `${this._left}px`; + this.element.style.top = `${this._top}px`; + this._setState('idle'); + } else if (this._respawnPhase === 'respawning') { + const landing = this._host.getLanding(size); + this._left = landing.left; + this.element.style.left = `${this._left}px`; + this.fallTo(landing.top); + this._host.scheduleResize(); + } + } +} + export class ChatPetWidget extends Disposable { + /** Active subagent pets keyed by request and tool call identity. */ + private readonly _subagentPets = new Map(); + /** Active subagent identities, including those waiting for an available pet slot. */ + private _activeSubagentIds: ReadonlySet = new Set(); + /** Disappearing pets still occupy a slot until their effect finishes. */ + private _despawningSubagentPetCount = 0; + /** Chat model currently supplying active subagents. */ + private _subagentPetModel: IChatModel | undefined; + /** Resources for active subagent pets and their disappearance effects. */ + private readonly _subagentPetEffects = this._register(new DisposableStore()); + /** Coalesces bounds checks while the chat is resizing. */ + private readonly _subagentPetResizeScheduler = this._register(new RunOnceScheduler(() => this._reconcileSubagentPetResize(), 16)); + private readonly _subagentPetArrivalScheduler = this._register(new RunOnceScheduler(() => this._updateSubagentPets(this._activeSubagentIds, true), SUBAGENT_PET_ARRIVAL_DELAY)); + private readonly _subagentPetArrivalDelay: number; + /** Overlay layer containing subagent pets. */ + private readonly _subagentPetLayer: HTMLElement; + /** Shared widget services, initialized when the first subagent pet appears. */ + private _subagentPetHost: SubagentPetHost | undefined; private parent: HTMLElement; private dragBounds: HTMLElement; private movementBounds: HTMLElement; @@ -1354,6 +1645,7 @@ export class ChatPetWidget extends Disposable { private _dragOrigin: readonly [number, number] | undefined; private _dragPosition: readonly [number, number] | undefined; private readonly _animationVisibility = new Map(); + private readonly _animationObserver: IntersectionObserver | undefined; private readonly _onDidChangeAnimationVisibility = this._register(new Emitter()); private readonly _dragMonitor = this._register(new GlobalPointerMoveMonitor()); private readonly _idleExpired = observableValue(this, false); @@ -1431,12 +1723,15 @@ export class ChatPetWidget extends Disposable { private _color: ChatPetColor; private _selectedAccessory: ChatPetAccessoryId | undefined; private _scale = 1; + private readonly _random: () => number; constructor( host: IChatPetWidgetHost, options: { readonly resizeObserverCtor?: typeof ResizeObserver; readonly intersectionObserverCtor?: typeof IntersectionObserver; + readonly random?: () => number; + readonly subagentPetArrivalDelay?: number; } | undefined, @IChatPetService private readonly chatPetService: IChatPetService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @@ -1447,6 +1742,8 @@ export class ChatPetWidget extends Disposable { @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); + this._random = options?.random ?? Math.random; + this._subagentPetArrivalDelay = options?.subagentPetArrivalDelay ?? SUBAGENT_PET_ARRIVAL_DELAY; this.parent = host.parent; this.dragBounds = host.dragBounds; @@ -1459,6 +1756,7 @@ export class ChatPetWidget extends Disposable { this.parent.classList.add('chat-pet-host'); this._overlay = dom.$(`.${CHAT_PET_OVERLAY_CLASS}`); this.parent.prepend(this._overlay); + this._subagentPetLayer = dom.append(this._overlay, dom.$('.chat-subagent-pet-layer')); this._register(toDisposable(() => { this.parent.classList.remove('chat-pet-host'); this._overlay.remove(); @@ -1564,16 +1862,19 @@ export class ChatPetWidget extends Disposable { return; } for (const entry of entries) { - this._animationVisibility.set(entry.target, entry.isIntersecting && entry.boundingClientRect.width > 0 && entry.boundingClientRect.height > 0); + if (this._animationVisibility.has(entry.target)) { + this._animationVisibility.set(entry.target, entry.isIntersecting && entry.boundingClientRect.width > 0 && entry.boundingClientRect.height > 0); + } } this._updateAnimationVisibility(); }); + this._animationObserver = observer; this._register(toDisposable(() => { observer.disconnect(); this._animationVisibility.clear(); })); for (const element of [this._visual, ...this._sprites.map(sprite => sprite.container), this._speechBubble.container, this._respawnEffect.container]) { - observer.observe(element); + this._register(this._observeAnimationVisibility(element)); } } this._register(dom.addDisposableListener(dom.getWindow(this._button.element).document, dom.EventType.POINTER_MOVE, (event: PointerEvent) => { @@ -1834,8 +2135,20 @@ export class ChatPetWidget extends Disposable { this._finishDisable(); } } + for (const subagentPet of this._subagentPets.values()) { + subagentPet.updateBlink(); + if (enabled && (wasMotionReduced !== this._motionReduced || colorChanged || accessoryChanged)) { + subagentPet.updateAppearance(wasMotionReduced !== this._motionReduced, variantChanged, accessoryChanged); + } + } if (!enabled) { + this._subagentPetResizeScheduler.cancel(); + this._subagentPetArrivalScheduler.cancel(); + this._activeSubagentIds = new Set(); + this._despawningSubagentPetCount = 0; + this._subagentPets.clear(); + this._subagentPetEffects.clear(); this._hopController.cancel(); this._idleScheduler.cancel(); this._transientScheduler.cancel(); @@ -1896,6 +2209,70 @@ export class ChatPetWidget extends Disposable { this._renderState(renderedState, variantChanged, isDragging); })); + this._register(autorun(reader => { + const enabled = isChatPetVisible(this.chatPetService.enabled.read(reader), windowActive.read(reader)); + const model = this._host.read(reader).model.read(reader); + if (model !== this._subagentPetModel) { + this._subagentPetArrivalScheduler.cancel(); + this._updateSubagentPets(new Set()); + this._subagentPetModel = model; + } + if (!enabled || !model) { + return; + } + observableSignalFromEvent(this, model.onDidChange).read(reader); + const activeSubagentIds = new Set(); + let initializing = true; + for (const request of model.getRequests()) { + const response = request.response; + if (!response) { + continue; + } + let previousResponseSubagentIds = new Set(); + reader.store.add(autorun(responseReader => { + observableSignalFromEvent(this, response.onDidChange).read(responseReader); + const responseSubagentIds = new Set(); + for (const part of response.response.value) { + if (part.kind !== 'toolInvocation') { + continue; + } + part.toolSpecificDataKind.read(responseReader); + const data = part.toolSpecificData; + if (data?.kind === 'subagent') { + // Metadata updates also notify through the tool state. + part.state.read(responseReader); + } + if (data?.kind === 'subagent' && data.presentation !== 'phase' && data.hasStarted !== false && (getSubagentIsActive(data) ?? !IChatToolInvocation.isComplete(part, responseReader))) { + responseSubagentIds.add(JSON.stringify([request.id, part.toolCallId])); + } + } + // Keep unchanged IDs in place to preserve waiting order for available pet slots. + let changed = false; + for (const id of previousResponseSubagentIds) { + if (!responseSubagentIds.has(id)) { + activeSubagentIds.delete(id); + changed = true; + } + } + for (const id of responseSubagentIds) { + if (!previousResponseSubagentIds.has(id)) { + activeSubagentIds.add(id); + changed = true; + } + } + if (!changed) { + return; + } + previousResponseSubagentIds = responseSubagentIds; + if (!initializing) { + this._updateSubagentPets(activeSubagentIds); + } + })); + } + initializing = false; + this._updateSubagentPets(activeSubagentIds); + })); + this._register(autorun(reader => { const chatModel = this._host.read(reader).model.read(reader); const response = chatModel?.lastRequestObs.read(reader)?.response; @@ -2100,6 +2477,16 @@ export class ChatPetWidget extends Disposable { this._updateAnimationVisibility(); } + /** Tracks sprite visibility until its owning element is disposed. */ + private _observeAnimationVisibility(element: HTMLElement): IDisposable { + this._animationVisibility.set(element, true); + this._animationObserver?.observe(element); + return toDisposable(() => { + this._animationObserver?.unobserve(element); + this._animationVisibility.delete(element); + }); + } + private _isAnimationVisible(element: HTMLElement): boolean { return element.isConnected && !dom.getWindow(element).document.hidden && this._animationVisibility.get(element) !== false; } @@ -2279,6 +2666,7 @@ export class ChatPetWidget extends Disposable { } private _handleHostLayoutChange(): void { + this._scheduleSubagentPetResize(); if (this._jumpGame.value) { this._jumpGame.value.layout(); return; @@ -2308,6 +2696,9 @@ export class ChatPetWidget extends Disposable { } private _updatePlatformPosition(): void { + if (this._enabled && this._subagentPets.size) { + this._settleSubagentPets(true); + } if (this._jumpGame.value) { this._jumpGame.value.layout(); return; @@ -2943,13 +3334,228 @@ export class ChatPetWidget extends Disposable { return this._button.element.offsetLeft; } + /** Returns the visible bounds and platforms for subagent pet placement. */ + private _getSubagentPetBounds(): { overlay: DOMRect; movement: DOMRect; platforms: readonly IChatPetPlatform[]; left: number; right: number; bottom: number; floor: number } { + const overlay = this._overlay.getBoundingClientRect(); + const input = this.dragBounds.getBoundingClientRect(); + const movement = this.movementBounds.getBoundingClientRect(); + const platforms = this._getPlatforms(); + const platform = getChatPetFallTarget(input.left + input.width / 2, movement.top - 1, 0, 0, platforms, input.top).platform; + const left = Math.max(0, input.left, movement.left, platform?.left ?? input.left); + const right = Math.min(dom.getWindow(this._overlay).innerWidth, input.right, movement.right, platform?.right ?? input.right); + const inset = Math.min(SUBAGENT_PET_EDGE_INSET, Math.max(0, (right - left) / 4)); + const floor = Math.min(input.top, movement.bottom); + return { overlay, movement, platforms, left: left + inset - overlay.left, right: right - inset - overlay.left, bottom: Math.min(platform?.top ?? input.top, floor) - overlay.top, floor }; + } + + /** Choose a random landing point, accounting for subagent pets already on the platform. */ + private _getSubagentPetLanding(size: number): { left: number; top: number } { + const bounds = this._getSubagentPetBounds(); + const { overlay, movement, platforms, floor } = bounds; + const minimumLeft = bounds.left; + const maximumLeft = Math.max(minimumLeft, bounds.right - size); + const mainPetLeft = this._button.element.offsetLeft; + const beforeMainPet = Math.max(0, Math.min(maximumLeft, mainPetLeft - size) - minimumLeft); + const afterMainPetStart = Math.max(minimumLeft, mainPetLeft + this._getDisplaySize()); + const afterMainPet = Math.max(0, maximumLeft - afterMainPetStart); + const available = beforeMainPet + afterMainPet; + const minimumTop = Math.max(movement.top - overlay.top, bounds.bottom - SUBAGENT_PET_MAX_STACKING_HEIGHT); + const attempts = Math.max(1, Math.ceil(available / Math.max(1, size / 2))); + const start = this._random() * available; + let best: { left: number; top: number } | undefined; + for (let index = 0; index < attempts; index++) { + const offset = available > 0 ? (start + index * available / attempts) % available : 0; + const left = available > 0 ? (offset < beforeMainPet ? minimumLeft + offset : afterMainPetStart + offset - beforeMainPet) : minimumLeft; + const landing = getChatPetFallTarget(overlay.left + left, -size, size, size, platforms, floor); + let top = landing.top - overlay.top; + for (const otherSubagentPet of this._subagentPets.values()) { + if (otherSubagentPet.isRespawning()) { + continue; + } + if (left < otherSubagentPet.left + size && left + size > otherSubagentPet.left) { + top = Math.min(top, otherSubagentPet.top - size); + } + } + if (top >= minimumTop - SUBAGENT_PET_BOUNDARY_EPSILON) { + return { left, top }; + } + if (!best || top > best.top) { + best = { left, top }; + } + } + // If the area is full, allow overlap instead of shrinking the subagent pets. + return { ...best!, top: Math.max(best!.top, minimumTop) }; + } + + /** Keeps existing pets for active subagents and fills available slots up to the limit. */ + private _updateSubagentPets(activeSubagentIds: ReadonlySet, arrivalReady = false): void { + this._activeSubagentIds = new Set(activeSubagentIds); + let removed = false; + let added = false; + for (const [id, subagentPet] of this._subagentPets) { + if (!activeSubagentIds.has(id)) { + removed = true; + this._subagentPets.delete(id); + this._despawningSubagentPetCount++; + subagentPet.despawn(() => { + this._subagentPetEffects.delete(subagentPet); + this._despawningSubagentPetCount--; + this._updateSubagentPets(this._activeSubagentIds); + }); + } + } + for (const id of activeSubagentIds) { + if (this._subagentPets.size + this._despawningSubagentPetCount >= SUBAGENT_PET_MAX_COUNT) { + break; + } + if (this._subagentPets.has(id)) { + continue; + } + if (this._subagentPetArrivalDelay > 0 && !arrivalReady) { + if (!this._subagentPetArrivalScheduler.isScheduled()) { + this._subagentPetArrivalScheduler.schedule(this._subagentPetArrivalDelay); + } + break; + } + added = true; + const { left, top } = this._getSubagentPetLanding(getSubagentPetSize(this._scale)); + const subagentPet = this._subagentPetEffects.add(new SubagentPet(this._getSubagentPetHost(), left, top)); + this._subagentPets.set(id, subagentPet); + arrivalReady = false; + } + if (added || removed) { + this._scheduleSubagentPetResize(); + } + if (removed && this._subagentPets.size) { + this._settleSubagentPets(); + } + } + + /** Creates the shared subagent pet host on first use. */ + private _getSubagentPetHost(): SubagentPetHost { + if (!this._subagentPetHost) { + const widget = this; + this._subagentPetHost = { + layer: this._subagentPetLayer, + overlay: this._overlay, + eyes: this._eyes, + onDidChangeAnimationVisibility: this._onDidChangeAnimationVisibility.event, + get enabled() { return widget._enabled; }, + get motionReduced() { return widget._motionReduced; }, + get variant() { return widget._variant; }, + get color() { return widget._color; }, + get accessory() { return widget._selectedAccessory; }, + get scale() { return widget._scale; }, + random: this._random, + isAnimationVisible: element => this._isAnimationVisible(this._visual) && this._isAnimationVisible(element), + observeAnimationVisibility: element => this._observeAnimationVisibility(element), + getDragBounds: () => this.dragBounds.getBoundingClientRect(), + getMovementBounds: () => this.movementBounds.getBoundingClientRect(), + getLanding: size => this._getSubagentPetLanding(size), + scheduleResize: () => this._scheduleSubagentPetResize(), + startAnimation: (source, sprite, animation, onComplete, reverse, onFrame, renderFrame) => this._startSpriteAnimation(source, sprite, animation, onComplete, reverse, onFrame, undefined, undefined, renderFrame), + }; + } + return this._subagentPetHost; + } + + /** Settle each column from the bottom up so remaining subagent pets can support those above them. */ + private _settleSubagentPets(platformChanged = false): void { + const overlay = this._overlay.getBoundingClientRect(); + const platforms = this._getPlatforms(); + const floor = platformChanged ? this.movementBounds.getBoundingClientRect().bottom : Math.min(this.dragBounds.getBoundingClientRect().top, this.movementBounds.getBoundingClientRect().bottom); + const size = getSubagentPetSize(this._scale); + const subagentPets = [...this._subagentPets.values()].filter(subagentPet => !subagentPet.isRespawning()).sort((a, b) => b.top - a.top); + for (const [index, subagentPet] of subagentPets.entries()) { + const landing = getChatPetFallTarget(overlay.left + subagentPet.left, overlay.top + subagentPet.top - POSITION_EPSILON, size, size, platforms, floor); + let top = Math.max(subagentPet.top, landing.top - overlay.top); + let supported = !!landing.platform; + for (let below = 0; below < index; below++) { + const support = subagentPets[below]; + if (!support.isRespawning() && subagentPet.left < support.left + size && subagentPet.left + size > support.left && support.top >= subagentPet.top + size - POSITION_EPSILON && support.top - size <= top) { + top = Math.min(top, support.top - size); + supported = true; + } + } + if (top > subagentPet.top + POSITION_EPSILON) { + subagentPet.fallTo(top, platformChanged && !supported); + } + } + } + + /** Schedules one bounds check for the current group of subagent pets. */ + private _scheduleSubagentPetResize(): void { + if (this._subagentPets.size && !this._subagentPetResizeScheduler.isScheduled()) { + this._subagentPetResizeScheduler.schedule(); + } + } + + /** Relocates pets outside the bounds, also checking overlaps and support after scaling. */ + private _reconcileSubagentPetResize(checkPlacement = false): void { + const subagentPets = [...this._subagentPets.values()].filter(subagentPet => !subagentPet.isRespawning()); + if (!subagentPets.length) { + return; + } + if (checkPlacement) { + subagentPets.sort((a, b) => b.top - a.top); + } + const { overlay, movement, platforms, floor, left, right, bottom } = this._getSubagentPetBounds(); + const size = getSubagentPetSize(this._scale); + let displaced = false; + for (const subagentPet of subagentPets) { + const subagentPetLeft = subagentPet.left; + const subagentPetTop = subagentPet.top; + const outsideBounds = subagentPetLeft < left - SUBAGENT_PET_BOUNDARY_EPSILON + || subagentPetLeft + size > right + SUBAGENT_PET_BOUNDARY_EPSILON + || subagentPetTop < movement.top - overlay.top - SUBAGENT_PET_BOUNDARY_EPSILON + || subagentPetTop + size > bottom + SUBAGENT_PET_BOUNDARY_EPSILON; + let invalidPlacement = false; + if (checkPlacement && !outsideBounds) { + const overlaps = subagentPets.some(other => other !== subagentPet && !other.isRespawning() + && subagentPetLeft < other.left + size - SUBAGENT_PET_BOUNDARY_EPSILON && subagentPetLeft + size > other.left + SUBAGENT_PET_BOUNDARY_EPSILON + && subagentPetTop < other.top + size - SUBAGENT_PET_BOUNDARY_EPSILON && subagentPetTop + size > other.top + SUBAGENT_PET_BOUNDARY_EPSILON); + const landing = getChatPetFallTarget(overlay.left + subagentPetLeft, overlay.top + subagentPetTop - POSITION_EPSILON, size, size, platforms, floor); + const supported = Math.abs(landing.top - overlay.top - subagentPetTop) <= SUBAGENT_PET_BOUNDARY_EPSILON + || subagentPets.some(other => other !== subagentPet && !other.isRespawning() + && subagentPetLeft < other.left + size && subagentPetLeft + size > other.left + && Math.abs(subagentPetTop + size - other.top) <= SUBAGENT_PET_BOUNDARY_EPSILON); + invalidPlacement = overlaps || !supported; + } + if (outsideBounds || invalidPlacement) { + displaced = true; + subagentPet.fallTo(movement.bottom - overlay.top - size, true); + } + } + if (displaced) { + this._settleSubagentPets(); + } + } + private _getDisplaySize(): number { return CHAT_PET_SOURCE_SIZE / 2 * this._scale; } private _setScale(scale: number): void { this._stopJumpGame('restore'); + const previousSize = getSubagentPetSize(this._scale); this._scale = scale; + const subagentPetScale = scale * SUBAGENT_PET_SCALE; + const size = getSubagentPetSize(scale); + const subagentPets = [...this._subagentPets.values()].map(subagentPet => ({ subagentPet, left: subagentPet.left, top: subagentPet.top })).sort((a, b) => b.top - a.top); + for (const [index, entry] of subagentPets.entries()) { + let supportTop: number | undefined; + if (!entry.subagentPet.isRespawning()) { + for (let below = 0; below < index; below++) { + const support = subagentPets[below]; + if (!support.subagentPet.isRespawning() && entry.left < support.left + previousSize && entry.left + previousSize > support.left && Math.abs(entry.top + previousSize - support.top) <= SUBAGENT_PET_BOUNDARY_EPSILON) { + supportTop = Math.min(supportTop ?? Infinity, support.subagentPet.top - size); + } + } + } + entry.subagentPet.setScale(subagentPetScale, supportTop ?? entry.top + previousSize - size); + } + this._reconcileSubagentPetResize(true); + this._scheduleSubagentPetResize(); const displaySize = this._getDisplaySize(); this._button.element.style.width = `${displaySize}px`; this._button.element.style.height = `${displaySize}px`; @@ -4016,7 +4622,7 @@ export class ChatPetWidget extends Disposable { } } - private _startSpriteAnimation(source: ChatPetSpriteSource, sprite: ChatPetSpriteElement, animationDisposable: MutableDisposable, onComplete?: () => void, reverse = false, onFrame?: (frameIndex: number) => void, state?: ChatPetState, initialFrame?: number): void { + private _startSpriteAnimation(source: ChatPetSpriteSource, sprite: ChatPetSpriteElement, animationDisposable: MutableDisposable, onComplete?: () => void, reverse = false, onFrame?: (frameIndex: number) => void, state?: ChatPetState, initialFrame?: number, renderFrame?: (context: CanvasRenderingContext2D, frameIndex: number) => boolean): void { sprite.color = this._color; const { frameDurations } = source; const { image, canvas } = sprite; @@ -4040,7 +4646,8 @@ export class ChatPetWidget extends Disposable { const drawFrame = (animationFrameIndex: number) => { renderedFrameIndex = animationFrameIndex; const frameIndex = source.frameIndices?.[animationFrameIndex] ?? animationFrameIndex; - if (state) { + const rendered = renderFrame?.(context, frameIndex); + if (!rendered && state) { const activeAccessory = sprite.activeAccessory ? getChatPetAccessory(sprite.activeAccessory) : undefined; drawChatPetComposite( context, @@ -4061,7 +4668,7 @@ export class ChatPetWidget extends Disposable { ); this._drawPropeller(sprite.activeAccessory, sprite.activeAccessoryImage, source, state, source.accessoryRigFrame ?? frameIndex); this._drawEyeAccessory(sprite.activeAccessory, sprite.activeAccessoryImage, source, state, source.accessoryRigFrame ?? frameIndex); - } else { + } else if (!rendered) { context.clearRect(0, 0, source.frameWidth, frameHeight); context.drawImage(getChatPetColoredSprite(image, sprite.color), frameIndex * source.frameWidth, 0, source.frameWidth, frameHeight, 0, 0, source.frameWidth, frameHeight); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/media/chatPet.css b/src/vs/workbench/contrib/chat/browser/widget/media/chatPet.css index 953b1d2a80e0c0..88c70c325a7452 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/media/chatPet.css +++ b/src/vs/workbench/contrib/chat/browser/widget/media/chatPet.css @@ -197,6 +197,35 @@ pointer-events: none; } +.chat-subagent-pet-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.chat-subagent-pet, +.chat-subagent-pet-despawning { + position: absolute; + width: 48px; + height: 48px; + transform-origin: top left; + pointer-events: none; +} + +.chat-subagent-pet-canvas { + width: 48px; + height: 48px; + image-rendering: pixelated; +} + +.chat-subagent-pet .chat-pet-eye { + height: 12px; +} + +.chat-subagent-pet .chat-pet-pupil { + height: 8px; +} + .chat-pet-sprite { position: absolute; bottom: 0; @@ -489,7 +518,8 @@ .chat-pet-button[data-state='typing'] .chat-pet-eyes.blink .chat-pet-pupil, .chat-pet-button[data-state='painting'] .chat-pet-eyes.blink .chat-pet-pupil, .chat-pet-button[data-state='buttonPress'] .chat-pet-eyes.blink .chat-pet-pupil, -.chat-pet-button[data-state='love'] .chat-pet-eyes.blink .chat-pet-pupil { +.chat-pet-button[data-state='love'] .chat-pet-eyes.blink .chat-pet-pupil, +.chat-subagent-pet .chat-pet-eyes.blink .chat-pet-pupil { animation-name: chat-pet-tall-eye-blink; } diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts index 9645fd320bb8ad..eea11a1c365c31 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts @@ -102,11 +102,11 @@ suite('ChatPetWidget', () => { this.targets.clear(); } - setVisible(visible: boolean): void { + setVisible(visible: boolean, element?: Element): void { if (this.targets.size === 0) { return; } - this.callback([...this.targets].map(target => new class extends mock() { + this.callback([...this.targets].filter(target => !element || target === element).map(target => new class extends mock() { override readonly target = target; override readonly isIntersecting = visible; override readonly boundingClientRect = target.getBoundingClientRect(); @@ -114,7 +114,13 @@ suite('ChatPetWidget', () => { } } - function createHostTransitionHarness(motionReduced = false, initialTransition: IChatPetWidgetHost['transition'] = 'teleport', color?: ChatPetColor, intersectionObserverCtor?: typeof IntersectionObserver, setPlatformOccupation?: IChatPetWidgetHost['setPlatformOccupation'], supportsJumpGame = false, initializeService?: (service: ChatPetService) => void) { + interface SubagentPetTestOptions { + readonly initialModel?: IChatModel; + readonly random?: () => number; + readonly subagentPetArrivalDelay?: number; + } + + function createHostTransitionHarness(motionReduced = false, initialTransition: IChatPetWidgetHost['transition'] = 'teleport', color?: ChatPetColor, intersectionObserverCtor?: typeof IntersectionObserver, setPlatformOccupation?: IChatPetWidgetHost['setPlatformOccupation'], supportsJumpGame = false, initializeService?: (service: ChatPetService) => void, options: SubagentPetTestOptions = {}) { const root = mainWindow.document.createElement('div'); root.style.cssText = 'position:fixed;left:0;top:0;width:800px;height:640px'; if (supportsJumpGame) { @@ -155,10 +161,12 @@ suite('ChatPetWidget', () => { onDidChangePlatform: platformChanged.event, setPlatformOccupation, }); - const firstHost = createHost(firstParent, initialTransition); + const firstHost = { ...createHost(firstParent, initialTransition), model: constObservable(options.initialModel) }; const secondHost: IChatPetWidgetHost = { ...createHost(secondParent, 'fall'), model: constObservable(new class extends mock() { + override readonly onDidChange = Event.None; + override getRequests(): IChatRequestModel[] { return []; } override readonly hasActiveRequest = constObservable(true); override readonly lastRequestObs = constObservable(undefined); }()), @@ -177,7 +185,7 @@ suite('ChatPetWidget', () => { } initializeService?.(service); const widget = disposables.add(new ChatPetWidget( - firstHost, { resizeObserverCtor: TestResizeObserver, intersectionObserverCtor }, service, accessibilityService, + firstHost, { resizeObserverCtor: TestResizeObserver, intersectionObserverCtor, random: options.random, subagentPetArrivalDelay: options.subagentPetArrivalDelay ?? 0 }, service, accessibilityService, new class extends mock() { override showContextMenu(delegate: IContextMenuDelegate): void { contextMenu = delegate; } }(), @@ -206,6 +214,10 @@ suite('ChatPetWidget', () => { }; } + function createSubagentPetTestHarness(options: SubagentPetTestOptions = {}, motionReduced = false) { + return createHostTransitionHarness(motionReduced, undefined, undefined, undefined, undefined, false, undefined, options); + } + /** * Resolves once `condition` holds. Pet transitions advance through sprite loads, CSS transitions, * animation frames and timers, and every step that a test waits for changes the DOM, so the @@ -2961,6 +2973,836 @@ suite('ChatPetWidget', () => { ]); }); + /** Creates an active subagent tool invocation for subagent pet tests. */ + function createSubagentTool(id: string, displayName = id): ChatToolInvocation { + const tool = new ChatToolInvocation(undefined, { id, displayName, modelDescription: 'Subagent', source: ToolDataSource.Internal }, id, undefined, {}); + tool.toolSpecificData = { kind: 'subagent', isActive: true }; + return tool; + } + + function createSubagentTestModel(parts: IChatProgressResponseContent[], onDidChange: Event = Event.None): IChatModel { + const response = new class extends mock() { + override readonly onDidChange = onDidChange; + override readonly isPendingConfirmation = constObservable(undefined); + override readonly response = new class extends mock() { override readonly value = parts; }(); + }(); + const request = new class extends mock() { override readonly id = 'request'; override readonly response = response; }(); + return new class extends mock() { + override readonly onDidChange = Event.None; + override readonly hasActiveRequest = constObservable(true); + override readonly lastRequestObs = constObservable(request); + override getRequests(): IChatRequestModel[] { return [request]; } + }(); + } + + function setSubagentPetPosition(widget: ChatPetWidget, element: HTMLElement, left: number, top: number): void { + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Set up positions without exposing a test-only API. + const subagentPet = [...widget['_subagentPets'].values()].find(subagentPet => subagentPet.element === element)!; + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Set up the private position for layout tests. + subagentPet['_left'] = left; + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Set up the private position for layout tests. + subagentPet['_top'] = top; + element.style.left = `${left}px`; + element.style.top = `${top}px`; + } + + test('subagent pets update only the changed response while tracking older subagents', () => { + const { widget, firstHost, overlay } = createHostTransitionHarness(true); + const changes = [disposables.add(new Emitter()), disposables.add(new Emitter())]; + const tools = ['older', 'current'].map(id => createSubagentTool(id)); + const reads = [0, 0]; + const requests = tools.map((tool, index) => { + const response = new class extends mock() { + override readonly onDidChange = changes[index].event; + override readonly isPendingConfirmation = constObservable(undefined); + override readonly response = new class extends mock() { + override get value(): IChatProgressResponseContent[] { reads[index]++; return [tool]; } + }(); + }(); + return new class extends mock() { override readonly id = `request-${index}`; override readonly response = response; }(); + }); + const model = new class extends mock() { + override readonly onDidChange = Event.None; + override readonly hasActiveRequest = constObservable(true); + override readonly lastRequestObs = constObservable(requests[1]); + override getRequests(): IChatRequestModel[] { return requests; } + }(); + widget.setHost({ ...firstHost, model: constObservable(model) }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 2); + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Verify streamed updates do not reconcile unchanged pets. + const updateSubagentPets = sinon.spy(widget['_updateSubagentPets']); + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Observe reconciliation without exposing a test-only API. + widget['_updateSubagentPets'] = updateSubagentPets; + reads[0] = 0; + changes[1].fire({ reason: 'other' }); + assert.strictEqual(reads[0], 0); + assert.ok(updateSubagentPets.notCalled); + tools[0].toolSpecificData = { kind: 'subagent', isActive: false }; + changes[0].fire({ reason: 'other' }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 1); + }); + + test('subagent pets react to tool metadata notifications without a response event', () => { + const { widget, firstHost, overlay } = createHostTransitionHarness(true); + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool])) }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 1); + tool.toolSpecificData = { kind: 'subagent', isActive: false }; + tool.notifyToolSpecificDataChanged(); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 0); + }); + + test('subagent pets arrive in sequence and skip subagents that have finished', () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + disposables.add(toDisposable(() => clock.restore())); + const { widget, firstHost, overlay } = createSubagentPetTestHarness({ subagentPetArrivalDelay: 120 }, true); + const changed = disposables.add(new Emitter()); + const tools = Array.from({ length: 12 }, (_, index) => createSubagentTool(`subagent-${index}`)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 0); + tools[1].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + clock.tick(119); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 0); + clock.tick(1); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 1); + clock.tick(120); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 2); + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Check the waiting subagent was skipped. + assert.ok(!widget['_subagentPets'].has(JSON.stringify(['request', 'subagent-1']))); + clock.tick(120 * 12); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet, .chat-subagent-pet-despawning').length, 10); + }); + + test('subagent pet arrivals stop when disabled or the model changes', () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + disposables.add(toDisposable(() => clock.restore())); + const { widget, firstHost, overlay, service } = createSubagentPetTestHarness({ subagentPetArrivalDelay: 120 }, true); + const tools = ['first', 'second'].map(id => createSubagentTool(id)); + const model = observableValue('model', createSubagentTestModel(tools)); + widget.setHost({ ...firstHost, model }); + clock.tick(120); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 1); + model.set(undefined, undefined); + clock.tick(120); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 0); + model.set(createSubagentTestModel(tools), undefined); + service.toggle(); + clock.tick(240); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet, .chat-subagent-pet-despawning').length, 0); + }); + + test('subagent pets fill available slots without replacing active pets', async () => { + const { widget, firstHost, overlay } = createHostTransitionHarness(true); + const changed = disposables.add(new Emitter()); + const tools = Array.from({ length: 12 }, (_, index) => createSubagentTool(`subagent-${index}`)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + const initial = [...overlay.querySelectorAll('.chat-subagent-pet')]; + assert.strictEqual(initial.length, 10); + tools[10].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + assert.deepStrictEqual([...overlay.querySelectorAll('.chat-subagent-pet')], initial); + tools[0].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet, .chat-subagent-pet-despawning').length, 10); + await waitForPetAnimation(() => overlay.querySelectorAll('.chat-subagent-pet').length === 10); + const after = [...overlay.querySelectorAll('.chat-subagent-pet')]; + assert.deepStrictEqual(after.slice(0, 9), initial.slice(1)); + assert.ok(!initial.includes(after[9])); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet-despawning').length, 0); + }); + + test('subagent pets preserve waiting order when an earlier response changes', async () => { + const { widget, firstHost, overlay } = createHostTransitionHarness(true); + const changed = disposables.add(new Emitter()); + const olderTools = Array.from({ length: 11 }, (_, index) => createSubagentTool(`older-${index}`)); + const newerTools = [createSubagentTool('newer')]; + const requests = [olderTools, newerTools].map((parts, index) => { + const response = new class extends mock() { + override readonly onDidChange = index === 0 ? changed.event : Event.None; + override readonly isPendingConfirmation = constObservable(undefined); + override readonly response = new class extends mock() { override readonly value = parts; }(); + }(); + return new class extends mock() { override readonly id = `request-${index}`; override readonly response = response; }(); + }); + const model = new class extends mock() { + override readonly onDidChange = Event.None; + override readonly hasActiveRequest = constObservable(true); + override readonly lastRequestObs = constObservable(requests[1]); + override getRequests(): IChatRequestModel[] { return requests; } + }(); + widget.setHost({ ...firstHost, model: constObservable(model) }); + olderTools.push(createSubagentTool('later')); + changed.fire({ reason: 'other' }); + olderTools[0].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + await waitForPetAnimation(() => overlay.querySelectorAll('.chat-subagent-pet').length === 10); + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Verify which waiting subagent received the slot. + const pets = widget['_subagentPets']; + assert.deepStrictEqual({ older: pets.has(JSON.stringify(['request-0', 'older-10'])), newer: pets.has(JSON.stringify(['request-1', 'newer'])) }, { older: true, newer: false }); + }); + + test('shows one subagent pet per active subagent and removes it when it stops', async () => { + const { widget, firstHost, button, overlay, service } = createHostTransitionHarness(); + const responseChanged = disposables.add(new Emitter()); + const parts: IChatProgressResponseContent[] = []; + const modelValue = observableValue('model', createSubagentTestModel(parts, responseChanged.event)); + widget.setHost({ ...firstHost, model: modelValue }); + service.unlockAchievement(getChatPetAchievementForAccessory(ChatPetAccessoryIds.CowboyHat).id); + service.setAccessory(ChatPetAccessoryIds.CowboyHat); + const createSubagent = (id: string) => { + const tool = createSubagentTool(id); + parts.push(tool); + responseChanged.fire({ reason: 'other' }); + return tool; + }; + button.style.left = '0px'; + button.style.top = '-100px'; + const mainPupils = button.querySelectorAll('.chat-pet-pupil'); + for (const pupil of mainPupils) { + pupil.style.transform = 'translate(2px, -2px)'; + } + const first = createSubagent('first'); + const firstSubagentPet = overlay.querySelector('.chat-subagent-pet')!; + assert.deepStrictEqual([...firstSubagentPet.querySelectorAll('.chat-pet-pupil')].map(pupil => pupil.style.transform), ['', '']); + assert.deepStrictEqual([...mainPupils].map(pupil => pupil.style.transform), ['translate(2px, -2px)', 'translate(2px, -2px)']); + assert.ok(firstSubagentPet.offsetLeft >= button.offsetLeft + button.offsetWidth); + const subagentPetSize = 48 * 0.5; + assert.strictEqual(Number.parseFloat(firstSubagentPet.style.top) + subagentPetSize, 0); + const [bodyImage, accessoryImage] = firstSubagentPet.querySelectorAll('img'); + assert.ok(accessoryImage?.src.includes('/accessories/')); + await Promise.all([bodyImage.decode(), accessoryImage.decode()]); + const subagentPetCanvas = firstSubagentPet.querySelector('canvas')!; + const draws = sinon.spy(subagentPetCanvas.getContext('2d')!, 'drawImage'); + bodyImage.dispatchEvent(new mainWindow.Event('load')); + assert.ok(draws.calledWith(accessoryImage)); + assert.strictEqual(draws.getCalls().filter(call => call.args[0] !== accessoryImage).length, 1); + draws.restore(); + button.dataset.state = 'idle'; + const subagentPetPupil = firstSubagentPet.querySelector('.chat-pet-pupil')!; + const mainPupil = button.querySelector('.chat-pet-pupil')!; + assert.strictEqual(mainWindow.getComputedStyle(subagentPetPupil).height, mainWindow.getComputedStyle(mainPupil).height); + assert.strictEqual(mainWindow.getComputedStyle(subagentPetPupil).height, '8px'); + widget.setHost({ ...firstHost, transition: undefined, model: modelValue, getPlatforms: () => { + const bounds = overlay.getBoundingClientRect(); + return [ + { left: bounds.left, right: bounds.right, top: bounds.top - 60 }, + { left: bounds.left, right: bounds.right, top: bounds.top, isDefault: true }, + ]; + } }); + button.style.left = '300px'; + button.style.top = '-140px'; + createSubagent('second'); + const subagentPets = overlay.querySelectorAll('.chat-subagent-pet'); + assert.ok(subagentPets[1].offsetLeft + subagentPetSize <= button.offsetLeft || subagentPets[1].offsetLeft >= button.offsetLeft + button.offsetWidth); + assert.strictEqual(Number.parseFloat(subagentPets[1].style.top) + subagentPetSize, -60); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 2); + assert.strictEqual([...overlay.querySelectorAll('.chat-subagent-pet')].filter(subagentPet => subagentPet.getAnimations().length > 0).length, 2); + assert.strictEqual(button.querySelectorAll('.chat-subagent-pet').length, 0); + assert.ok(overlay.querySelector('.chat-subagent-pet img')?.getAttribute('src')?.includes('buddy-')); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + const position = subagentPet.style.left; + button.style.left = '300px'; + button.style.transform = 'rotate(45deg)'; + assert.strictEqual(subagentPet.style.left, position); + first.toolSpecificData = { kind: 'subagent', isActive: false }; + responseChanged.fire({ reason: 'other' }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 1); + assert.ok(firstSubagentPet.classList.contains('chat-subagent-pet-despawning')); + assert.strictEqual(overlay.querySelector('.chat-subagent-pet'), subagentPets[1]); + const third = createSubagent('third'); + const thirdSubagentPet = overlay.querySelectorAll('.chat-subagent-pet')[1]; + parts.splice(parts.indexOf(third), 1); + const replacement = createSubagentTool('replacement', 'Replacement'); + parts.push(replacement); + responseChanged.fire({ reason: 'other' }); + assert.ok(thirdSubagentPet.classList.contains('chat-subagent-pet-despawning')); + assert.strictEqual(overlay.querySelector('.chat-subagent-pet'), subagentPets[1]); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 2); + assert.ok(overlay.querySelector('.chat-subagent-pet-despawning img')?.getAttribute('src')?.includes('buddy-respawn-')); + modelValue.set(undefined, undefined); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 0); + await waitForPetAnimation(() => !overlay.querySelector('.chat-subagent-pet-despawning')); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet-despawning').length, 0); + }); + + test('subagent pets use restored geometry when the initial model already has a subagent', () => { + const tool = createSubagentTool('subagent', 'Subagent'); + const model = createSubagentTestModel([tool]); + const { button, overlay } = createHostTransitionHarness(true, 'teleport', undefined, undefined, undefined, false, service => { + service.setScale(2); + service.setHorizontalPosition(0.8); + }, { initialModel: model }); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + assert.strictEqual(Number.parseFloat(subagentPet.style.transform.slice(6)), 1); + assert.ok(subagentPet.offsetLeft + 48 <= button.offsetLeft || subagentPet.offsetLeft >= button.offsetLeft + button.offsetWidth); + }); + + test('subagent pets stop when disabled and return for active subagents when re-enabled', async () => { + const { widget, firstHost, overlay, service } = createHostTransitionHarness(); + const changed = disposables.add(new Emitter()); + const parts: IChatProgressResponseContent[] = []; + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(parts, changed.event)) }); + const tool = createSubagentTool('first', 'First'); + parts.push(tool); + changed.fire({ reason: 'other' }); + const first = overlay.querySelector('.chat-subagent-pet')!; + await whenSpriteLoaded(first.querySelector('img')!); + service.toggle(); + assert.strictEqual(first.isConnected, false); + const second = createSubagentTool('second', 'Second'); + parts.push(second); + changed.fire({ reason: 'other' }); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 0); + service.toggle(); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet').length, 2); + }); + + test('subagent pets avoid existing positions when the main pet moves between subagents', () => { + const { widget, firstHost, button, overlay } = createHostTransitionHarness(true); + const changed = disposables.add(new Emitter()); + const parts: IChatProgressResponseContent[] = []; + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(parts, changed.event)) }); + const add = (id: string) => { + const tool = createSubagentTool(id); + parts.push(tool); + changed.fire({ reason: 'other' }); + }; + button.style.left = '300px'; + add('first'); + button.style.left = '324px'; + add('second'); + const [first, second] = overlay.querySelectorAll('.chat-subagent-pet'); + assert.ok(second.offsetLeft + 24 <= first.offsetLeft || first.offsetLeft + 24 <= second.offsetLeft + || Number.parseFloat(second.style.top) + 24 <= Number.parseFloat(first.style.top) || Number.parseFloat(first.style.top) + 24 <= Number.parseFloat(second.style.top)); + }); + + test('subagent pets spawn across the platform and stack where their paths overlap', async () => { + let randomValue = 0; + const { widget, firstHost, button, overlay, firstParent, layout } = createSubagentPetTestHarness({ random: () => randomValue }, true); + const changed = disposables.add(new Emitter()); + const parts: IChatProgressResponseContent[] = []; + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(parts, changed.event)) }); + button.style.left = '300px'; + const add = (id: string, position: number) => { + randomValue = position; + const tool = createSubagentTool(id); + parts.push(tool); + changed.fire({ reason: 'other' }); + }; + add('left', 0.1); + add('right', 0.9); + add('above', 0.1); + const [left, right, above] = [...overlay.querySelectorAll('.chat-subagent-pet')]; + assert.ok(right.offsetLeft - left.offsetLeft > 200); + assert.strictEqual(above.style.left, left.style.left); + assert.strictEqual(Number.parseFloat(above.style.top) + 24, Number.parseFloat(left.style.top)); + firstParent.style.width = '120px'; + layout(); + const bounds = firstParent.getBoundingClientRect(); + await waitForPetAnimation(() => [left, right, above].every(subagentPet => { + const rect = subagentPet.getBoundingClientRect(); + return rect.left >= bounds.left - 0.1 && rect.right <= bounds.right + 0.1 && rect.bottom <= bounds.top + 0.1 && subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-'); + })); + const rects = [left, right, above].map(subagentPet => subagentPet.getBoundingClientRect()); + assert.ok(rects.every(rect => rect.left >= bounds.left - 0.1 && rect.right <= bounds.right + 0.1 && rect.bottom <= bounds.top + 0.1)); + assert.ok(rects.every((rect, index) => rects.slice(index + 1).every(other => + rect.right <= other.left + 0.1 || other.right <= rect.left + 0.1 || rect.bottom <= other.top + 0.1 || other.bottom <= rect.top + 0.1))); + }); + + test('subagent pets remain stacked when their size changes', () => { + const { widget, firstHost, overlay, service } = createHostTransitionHarness(true); + const tools = ['bottom', 'middle', 'top'].map(id => createSubagentTool(id)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools)) }); + const pets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + pets.forEach((pet, index) => setSubagentPetPosition(widget, pet, 48, -(index + 1) * 24)); + for (const scale of [2, 1]) { + service.setScale(scale); + const rects = pets.map(pet => pet.getBoundingClientRect()); + assert.ok(Math.abs(rects[1].bottom - rects[0].top) < 0.1); + assert.ok(Math.abs(rects[2].bottom - rects[1].top) < 0.1); + } + }); + + for (const reducedMotion of [false, true]) { + for (const enlarge of [true, false]) { + test(`subagent pets relocate only invalid placements when ${enlarge ? 'enlarged' : 'shrunk'} (${reducedMotion ? 'reduced motion' : 'animated'})`, async () => { + const { widget, firstHost, overlay, service } = createHostTransitionHarness(reducedMotion); + service.setScale(enlarge ? 1 : 2); + const tools = ['first', 'second', 'unaffected'].map(id => createSubagentTool(id)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools)) }); + const pets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + const positions = enlarge ? [[120, -24], [150, -24], [280, -24]] : [[48, -48], [80, -96], [280, -48]]; + pets.forEach((pet, index) => { + pet.getAnimations().forEach(animation => animation.cancel()); + setSubagentPetPosition(widget, pet, positions[index][0], positions[index][1]); + }); + service.setScale(enlarge ? 2 : 1); + assert.deepStrictEqual(pets.map(pet => Number.parseFloat(pet.style.top) > 0), enlarge ? [true, false, false] : [false, true, false]); + await waitForPetAnimation(() => pets.every(pet => pet.getAnimations().length === 0 && pet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-') === true)); + const rects = pets.map(pet => pet.getBoundingClientRect()); + assert.ok(rects.every((rect, index) => rects.slice(index + 1).every(other => + rect.right <= other.left + 0.1 || other.right <= rect.left + 0.1 || rect.bottom <= other.top + 0.1 || other.bottom <= rect.top + 0.1))); + }); + } + + test(`subagent pets keep their size and only displaced pets respawn (${reducedMotion ? 'reduced motion' : 'animated'})`, async () => { + const { widget, firstHost, overlay, firstParent, layout } = createHostTransitionHarness(reducedMotion); + const tools = ['stays', 'upper', 'support', 'outside'].map(id => createSubagentTool(id)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools)) }); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + const scales = subagentPets.map(subagentPet => subagentPet.style.transform); + for (const [index, subagentPet] of subagentPets.entries()) { + subagentPet.getAnimations().forEach(animation => animation.cancel()); + setSubagentPetPosition(widget, subagentPet, [20, 80, 90, 220][index], index === 1 ? -48 : -24); + } + firstParent.style.width = '120px'; + layout(); + layout(); + layout(); + assert.deepStrictEqual(subagentPets.map(subagentPet => subagentPet.style.left), ['20px', '80px', '90px', '220px']); + await waitForPetAnimation(() => subagentPets[2].querySelector('img')?.getAttribute('src')?.includes('buddy-respawn-') === true + && subagentPets[3].querySelector('img')?.getAttribute('src')?.includes('buddy-respawn-') === true); + assert.deepStrictEqual({ + stays: [subagentPets[0].style.left, subagentPets[0].style.top], + upper: [subagentPets[1].style.left, subagentPets[1].style.top], + }, { stays: ['20px', '-24px'], upper: ['80px', '-24px'] }); + await waitForPetAnimation(() => subagentPets.every(subagentPet => subagentPet.getAnimations().length === 0 && subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-') === true)); + assert.deepStrictEqual(subagentPets.map(subagentPet => subagentPet.style.transform), scales); + const input = firstParent.getBoundingClientRect(); + const rects = subagentPets.map(subagentPet => subagentPet.getBoundingClientRect()); + assert.ok(rects.every(rect => rect.left >= input.left - 0.1 && rect.right <= input.right + 0.1 && rect.bottom <= input.top + 0.1)); + assert.ok(rects.every((rect, index) => rects.slice(index + 1).every(other => + rect.right <= other.left + 0.1 || other.right <= rect.left + 0.1 || rect.bottom <= other.top + 0.1 || other.bottom <= rect.top + 0.1))); + }); + } + + test('subagent pets start falling near the edge while resizing continues', () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + disposables.add(toDisposable(() => clock.restore())); + const { widget, firstHost, firstParent, overlay, layout } = createHostTransitionHarness(true); + const tool = createSubagentTool('edge', 'Edge'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool])) }); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + setSubagentPetPosition(widget, subagentPet, 98, -24); + firstParent.style.width = '120px'; + layout(); + clock.tick(8); + layout(); + assert.ok(subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-')); + clock.tick(8); + assert.ok(subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-respawn-')); + }); + + test('subagent pets spawn inside the visible window when their platform extends beyond it', () => { + const { widget, firstHost, root, firstParent, button, overlay } = createSubagentPetTestHarness({ random: () => 0.99 }, true); + root.style.width = `${mainWindow.innerWidth + 240}px`; + firstParent.style.left = `${mainWindow.innerWidth - 80}px`; + firstParent.style.width = '240px'; + const changed = disposables.add(new Emitter()); + const tools: ChatToolInvocation[] = []; + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + button.style.left = '0px'; + const tool = createSubagentTool('edge', 'Edge'); + tools.push(tool); + changed.fire({ reason: 'other' }); + const rect = overlay.querySelector('.chat-subagent-pet')!.getBoundingClientRect(); + assert.ok(rect.right <= mainWindow.innerWidth - 12 + 0.1); + }); + + for (const petLeft of [0, 192]) { + for (const staggered of [false, true]) { + test(`subagent pets land above the input without a resize (main pet at ${petLeft}, ${staggered ? 'staggered' : 'together'})`, () => { + const { widget, firstHost, button, overlay, firstParent } = createHostTransitionHarness(true); + firstParent.style.width = '240px'; + button.style.left = `${petLeft}px`; + const changed = disposables.add(new Emitter()); + const tools: ChatToolInvocation[] = []; + widget.setHost({ ...firstHost, transition: undefined, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + const checkLanding = (count: number) => { + const input = firstParent.getBoundingClientRect(); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')].map(subagentPet => subagentPet.getBoundingClientRect()); + assert.deepStrictEqual({ + count: subagentPets.length, + aboveInput: subagentPets.every(subagentPet => subagentPet.bottom <= input.top + 0.1), + withinWidth: subagentPets.every(subagentPet => subagentPet.left >= input.left - 0.1 && subagentPet.right <= input.right + 0.1), + }, { count, aboveInput: true, withinWidth: true }); + }; + for (let index = 0; index < 10; index++) { + const id = `subagent-${index}`; + const tool = createSubagentTool(id); + tools.push(tool); + if (staggered) { + changed.fire({ reason: 'other' }); + checkLanding(index + 1); + } + } + changed.fire({ reason: 'other' }); + checkLanding(10); + tools[0].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + checkLanding(9); + }); + } + } + + test('subagent pets keep their initial size when crowded and resized', () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + disposables.add(toDisposable(() => clock.restore())); + const { widget, firstHost, overlay, firstParent, root, layout } = createHostTransitionHarness(true); + const tools = Array.from({ length: 100 }, (_, index) => createSubagentTool(`subagent-${index}`)); + widget.setHost({ ...firstHost, transition: undefined, model: constObservable(createSubagentTestModel(tools)) }); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + const initialSize = subagentPets[0].getBoundingClientRect().width; + assert.ok(Math.abs(initialSize - 24) < 0.1); + assert.ok(subagentPets.every(subagentPet => Math.abs(subagentPet.getBoundingClientRect().width - initialSize) < 0.1)); + for (const width of [120, 80, 120]) { + firstParent.style.width = `${width}px`; + root.style.height = '64px'; + firstParent.style.top = '32px'; + layout(); + clock.tick(16); + assert.ok(subagentPets.every(subagentPet => Math.abs(subagentPet.getBoundingClientRect().width - initialSize) < 0.1)); + } + }); + + for (const petLeft of [0, 300]) { + test(`subagent pets stay in a bounded area with many subagents (main pet at ${petLeft})`, async () => { + const { widget, firstHost, button, overlay, firstParent, root, layout } = createHostTransitionHarness(true); + const changed = disposables.add(new Emitter()); + const tools = Array.from({ length: 100 }, (_, index) => createSubagentTool(`subagent-${index}`)); + button.style.left = `${petLeft}px`; + widget.setHost({ ...firstHost, transition: undefined, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + const checkBounds = (count: number) => { + const rects = [...overlay.querySelectorAll('.chat-subagent-pet')].map(subagentPet => subagentPet.getBoundingClientRect()); + const input = firstParent.getBoundingClientRect(); + const movement = root.getBoundingClientRect(); + const left = Math.min(...rects.map(rect => rect.left)); + const right = Math.max(...rects.map(rect => rect.right)); + const top = Math.min(...rects.map(rect => rect.top)); + const bottom = Math.max(...rects.map(rect => rect.bottom)); + // This many pets cannot fit in the narrowest area without overlapping. + assert.deepStrictEqual({ + count: rects.length, + withinChat: left >= input.left - 0.1 && right <= input.right + 0.1 && top >= movement.top - 0.1 && bottom <= Math.min(input.top, movement.bottom) + 0.1, + bounded: right - left <= input.width + 0.1 && bottom - top <= 500.1, + largeEnough: rects.every(rect => rect.width >= 9.5 && rect.height >= 9.5), + }, { count, withinChat: true, bounded: true, largeEnough: true }, JSON.stringify({ left, right, top, bottom, input: input.toJSON(), movement: movement.toJSON() })); + }; + checkBounds(10); + firstParent.style.width = '120px'; + layout(); + await waitForPetAnimation(() => subagentPets.every(subagentPet => { + const rect = subagentPet.getBoundingClientRect(); + const input = firstParent.getBoundingClientRect(); + return rect.left >= input.left - 0.1 && rect.right <= input.right + 0.1 && rect.bottom <= input.top + 0.1 && subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-'); + })); + checkBounds(10); + root.style.height = '64px'; + firstParent.style.top = '32px'; + layout(); + await waitForPetAnimation(() => subagentPets.every(subagentPet => { + const rect = subagentPet.getBoundingClientRect(); + const input = firstParent.getBoundingClientRect(); + return rect.left >= input.left - 0.1 && rect.right <= input.right + 0.1 && rect.top >= root.getBoundingClientRect().top - 0.1 && rect.bottom <= input.top + 0.1 && subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-'); + })); + checkBounds(10); + tools[0].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + checkBounds(9); + assert.deepStrictEqual([...overlay.querySelectorAll('.chat-subagent-pet')], subagentPets.slice(1)); + await waitForPetAnimation(() => overlay.querySelectorAll('.chat-subagent-pet').length === 10); + tools[0].toolSpecificData = { kind: 'subagent', isActive: true }; + changed.fire({ reason: 'other' }); + checkBounds(10); + }); + } + + for (const reducedMotion of [false, true]) { + for (const removedIndex of [0, 1]) { + test(`subagent pets fall when their ${removedIndex === 0 ? 'bottom' : 'middle'} support finishes (${reducedMotion ? 'reduced motion' : 'animated'})`, () => { + const { widget, firstHost, overlay, setReducedMotion } = createHostTransitionHarness(reducedMotion); + const changed = disposables.add(new Emitter()); + const tools = ['bottom', 'middle', 'top', 'neighbor'].map(id => createSubagentTool(id)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + // A three-high stack on the input platform and an independent neighbor on the ground. + subagentPets.forEach((subagentPet, index) => { + subagentPet.getAnimations().forEach(animation => animation.cancel()); + setSubagentPetPosition(widget, subagentPet, index === 3 ? 96 : 48, index === 3 ? -24 : -(index + 1) * 24); + }); + const neighborPosition = subagentPets[3].getBoundingClientRect().toJSON(); + tools[removedIndex].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + assert.deepStrictEqual({ + remaining: [...overlay.querySelectorAll('.chat-subagent-pet')], + tops: subagentPets.filter((_, index) => index !== removedIndex).map(subagentPet => subagentPet.style.top), + falling: subagentPets[2].getAnimations().length > 0, + neighbor: subagentPets[3].getBoundingClientRect().toJSON(), + }, { remaining: subagentPets.filter((_, index) => index !== removedIndex), tops: ['-24px', '-48px', '-24px'], falling: !reducedMotion, neighbor: neighborPosition }); + // Removing the next support mid-fall must continue from the currently rendered position. + for (const animation of subagentPets[2].getAnimations()) { + animation.pause(); + } + const previousTop = subagentPets[2].getBoundingClientRect().top - overlay.getBoundingClientRect().top; + tools[1 - removedIndex].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + assert.strictEqual(subagentPets[2].style.top, '-24px'); + if (!reducedMotion) { + assert.ok(Math.abs(Number.parseFloat((subagentPets[2].getAnimations()[0].effect as KeyframeEffect).getKeyframes()[0].top as string) - previousTop) < 0.1); + setReducedMotion(true); + } + assert.deepStrictEqual({ + falling: subagentPets[2].getAnimations().length > 0, + bottom: subagentPets[2].getBoundingClientRect().bottom, + }, { falling: false, bottom: overlay.getBoundingClientRect().top }); + }); + } + } + + test('subagent pets keep a large initial group on the approval prompt', () => { + const { widget, firstHost, overlay, firstParent, button } = createHostTransitionHarness(true); + firstParent.style.width = '240px'; + button.style.left = '192px'; + const tools = Array.from({ length: 20 }, (_, index) => createSubagentTool(`subagent-${index}`)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools)), getPlatforms: () => { + const bounds = firstParent.getBoundingClientRect(); + return [{ left: bounds.left + 20, right: bounds.right - 20, top: bounds.top - 60, isDefault: true }]; + } }); + const bounds = firstParent.getBoundingClientRect(); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + assert.deepStrictEqual({ + count: subagentPets.length, + onPrompt: subagentPets.every(subagentPet => { + const rect = subagentPet.getBoundingClientRect(); + return rect.bottom <= bounds.top - 60 + 0.1 && rect.left >= bounds.left + 20 - 0.1 && rect.right <= bounds.right - 20 + 0.1; + }), + }, { count: 10, onPrompt: true }); + }); + + for (const reducedMotion of [false, true]) { + test(`subagent pets fall and respawn when a prompt replaces their support (${reducedMotion ? 'reduced motion' : 'animated'})`, async () => { + const { widget, firstHost, overlay, firstParent, root, platformChanged } = createHostTransitionHarness(reducedMotion); + let promptVisible = false; + const tools = ['first', 'second'].map(id => createSubagentTool(id)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools)), getPlatforms: () => { + const bounds = firstParent.getBoundingClientRect(); + return [{ left: bounds.left, right: bounds.right, top: bounds.top - (promptVisible ? 60 : 0), isDefault: true }]; + } }); + const subagentPets = [...overlay.querySelectorAll('.chat-subagent-pet')]; + await waitForPetAnimation(() => subagentPets.every(subagentPet => subagentPet.getAnimations().length === 0 && subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-') === true)); + promptVisible = true; + platformChanged.fire(); + assert.ok(subagentPets.every(subagentPet => Math.abs(Number.parseFloat(subagentPet.style.top) + 24 + overlay.getBoundingClientRect().top - root.getBoundingClientRect().bottom) < 0.1)); + await waitForPetAnimation(() => subagentPets.every(subagentPet => subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-respawn-') === true)); + await waitForPetAnimation(() => subagentPets.every(subagentPet => subagentPet.getAnimations().length === 0 && subagentPet.querySelector('img')?.getAttribute('src')?.includes('buddy-idle-') === true)); + assert.deepStrictEqual({ + identity: [...overlay.querySelectorAll('.chat-subagent-pet')], + onPrompt: subagentPets.every(subagentPet => subagentPet.getBoundingClientRect().bottom <= firstParent.getBoundingClientRect().top - 60 + 0.1), + }, { identity: subagentPets, onPrompt: true }); + promptVisible = false; + platformChanged.fire(); + await waitForPetAnimation(() => subagentPets.every(subagentPet => subagentPet.getAnimations().length === 0)); + assert.ok(subagentPets.every(subagentPet => subagentPet.getBoundingClientRect().bottom <= firstParent.getBoundingClientRect().top + 0.1)); + }); + } + + test('subagent pets cancel a pending prompt respawn when their subagent finishes', async () => { + const { widget, firstHost, overlay, firstParent, platformChanged } = createHostTransitionHarness(true); + const changed = disposables.add(new Emitter()); + let promptVisible = false; + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool], changed.event)), getPlatforms: () => { + const bounds = firstParent.getBoundingClientRect(); + return [{ left: bounds.left, right: bounds.right, top: bounds.top - (promptVisible ? 60 : 0), isDefault: true }]; + } }); + promptVisible = true; + platformChanged.fire(); + const image = overlay.querySelector('.chat-subagent-pet img')!; + await whenSpriteLoaded(image); + assert.ok(image.getAttribute('src')?.includes('buddy-respawn-')); + tool.toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + await waitForPetAnimation(() => !overlay.querySelector('.chat-subagent-pet, .chat-subagent-pet-despawning')); + assert.strictEqual(overlay.querySelectorAll('.chat-subagent-pet, .chat-subagent-pet-despawning').length, 0); + }); + + test('subagent pets update appearance and motion settings while active', async () => { + const { widget, firstHost, button, overlay, service, setReducedMotion } = createHostTransitionHarness(); + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool])) }); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + subagentPet.getAnimations().forEach(animation => animation.cancel()); + for (const scale of [1.6, 0.4, 1]) { + service.setScale(scale); + assert.strictEqual(Number.parseFloat(subagentPet.style.transform.slice(6)), scale * 0.5); + assert.ok(Math.abs(subagentPet.getBoundingClientRect().width - button.getBoundingClientRect().width / 2) < 0.1); + } + const body = subagentPet.querySelector('img')!; + await whenSpriteLoaded(body); + setReducedMotion(true); + await whenSpriteLoaded(body); + assert.ok(body.getAttribute('src')?.endsWith('-96.png')); + setReducedMotion(false); + await whenSpriteLoaded(body); + assert.ok(body.getAttribute('src')?.endsWith('.spritesheet.png')); + service.unlockAchievement(ChatPetAchievementIds.Blobby); + service.setColor('stable'); + await whenSpriteLoaded(body); + assert.ok(body.getAttribute('src')?.includes('buddy-idle-stable')); + service.setColor('#12abcd'); + assert.strictEqual(subagentPet.querySelector('.chat-pet-eyes')!.style.color, button.querySelector('.chat-pet-eyes')!.style.color); + service.unlockAchievement(getChatPetAchievementForAccessory(ChatPetAccessoryIds.CowboyHat).id); + service.setAccessory(ChatPetAccessoryIds.CowboyHat); + const hat = subagentPet.querySelectorAll('img')[1]; + assert.ok(hat?.src.includes('/accessories/')); + service.setAccessory(undefined); + assert.strictEqual(subagentPet.querySelectorAll('img').length, 1); + }); + + test('subagent pets stop squishing when reduced motion is enabled during landing', async () => { + const { widget, firstHost, overlay, setReducedMotion } = createHostTransitionHarness(); + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool])) }); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + const image = subagentPet.querySelector('img')!; + await whenSpriteLoaded(image); + subagentPet.getAnimations()[0]?.dispatchEvent(new mainWindow.Event('finish')); + await whenSpriteLoaded(image); + assert.ok(image.getAttribute('src')?.includes('buddy-splat-')); + setReducedMotion(true); + await whenSpriteLoaded(image); + assert.ok(image.getAttribute('src')?.includes('buddy-idle-')); + assert.ok(image.getAttribute('src')?.endsWith('-96.png')); + assert.ok(subagentPet.querySelector('.chat-pet-eyes.tracking')); + }); + + test('subagent pets squish on landing and return to their own idle animation', async () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + disposables.add(toDisposable(() => clock.restore())); + const { widget, firstHost, overlay } = createHostTransitionHarness(); + const changed = disposables.add(new Emitter()); + const tools = ['first', 'second'].map(id => createSubagentTool(id)); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel(tools, changed.event)) }); + const [first, second] = overlay.querySelectorAll('.chat-subagent-pet'); + for (const subagentPet of [first, second]) { + for (const animation of subagentPet.getAnimations()) { + animation.pause(); + } + } + const image = first.querySelector('img')!; + const secondImage = second.querySelector('img')!; + const eyes = first.querySelector('.chat-pet-eyes')!; + await Promise.all([whenSpriteLoaded(image), whenSpriteLoaded(secondImage)]); + const idleSource = image.getAttribute('src'); + const land = (subagentPet: HTMLElement) => subagentPet.getAnimations()[0]?.dispatchEvent(new mainWindow.Event('finish')); + land(first); + await whenSpriteLoaded(image); + assert.deepStrictEqual({ + squishing: image.getAttribute('src')?.includes('buddy-splat-'), + arriving: first.getAnimations().length > 0, + idleEyes: eyes.classList.contains('tracking'), + otherSource: secondImage.getAttribute('src'), + }, { squishing: true, arriving: false, idleEyes: false, otherSource: idleSource }); + clock.tick(520); + await whenSpriteLoaded(image); + assert.deepStrictEqual({ source: image.getAttribute('src'), idleEyes: eyes.classList.contains('tracking') }, { source: idleSource, idleEyes: true }); + land(second); + await whenSpriteLoaded(secondImage); + tools[1].toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + land(second); + clock.tick(900); + assert.deepStrictEqual({ active: [...overlay.querySelectorAll('.chat-subagent-pet')], removed: !second.isConnected }, { active: [first], removed: true }); + }); + + test('subagent pets use the reduced-motion disappearance sprite', () => { + const { widget, firstHost, overlay } = createHostTransitionHarness(true); + const changed = disposables.add(new Emitter()); + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool], changed.event)) }); + assert.ok(overlay.querySelector('.chat-subagent-pet')); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + const image = subagentPet.querySelector('img')!; + const idleSource = image.getAttribute('src'); + subagentPet.getAnimations()[0]?.dispatchEvent(new mainWindow.Event('finish')); + assert.strictEqual(image.getAttribute('src'), idleSource); + tool.toolSpecificData = { kind: 'subagent', isActive: false }; + changed.fire({ reason: 'other' }); + assert.ok(overlay.querySelector('.chat-subagent-pet-despawning img')?.getAttribute('src')?.endsWith('-96.png')); + }); + + test('subagent pets pause invisible sprites, resume independently, and unobserve after despawning', async () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + disposables.add(toDisposable(() => clock.restore())); + let visibilityObserver: TestIntersectionObserver | undefined; + class VisibilityObserver extends TestIntersectionObserver { + constructor(callback: IntersectionObserverCallback) { + super(callback); + visibilityObserver = this; + } + } + const { widget, firstHost, overlay } = createHostTransitionHarness(false, 'teleport', 'stable', VisibilityObserver); + const responseChanged = disposables.add(new Emitter()); + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool], responseChanged.event)) }); + const pet = overlay.querySelector('.chat-subagent-pet')!; + pet.getAnimations().forEach(animation => animation.cancel()); + await whenSpriteLoaded(pet.querySelector('img')!); + const draws = sinon.spy(pet.querySelector('canvas')!.getContext('2d')!, 'drawImage'); + disposables.add(toDisposable(() => draws.restore())); + assert.ok(visibilityObserver); + const unobserve = sinon.spy(visibilityObserver, 'unobserve'); + const snapshots: number[] = []; + clock.tick(800); + snapshots.push(draws.callCount); + visibilityObserver.setVisible(false); + clock.tick(1_200); + snapshots.push(draws.callCount); + // A subagent pet can be visible while the main pet remains outside the viewport. + visibilityObserver.setVisible(true, pet); + snapshots.push(draws.callCount); + clock.tick(800); + snapshots.push(draws.callCount); + visibilityObserver.setVisible(false, pet); + tool.toolSpecificData = { kind: 'subagent', isActive: false }; + responseChanged.fire({ reason: 'other' }); + const observedWhileDespawning = !unobserve.calledWith(pet); + clock.tick(2_000); + assert.deepStrictEqual({ snapshots, observedWhileDespawning, removed: !pet.isConnected, unobserved: unobserve.calledWith(pet) }, { + snapshots: [1, 1, 2, 3], observedWhileDespawning: true, removed: true, unobserved: true, + }); + }); + + test('subagent pets blink and move their eyes with their own idle frames', async () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + disposables.add(toDisposable(() => clock.restore())); + const { widget, firstHost, overlay, setReducedMotion } = createSubagentPetTestHarness({ random: () => 0 }); + const tool = createSubagentTool('subagent', 'Subagent'); + widget.setHost({ ...firstHost, model: constObservable(createSubagentTestModel([tool])) }); + const subagentPet = overlay.querySelector('.chat-subagent-pet')!; + // Exercise idle frames independently of the arrival and landing animation. + subagentPet.getAnimations().forEach(animation => animation.cancel()); + const eyes = subagentPet.querySelector('.chat-pet-eyes')!; + const pupil = subagentPet.querySelector('.chat-pet-pupil')!; + await whenSpriteLoaded(subagentPet.querySelector('img')!); + assert.ok(!eyes.classList.contains('bobbed')); + clock.tick(800); + assert.ok(eyes.classList.contains('bobbed')); + clock.tick(600); + assert.ok(eyes.classList.contains('blink')); + assert.strictEqual(mainWindow.getComputedStyle(pupil).animationName, 'chat-pet-tall-eye-blink'); + pupil.dispatchEvent(new mainWindow.AnimationEvent('animationend', { animationName: 'chat-pet-tall-eye-blink' })); + assert.ok(!eyes.classList.contains('blink')); + clock.tick(600); + assert.ok(!eyes.classList.contains('bobbed')); + setReducedMotion(true); + clock.tick(3_400); + assert.ok(!eyes.classList.contains('blink')); + assert.ok(!eyes.classList.contains('bobbed')); + }); + for (const variant of ['stable', 'insiders'] as const) { for (const reducedMotion of [false, true]) { test(`paints only while a visible image-generation tool is active (${variant}, ${reducedMotion ? 'reduced motion' : 'animated'})`, async () => { @@ -2979,6 +3821,8 @@ suite('ChatPetWidget', () => { override readonly response = response; }(); const model = new class extends mock() { + override readonly onDidChange = Event.None; + override getRequests(): IChatRequestModel[] { return [request]; } override readonly hasActiveRequest = hasActiveRequest; override readonly lastRequestObs = constObservable(request); }();