Skip to content

Stabilize floating monitor drag - #6984

Merged
shimmyshimmer merged 8 commits into
mainfrom
fix/stabilize-floating-monitor
Jul 9, 2026
Merged

shimmyshimmer merged 8 commits into
mainfrom
fix/stabilize-floating-monitor

Conversation

@shimmyshimmer

@shimmyshimmer shimmyshimmer commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Stop the live monitor from layout-animating its fixed floating panel.
  • Start dragging only from the grip handle instead of the whole panel.
  • Preserve the close exit animation with AnimatePresence and callback-backed drag constraints.
  • Keep the API item in the settings menu free of the old New badge.
  • Export shared stores and helpers through feature indexes.
  • Harden Windows Studio smoke checks that were failing from CI environment issues.

Why

The floating monitor mixed layout animation, full-panel drag listening, and native resize on the same fixed element. Metric refreshes and resize changes could re-project the panel and make it jump even when nothing was being dragged.

The API badge removal was already merged separately, but this branch was still carrying the old badge markup. This keeps the active PR from reintroducing it.

The CI hardening keeps Windows no-build-tools checks sandboxed with temporary discovery roots and a filtered Path, instead of renaming protected Program Files directories. The overrides are set in-script because the runner does not apply step-level env keys containing parentheses. It also resets the Playwright browser session in place before the shutdown re-login after password rotation, since macOS Chromium runs --single-process and cannot host a second context.

Testing

  • node temp/pr-simulations/pr-invariants.mjs temp/unsloth-full
  • Chrome headless local browser simulation: PASS
  • Firefox headless screenshot local browser simulation: PASS
  • npx eslint src/components/floating-monitor.tsx src/components/app-sidebar.tsx src/features/settings/index.ts src/features/chat/index.ts src/i18n/locales/en.ts src/i18n/locales/ja.ts src/i18n/locales/zh-CN.ts src/i18n/locales/pt-br.ts
  • npx biome check src/components/floating-monitor.tsx src/features/settings/index.ts src/features/chat/index.ts
  • npm run i18n:check
  • npm run typecheck
  • npm run build
  • git diff --check
  • python -m py_compile tests/studio/playwright_chat_ui.py inside a uv venv
  • ruby -e 'require "yaml"; YAML.load_file(".github/workflows/studio-windows-inference-smoke.yml")'
  • PowerShell run of the extracted Find-VsBuildTools against a fake VS 2026 tree: detected with real discovery roots, undetectable after the in-script overrides
  • Reproduced the macOS TargetClosedError under --single-process Chromium with the same launch args; the same-context reset passed 11 consecutive runs

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the FloatingMonitor component to use Framer Motion's useDragControls for manual drag handling and updates the import path for useMonitorOverlayStore by exporting it from the settings module index. Feedback highlights that exit animations are currently broken due to an early return when the monitor is closed. To resolve this, it is recommended to wrap the component in AnimatePresence and replace the useRef with a callback ref (useState) to properly track the constraints element during unmounting and remounting.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

dragControls.start(event);
}

if (!isOpen) return null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Issue: Exit animations are broken due to early return and DOM ref tracking issue on unmount/remount

  1. Exit Animations Broken: When isOpen becomes false (e.g., when clicking the close button), the component immediately re-renders and hits the early return if (!isOpen) return null; at line 50. Because it returns null immediately, the component's children are unmounted instantly, preventing Framer Motion's <motion.div> exit animations from playing.
  2. Ref Tracking Issue: The component conditionally renders the constraints container. When an element unmounts and remounts while the parent component remains mounted, using useRef to track the DOM element can cause issues because React doesn't notify when the ref's value changes. We should use React state (a callback ref) instead of useRef to track the DOM element.

Solution

To fix these issues:

  1. Remove the early return if (!isOpen) return null;.
  2. Import AnimatePresence from motion/react.
  3. Wrap the JSX in <AnimatePresence> and conditionally render the content based on isOpen inside it.
  4. Replace useRef with useState for tracking the constraints element to ensure correct behavior when it mounts/unmounts.

Here is how the component can be refactored:

import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { useMonitorOverlayStore } from "@/features/settings";
import { useSystemInfo } from "@/hooks/use-system";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { CpuIcon, GripVerticalIcon, XIcon } from "lucide-react";
import { motion, useDragControls, AnimatePresence } from "motion/react";
import { useState, type PointerEvent } from "react";

// ... helper functions ...

export function FloatingMonitor() {
  const t = useT();
  const { isOpen, setIsOpen } = useMonitorOverlayStore();
  const systemInfo = useSystemInfo({ enabled: isOpen, pollMs: 5000 });

  const [constraintsRef, setConstraintsRef] = useState<HTMLDivElement | null>(null);
  const dragControls = useDragControls();

  function startDrag(event: PointerEvent<HTMLDivElement>) {
    event.preventDefault();
    dragControls.start(event);
  }

  const ramTotal = systemInfo.memory?.total_gb ?? 0;
  const ramAvailable = systemInfo.memory?.available_gb ?? 0;
  const ramUsed = Math.max(0, ramTotal - ramAvailable);
  const ramPercent = clampPercent(systemInfo.memory?.percent_used ?? 0);

  const devices = systemInfo.gpu?.devices ?? [];
  const vramTotal = devices.reduce(
    (sum, device) => sum + (device.memory_total_gb ?? 0),
    0,
  );
  const vramUsed = devices.reduce(
    (sum, device) => sum + (device.vram_used_gb ?? 0),
    0,
  );
  const vramPercent = clampPercent(
    vramTotal > 0 ? (vramUsed / vramTotal) * 100 : 0,
  );

  const hasGpu = (systemInfo.gpu?.available ?? false) && devices.length > 0;

  return (
    <AnimatePresence>
      {isOpen && (
        <div
          ref={setConstraintsRef}
          className="fixed inset-0 z-50 pointer-events-none"
        >
          <motion.div
            drag={true}
            dragControls={dragControls}
            dragListener={false}
            dragConstraints={constraintsRef ?? undefined}
            dragElastic={0}
            dragMomentum={false}
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.9 }}
            className="settings-surface fixed bottom-4 right-4 w-64 max-w-[calc(100vw-2rem)] resize overflow-hidden rounded-xl border border-border/70 p-3 shadow-border ring-0 backdrop-blur-sm pointer-events-auto cursor-default select-none"
          >
            {/* ... rest of the component ... */}
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
}
References
  1. Use React state instead of useRef to track DOM elements that may unmount and remount (e.g., due to key changes or conditional rendering) while the parent component remains mounted. This ensures that useEffect hooks depending on the element will correctly re-run and re-attach event listeners or update calculations when the element changes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 29a3438: the early return is gone, AnimatePresence wraps the conditional render, and the constraints element is tracked with state. One correction to the snippet: dragConstraints takes a ref object rather than a raw element, so the component memoizes { current: element } instead of passing the element directly.

@shimmyshimmer
shimmyshimmer marked this pull request as ready for review July 8, 2026 15:22
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex

The runner does not apply step-level env keys containing parentheses,
so ProgramFiles(x86) kept its real value and Find-VsBuildTools still
detected VS through vswhere. Set the overrides inside each pwsh step
instead; child processes inherit them. The resolver step moves to pwsh
because bash cannot export a variable named ProgramFiles(x86).
macOS runs Chromium with --single-process, where closing the last
context tears down the whole browser, so the shutdown re-login died
with TargetClosedError on new_page. Clear cookies and swap pages
inside the same context instead, opening the replacement page before
closing the old one.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed fixes for the two failing checks.

Studio install + inference without Visual Studio

The no-build-tools steps set ProgramFiles(x86) through step-level env:, but the runner does not apply env keys containing parentheses. The real value stayed visible, vswhere was still found, and the assert failed with Find-VsBuildTools still detects VS: Visual Studio 18 2026. The overrides now happen at the top of each step script, which also propagates them to child processes. The resolver step moved from bash to pwsh because bash cannot export a variable named ProgramFiles(x86) at all.

Verified by extracting Find-VsBuildTools with Get-FunctionSource (same as the workflow does) and running it against a fake VS 2026 Enterprise tree: detection fires with real discovery roots and returns null after the in-script overrides, and printenv from a child process confirms the redirected values are inherited.

Chat UI Tests (macOS)

The shutdown re-login closed the browser context and opened a new one. macOS runs Chromium with --single-process, where closing the last context tears down the whole browser, so ctx.new_page() failed with TargetClosedError at line 1281. Only the macOS job failed because Linux and Windows do not use --single-process. The reset now stays in the same context: clear cookies to drop the stale token, open the replacement page first, then close the old page. The context-level init script already covers pages created later, so nothing needs reinstalling.

Reproduced the exact TargetClosedError locally with the same launch args, confirmed a second context also fails under --single-process (so reordering context creation would not have helped), and the same-context reset passed 11 consecutive runs.

py_compile, YAML parse, and actionlint all come back clean (actionlint findings are identical to the base branch).

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

setConfirmingDelete(null);

P2 Badge Reset the delete-files toggle after project deletion

After a user enables Delete files and sandbox folder and confirms a project deletion, this controlled close path leaves deleteProjectFiles set to true because the reset-on-target-change effect was removed and onOpenChange is not invoked by this state update. The next project-delete dialog therefore opens pre-checked with the destructive Delete all action, making an accidental second filesystem deletion much easier; reset the flag when closing or after consuming it.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1410 to +1412
$env:ProgramFiles = $env:NO_BUILD_TOOLS_PROGRAMFILES
${env:ProgramFiles(x86)} = $env:NO_BUILD_TOOLS_PROGRAMFILES_X86
$env:Path = $env:NO_BUILD_TOOLS_PATH

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the no-build-tools PATH sanitized during install

When this step runs on Windows hosts where the installer installs or updates Python/uv, these one-time assignments do not keep build tools hidden: install.ps1's Refresh-SessionPath rebuilds PATH from Machine/User before the current value, and studio/setup.ps1's environment refresh can reload ProgramFiles/PATH as well. That can re-expose the runner's real CMake/VS before ./install.ps1 exercises the prebuilt path, so the no-VS smoke can pass without actually simulating a no-build-tools machine; keep the filter active after refreshes or assert again inside/after the install.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 2de692f. Refresh-SessionPath (called unconditionally near the end of install.ps1) and setup.ps1's Refresh-Environment both rebuild the session Path from the Machine and User scopes, which would have re-added the CMake directory mid-install. The Prepare step now filters those two scopes as well, using normalized comparison so trailing-slash and unexpanded %VAR% spellings still match, and the cleanup step restores the saved originals. I verified the merge logic from Refresh-SessionPath against emulated scopes: unfiltered scopes re-expose CMake, filtered scopes stay clean.

One correction: the ProgramFiles half of this does not apply. Refresh-Environment copies registry environment values, and ProgramFiles is not stored in the Machine or User environment hives, so the in-script override survives both refreshes.

# be created. Clear cookies to drop the stale token and open the new page
# before closing the old one; the context init script covers the new page.
try:
ctx.clear_cookies()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear localStorage auth before reopening login

In the post-rotation relogin path, clearing cookies does not remove the stale Studio credentials because the frontend stores unsloth_auth_token and unsloth_auth_refresh_token in localStorage. When the old JWT remains after /change-password rotates the signing secret, the guest guard can still see a token key and redirect the fresh page away from /login, so the subsequent #password wait flakes; clear those localStorage keys in this context before navigating.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in fbdb22b. The tokens are unsloth_auth_token and unsloth_auth_refresh_token in localStorage, and requireGuest redirects off /login on their mere presence without validating them, so clearing cookies alone missed the actual stale credentials. The reset now removes both keys on the old page before opening the replacement page. In practice the app self-heals (a 401 clears the tokens and redirects back to auth), which is why this step passed historically, but dropping the keys makes the /login navigation deterministic instead of relying on the tolerated redirect bounce. Verified against a live Studio: with a stale token injected, the reset block lands on /login with the password field visible and no auth keys left.

install.ps1's Refresh-SessionPath and setup.ps1's Refresh-Environment
rebuild the session Path from the Machine and User registry scopes, so
the process-level filter could be undone mid-install and re-expose
CMake. Filter those scopes in the Prepare step with normalized dir
matching and restore them in cleanup.
Auth tokens live in localStorage, not cookies, and the login guest
guard redirects on their mere presence. Remove them during the session
reset so the /login navigation is deterministic instead of relying on
the tolerated redirect bounce.
@shimmyshimmer
shimmyshimmer merged commit 1b82521 into main Jul 9, 2026
40 checks passed
@shimmyshimmer
shimmyshimmer deleted the fix/stabilize-floating-monitor branch July 9, 2026 07:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant