11"""Host-side progress for long commands without changing measured model work."""
22
3+ import asyncio
34import csv
5+ import os
46import subprocess
7+ import sys
58import time
69
10+ from prompt_toolkit .application import Application
11+ from prompt_toolkit .data_structures import Point
12+ from prompt_toolkit .key_binding import KeyBindings
13+ from prompt_toolkit .layout import HSplit , Layout , Window
14+ from prompt_toolkit .layout .controls import FormattedTextControl
15+ from prompt_toolkit .widgets import Frame
16+
17+ from .failures import tail
18+
719
820def memory_status (path ):
921 """Read only the last complete sample; tolerate partial writes and startup."""
@@ -24,24 +36,105 @@ def memory_status(path):
2436 return ""
2537
2638
39+ def interactive_terminal ():
40+ return (
41+ sys .stdin .isatty () and sys .stdout .isatty () and os .environ .get ("TERM" ) != "dumb"
42+ )
43+
44+
45+ def log_tail (path , lines = 12 ):
46+ """Bound reads and remove terminal controls from untrusted subprocess output."""
47+ text = tail (path , limit = 16384 )
48+ return (
49+ "\n " .join (
50+ "" .join (char if char .isprintable () or char == "\t " else "" for char in line )
51+ for line in text .splitlines ()[- lines :]
52+ )
53+ or "Waiting for log output…"
54+ )
55+
56+
57+ def live_view (status , log ):
58+ bindings = KeyBindings ()
59+
60+ @bindings .add ("c-c" )
61+ @bindings .add ("c-d" )
62+ def cancel (event ):
63+ event .app .exit (exception = KeyboardInterrupt ())
64+
65+ return Application (
66+ layout = Layout (
67+ HSplit (
68+ [
69+ Window (FormattedTextControl (status ), height = 2 , wrap_lines = True ),
70+ Frame (
71+ Window (
72+ FormattedTextControl (
73+ lambda : log_tail (log ),
74+ show_cursor = False ,
75+ get_cursor_position = lambda : Point (
76+ x = 0 , y = len (log_tail (log ).splitlines ()) - 1
77+ ),
78+ ),
79+ height = 12 ,
80+ wrap_lines = False ,
81+ ),
82+ title = f"Log tail: { log .name } " ,
83+ ),
84+ ]
85+ )
86+ ),
87+ key_bindings = bindings ,
88+ full_screen = False ,
89+ erase_when_done = True ,
90+ refresh_interval = 0.25 ,
91+ )
92+
93+
2794def run_logged (args , log , interval = 15 ):
28- """Keep full logs on disk and print periodic stage status, including failures."""
95+ """Retain progress on disk and show a live status/log panel on terminals."""
96+ if interval <= 0 :
97+ raise ValueError ("progress interval must be positive" )
2998 label = "Image build" if log .name == "build.log" else log .parent .name
99+ progress_log = log .with_name (f"{ log .stem } .progress.log" )
30100 started = time .monotonic ()
31- print (f"{ label } : started; log: { log } " , flush = True )
32- with log .open ("w" ) as stream :
101+
102+ def status ():
103+ return f"{ label } : { time .monotonic () - started :.0f} s elapsed" + memory_status (
104+ log .parent / "memory.csv"
105+ )
106+
107+ initial = f"{ label } : started; log: { log } ; progress: { progress_log } "
108+ print (initial , flush = True )
109+ with log .open ("w" ) as stream , progress_log .open ("w" , buffering = 1 ) as progress :
110+ progress .write (initial + "\n " )
33111 process = subprocess .Popen (args , stdout = stream , stderr = subprocess .STDOUT )
34112 try :
35- while True :
36- try :
37- code = process .wait (timeout = interval )
38- break
39- except subprocess .TimeoutExpired :
40- detail = memory_status (log .parent / "memory.csv" )
41- print (
42- f"{ label } : { time .monotonic () - started :.0f} s elapsed{ detail } " ,
43- flush = True ,
44- )
113+ if interactive_terminal ():
114+ app = live_view (status , log )
115+
116+ async def monitor ():
117+ try :
118+ next_sample = started + interval
119+ while process .poll () is None :
120+ now = time .monotonic ()
121+ if now >= next_sample :
122+ progress .write (status () + "\n " )
123+ next_sample = now + interval
124+ await asyncio .sleep (min (0.25 , interval ))
125+ except Exception as error :
126+ app .exit (exception = error )
127+ else :
128+ app .exit (result = process .returncode )
129+
130+ code = app .run (pre_run = lambda : app .create_background_task (monitor ()))
131+ else :
132+ while True :
133+ try :
134+ code = process .wait (timeout = interval )
135+ break
136+ except subprocess .TimeoutExpired :
137+ progress .write (status () + "\n " )
45138 except BaseException :
46139 # Let container_phase's finally block remove a cancelled container.
47140 # Reap the host Docker client so cancellation never leaves it running.
@@ -51,12 +144,14 @@ def run_logged(args, log, interval=15):
51144 except subprocess .TimeoutExpired :
52145 process .kill ()
53146 process .wait ()
147+ progress .write (f"{ status ()} ; interrupted\n " )
54148 raise
55- status = "completed" if code == 0 else f"failed (exit { code } )"
56- print (
57- f"{ label } : { status } after { time .monotonic () - started :.0f} s"
58- + memory_status (log .parent / "memory.csv" ),
59- flush = True ,
60- )
149+ outcome = "completed" if code == 0 else f"failed (exit { code } )"
150+ final = (
151+ f"{ label } : { outcome } after { time .monotonic () - started :.0f} s"
152+ + memory_status (log .parent / "memory.csv" )
153+ )
154+ progress .write (final + "\n " )
155+ print (final , flush = True )
61156 if code :
62157 raise subprocess .CalledProcessError (code , args )
0 commit comments