@@ -180,6 +180,16 @@ func (rpty *bufferedReconnectingPTY) Attach(ctx context.Context, connID string,
180180
181181// Once we are ready, attach the active connection while we hold the mutex.
182182_ ,err := rpty .state .waitForStateOrContext (ctx ,StateReady ,func (state State ,err error )error {
183+ // Write any previously stored data for the TTY. Since the command might be
184+ // short-lived and have already exited, make sure we always at least output
185+ // the buffer before returning.
186+ prevBuf := slices .Clone (rpty .circularBuffer .Bytes ())
187+ _ ,writeErr := conn .Write (prevBuf )
188+ if writeErr != nil {
189+ rpty .metrics .WithLabelValues ("write" ).Add (1 )
190+ return xerrors .Errorf ("write buffer to conn: %w" ,writeErr )
191+ }
192+
183193if state != StateReady {
184194return xerrors .Errorf ("reconnecting pty ready wait: %w" ,err )
185195}
@@ -194,14 +204,7 @@ func (rpty *bufferedReconnectingPTY) Attach(ctx context.Context, connID string,
194204rpty .metrics .WithLabelValues ("resize" ).Add (1 )
195205}
196206
197- // Write any previously stored data for the TTY and store the connection for
198- // future writes.
199- prevBuf := slices .Clone (rpty .circularBuffer .Bytes ())
200- _ ,err = conn .Write (prevBuf )
201- if err != nil {
202- rpty .metrics .WithLabelValues ("write" ).Add (1 )
203- return xerrors .Errorf ("write buffer to conn: %w" ,err )
204- }
207+ // Store the connection for future writes.
205208rpty .activeConns [connID ]= conn
206209
207210return nil