Skip to content

Commit 62fe665

Browse files
authored
fix(computer-use): work in short moments and hand the Mac back to the person (#6591)
* fix(computer-use): share the Mac with the person instead of asking for control back When the person used the Mac during a step, computer use could raise its window and send input under their hands, and if another window came to the front it told the agent to hand control to the person and wait for Continue. In control mode the helper now waits until the person has left the mouse and keyboard alone for half a second before it opens, looks or acts. It reads that from the HID system's idle time, which the agent's process-targeted input does not reach. It then brings its window back to the front, at most twice per call. Between steps of a batch it waits and refocuses instead of failing, and re-checks the window against the observation when no input has landed yet. Another window in front is reported as focus_lost with next "observe". A person who keeps working for ten seconds gets person_active and nothing is sent. Only Take over still asks for Continue. Signed-off-by: Jalil <reachjalil@gmail.com> * fix(computer-use): act at once and hand the front back instead of waiting for the person Waiting for half a second of stillness made computer use slow whenever the person moved the mouse. The agent now takes the front only for the moment it needs, then gives it back. Moving the mouse never holds the agent up. It defers at most half a second, and only to the next gap in the person's typing or the release of a held button, so their keys and drags do not land in its window. It remembers which app had the front, and 0.4 s after its last call gives the front back to that app, unless the person has already moved on. An action and the read after it count as one moment. A click or key press of the person's during the agent's moment stops that step with person_interrupted and next "observe". The front stays where the person put it, and the read right after takes no focus. Take over still pauses for Continue. The ten-second person_active wait is gone. Signed-off-by: Jalil <reachjalil@gmail.com> * fix(computer-use): never hand the front away from a person typing in the agent's window The hand-back used the same filter as interrupts, which treats input within 50 ms of the agent's own post as the agent's. A keystroke of the person's in that window could go unseen, and the hand-back would then move the front to another app while they kept typing. The hand-back now reads click and key times unfiltered. Any of them since the agent took the front keeps the front where it is. Input that might be the agent's own only costs a hand-back, never moves the person's typing. The filter remains only for stopping the agent's own step. Signed-off-by: Jalil <reachjalil@gmail.com> --------- Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 0719937 commit 62fe665

3 files changed

Lines changed: 465 additions & 19 deletions

File tree

‎packages/computer-use/native/Sources/ComputerUse/Contract.swift‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,110 @@ enum ObservationPreparation {
276276
}
277277
}
278278

279+
/// Shares the Mac with the person using it. The agent takes the front only for
280+
/// the moment it needs to look or act, then gives it back to the app that had it.
281+
/// Moving the mouse never holds the agent up; a click or key press during its
282+
/// moment stops that step. Only Take over pauses the agent for Continue.
283+
enum SharedDesktop {
284+
static let refocusLimit = 2
285+
/// Keys this recent mean the person is mid-typing.
286+
static let typingGap: TimeInterval = 0.2
287+
/// The longest the agent defers to typing or a held button before it goes anyway.
288+
static let deferLimit: TimeInterval = 0.5
289+
/// Calls closer together than this are one moment, with no hand-back between them.
290+
static let handBackDelay: TimeInterval = 0.4
291+
static let poll: TimeInterval = 0.05
292+
293+
// Input times come from the HID system state, which only physical devices
294+
// update. The agent's events go to one process and never enter it, so every
295+
// time read here is the person's: nothing is discounted by timing.
296+
297+
/// Mid-keystroke or holding a button: raising another window now would send the
298+
/// person's next key or drag into it.
299+
static func personBusy(keyAt: TimeInterval, buttonDown: Bool, now: TimeInterval) -> Bool {
300+
buttonDown || now - keyAt < typingGap
301+
}
302+
303+
/// A click or key press of the person's after the agent's moment began.
304+
static func personInterrupted(inputAt: TimeInterval, since start: TimeInterval) -> Bool {
305+
inputAt > start
306+
}
307+
static let interrupted = UseError("person_interrupted", "The person clicked or typed, so this step stopped and the computer is theirs for now. Observe again to continue.", next: "observe")
308+
309+
/// Takes the next gap in the person's typing or the release of a held button,
310+
/// waiting `deferLimit` at most. Moving the mouse never delays the agent.
311+
@MainActor static func takeGap(busy: () -> Bool, now: () -> TimeInterval, check: () throws -> Void,
312+
sleep: (TimeInterval) async throws -> Void) async throws {
313+
let started = now()
314+
while busy(), now() - started < deferLimit {
315+
try check()
316+
try await sleep(poll)
317+
}
318+
try check()
319+
}
320+
321+
/// Brings the selected window forward, then stops if the person clicked or typed
322+
/// while it came forward: that input may have landed in the agent's window, so
323+
/// no control or observation follows. Never raises under a held button, however
324+
/// long it is held: the release of a drag begun in another app would land in the
325+
/// agent's window as a drop.
326+
@MainActor static func acquire(now: () -> TimeInterval, buttonDown: () -> Bool, focus: () async throws -> Void,
327+
interrupted: (TimeInterval) -> Bool) async throws {
328+
if buttonDown() { throw SharedDesktop.interrupted }
329+
let baseline = now()
330+
try await focus()
331+
if interrupted(baseline) { throw SharedDesktop.interrupted }
332+
}
333+
334+
/// Brings the selected window back when something else is in front, at most
335+
/// `refocusLimit` times in one call, so the agent never fights the person for it.
336+
/// A person who clicked or typed since the step began keeps the front: the step
337+
/// stops before the window is raised, not after.
338+
@MainActor static func returnFocus(used: inout Int, inFront: () -> Bool, personActed: () -> Bool = { false },
339+
focus: () async throws -> Void) async throws -> Bool {
340+
if inFront() { return false }
341+
if personActed() { throw interrupted }
342+
guard used < refocusLimit else { throw contested }
343+
used += 1
344+
do { try await focus() }
345+
catch let error as UseError where error.code == "window_not_frontmost" { throw contested }
346+
return true
347+
}
348+
static let contested = UseError("focus_contested", "Another window keeps coming to the front, so nothing more was sent. Observe again in a few seconds.", next: "observe")
349+
350+
/// The app the agent took the front from, given back once its moment ends.
351+
struct HandBack {
352+
private(set) var pid: pid_t?
353+
private(set) var takenAt: TimeInterval?
354+
/// The first app in front wins: one moment can raise the target more than once.
355+
mutating func record(frontmost: pid_t?, target: pid_t, own: pid_t, at now: TimeInterval) {
356+
guard pid == nil, let frontmost, frontmost != target, frontmost != own else { return }
357+
pid = frontmost; takenAt = now
358+
}
359+
/// Returns the app to give the front back to, only while the agent's window
360+
/// still has it and the person has not clicked or typed since it was taken.
361+
/// `lastPersonInput` is unfiltered: input that might be the agent's own still
362+
/// keeps the front where it is, so typing never moves to another app.
363+
mutating func take(frontmost: pid_t?, target: pid_t, lastPersonInput: TimeInterval) -> pid_t? {
364+
defer { forget() }
365+
guard frontmost == target, let takenAt, lastPersonInput <= takenAt else { return nil }
366+
return pid
367+
}
368+
mutating func forget() { pid = nil; takenAt = nil }
369+
}
370+
371+
/// A window in front of the selected one is the person or another app at work,
372+
/// not a takeover, so the model looks again instead of waiting for Continue.
373+
static func yielding(_ error: UseError) -> UseError {
374+
guard error.code == "window_not_frontmost" else { return error }
375+
return UseError("focus_lost", "Another window came to the front, so input stopped there. Observe again; the selected window is brought back first.", next: "observe")
376+
}
377+
static func yielding(_ error: Error) -> Error {
378+
guard let use = error as? UseError else { return error }
379+
return yielding(use) as UseError
380+
}
381+
}
382+
279383
/// Pointer timing and paths. Apps react to input the way a person produces it:
280384
/// a press that lasts, a drag that travels and a pause over the drop target.
281385
enum PointerMotion {

0 commit comments

Comments
 (0)