@@ -516,7 +516,10 @@ export function TerminalViewport({
516516 // never started, so only "exited" triggers the message — as with xterm.)
517517 synchronizedStatusRef . current = "closed" ;
518518 synchronizeTerminalStatus ( terminal , latestSession . status ) ;
519- if ( autoFocus && visibleRef . current ) window . requestAnimationFrame ( ( ) => terminal . focus ( ) ) ;
519+ // Startup may finish after the user has returned to the composer.
520+ if ( visibleRef . current && mount . contains ( document . activeElement ) ) {
521+ terminal . focus ( ) ;
522+ }
520523
521524 const dismissSelectionAction = ( supersede = false ) => {
522525 const ownsMenu =
@@ -870,10 +873,10 @@ export function TerminalViewport({
870873
871874 return ( ) => {
872875 cancelled = true ;
876+ const hadFocus = mount . contains ( document . activeElement ) ;
873877 teardown ?.( ) ;
878+ if ( hadFocus && mount . isConnected ) mount . focus ( { preventScroll : true } ) ;
874879 } ;
875- // autoFocus is intentionally omitted;
876- // it is only read at mount time and must not trigger terminal teardown/recreation.
877880 } , [ cwd , environmentId , runtimeEnvKey , terminalId , threadId , worktreePath ] ) ;
878881
879882 useEffect ( ( ) => {
@@ -904,24 +907,14 @@ export function TerminalViewport({
904907 writeSystemMessage ( terminal , current . error ) ;
905908 }
906909
907- if ( previous . version === 0 && autoFocus && visibleRef . current ) {
908- window . requestAnimationFrame ( ( ) => {
909- terminal . focus ( ) ;
910- } ) ;
911- }
912910 previousSessionRef . current = current ;
913- } , [ autoFocus , terminalOutput , terminalError , terminalStatus , terminalVersion ] ) ;
911+ } , [ terminalOutput , terminalError , terminalStatus , terminalVersion ] ) ;
914912
915913 useEffect ( ( ) => {
916914 if ( ! autoFocus || ! visible ) return ;
917- const terminal = terminalRef . current ;
918- if ( ! terminal ) return ;
919- const frame = window . requestAnimationFrame ( ( ) => {
920- terminal . focus ( ) ;
921- } ) ;
922- return ( ) => {
923- window . cancelAnimationFrame ( frame ) ;
924- } ;
915+ // Claim focus when requested, then hand it to the terminal once ready only
916+ // if the user has not focused something else in the meantime.
917+ ( terminalRef . current ?? containerRef . current ) ?. focus ( ) ;
925918 } , [ autoFocus , focusRequestId , visible ] ) ;
926919
927920 useEffect ( ( ) => {
@@ -944,6 +937,7 @@ export function TerminalViewport({
944937 return (
945938 < div
946939 ref = { containerRef }
940+ tabIndex = { - 1 }
947941 className = "relative h-full w-full overflow-hidden bg-[var(--terminal-background)]"
948942 />
949943 ) ;
0 commit comments