Skip to content

Commit fbd8fbd

Browse files
committed
fix(computer-use): stop macOS capture after resize failure
1 parent 9330c8c commit fbd8fbd

3 files changed

Lines changed: 87 additions & 29 deletions

File tree

‎scripts/fixtures/computer-use-capture.m‎

Lines changed: 66 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,25 @@
11
#import <AppKit/AppKit.h>
22
#import <CoreMedia/CoreMedia.h>
3+
#import <ScreenCaptureKit/ScreenCaptureKit.h>
4+
#import <objc/runtime.h>
35
@interface NSObject (OBFCaptureTimingFixture)
46
@property(nonatomic) CMTime lastObservedSample;
57
@property(nonatomic) CMTime inputBarrier;
68
@end
79
#include <stdio.h>
810
#include <stdatomic.h>
11+
// The native bridge distinguishes an unavailable surface from a stopped
12+
// stream. Only status 1 initializes the frame and bounds output parameters.
13+
static const int captureOK = 1;
14+
static const int captureNoSurface = 2;
915
static atomic_bool stoppedWithIdentity;
1016
static atomic_uint stopCount;
1117
static uint32_t expectedWindow;
12-
static uint64_t expectedGeneration = 1;
18+
static atomic_uint_fast64_t expectedGeneration = 1;
19+
static atomic_uint_fast64_t expectedRevision = UINT64_MAX;
1320
extern uint32_t obf_capture_validate_target(int32_t, uint32_t, char *, size_t);
1421
extern void *obf_capture_start(int32_t, uint32_t, uint64_t, char *, size_t);
22+
extern void obf_capture_bind_revision(void *, uint64_t);
1523
extern void obf_capture_mark_input(void *);
1624
extern int obf_capture_bounds(void *, double *, char *, size_t);
1725
extern int obf_capture_frame(void *, uint8_t **, size_t *, uint32_t *, uint32_t *, uint32_t *, double *, uint64_t *, char *, size_t);
@@ -21,9 +29,24 @@ @interface NSObject (OBFCaptureTimingFixture)
2129
extern void obf_pointer_hide(void);
2230
void obf_control_native_stopped(uint64_t generation, uint64_t revision, int32_t pid, uint32_t windowID, const char *reason) {
2331
atomic_fetch_add(&stopCount, 1);
24-
if(generation == expectedGeneration && pid == getpid() && windowID == expectedWindow) atomic_store(&stoppedWithIdentity, true);
32+
if (generation == expectedGeneration && revision == expectedRevision &&
33+
pid == getpid() && windowID == expectedWindow) atomic_store(&stoppedWithIdentity, true);
2534
fprintf(stderr, "Stopped: %s\n", reason);
2635
}
36+
// Force an error from the reconfiguration completion while the real stream
37+
// is still live. The control owner must be notified before explicit Stop.
38+
static void rejectResize(id stream, SEL selector, SCStreamConfiguration *config, void (^completion)(NSError *)) {
39+
completion([NSError errorWithDomain:@"OpenBitFunCaptureFixture" code:1
40+
userInfo:@{NSLocalizedDescriptionKey: @"Fixture resize rejected"}]);
41+
}
42+
static BOOL windowIDStillExists(uint32_t windowID) {
43+
CFArrayRef windows = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID);
44+
for (NSDictionary *window in CFBridgingRelease(windows)) {
45+
if ([window[(id)kCGWindowNumber] unsignedIntValue] == windowID &&
46+
[window[(id)kCGWindowOwnerPID] intValue] == getpid()) return YES;
47+
}
48+
return NO;
49+
}
2750
// Opt-in diagnostic for a real application: only reads captured frames and
2851
// prints window identity/geometry. No pixels are persisted and no input is sent.
2952
static void observeApp(pid_t pid) {
@@ -34,7 +57,7 @@ static void observeApp(pid_t pid) {
3457
int result=0; uint32_t bound=0;
3558
for(int i=0;i<20;i++){
3659
uint8_t *bytes=NULL;size_t length=0;uint32_t w=0,ht=0,wid=0;double bounds[4]={0};uint64_t sequence=0;
37-
if(!obf_capture_frame(h,&bytes,&length,&w,&ht,&wid,bounds,&sequence,error,sizeof(error))){fprintf(stderr,"FRAME_ERROR %s\n",error);result=1;break;}
60+
if(obf_capture_frame(h,&bytes,&length,&w,&ht,&wid,bounds,&sequence,error,sizeof(error)) != captureOK){fprintf(stderr,"FRAME_ERROR %s\n",error);result=1;break;}
3861
if(i==0)bound=wid;
3962
if(wid!=bound || atomic_load(&stopCount)){result=1;break;}
4063
obf_capture_free(bytes);
@@ -82,9 +105,10 @@ int main(int argc, const char **argv) { @autoreleasepool {
82105
return 0;
83106
}
84107
BOOL minimize = argc > 1 && strcmp(argv[1], "--minimized") == 0;
108+
BOOL rejectConfiguration = argc > 1 && strcmp(argv[1], "--resize-error") == 0;
85109
NSApplication *app = NSApplication.sharedApplication;
86110
[app setActivationPolicy:NSApplicationActivationPolicyAccessory];
87-
NSWindow *target = [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,240,160) styleMask:(minimize ? NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable : NSWindowStyleMaskBorderless) backing:NSBackingStoreBuffered defer:NO];
111+
__block NSWindow *target = [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,240,160) styleMask:(minimize ? NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable : NSWindowStyleMaskBorderless) backing:NSBackingStoreBuffered defer:NO];
88112
target.backgroundColor = NSColor.redColor;
89113
target.releasedWhenClosed = NO;
90114
[target orderFront:nil];
@@ -99,9 +123,29 @@ int main(int argc, const char **argv) { @autoreleasepool {
99123
void *handle = obf_capture_start(getpid(), targetID, 1, error, sizeof(error));
100124
int result = 1;
101125
if (!handle) fprintf(stderr,"FAIL start: %s\n",error);
102-
else {
126+
else if (rejectConfiguration) {
127+
expectedRevision = 4;
128+
obf_capture_bind_revision(handle, expectedRevision);
129+
Method update = class_getInstanceMethod(SCStream.class, @selector(updateConfiguration:completionHandler:));
130+
IMP original = method_setImplementation(update, (IMP)rejectResize);
131+
dispatch_sync(dispatch_get_main_queue(), ^{
132+
[target setFrame:NSMakeRect(100,100,280,190) display:YES];
133+
});
134+
[NSThread sleepForTimeInterval:0.15];
135+
uint8_t *bytes = NULL; size_t length = 0;
136+
uint32_t width = 0, height = 0, windowID = 0; uint64_t sequence = 0; double bounds[4] = {0};
137+
int status = obf_capture_frame(handle, &bytes, &length, &width, &height, &windowID, bounds, &sequence, error, sizeof(error));
138+
method_setImplementation(update, original);
139+
if (status == 0 && !bytes && atomic_load(&stoppedWithIdentity) &&
140+
strstr(error, "CAPTURE_STOPPED:") && strstr(error, "Fixture resize rejected")) {
141+
puts("PASS failed resize revokes the live capture before explicit Stop");
142+
result = 0;
143+
} else fprintf(stderr, "FAIL resize failure did not revoke capture: status=%d error=%s\n", status, error);
144+
obf_capture_free(bytes);
145+
obf_capture_stop(handle);
146+
} else {
103147
uint8_t *bytes = NULL; size_t length=0; uint32_t width=0,height=0,windowID=0; uint64_t sequence=0; double bounds[4]={0};
104-
if (!obf_capture_frame(handle,&bytes,&length,&width,&height,&windowID,bounds,&sequence,error,sizeof(error))) fprintf(stderr,"FAIL frame: %s\n",error);
148+
if (obf_capture_frame(handle,&bytes,&length,&width,&height,&windowID,bounds,&sequence,error,sizeof(error)) != captureOK) fprintf(stderr,"FAIL frame: %s\n",error);
105149
else {
106150
size_t center = ((height/2)*width + width/2)*4;
107151
printf("Frame %ux%u target=%u returned=%u sequence=%llu center RGBA=%u,%u,%u,%u bounds=%.0f,%.0f,%.0f,%.0f\n",width,height,targetID,windowID,sequence,bytes[center],bytes[center+1],bytes[center+2],bytes[center+3],bounds[0],bounds[1],bounds[2],bounds[3]);
@@ -116,8 +160,8 @@ int main(int argc, const char **argv) { @autoreleasepool {
116160
uint8_t *fresh = NULL; size_t freshLength = 0;
117161
uint32_t freshWidth = 0, freshHeight = 0, freshWindow = 0;
118162
uint64_t freshSequence = 0; double freshBounds[4] = {0};
119-
if (!obf_capture_frame(handle, &fresh, &freshLength, &freshWidth, &freshHeight,
120-
&freshWindow, freshBounds, &freshSequence, error, sizeof(error)) ||
163+
if (obf_capture_frame(handle, &fresh, &freshLength, &freshWidth, &freshHeight,
164+
&freshWindow, freshBounds, &freshSequence, error, sizeof(error)) != captureOK ||
121165
CMTimeCompare([(__bridge id)handle lastObservedSample], barrier) < 0) {
122166
fprintf(stderr, "FAIL capture returned a pre-input sample: %s\n", error); result = 1;
123167
} else puts("PASS post-input observation waits for a newer complete or idle sample");
@@ -132,8 +176,8 @@ int main(int argc, const char **argv) { @autoreleasepool {
132176
uint8_t *repeat = NULL; size_t repeatLength = 0;
133177
uint32_t repeatWidth = 0, repeatHeight = 0, repeatWindow = 0;
134178
uint64_t repeatSequence = 0; double repeatBounds[4] = {0};
135-
if (!obf_capture_frame(handle, &repeat, &repeatLength, &repeatWidth, &repeatHeight,
136-
&repeatWindow, repeatBounds, &repeatSequence, error, sizeof(error)) ||
179+
if (obf_capture_frame(handle, &repeat, &repeatLength, &repeatWidth, &repeatHeight,
180+
&repeatWindow, repeatBounds, &repeatSequence, error, sizeof(error)) != captureOK ||
137181
repeatWindow != targetID || atomic_load(&stoppedWithIdentity)) {
138182
fprintf(stderr, "FAIL persistent observation %d: %s\n", observation, error); result = 1;
139183
}
@@ -171,21 +215,21 @@ int main(int argc, const char **argv) { @autoreleasepool {
171215
dispatch_sync(dispatch_get_main_queue(), ^{ [target setFrameOrigin:NSMakePoint(110,100)]; });
172216
[NSThread sleepForTimeInterval:0.15]; // WindowServer commits the AppKit geometry asynchronously.
173217
double inputBounds[4] = {0};
174-
if (!obf_capture_bounds(handle, inputBounds, error, sizeof(error)) || inputBounds[0] != 110) {
218+
if (obf_capture_bounds(handle, inputBounds, error, sizeof(error)) != captureOK || inputBounds[0] != 110) {
175219
fprintf(stderr,"FAIL input-only geometry retained stale origin: %s\n",error); result=1;
176220
} else puts("PASS input geometry updates after movement without copying or encoding a frame");
177221
uint8_t *movedBytes = NULL; size_t movedLength = 0;
178222
uint32_t movedWidth=0,movedHeight=0,movedWindow=0; uint64_t movedSequence=0; double movedBounds[4]={0};
179223
int moved = obf_capture_frame(handle,&movedBytes,&movedLength,&movedWidth,&movedHeight,&movedWindow,movedBounds,&movedSequence,error,sizeof(error));
180-
if (!moved || movedBounds[0] != 110) {
224+
if (moved != captureOK || movedBounds[0] != 110) {
181225
fprintf(stderr,"FAIL moved geometry not refreshed: %s\n",error); result=1;
182226
} else puts("PASS moved window returns the new coordinate basis");
183227
if(movedBytes) obf_capture_free(movedBytes);
184228
dispatch_sync(dispatch_get_main_queue(), ^{ [target setFrame:NSMakeRect(110,100,280,190) display:YES]; });
185229
[NSThread sleepForTimeInterval:0.15];
186230
movedBytes = NULL;
187231
int resized = obf_capture_frame(handle,&movedBytes,&movedLength,&movedWidth,&movedHeight,&movedWindow,movedBounds,&movedSequence,error,sizeof(error));
188-
if (!resized || movedWidth != 280 || movedHeight != 190 || movedBounds[2] != 280 || movedBounds[3] != 190) {
232+
if (resized != captureOK || movedWidth != 280 || movedHeight != 190 || movedBounds[2] != 280 || movedBounds[3] != 190) {
189233
fprintf(stderr,"FAIL resized stream did not produce matching pixels: %s\n",error); result=1;
190234
} else puts("PASS resized window updates SCStream and waits for matching frame dimensions");
191235
if(movedBytes) obf_capture_free(movedBytes);
@@ -196,9 +240,8 @@ int main(int argc, const char **argv) { @autoreleasepool {
196240
uint8_t *hiddenBytes = NULL; size_t hiddenLength = 0;
197241
uint32_t hiddenWidth=0,hiddenHeight=0,hiddenWindow=0; uint64_t hiddenSequence=0; double hiddenBounds[4]={0};
198242
int hidden = obf_capture_frame(handle,&hiddenBytes,&hiddenLength,&hiddenWidth,&hiddenHeight,&hiddenWindow,hiddenBounds,&hiddenSequence,error,sizeof(error));
199-
if (hidden) {
200-
size_t center = ((hiddenHeight/2)*hiddenWidth+hiddenWidth/2)*4;
201-
fprintf(stderr,"HIDDEN frame center after changing background to green: %u,%u,%u\n",hiddenBytes[center],hiddenBytes[center+1],hiddenBytes[center+2]);
243+
if (hidden == captureOK || hiddenBytes) {
244+
fprintf(stderr,"FAIL hidden target returned a frame\n");
202245
result = 1;
203246
obf_capture_free(hiddenBytes);
204247
} else if (!strstr(error,"TARGET_")) {
@@ -214,12 +257,17 @@ int main(int argc, const char **argv) { @autoreleasepool {
214257
if(!handle) { fprintf(stderr,"FAIL restored target restart: %s\n",error); result=1; }
215258
}
216259
if (result == 0) {
217-
dispatch_sync(dispatch_get_main_queue(), ^{ [target close]; });
260+
// A retained NSWindow can keep its WindowServer ID after
261+
// close. Release it so this exercises loss of the window.
262+
dispatch_sync(dispatch_get_main_queue(), ^{ [target close]; target = nil; });
218263
[NSThread sleepForTimeInterval:0.2];
219264
uint8_t *closedBytes = NULL; size_t closedLength = 0;
220265
uint32_t closedWidth=0,closedHeight=0,closedWindow=0; uint64_t closedSequence=0; double closedBounds[4]={0};
221266
int closed = obf_capture_frame(handle,&closedBytes,&closedLength,&closedWidth,&closedHeight,&closedWindow,closedBounds,&closedSequence,error,sizeof(error));
222-
if (closed || !atomic_load(&stoppedWithIdentity)) {
267+
if (closed == captureNoSurface && !closedBytes &&
268+
strstr(error, "TARGET_SURFACE_UNAVAILABLE:") && windowIDStillExists(targetID)) {
269+
puts("PASS AppKit retained the closed window ID and capture returned no pixels");
270+
} else if (closed != 0 || closedBytes || !atomic_load(&stoppedWithIdentity)) {
223271
fprintf(stderr,"FAIL closed target did not revoke capture with its identity: %s\n",error); result=1;
224272
} else puts("PASS closed window revokes capture with its original generation and target");
225273
if(closedBytes) obf_capture_free(closedBytes);

‎scripts/test-macos-control-capture.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ try {
3131
} else {
3232
await run(binary, []);
3333
await run(binary, ['--minimized']);
34+
await run(binary, ['--resize-error']);
3435
}
3536
} finally {
3637
await rm(directory, { recursive: true, force: true });

‎src/crates/services/computer-use/src/computer_use/macos_capture.m‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -218,24 +218,33 @@ - (instancetype)init {
218218
}
219219
return self;
220220
}
221-
- (void)fail:(NSString *)reason {
221+
- (BOOL)fail:(NSString *)reason {
222222
[self.condition lock];
223+
if (self.stopped) {
224+
[self.condition unlock];
225+
return NO;
226+
}
223227
self.stopped = YES;
224228
self.failure = reason ?: @"Capture stopped";
225229
self.pixels = nil;
226230
[self.condition broadcast];
227231
[self.condition unlock];
228232
obf_focus_loss_stop_matching(self.pid, self.windowID, self.generation, false, 0, 0);
233+
return YES;
234+
}
235+
- (void)reportTerminalFailure:(NSString *)reason {
236+
if (![self fail:reason]) return;
237+
// A failed stream must also revoke its control binding. The owner tears
238+
// down the matching stream asynchronously, outside the capture lock.
239+
obf_control_native_stopped(self.generation, self.targetRevision, self.pid, self.windowID, reason.UTF8String);
229240
}
230241
- (void)stream:(SCStream *)stream didStopWithError:(NSError *)error {
231-
[self fail:[NSString stringWithFormat:@"CAPTURE_STOPPED: %@", error.localizedDescription]];
232-
obf_control_native_stopped(self.generation, self.targetRevision, self.pid, self.windowID, self.failure.UTF8String);
242+
[self reportTerminalFailure:[NSString stringWithFormat:@"CAPTURE_STOPPED: %@", error.localizedDescription]];
233243
}
234244
// macOS 15.2+: a closed target must immediately revoke input, even if the
235245
// framework keeps the stream available for a later reopened window.
236246
- (void)streamDidBecomeInactive:(SCStream *)stream {
237-
[self fail:@"TARGET_WINDOW_UNAVAILABLE: Shared window became inactive"];
238-
obf_control_native_stopped(self.generation, self.targetRevision, self.pid, self.windowID, self.failure.UTF8String);
247+
[self reportTerminalFailure:@"TARGET_WINDOW_UNAVAILABLE: Shared window became inactive"];
239248
[stream stopCaptureWithCompletionHandler:^(NSError *error) { (void)error; }];
240249
}
241250
- (void)stream:(SCStream *)stream didOutputSampleBuffer:(CMSampleBufferRef)sample ofType:(SCStreamOutputType)type {
@@ -548,8 +557,7 @@ uint32_t obf_capture_default_window(int32_t pid, char *error, size_t capacity) {
548557
int obf_capture_status(void *handle, char *error, size_t capacity) {
549558
OBFWindowCapture *session = (__bridge OBFWindowCapture *)handle;
550559
if (obf_session_locked()) {
551-
[session fail:@"SESSION_LOCKED: Execution host screen is locked; start control again after unlocking"];
552-
obf_control_native_stopped(session.generation, session.targetRevision, session.pid, session.windowID, session.failure.UTF8String);
560+
[session reportTerminalFailure:@"SESSION_LOCKED: Execution host screen is locked; start control again after unlocking"];
553561
[session.stream stopCaptureWithCompletionHandler:^(NSError *e) { (void)e; }];
554562
obf_error(error, capacity, session.failure);
555563
return 0;
@@ -561,8 +569,7 @@ int obf_capture_status(void *handle, char *error, size_t capacity) {
561569
BOOL wasStopped = session.stopped;
562570
[session.condition unlock];
563571
if (!wasStopped && !valid) {
564-
[session fail:@"TARGET_WINDOW_UNAVAILABLE: Original target window was closed"];
565-
obf_control_native_stopped(session.generation, session.targetRevision, session.pid, session.windowID, session.failure.UTF8String);
572+
[session reportTerminalFailure:@"TARGET_WINDOW_UNAVAILABLE: Original target window was closed"];
566573
[session.stream stopCaptureWithCompletionHandler:^(NSError *e) { (void)e; }];
567574
}
568575
[session.condition lock];
@@ -689,7 +696,7 @@ int obf_capture_frame(void *handle, uint8_t **bytes, size_t *length, uint32_t *w
689696
CGRect frame = CGRectZero;
690697
BOOL onScreen = NO;
691698
if (!obf_window_info(session.pid, session.windowID, &frame, &onScreen)) {
692-
[session fail:@"TARGET_WINDOW_UNAVAILABLE: Original target window was closed"];
699+
[session reportTerminalFailure:@"TARGET_WINDOW_UNAVAILABLE: Original target window was closed"];
693700
}
694701
[session.condition lock];
695702
if (session.stopped) {
@@ -710,7 +717,9 @@ int obf_capture_frame(void *handle, uint8_t **bytes, size_t *length, uint32_t *w
710717
SCStreamConfiguration *configuration = session.configuration;
711718
[session.condition unlock];
712719
[session.stream updateConfiguration:configuration completionHandler:^(NSError *updateError) {
713-
if (updateError) [session fail:updateError.localizedDescription];
720+
if (updateError) {
721+
[session reportTerminalFailure:[NSString stringWithFormat:@"CAPTURE_STOPPED: Window capture resize failed: %@", updateError.localizedDescription]];
722+
}
714723
}];
715724
[session.condition lock];
716725
}

0 commit comments

Comments
 (0)