11// The files a bot made, kept current (spec 8.5, 15.1): read when the bot is
2- // opened, and again while it works and when it stops, since a scan of its
3- // folders is the only way to see what a script or a command made.
2+ // opened, again while it works with the files panel in sight, and when it
3+ // stops, since a scan of its folders is the only way to see what a script
4+ // or a command made. Each read walks the folders, so nobody pays for it
5+ // while the list is out of sight.
46
57import { useCallback , useEffect , useRef , useState } from "react" ;
68import { errorText } from "../../lib/api" ;
79import type { Bot , BotFile } from "../../lib/protocol.gen" ;
10+ import { useWindowVisible } from "../../shell/visibility" ;
811import { useApi , useApp } from "../../store/context" ;
912
10- /** How often the list is read while the bot works. */
13+ /** How often the list is read while the bot works and the panel is in sight . */
1114const WHILE_WORKING_MS = 4000 ;
1215
1316export interface BotFiles {
@@ -18,7 +21,8 @@ export interface BotFiles {
1821 refresh ( ) : Promise < void > ;
1922}
2023
21- export function useBotFiles ( bot : Pick < Bot , "id" | "state" > ) : BotFiles {
24+ /** `watching`: the files panel is open. */
25+ export function useBotFiles ( bot : Pick < Bot , "id" | "state" > , watching : boolean ) : BotFiles {
2226 const api = useApi ( ) ;
2327 const open = useApp ( ( state ) => state . connection . kind === "open" ) ;
2428 const [ files , setFiles ] = useState < BotFile [ ] > ( [ ] ) ;
@@ -60,6 +64,7 @@ export function useBotFiles(bot: Pick<Bot, "id" | "state">): BotFiles {
6064
6165 const working = bot . state === "busy" || bot . state === "needs_approval" ;
6266 const wasWorking = useRef ( working ) ;
67+ const inSight = useWindowVisible ( ) && watching ;
6368 useEffect ( ( ) => {
6469 if ( ! open ) {
6570 return ;
@@ -69,12 +74,14 @@ export function useBotFiles(bot: Pick<Bot, "id" | "state">): BotFiles {
6974 void refresh ( ) ;
7075 }
7176 wasWorking . current = working ;
72- if ( ! working ) {
77+ if ( ! working || ! inSight ) {
7378 return ;
7479 }
80+ // Coming into sight mid-turn shows what was made meanwhile.
81+ void refresh ( ) ;
7582 const timer = setInterval ( ( ) => void refresh ( ) , WHILE_WORKING_MS ) ;
7683 return ( ) => clearInterval ( timer ) ;
77- } , [ open , working , refresh ] ) ;
84+ } , [ open , working , inSight , refresh ] ) ;
7885
7986 return { files, loading, error, refresh } ;
8087}
0 commit comments