diff --git a/changes/plugin-held-input-retry.json b/changes/plugin-held-input-retry.json new file mode 100644 index 0000000..8714def --- /dev/null +++ b/changes/plugin-held-input-retry.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "插件退出或长时间不再调用后,宿主替它抬起按住的输入时若释放失败会自动重试,不再让修饰键一直卡在客体里。释放期间插件新按下的键不会被误抬起,也不会从宿主记录中丢失。", + "en": "When the host lifts input a plugin left held and that release fails, it now retries instead of leaving a modifier stuck in the guest. A key the plugin pressed while a release was in flight is no longer lifted by mistake or dropped from the host's record." +} diff --git a/internal/app/computer_use_held.go b/internal/app/computer_use_held.go index 712beea..fe9e3ef 100644 --- a/internal/app/computer_use_held.go +++ b/internal/app/computer_use_held.go @@ -15,6 +15,12 @@ import ( // plugin's next call. var heldInputIdleTimeout = 2 * time.Minute +// heldReleaseRetryTimeout is how long the host waits before trying a fallback +// release again. A release can fail while the VM is still running, for example +// while its console is busy, and a plugin that already exited will never make +// the next call that would otherwise retry it. +var heldReleaseRetryTimeout = 30 * time.Second + // heldReleaseTimeout bounds one fallback release, which runs while the plugin // that held the input may already be gone. const heldReleaseTimeout = 5 * time.Second @@ -29,6 +35,10 @@ type heldInputs struct { buttons map[string]bool touched time.Time timer *time.Timer + // generation counts every change to this record. A release that finishes + // after the plugin pressed something new compares it with the generation it + // snapshotted, so it never deletes a press it did not lift. + generation uint64 } // noteHeldKey records or forgets one key transition. code must already be a @@ -77,19 +87,25 @@ func (a *App) heldLocked(pluginID, vmKey string) *heldInputs { return held } -// touchHeldLocked drops a record that holds nothing and rearms the idle timer -// of one that still does. The caller holds computerUseHeldMu. +// touchHeldLocked marks the record as changed, drops it when it holds nothing +// and rearms its idle timer otherwise. The caller holds computerUseHeldMu. func (a *App) touchHeldLocked(pluginID, vmKey string, held *heldInputs) { + held.generation++ held.touched = time.Now() - if held.timer != nil { - held.timer.Stop() - held.timer = nil - } if len(held.keys)+len(held.buttons) == 0 { a.pruneHeldLocked(pluginID, vmKey) return } - held.timer = time.AfterFunc(heldInputIdleTimeout, func() { + a.armHeldTimerLocked(pluginID, vmKey, held, heldInputIdleTimeout) +} + +// armHeldTimerLocked replaces the record's timer with one that fires after d. +// The caller holds computerUseHeldMu. +func (a *App) armHeldTimerLocked(pluginID, vmKey string, held *heldInputs, d time.Duration) { + if held.timer != nil { + held.timer.Stop() + } + held.timer = time.AfterFunc(d, func() { a.releaseHeldForVM(pluginID, vmKey) }) } @@ -113,17 +129,18 @@ func (a *App) pruneHeldLocked(pluginID, vmKey string) { } } -// heldState returns what one plugin holds in one VM, sorted. -func (a *App) heldState(pluginID, vmKey string) (keys, buttons []string) { +// heldSnapshot returns what one plugin holds in one VM, sorted, with the +// generation it was read at. +func (a *App) heldSnapshot(pluginID, vmKey string) (keys, buttons []string, generation uint64) { a.computerUseHeldMu.Lock() defer a.computerUseHeldMu.Unlock() byVM := a.computerUseHeld[pluginID] if byVM == nil { - return nil, nil + return nil, nil, 0 } held := byVM[vmKey] if held == nil { - return nil, nil + return nil, nil, 0 } for code := range held.keys { keys = append(keys, code) @@ -133,7 +150,18 @@ func (a *App) heldState(pluginID, vmKey string) (keys, buttons []string) { } sort.Strings(keys) sort.Strings(buttons) - return keys, buttons + return keys, buttons, held.generation +} + +// heldGeneration returns the record's current generation, or 0 when there is +// no record. +func (a *App) heldGeneration(pluginID, vmKey string) uint64 { + a.computerUseHeldMu.Lock() + defer a.computerUseHeldMu.Unlock() + if held := a.computerUseHeld[pluginID][vmKey]; held != nil { + return held.generation + } + return 0 } // heldVMs lists the VMs one plugin currently holds input in. @@ -147,16 +175,13 @@ func (a *App) heldVMs(pluginID string) map[string]bool { return out } -// dropHeld forgets the named keys and buttons of one plugin and VM. It is -// called only after the release reached the guest. +// dropHeld forgets the named keys and buttons of one plugin and VM. It is used +// when the caller itself named what it lifted, so there is no snapshot to +// compare with. func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) { a.computerUseHeldMu.Lock() defer a.computerUseHeldMu.Unlock() - byVM := a.computerUseHeld[pluginID] - if byVM == nil { - return - } - held := byVM[vmKey] + held := a.computerUseHeld[pluginID][vmKey] if held == nil { return } @@ -169,6 +194,42 @@ func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) { a.touchHeldLocked(pluginID, vmKey, held) } +// dropHeldIfGeneration forgets the named keys and buttons only when the record +// has not changed since generation was read. A record that changed in the +// meantime may hold a press this release did not lift, so it keeps everything +// and its timer releases it later. +func (a *App) dropHeldIfGeneration(pluginID, vmKey string, keys, buttons []string, generation uint64) bool { + a.computerUseHeldMu.Lock() + defer a.computerUseHeldMu.Unlock() + held := a.computerUseHeld[pluginID][vmKey] + if held == nil { + return false + } + if held.generation != generation { + return false + } + for _, code := range keys { + delete(held.keys, code) + } + for _, button := range buttons { + delete(held.buttons, button) + } + a.touchHeldLocked(pluginID, vmKey, held) + return true +} + +// rearmHeld schedules another fallback release for a record whose release +// failed while the VM is still running. +func (a *App) rearmHeld(pluginID, vmKey string) { + a.computerUseHeldMu.Lock() + defer a.computerUseHeldMu.Unlock() + held := a.computerUseHeld[pluginID][vmKey] + if held == nil || len(held.keys)+len(held.buttons) == 0 { + return + } + a.armHeldTimerLocked(pluginID, vmKey, held, heldReleaseRetryTimeout) +} + // forgetHeld drops the record of one plugin and VM without touching the // guest. It is for a VM that is not running: nothing in a powered-off guest // can still be held, and a release sent later could lift a key the user is @@ -209,10 +270,10 @@ func (a *App) heldConsoleRoute(vmKey string) (consoleRoute, bool) { // releaseHeldForVM lifts everything one plugin still holds in one VM. It is the // fallback for a plugin that can no longer release: its process exited, its // scope was disposed, or it stopped calling. A VM that is not running has -// nothing held, so its record is dropped instead of retried; a release that -// fails on a running VM keeps its record for the next attempt. +// nothing held, so its record is dropped instead of retried. A release that +// fails while the VM is running keeps its record and is retried. func (a *App) releaseHeldForVM(pluginID, vmKey string) { - keys, buttons := a.heldState(pluginID, vmKey) + keys, buttons, generation := a.heldSnapshot(pluginID, vmKey) if len(keys)+len(buttons) == 0 { a.forgetHeld(pluginID, vmKey) return @@ -222,6 +283,12 @@ func (a *App) releaseHeldForVM(pluginID, vmKey string) { a.forgetHeld(pluginID, vmKey) return } + // The plugin may have pressed something since the snapshot; lifting now + // would undo that press, so wait for the record to settle instead. + if a.heldGeneration(pluginID, vmKey) != generation { + a.rearmHeld(pluginID, vmKey) + return + } ctx, cancel := context.WithTimeout(context.Background(), heldReleaseTimeout) defer cancel() if err := a.consoleRelease(ctx, route, keys, buttons); err != nil { @@ -231,9 +298,14 @@ func (a *App) releaseHeldForVM(pluginID, vmKey string) { return } a.emitLog("plugin", "Could not release input held by "+pluginID+" in "+vmKey+": "+err.Error()) + a.rearmHeld(pluginID, vmKey) return } - a.dropHeld(pluginID, vmKey, keys, buttons) + if !a.dropHeldIfGeneration(pluginID, vmKey, keys, buttons, generation) { + // Something was pressed while the release was in flight. The record + // keeps it, and its timer lifts it if the plugin goes quiet again. + a.rearmHeld(pluginID, vmKey) + } } // releaseHeldForPlugin lifts everything one plugin holds in any VM. diff --git a/internal/app/host_api_test.go b/internal/app/host_api_test.go index 5d0e3db..b65a80f 100644 --- a/internal/app/host_api_test.go +++ b/internal/app/host_api_test.go @@ -196,14 +196,14 @@ func TestHeldLedgerTracksAndForgets(t *testing.T) { app.noteHeldButton("p", vmKey, "left", true) app.noteHeldKey("p", vmKey, "a", true) - keys, buttons := app.heldState("p", vmKey) + keys, buttons, _ := app.heldSnapshot("p", vmKey) if len(keys) != 2 || len(buttons) != 1 { t.Fatalf("held = %v %v", keys, buttons) } // Releasing one key keeps the rest. app.dropHeld("p", vmKey, []string{"a"}, nil) - if keys, _ := app.heldState("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" { + if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" { t.Fatalf("keys after drop = %v", keys) } @@ -221,6 +221,58 @@ func TestHeldLedgerTracksAndForgets(t *testing.T) { } } +// TestHeldLedgerKeepsAPressMadeDuringARelease checks that a release which +// finished after the plugin pressed something new does not delete that press +// from the record: the fallback would then no longer know to lift it. +func TestHeldLedgerKeepsAPressMadeDuringARelease(t *testing.T) { + app := &App{} + const vmKey = "driver:vm" + app.noteHeldKey("p", vmKey, "meta_l", true) + keys, buttons, generation := app.heldSnapshot("p", vmKey) + + // The plugin presses another key while the release is in flight. + app.noteHeldKey("p", vmKey, "shift", true) + + if app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) { + t.Fatal("a stale release deleted a press it did not lift") + } + if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 2 { + t.Fatalf("keys = %v, want both presses kept", keys) + } + + // A release whose snapshot is still current does clear the record. + keys, buttons, generation = app.heldSnapshot("p", vmKey) + if !app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) { + t.Fatal("a current release was refused") + } + if vms := app.heldVMs("p"); len(vms) != 0 { + t.Fatalf("ledger still holds %v", vms) + } +} + +// TestHeldLedgerRetriesAfterTheIdleTimeout checks that a record whose fallback +// release could not run keeps a timer: a plugin that already exited never +// makes the call that would otherwise retry it. +func TestHeldLedgerRetriesAfterTheIdleTimeout(t *testing.T) { + previousIdle, previousRetry := heldInputIdleTimeout, heldReleaseRetryTimeout + heldInputIdleTimeout = time.Hour + heldReleaseRetryTimeout = 20 * time.Millisecond + t.Cleanup(func() { heldInputIdleTimeout, heldReleaseRetryTimeout = previousIdle, previousRetry }) + + app := &App{} + app.noteHeldKey("p", "driver:vm", "meta_l", true) + app.rearmHeld("p", "driver:vm") + deadline := time.Now().Add(2 * time.Second) + for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + // The VM is not running here, so the retry drops the record instead of + // leaving a key pressed forever. + if vms := app.heldVMs("p"); len(vms) != 0 { + t.Fatalf("the retry left %v behind", vms) + } +} + // TestHeldLedgerReleasesAfterTheIdleTimeout checks that a plugin which stops // calling mid-hold does not leave the guest stuck: the record carries its own // timer, and a VM that is not running has nothing left to lift.