Files
Reims-Go/internal/app/agent_session_flow.go
T
YXC0915 577b2f73ed
Windows CI / verify (push) Successful in 6m28s
Merge GitHub client updates into the Gitea mainline
2026-12-07 03:33:06 +08:00

1842 lines
54 KiB
Go

package app
import (
"context"
"encoding/json"
"errors"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/host/sessionoverlay"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
type completedOverlayEntry struct {
pluginID string
driverID string
vmName string
pid uint32
}
type agentSession struct {
vmKey string
driverID string
vmName string
vmDir string
pluginID string
pluginName string
label string
stage string
status string
message string
takeoverPolicy string // "auto" | "manual" | "lock"
pausedForUser bool
hostPaused bool
takeoverPaused bool
takeoverUntil time.Time
startedAt time.Time
unboundSince time.Time
ephemeralGrant bool
isAutoInstall bool
autoInstallMode string
secretSetting string
saveUnlockCredential bool
finishInstallDone bool
sawSetupAssistant bool
suppressedInstallGuide bool
lastOverlayPID uint32
lastPIDProbeAt time.Time
ctx context.Context
cancel context.CancelFunc
watchGen uint64
watchCancel context.CancelFunc
}
// AgentSessionView is the read-only session snapshot exposed to the frontend,
// CLI, tray menu, and Win32 VM overlay.
type AgentSessionView struct {
VMKey string `json:"vm_key"`
DriverID string `json:"driver_id"`
VMName string `json:"vm_name"`
PluginID string `json:"plugin_id"`
PluginName string `json:"plugin_name"`
Label string `json:"label,omitempty"`
Stage string `json:"stage,omitempty"`
StageLabel string `json:"stage_label,omitempty"`
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Phase string `json:"phase,omitempty"`
AuthUntilPhaseExit bool `json:"auth_until_phase_exit,omitempty"`
AuthRemainingSec int `json:"auth_remaining_sec,omitempty"`
TakeoverPolicy string `json:"takeover_policy,omitempty"`
InputLocked bool `json:"input_locked,omitempty"`
PausedForUser bool `json:"paused_for_user,omitempty"`
TakeoverPaused bool `json:"takeover_paused,omitempty"`
TakeoverManualWait bool `json:"takeover_manual_wait,omitempty"`
TakeoverRemainSec int `json:"takeover_remaining_sec,omitempty"`
StartedAt string `json:"started_at"`
}
func (a *App) sessionHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
return map[string]plugin.RPCRequestHandler{
"host/session.begin": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/session.begin", a.handleSessionBegin),
"host/session.update": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/session.update", a.handleSessionUpdate),
"host/session.end": a.sessionEndHandler(mgr, pluginID),
}
}
func parseVMRefFromRaw(raw json.RawMessage) string {
if len(raw) == 0 {
return ""
}
var req struct {
VM string `json:"vm"`
}
if json.Unmarshal(raw, &req) != nil {
return ""
}
return strings.TrimSpace(req.VM)
}
func (a *App) sessionEndHandler(mgr *plugin.Manager, pluginID string) plugin.RPCRequestHandler {
authorized := a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/session.end", a.handleSessionEnd)
return func(ctx context.Context, raw json.RawMessage) (any, error) {
if refStr := parseVMRefFromRaw(raw); refStr != "" {
if vm, err := a.resolveComputerUseVMInfo(refStr); err == nil && a.hasActiveAgentSessionOwnedBy(vm.Ref().Key(), pluginID) {
res, err := a.handleSessionEnd(ctx, raw, mgr, pluginID)
if mgr.Broker() != nil {
if err != nil {
mgr.Broker().Audit(pluginID, "HOST_API_ERROR", "host/session.end")
} else {
mgr.Broker().Audit(pluginID, "HOST_API", "host/session.end")
}
}
return res, err
}
}
return authorized(ctx, raw)
}
}
func (a *App) handleSessionBegin(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.SessionBeginParams](mgr, pluginID, "host/session.begin", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
if strings.Contains(err.Error(), "not_authorized") {
a.abortAgentSessionForVMRef(mgr, pluginID, req.VM, "permission_denied", true)
}
return nil, err
}
if req.RequestProtectedPhaseAuth {
phase, err := a.effectiveVMPhaseStrict(vm)
if err != nil {
return nil, err
}
if phase == driver.PhaseInstaller || phase == driver.PhaseRecovery {
if err := a.authorizeProtectedPhase(ctx, mgr, pluginID, vm, phase, true, req.PreferUntilPhaseExit); err != nil {
return nil, err
}
}
}
policy := strings.ToLower(strings.TrimSpace(req.TakeoverPolicy))
if policy != "manual" && policy != "lock" {
policy = "auto"
}
a.beginAgentSession(mgr, pluginID, vm, strings.TrimSpace(req.Label), strings.TrimSpace(req.Stage), policy, false)
return map[string]any{"ok": true, "vm": vm.Ref().Key()}, nil
}
func (a *App) handleSessionUpdate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.SessionUpdateParams](mgr, pluginID, "host/session.update", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
key := vm.Ref().Key()
a.sessionMu.Lock()
sess := a.agentSessions[key]
if sess == nil || sess.pluginID != pluginID {
a.sessionMu.Unlock()
return nil, errors.New("no active session owned by this plugin")
}
if stg := strings.TrimSpace(req.Stage); stg != "" {
sess.stage = stg
if stg == "stage5_setup_assistant" {
sess.sawSetupAssistant = true
}
} else if stp := strings.TrimSpace(req.Step); stp != "" {
sess.stage = stp
if stp == "stage5_setup_assistant" {
sess.sawSetupAssistant = true
}
}
now := time.Now()
if sess.takeoverPaused && !sess.takeoverUntil.IsZero() && !now.Before(sess.takeoverUntil) {
sess.takeoverPaused = false
sess.takeoverUntil = time.Time{}
}
hostHeld := sess.hostPaused || sess.takeoverPaused
if req.Status != "" {
nextStatus := strings.TrimSpace(req.Status)
if !hostHeld || nextStatus != "running" {
sess.status = nextStatus
}
}
if req.Message != "" {
sess.message = strings.TrimSpace(req.Message)
}
if req.PausedForUser != nil {
if *req.PausedForUser {
sess.pausedForUser = true
} else if !hostHeld {
// Plugins may only clear plugin-initiated pauses; host physical
// takeover or explicit user Pause must be resumed via ResumeAgentSession.
sess.pausedForUser = false
}
}
a.sessionMu.Unlock()
a.syncTakeoverTargets()
a.refreshAgentSessionVisuals(key)
a.emitStateChangedEvent()
return map[string]any{"ok": true}, nil
}
func (a *App) handleSessionEnd(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.SessionEndParams](mgr, pluginID, "host/session.end", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil {
return nil, err
}
key := vm.Ref().Key()
if strings.TrimSpace(req.Status) != "" || strings.TrimSpace(req.Message) != "" {
a.sessionMu.Lock()
if sess := a.agentSessions[key]; sess != nil && (pluginID == "" || sess.pluginID == pluginID) {
if st := strings.TrimSpace(req.Status); st != "" {
sess.status = st
}
if msg := strings.TrimSpace(req.Message); msg != "" {
sess.message = msg
}
}
a.sessionMu.Unlock()
}
a.endAgentSession(mgr, pluginID, key, "session_ended")
return map[string]any{"ok": true}, nil
}
func (a *App) pluginDisplayName(mgr *plugin.Manager, pluginID string) string {
if mgr == nil || mgr.Registry() == nil {
return pluginID
}
loc := a.computerUseLocale()
if info, ok := mgr.Registry().Info(pluginID); ok {
if name := strings.TrimSpace(info.Name.Get(string(loc))); name != "" {
return name
}
}
return pluginID
}
func (a *App) isAutoInstallerPlugin(mgr *plugin.Manager, pluginID string) bool {
if pluginID == "" {
return false
}
if mgr == nil {
a.mu.Lock()
mgr = a.pluginMgr
a.mu.Unlock()
}
if mgr == nil || mgr.Registry() == nil {
return false
}
for _, item := range mgr.Registry().AutoInstallersForFamily("") {
if item.PluginID == pluginID {
return true
}
}
return false
}
func (a *App) setAgentSessionAutoInstallConfig(vmKey, pluginID, mode, secretSetting string, saveUnlockCredential bool) {
mode = strings.ToLower(strings.TrimSpace(mode))
secretSetting = strings.TrimSpace(secretSetting)
a.sessionMu.Lock()
if sess := a.agentSessions[vmKey]; sess != nil && (pluginID == "" || sess.pluginID == pluginID) {
sess.isAutoInstall = true
if mode != "" {
sess.autoInstallMode = mode
}
sess.secretSetting = secretSetting
sess.saveUnlockCredential = saveUnlockCredential
}
a.sessionMu.Unlock()
}
func (a *App) hasActiveAgentSessionOwnedBy(vmKey, pluginID string) bool {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
sess := a.agentSessions[vmKey]
return sess != nil && (pluginID == "" || sess.pluginID == pluginID)
}
func (a *App) startAutoInstallSessionWatch(vmKey, pluginID string) (context.Context, uint64, bool) {
var prevCancel context.CancelFunc
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil || (pluginID != "" && sess.pluginID != pluginID) {
a.sessionMu.Unlock()
return nil, 0, false
}
prevCancel = sess.watchCancel
sess.watchGen++
gen := sess.watchGen
wctx, wcancel := context.WithCancel(sess.ctx)
sess.watchCancel = wcancel
a.sessionMu.Unlock()
if prevCancel != nil {
prevCancel()
}
return wctx, gen, true
}
func (a *App) isCurrentAutoInstallSessionWatch(vmKey, pluginID string, gen uint64) bool {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
sess := a.agentSessions[vmKey]
return sess != nil && (pluginID == "" || sess.pluginID == pluginID) && sess.watchGen == gen
}
// handlePluginPermissionDeniedForVM immediately aborts any active Agent or
// auto-install session owned by pluginID on vmKey when permission is denied,
// wipes temporary credentials, unlocks VM input, notifies the plugin to stop,
// and falls back to showing the original manual installation guide.
func (a *App) handlePluginPermissionDeniedForVM(mgr *plugin.Manager, pluginID, vmKey, vmName, reason string) {
if mgr == nil {
a.mu.Lock()
mgr = a.pluginMgr
a.mu.Unlock()
}
vmKey = strings.TrimSpace(vmKey)
driverID := ""
if ref, ok := driver.ParseVMRef(vmKey); ok {
driverID = ref.DriverID
if strings.TrimSpace(vmName) == "" {
vmName = ref.Name
}
} else if strings.TrimSpace(vmName) == "" && vmKey != "" {
vmName = vmKey
}
if reason == "" {
reason = "permission_denied"
}
a.sessionMu.Lock()
existing := a.agentSessions[vmKey]
otherActive := existing != nil && pluginID != "" && existing.pluginID != pluginID
completedEnt, hasCompleted := a.completedOverlays[vmKey]
otherCompleted := hasCompleted && pluginID != "" && completedEnt.pluginID != pluginID
sess := existing
if otherActive {
sess = nil
}
if sess != nil {
delete(a.agentSessions, vmKey)
delete(a.completedOverlays, vmKey)
}
ov := a.sessionOverlay
a.sessionMu.Unlock()
if sess == nil {
if otherActive || otherCompleted {
return
}
a.restoreManualInstallGuideFallback(driverID, vmName)
return
}
sess.cancel()
if sess.ephemeralGrant {
a.revokeEphemeralVMAccess(sess.pluginID, vmKey)
}
if mgr != nil && sess.secretSetting != "" {
_ = mgr.SetSettings(sess.pluginID, vmKey, map[string]any{sess.secretSetting: ""})
}
a.revokeApprovedProtectedPhaseForPluginVM(sess.pluginID, vmKey, reason)
if ov != nil {
ov.Remove(vmKey)
}
a.syncTakeoverTargets()
fallbackMsg := i18n.T(a.computerUseLocale(), "agent.session.denied_fallback")
if mgr != nil {
mgr.NotifySidecar(sess.pluginID, "session/stopped", map[string]any{
"vm": vmKey,
"reason": reason,
"message": fallbackMsg,
})
if mgr.Broker() != nil {
mgr.Broker().Audit(sess.pluginID, "SESSION_END", vmKey+" "+reason)
}
}
a.prepareInstallGuideRestoreAfterSession(sess, false)
a.restoreManualInstallGuideFallback(sess.driverID, sess.vmName)
}
func (a *App) resolveAbortTargetForVMRef(vmRefHint string) (vmKey, vmName string) {
vmRefHint = strings.TrimSpace(vmRefHint)
if vmRefHint == "" {
return "", ""
}
if vm, err := a.resolveComputerUseVMInfo(vmRefHint); err == nil {
return vm.Ref().Key(), vm.Name
}
if ref, ok := driver.ParseVMRef(vmRefHint); ok {
return ref.Key(), ref.Name
}
return vmKeyForDriver("", vmRefHint), vmRefHint
}
// abortAgentSessionForVMRef handles a per-VM authorization denial (such as
// allow_ai_access disabled for one VM) without disturbing the plugin's active
// sessions on other authorized VMs.
func (a *App) abortAgentSessionForVMRef(mgr *plugin.Manager, pluginID, vmRefHint, reason string, includeUnownedHint bool) {
vmKey, vmName := a.resolveAbortTargetForVMRef(vmRefHint)
if vmKey == "" {
return
}
if includeUnownedHint || a.hasActiveAgentSessionOwnedBy(vmKey, pluginID) {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, vmKey, vmName, reason)
}
}
func (a *App) abortAgentSessionsForPluginPermissionDenial(mgr *plugin.Manager, pluginID, vmRefHint, reason string, includeUnownedHint bool) {
type target struct {
vmKey string
vmName string
}
seen := map[string]bool{}
var targets []target
if pluginID != "" {
a.sessionMu.Lock()
for k, s := range a.agentSessions {
if s != nil && s.pluginID == pluginID && !seen[k] {
seen[k] = true
targets = append(targets, target{vmKey: k, vmName: s.vmName})
}
}
a.sessionMu.Unlock()
}
if vmKey, vmName := a.resolveAbortTargetForVMRef(vmRefHint); vmKey != "" {
if !seen[vmKey] && (includeUnownedHint || a.hasActiveAgentSessionOwnedBy(vmKey, pluginID)) {
seen[vmKey] = true
targets = append(targets, target{vmKey: vmKey, vmName: vmName})
}
}
for _, t := range targets {
a.handlePluginPermissionDeniedForVM(mgr, pluginID, t.vmKey, t.vmName, reason)
}
}
func (a *App) markAgentSessionFinishInstallDone(vmKey string) {
if vmKey == "" {
return
}
a.sessionMu.Lock()
if sess := a.agentSessions[vmKey]; sess != nil {
sess.finishInstallDone = true
}
a.sessionMu.Unlock()
}
func (a *App) beginAgentSession(mgr *plugin.Manager, pluginID string, vm driver.VMInfo, label, stage, takeoverPolicy string, ephemeral bool) {
key := vm.Ref().Key()
pName := a.pluginDisplayName(mgr, pluginID)
isAuto := a.isAutoInstallerPlugin(mgr, pluginID)
sctx, cancel := context.WithCancel(context.Background())
type replacedSessionSnapshot struct {
pluginID string
vmKey string
watchCancel context.CancelFunc
cancel context.CancelFunc
ephemeralGrant bool
secretSetting string
}
var prevSnap *replacedSessionSnapshot
a.sessionMu.Lock()
if a.ephemeralVMAccess != nil && a.ephemeralVMAccess[pluginID] != nil && a.ephemeralVMAccess[pluginID][key] {
ephemeral = true
}
if a.agentSessions == nil {
a.agentSessions = map[string]*agentSession{}
}
delete(a.completedOverlays, key)
if existing := a.agentSessions[key]; existing != nil {
if existing.pluginID == pluginID {
if label != "" {
existing.label = label
}
if stage != "" {
existing.stage = stage
}
if takeoverPolicy != "" {
existing.takeoverPolicy = takeoverPolicy
}
if ephemeral {
existing.ephemeralGrant = true
}
if vm.Directory != "" && existing.vmDir == "" {
existing.vmDir = vm.Directory
}
if isAuto {
existing.isAutoInstall = true
}
unbound := existing.lastOverlayPID == 0
if unbound && existing.unboundSince.IsZero() {
existing.unboundSince = time.Now()
}
a.sessionMu.Unlock()
cancel()
if a.suppressInstallGuideForVM(vm.Name) {
a.sessionMu.Lock()
if cur := a.agentSessions[key]; cur == existing {
cur.suppressedInstallGuide = true
}
a.sessionMu.Unlock()
}
a.markInstallGuideRecheck(vm.Name)
a.refreshAgentSessionVisuals(key)
a.syncTakeoverTargets()
if unbound {
a.wakePoll()
}
a.emitStateChangedEvent()
return
}
prevSnap = &replacedSessionSnapshot{
pluginID: existing.pluginID,
vmKey: existing.vmKey,
watchCancel: existing.watchCancel,
cancel: existing.cancel,
ephemeralGrant: existing.ephemeralGrant,
secretSetting: existing.secretSetting,
}
}
now := time.Now()
sess := &agentSession{
vmKey: key,
driverID: vm.DriverID,
vmName: vm.Name,
vmDir: vm.Directory,
pluginID: pluginID,
pluginName: pName,
label: label,
stage: stage,
status: "running",
takeoverPolicy: takeoverPolicy,
startedAt: now,
unboundSince: now,
ephemeralGrant: ephemeral,
isAutoInstall: isAuto,
ctx: sctx,
cancel: cancel,
}
a.agentSessions[key] = sess
a.sessionMu.Unlock()
if prevSnap != nil {
if prevSnap.watchCancel != nil {
prevSnap.watchCancel()
}
if prevSnap.cancel != nil {
prevSnap.cancel()
}
a.revokeProtectedPhaseForPluginVM(prevSnap.pluginID, prevSnap.vmKey, "session_replaced")
if prevSnap.ephemeralGrant {
a.revokeEphemeralVMAccess(prevSnap.pluginID, prevSnap.vmKey)
}
if mgr != nil {
if prevSnap.secretSetting != "" {
_ = mgr.SetSettings(prevSnap.pluginID, prevSnap.vmKey, map[string]any{prevSnap.secretSetting: ""})
}
mgr.NotifySidecar(prevSnap.pluginID, "session/stopped", map[string]any{
"vm": prevSnap.vmKey,
"reason": "session_replaced",
})
if mgr.Broker() != nil {
mgr.Broker().Audit(prevSnap.pluginID, "SESSION_END", prevSnap.vmKey+" session_replaced")
}
}
}
// Suppress any manual text install guide while an Agent/auto-install session owns the VM.
if a.suppressInstallGuideForVM(vm.Name) {
a.sessionMu.Lock()
if cur := a.agentSessions[key]; cur == sess {
cur.suppressedInstallGuide = true
}
a.sessionMu.Unlock()
}
a.markInstallGuideRecheck(vm.Name)
if mgr != nil && mgr.Broker() != nil {
mgr.Broker().Audit(pluginID, "SESSION_BEGIN", key)
}
a.refreshAgentSessionVisuals(key)
a.syncTakeoverTargets()
a.wakePoll()
a.emitStateChangedEvent()
}
func (a *App) ensureAgentSessionForWrite(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) {
key := vm.Ref().Key()
a.sessionMu.Lock()
sess := a.agentSessions[key]
a.sessionMu.Unlock()
if sess != nil && sess.pluginID == pluginID {
return
}
a.beginAgentSession(mgr, pluginID, vm, "", "", "auto", false)
}
func (a *App) hasActiveAgentSessions() bool {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
return len(a.agentSessions) > 0
}
const sessionDiscoverGraceWindow = 30 * time.Second
func (a *App) hasUnboundAgentSession() bool {
type unboundRef struct {
vmKey string
driverID string
vmName string
startedAt time.Time
unboundSince time.Time
}
a.sessionMu.Lock()
var unbound []unboundRef
for key, s := range a.agentSessions {
if s != nil && s.lastOverlayPID == 0 {
unbound = append(unbound, unboundRef{
vmKey: key,
driverID: s.driverID,
vmName: s.vmName,
startedAt: s.startedAt,
unboundSince: s.unboundSince,
})
}
}
a.sessionMu.Unlock()
if len(unbound) == 0 {
return false
}
now := time.Now()
a.mu.Lock()
var activeTransitions map[string]string
if len(a.transitions) > 0 {
activeTransitions = make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
activeTransitions[k] = v
}
}
var cachedStates map[string]string
if len(a.lastVMs) > 0 {
cachedStates = make(map[string]string, len(a.lastVMs))
for _, vm := range a.lastVMs {
cachedStates[vmKeyForDriver(vm.DriverID, vm.Name)] = vm.State
}
}
a.mu.Unlock()
for _, u := range unbound {
if tr := activeTransitions[u.vmKey]; tr == "starting" || tr == "resuming" {
return true
}
since := u.unboundSince
if since.IsZero() {
since = u.startedAt
}
state, known := cachedStates[u.vmKey]
if !known {
if now.Sub(since) < sessionDiscoverGraceWindow {
return true
}
continue
}
if state == "running" && now.Sub(since) < sessionDiscoverGraceWindow {
return true
}
}
return false
}
// bindAgentSessionPID immediately attaches a freshly observed live VM PID to an
// active Agent session so the overlay appears without waiting for the next poll.
func (a *App) bindAgentSessionPID(vmKey string, pid uint32) {
if vmKey == "" || pid == 0 {
return
}
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil || sess.lastOverlayPID == pid {
a.sessionMu.Unlock()
return
}
sess.lastOverlayPID = pid
sess.unboundSince = time.Time{}
a.sessionMu.Unlock()
a.refreshAgentSessionVisualsWithPID(vmKey, pid)
a.syncTakeoverTargets()
}
// refreshActiveAgentSessionAfterStart refreshes overlay PID binding and input
// lock targets immediately after a VM starts, resumes, or restarts.
func (a *App) refreshActiveAgentSessionAfterStart(vmKey string) {
if !a.hasActiveAgentSession(vmKey) {
return
}
a.refreshAgentSessionVisuals(vmKey)
a.syncTakeoverTargets()
}
// rebindAgentSessionAfterRestart clears any stale pre-restart PID cache on the
// active session, probes the freshly launched VM PID, and rebinds the overlay
// and input lock to the new VM window immediately.
func (a *App) rebindAgentSessionAfterRestart(vmKey string) uint32 {
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil {
a.sessionMu.Unlock()
return 0
}
sess.lastOverlayPID = 0
sess.unboundSince = time.Now()
sess.lastPIDProbeAt = time.Time{}
driverID := sess.driverID
vmName := sess.vmName
a.sessionMu.Unlock()
pid, _ := a.probeFreshVMPID(vmKey, driverID, vmName)
if pid > 0 {
a.bindAgentSessionPID(vmKey, pid)
return pid
}
a.refreshActiveAgentSessionAfterStart(vmKey)
return 0
}
func (a *App) endAgentSession(mgr *plugin.Manager, pluginID, vmKey, reason string) {
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil || (pluginID != "" && sess.pluginID != pluginID) {
a.sessionMu.Unlock()
return
}
delete(a.agentSessions, vmKey)
completed := strings.EqualFold(strings.TrimSpace(sess.status), "completed")
a.sessionMu.Unlock()
sess.cancel()
if sess.ephemeralGrant {
a.revokeEphemeralVMAccess(sess.pluginID, vmKey)
}
if mgr == nil {
a.mu.Lock()
mgr = a.pluginMgr
a.mu.Unlock()
}
if mgr != nil && sess.secretSetting != "" && (!completed || !sess.saveUnlockCredential) {
_ = mgr.SetSettings(sess.pluginID, vmKey, map[string]any{sess.secretSetting: ""})
}
if reason == "confirmation_denied" || reason == "permission_denied" {
a.revokeApprovedProtectedPhaseForPluginVM(sess.pluginID, vmKey, reason)
} else {
a.revokeProtectedPhaseForPluginVM(sess.pluginID, vmKey, reason)
}
handOffToGuide := a.prepareInstallGuideRestoreAfterSession(sess, completed)
showCompleted := false
removeOverlay := false
a.sessionMu.Lock()
if a.agentSessions[vmKey] == nil {
if completed && !handOffToGuide {
if a.completedOverlays == nil {
a.completedOverlays = map[string]completedOverlayEntry{}
}
a.completedOverlays[vmKey] = completedOverlayEntry{
pluginID: sess.pluginID,
driverID: sess.driverID,
vmName: sess.vmName,
pid: sess.lastOverlayPID,
}
showCompleted = true
} else {
delete(a.completedOverlays, vmKey)
removeOverlay = true
}
}
ov := a.sessionOverlay
a.sessionMu.Unlock()
if showCompleted {
a.showCompletedSessionOverlay(sess)
} else if removeOverlay && ov != nil {
ov.Remove(vmKey)
}
if mgr != nil && mgr.Broker() != nil {
mgr.Broker().Audit(sess.pluginID, "SESSION_END", vmKey+" "+reason)
}
a.syncTakeoverTargets()
if handOffToGuide || isMacOSDriverID(sess.driverID) {
a.wakePoll()
}
a.emitStateChangedEvent()
}
func (a *App) isCompletedOverlay(vmKey string) bool {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
_, ok := a.completedOverlays[vmKey]
return ok
}
func (a *App) dismissCompletedOverlay(vmKey string) {
if vmKey == "" {
return
}
a.sessionMu.Lock()
delete(a.completedOverlays, vmKey)
ov := a.sessionOverlay
a.sessionMu.Unlock()
if ov != nil {
ov.Remove(vmKey)
}
}
func (a *App) dismissCompletedOverlayByUser(vmKey string) {
if vmKey == "" {
return
}
a.sessionMu.Lock()
ent, had := a.completedOverlays[vmKey]
delete(a.completedOverlays, vmKey)
ov := a.sessionOverlay
a.sessionMu.Unlock()
if ov != nil {
ov.Remove(vmKey)
}
if had && ent.vmName != "" && isMacOSDriverID(ent.driverID) {
a.markInstallGuideRecheck(ent.vmName)
a.wakePoll()
}
}
func (a *App) completedSessionOverlayState(loc i18n.Locale, sess *agentSession, pid uint32, dark bool) sessionoverlay.State {
title := strings.TrimSpace(sess.pluginName)
if title == "" {
title = i18n.T(loc, "agent.session.completed_title")
}
statusLine := strings.TrimSpace(sess.message)
if statusLine == "" {
statusLine = i18n.T(loc, "agent.session.completed_status")
}
return sessionoverlay.State{
VMKey: sess.vmKey,
PID: pid,
Locale: string(loc),
Title: title,
StepBadge: i18n.T(loc, "agent.session.step_badge"),
StepText: i18n.T(loc, "agent.session.stage.completed"),
StatusLine: statusLine,
Completed: true,
CanPause: false,
CanResume: false,
CloseLabel: i18n.T(loc, "agent.session.close"),
CollapseLabel: i18n.T(loc, "agent.session.collapse"),
InputLocked: false,
Dark: dark,
}
}
func (a *App) showCompletedSessionOverlay(sess *agentSession) {
if sess == nil {
return
}
a.mu.Lock()
hasWindow := a.ctx != nil
dark := a.themeMode != "light"
a.mu.Unlock()
if !hasWindow {
return
}
pid := sess.lastOverlayPID
if polled, ok := a.polledVMForDriver(sess.driverID, sess.vmName); ok {
if polled.State == "running" && polled.PID != nil && *polled.PID > 0 {
pid = uint32(*polled.PID)
} else if polled.State == "stopped" || polled.State == "suspended" {
pid = 0
}
}
if pid == 0 {
a.dismissCompletedOverlay(sess.vmKey)
return
}
a.sessionMu.Lock()
if ent, ok := a.completedOverlays[sess.vmKey]; ok {
ent.pid = pid
a.completedOverlays[sess.vmKey] = ent
}
a.sessionMu.Unlock()
loc := a.computerUseLocale()
if ov := a.ensureSessionOverlay(); ov != nil {
ov.Upsert(a.completedSessionOverlayState(loc, sess, pid, dark))
}
}
// stopAgentSessionsForInactivePlugins tears down any live Agent/auto-install
// sessions whose owning plugin is no longer active (for example when the user
// disables the plugin mid-run), removing the VM-window overlay, unlocking input,
// and revoking ephemeral and protected-phase grants.
func (a *App) stopAgentSessionsForInactivePlugins(mgr *plugin.Manager) {
if mgr == nil || mgr.Registry() == nil {
return
}
reg := mgr.Registry()
var stale []*agentSession
type staleCompletedItem struct {
key string
ent completedOverlayEntry
}
var staleCompleted []staleCompletedItem
a.sessionMu.Lock()
for key, sess := range a.agentSessions {
if sess != nil && !reg.IsActive(sess.pluginID) {
stale = append(stale, sess)
delete(a.agentSessions, key)
}
}
for key, ent := range a.completedOverlays {
if !reg.IsActive(ent.pluginID) {
staleCompleted = append(staleCompleted, staleCompletedItem{key: key, ent: ent})
delete(a.completedOverlays, key)
}
}
ov := a.sessionOverlay
a.sessionMu.Unlock()
a.revokeProtectedPhaseForInactivePlugins(reg, mgr.Broker(), "plugin_disabled")
if len(stale) == 0 && len(staleCompleted) == 0 {
return
}
restoreGuides := false
for _, item := range staleCompleted {
if ov != nil {
ov.Remove(item.key)
}
if item.ent.vmName != "" && isMacOSDriverID(item.ent.driverID) {
a.markInstallGuideRecheck(item.ent.vmName)
restoreGuides = true
}
}
for _, sess := range stale {
sess.cancel()
a.revokeProtectedPhaseForPluginVM(sess.pluginID, sess.vmKey, "plugin_disabled")
if sess.ephemeralGrant {
a.revokeEphemeralVMAccess(sess.pluginID, sess.vmKey)
}
if sess.secretSetting != "" {
_ = mgr.SetSettings(sess.pluginID, sess.vmKey, map[string]any{sess.secretSetting: ""})
}
if ov != nil {
ov.Remove(sess.vmKey)
}
if mgr.Broker() != nil {
mgr.Broker().Audit(sess.pluginID, "SESSION_END", sess.vmKey+" plugin_disabled")
}
if a.prepareInstallGuideRestoreAfterSession(sess, false) || isMacOSDriverID(sess.driverID) {
restoreGuides = true
}
}
a.syncTakeoverTargets()
if restoreGuides {
a.wakePoll()
}
a.emitStateChangedEvent()
}
// StopAgentSession immediately cancels the active Agent/auto-install session on
// the VM, revokes protected-phase authorization, notifies the plugin via
// `session/stopped`, and tears down the VM-window overlay.
func (a *App) StopAgentSession(driverID, name string) error {
key := vmKeyForDriver(driverID, name)
a.sessionMu.Lock()
sess := a.agentSessions[key]
if sess != nil {
delete(a.agentSessions, key)
}
completedEnt, hadCompleted := a.completedOverlays[key]
delete(a.completedOverlays, key)
ov := a.sessionOverlay
a.sessionMu.Unlock()
a.revokeProtectedPhaseForVM(key, "user_stopped")
if ov != nil {
ov.Remove(key)
}
a.syncTakeoverTargets()
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
restoreGuide := false
if sess != nil {
sess.cancel()
if sess.ephemeralGrant {
a.revokeEphemeralVMAccess(sess.pluginID, key)
}
if mgr != nil {
if sess.secretSetting != "" {
_ = mgr.SetSettings(sess.pluginID, key, map[string]any{sess.secretSetting: ""})
}
mgr.NotifySidecar(sess.pluginID, "session/stopped", map[string]any{
"vm": key,
"reason": "user_stopped",
})
if mgr.Broker() != nil {
mgr.Broker().Audit(sess.pluginID, "SESSION_STOP", key)
}
}
if a.prepareInstallGuideRestoreAfterSession(sess, false) || isMacOSDriverID(sess.driverID) {
restoreGuide = true
}
} else if hadCompleted && completedEnt.vmName != "" && isMacOSDriverID(completedEnt.driverID) {
a.markInstallGuideRecheck(completedEnt.vmName)
restoreGuide = true
}
if restoreGuide {
a.wakePoll()
}
a.emitStateChangedEvent()
return nil
}
// PauseAgentSession pauses an active Agent/auto-install session on the VM,
// immediately unlocks physical mouse/keyboard input on the VM window, and
// notifies the owning Sidecar (`session/paused`).
func (a *App) PauseAgentSession(driverID, name string) error {
key := vmKeyForDriver(driverID, name)
loc := a.computerUseLocale()
a.sessionMu.Lock()
sess := a.agentSessions[key]
if sess == nil {
a.sessionMu.Unlock()
return nil
}
sess.pausedForUser = true
sess.hostPaused = true
sess.status = "paused_for_user"
sess.message = i18n.T(loc, "agent.session.paused_by_user")
pluginID := sess.pluginID
a.sessionMu.Unlock()
a.syncTakeoverTargets()
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.NotifySidecar(pluginID, "session/paused", map[string]any{
"vm": key,
"reason": "user_paused",
})
if mgr.Broker() != nil {
mgr.Broker().Audit(pluginID, "SESSION_PAUSE", key)
}
}
a.refreshAgentSessionVisuals(key)
a.emitStateChangedEvent()
return nil
}
// ResumeAgentSession clears a takeover or paused_for_user hold on the VM,
// restores any session input lock, and notifies the owning Sidecar (`session/resumed`).
func (a *App) ResumeAgentSession(driverID, name string) error {
key := vmKeyForDriver(driverID, name)
a.sessionMu.Lock()
sess := a.agentSessions[key]
if sess == nil {
a.sessionMu.Unlock()
return nil
}
sess.takeoverPaused = false
sess.takeoverUntil = time.Time{}
sess.pausedForUser = false
sess.hostPaused = false
if sess.status == "paused_for_user" {
sess.status = "running"
sess.message = ""
}
pluginID := sess.pluginID
a.sessionMu.Unlock()
a.syncTakeoverTargets()
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.NotifySidecar(pluginID, "session/resumed", map[string]any{"vm": key})
if mgr.Broker() != nil {
mgr.Broker().Audit(pluginID, "SESSION_RESUME", key)
}
}
a.refreshAgentSessionVisuals(key)
a.emitStateChangedEvent()
return nil
}
func (a *App) handlePhysicalUserTakeover(vmKey, reason string) {
now := time.Now()
a.mu.Lock()
pauseSec := 5
if a.cfg != nil {
pauseSec = a.cfg.EffectiveAgentTakeoverPauseSec()
}
mgr := a.pluginMgr
a.mu.Unlock()
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil {
a.sessionMu.Unlock()
return
}
manual := pauseSec == 0 || sess.takeoverPolicy == "manual"
wasPaused := sess.takeoverPaused
sess.takeoverPaused = true
if manual {
sess.takeoverUntil = time.Time{}
sess.pausedForUser = true
sess.hostPaused = true
} else {
sess.takeoverUntil = now.Add(time.Duration(pauseSec) * time.Second)
}
pluginID := sess.pluginID
a.sessionMu.Unlock()
if mgr != nil {
mgr.NotifySidecar(pluginID, "console/userTakeover", map[string]any{
"vm": vmKey,
"reason": reason,
"manual_resume": manual,
"pause_seconds": pauseSec,
})
if !wasPaused && mgr.Broker() != nil {
mgr.Broker().Audit(pluginID, "SESSION_TAKEOVER", vmKey+" "+reason)
}
}
a.refreshAgentSessionVisuals(vmKey)
a.emitStateChangedEvent()
}
func (a *App) checkUserTakeover(vmKey, vmName string) error {
now := time.Now()
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil {
a.sessionMu.Unlock()
return nil
}
if sess.takeoverPaused {
if !sess.takeoverUntil.IsZero() && !now.Before(sess.takeoverUntil) {
sess.takeoverPaused = false
sess.takeoverUntil = time.Time{}
a.sessionMu.Unlock()
a.refreshAgentSessionVisuals(vmKey)
return nil
}
a.sessionMu.Unlock()
return a.computerUseHostError("user_takeover", "err.computer_use.user_takeover", i18n.Vars{"name": vmName})
}
if sess.pausedForUser {
a.sessionMu.Unlock()
return a.computerUseHostError("session_paused", "err.computer_use.session_paused", i18n.Vars{"name": vmName})
}
a.sessionMu.Unlock()
return nil
}
// withSessionContext derives a call context that cancels immediately when the
// user clicks Stop on the VM's active session.
func (a *App) withSessionContext(ctx context.Context, vmKey string) (context.Context, context.CancelFunc) {
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
var sctx context.Context
if sess != nil {
sctx = sess.ctx
}
a.sessionMu.Unlock()
if sctx == nil {
return ctx, func() {}
}
derived, cancel := context.WithCancel(ctx)
stop := context.AfterFunc(sctx, cancel)
return derived, func() {
stop()
cancel()
}
}
func (a *App) hasActiveAgentSession(vmKey string) bool {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
return a.agentSessions[vmKey] != nil
}
func (a *App) grantEphemeralVMAccess(pluginID, vmKey string) {
a.sessionMu.Lock()
if a.ephemeralVMAccess == nil {
a.ephemeralVMAccess = map[string]map[string]bool{}
}
if a.ephemeralVMAccess[pluginID] == nil {
a.ephemeralVMAccess[pluginID] = map[string]bool{}
}
a.ephemeralVMAccess[pluginID][vmKey] = true
a.sessionMu.Unlock()
}
func (a *App) revokeEphemeralVMAccess(pluginID, vmKey string) {
a.sessionMu.Lock()
if m := a.ephemeralVMAccess[pluginID]; m != nil {
delete(m, vmKey)
if len(m) == 0 {
delete(a.ephemeralVMAccess, pluginID)
}
}
a.sessionMu.Unlock()
}
func (a *App) hasEphemeralVMAccess(pluginID, vmKey string) bool {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
return a.ephemeralVMAccess != nil && a.ephemeralVMAccess[pluginID] != nil && a.ephemeralVMAccess[pluginID][vmKey]
}
// activeAgentSessions returns live snapshots of all active remote-control sessions.
func (a *App) activeAgentSessions() []AgentSessionView {
now := time.Now()
loc := a.computerUseLocale()
a.sessionMu.Lock()
views := make([]AgentSessionView, 0, len(a.agentSessions))
for _, s := range a.agentSessions {
if s.takeoverPaused && !s.takeoverUntil.IsZero() && !now.Before(s.takeoverUntil) {
s.takeoverPaused = false
s.takeoverUntil = time.Time{}
}
running := s.status == "" || s.status == "running"
inputLocked := s.takeoverPolicy == "lock" && running && !s.pausedForUser && !s.takeoverPaused
v := AgentSessionView{
VMKey: s.vmKey,
DriverID: s.driverID,
VMName: s.vmName,
PluginID: s.pluginID,
PluginName: s.pluginName,
Label: s.label,
Stage: s.stage,
StageLabel: stageKnownName(loc, s.stage),
Status: s.status,
Message: s.message,
TakeoverPolicy: s.takeoverPolicy,
InputLocked: inputLocked,
PausedForUser: s.pausedForUser,
TakeoverPaused: s.takeoverPaused,
TakeoverManualWait: s.takeoverPaused && s.takeoverUntil.IsZero(),
StartedAt: s.startedAt.UTC().Format(time.RFC3339),
}
if s.takeoverPaused && !s.takeoverUntil.IsZero() {
rem := int(s.takeoverUntil.Sub(now).Seconds()) + 1
if rem < 0 {
rem = 0
}
v.TakeoverRemainSec = rem
}
views = append(views, v)
}
a.sessionMu.Unlock()
for i := range views {
if grant, ok := a.lookupProtectedPhaseGrant(views[i].PluginID, views[i].VMKey); ok && grant.isActive(now) {
views[i].Phase = grant.phase
views[i].AuthUntilPhaseExit = grant.untilPhaseExit
views[i].AuthRemainingSec = grant.remainingSeconds(now)
}
}
sort.Slice(views, func(i, j int) bool { return views[i].VMKey < views[j].VMKey })
return views
}
// syncAutoInstallSessionProgress mirrors stage/message updates returned by
// autoinstall/status into the live Agent session so the VM overlay always
// reflects the latest step even if the plugin did not emit a separate push.
func (a *App) syncAutoInstallSessionProgress(vmKey, pluginID, stage, message string) {
stage = strings.TrimSpace(stage)
message = strings.TrimSpace(message)
if vmKey == "" || (stage == "" && message == "") {
return
}
changed := false
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess != nil && (pluginID == "" || sess.pluginID == pluginID) {
if sess.isAutoInstall && sess.autoInstallMode == "recovery_only" && stage == "stage5_setup_assistant" {
stage = "stage5_wait_reboot"
}
if stage != "" && sess.stage != stage {
sess.stage = stage
changed = true
}
if message != "" && !sess.pausedForUser && !sess.takeoverPaused && sess.message != message {
sess.message = message
changed = true
}
}
a.sessionMu.Unlock()
if changed {
a.refreshAgentSessionVisuals(vmKey)
}
}
func isMachineStageID(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r > 127 || unicode.IsSpace(r) {
return false
}
}
return strings.ContainsAny(s, "_-.") || strings.HasPrefix(strings.ToLower(s), "stage") || strings.HasPrefix(strings.ToLower(s), "step")
}
func stageKnownName(loc i18n.Locale, slug string) string {
s := strings.ToLower(strings.Trim(slug, "_-. "))
switch {
case s == "":
return ""
case strings.Contains(s, "preflight") || strings.Contains(s, "prepare") || strings.Contains(s, "init"):
return i18n.T(loc, "agent.session.stage.preflight")
case strings.Contains(s, "reboot") || strings.Contains(s, "restart"):
return i18n.T(loc, "agent.session.stage.reboot")
case strings.Contains(s, "recovery") || strings.Contains(s, "boot"):
return i18n.T(loc, "agent.session.stage.boot_recovery")
case strings.Contains(s, "offline_terminal") || strings.Contains(s, "terminal"):
return i18n.T(loc, "agent.session.stage.offline_terminal")
case strings.Contains(s, "disk") || strings.Contains(s, "erase") || strings.Contains(s, "format") || strings.Contains(s, "apfs"):
return i18n.T(loc, "agent.session.stage.disk_utility")
case strings.Contains(s, "install_wait"):
return i18n.T(loc, "agent.session.stage.install_wait")
case strings.Contains(s, "finish_install"):
return i18n.T(loc, "agent.session.stage.finish_install")
case strings.Contains(s, "tools") || strings.Contains(s, "post_install") || strings.Contains(s, "guest"):
return i18n.T(loc, "agent.session.stage.guest_tools")
case strings.Contains(s, "reinstall") || strings.Contains(s, "install_macos") || strings.Contains(s, "macos_install") || s == "install":
return i18n.T(loc, "agent.session.stage.install_macos")
case strings.Contains(s, "setup") || strings.Contains(s, "assistant") || strings.Contains(s, "oobe"):
return i18n.T(loc, "agent.session.stage.setup_assistant")
case strings.Contains(s, "account") || strings.Contains(s, "user") || strings.Contains(s, "provision"):
return i18n.T(loc, "agent.session.stage.account")
case strings.Contains(s, "desktop") || strings.Contains(s, "verify"):
return i18n.T(loc, "agent.session.stage.desktop")
case strings.Contains(s, "complete") || strings.Contains(s, "done") || strings.Contains(s, "finish"):
return i18n.T(loc, "agent.session.stage.completed")
default:
return ""
}
}
func humanizeStageSlug(slug string) string {
parts := strings.FieldsFunc(slug, func(r rune) bool {
return r == '_' || r == '-' || r == '.'
})
for i, p := range parts {
if len(p) == 0 {
continue
}
lower := strings.ToLower(p)
switch lower {
case "macos":
parts[i] = "macOS"
case "ocr", "apfs", "vm", "ui", "ssh":
parts[i] = strings.ToUpper(lower)
default:
parts[i] = strings.ToUpper(lower[:1]) + lower[1:]
}
}
return strings.Join(parts, " ")
}
func formatSessionStage(loc i18n.Locale, rawStage string) string {
raw := strings.TrimSpace(rawStage)
if raw == "" {
return ""
}
if !isMachineStageID(raw) {
return raw
}
lower := strings.ToLower(raw)
stepNum := ""
rest := raw
for _, prefix := range []string{"stage", "step"} {
if strings.HasPrefix(lower, prefix) {
tail := raw[len(prefix):]
tail = strings.TrimLeft(tail, "_-.")
digits := 0
for digits < len(tail) && tail[digits] >= '0' && tail[digits] <= '9' {
digits++
}
if digits > 0 {
if n, err := strconv.Atoi(tail[:digits]); err == nil {
if n > 0 {
stepNum = strconv.Itoa(n)
}
rest = tail[digits:]
if len(rest) >= 2 && ((rest[0] >= 'a' && rest[0] <= 'z') || (rest[0] >= 'A' && rest[0] <= 'Z')) &&
(rest[1] == '_' || rest[1] == '-' || rest[1] == '.') {
rest = rest[1:]
}
rest = strings.TrimLeft(rest, "_-.")
}
}
break
}
}
name := stageKnownName(loc, rest)
if name == "" {
name = humanizeStageSlug(rest)
}
if stepNum != "" && name != "" {
return i18n.M(loc, "agent.session.step_numbered", i18n.Vars{"num": stepNum, "name": name})
}
if name != "" {
return name
}
return raw
}
func (a *App) sessionOverlayStep(loc i18n.Locale, view AgentSessionView) string {
if strings.EqualFold(strings.TrimSpace(view.Status), "completed") {
return i18n.T(loc, "agent.session.stage.completed")
}
if step := formatSessionStage(loc, view.Stage); step != "" {
return step
}
if view.Phase == driver.PhaseInstaller || view.Phase == driver.PhaseRecovery {
return i18n.M(loc, "err.computer_use.phase."+view.Phase, nil)
}
if view.PausedForUser || view.TakeoverPaused {
return i18n.T(loc, "agent.session.step_paused")
}
return i18n.T(loc, "agent.session.step_running")
}
func (a *App) sessionOverlayStatusLine(loc i18n.Locale, view AgentSessionView, stepText string) string {
switch {
case view.TakeoverManualWait:
return i18n.T(loc, "agent.session.takeover_manual")
case view.TakeoverPaused && view.TakeoverRemainSec > 0:
return i18n.M(loc, "agent.session.takeover_countdown", i18n.Vars{"seconds": view.TakeoverRemainSec})
case view.PausedForUser && view.Message != "":
return view.Message
case view.PausedForUser:
return i18n.T(loc, "agent.session.paused_manual")
case view.InputLocked && view.Message != "":
return i18n.T(loc, "agent.session.locked_prefix") + view.Message
case view.InputLocked:
return i18n.T(loc, "agent.session.locked_status")
case view.Message != "":
return view.Message
case view.PluginName != "" && view.PluginName != stepText:
return view.PluginName
default:
return ""
}
}
func (a *App) sessionBannerText(loc i18n.Locale, view AgentSessionView) (title, statusLine string) {
if view.Label != "" {
title = view.Label
} else {
title = i18n.M(loc, "agent.session.banner", i18n.Vars{"plugin": view.PluginName})
}
if view.Phase == driver.PhaseInstaller || view.Phase == driver.PhaseRecovery {
phaseLabel := i18n.M(loc, "err.computer_use.phase."+view.Phase, nil)
if view.AuthUntilPhaseExit {
title = i18n.M(loc, "agent.session.phase_banner", i18n.Vars{"phase": phaseLabel})
} else if view.AuthRemainingSec > 0 {
mins := (view.AuthRemainingSec + 59) / 60
title = i18n.M(loc, "agent.session.phase_banner_timer", i18n.Vars{"phase": phaseLabel, "minutes": mins})
}
}
switch {
case view.TakeoverManualWait:
statusLine = i18n.T(loc, "agent.session.takeover_manual")
case view.TakeoverPaused && view.TakeoverRemainSec > 0:
statusLine = i18n.M(loc, "agent.session.takeover_countdown", i18n.Vars{"seconds": view.TakeoverRemainSec})
case view.PausedForUser && view.Message != "":
statusLine = view.Message
case view.PausedForUser:
statusLine = i18n.T(loc, "agent.session.paused_manual")
case view.InputLocked && view.Message != "":
statusLine = i18n.T(loc, "agent.session.locked_prefix") + view.Message
case view.InputLocked && view.Stage != "":
statusLine = i18n.T(loc, "agent.session.locked_prefix") + view.Stage
case view.InputLocked:
statusLine = i18n.T(loc, "agent.session.locked_status")
case view.Message != "":
statusLine = view.Message
case view.Stage != "":
statusLine = view.Stage
default:
statusLine = view.PluginName
}
return title, statusLine
}
func (a *App) ensureSessionOverlay() *sessionoverlay.Manager {
a.sessionMu.Lock()
defer a.sessionMu.Unlock()
if a.sessionOverlay == nil && !a.sessionShuttingDown {
a.sessionOverlay = sessionoverlay.NewManager(sessionoverlay.Callbacks{
OnStop: func(vmKey string) {
if ref, ok := driver.ParseVMRef(vmKey); ok {
_ = a.StopAgentSession(ref.DriverID, ref.Name)
} else {
_ = a.StopAgentSession("", vmKey)
}
},
OnPause: func(vmKey string) {
if ref, ok := driver.ParseVMRef(vmKey); ok {
_ = a.PauseAgentSession(ref.DriverID, ref.Name)
} else {
_ = a.PauseAgentSession("", vmKey)
}
},
OnResume: func(vmKey string) {
if ref, ok := driver.ParseVMRef(vmKey); ok {
_ = a.ResumeAgentSession(ref.DriverID, ref.Name)
} else {
_ = a.ResumeAgentSession("", vmKey)
}
},
OnDismiss: func(vmKey string) {
a.dismissCompletedOverlayByUser(vmKey)
},
})
}
return a.sessionOverlay
}
func (a *App) refreshAgentSessionVisuals(vmKey string) {
a.refreshAgentSessionVisualsWithPID(vmKey, 0)
}
func (a *App) probeFreshVMPID(vmKey, driverID, vmName string) (uint32, bool) {
now := time.Now()
a.sessionMu.Lock()
sess := a.agentSessions[vmKey]
if sess == nil || (!sess.lastPIDProbeAt.IsZero() && now.Sub(sess.lastPIDProbeAt) < 300*time.Millisecond) {
a.sessionMu.Unlock()
return 0, false
}
sess.lastPIDProbeAt = now
a.sessionMu.Unlock()
pctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
vms, err := a.listVMsInternal(pctx)
cancel()
if err != nil {
return 0, false
}
wantDriver := driver.CanonicalDriverID(driverID)
if wantDriver == "" {
wantDriver = driver.BuiltinReimsMacOSDriverID
}
for _, vm := range vms {
if vm.Name == vmName && driver.CanonicalDriverID(vm.DriverID) == wantDriver && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
a.mu.Lock()
a.lastVMs = append([]driver.VMListItem(nil), vms...)
a.lastVMsAt = time.Now()
a.mu.Unlock()
return uint32(*vm.PID), true
}
}
return 0, true
}
func (a *App) refreshAgentSessionVisualsWithPID(vmKey string, pidHint uint32) {
a.mu.Lock()
hasWindow := a.ctx != nil
dark := a.themeMode != "light"
a.mu.Unlock()
if !hasWindow {
return
}
var target *AgentSessionView
for _, v := range a.activeAgentSessions() {
if v.VMKey == vmKey {
cp := v
target = &cp
break
}
}
if target == nil {
a.sessionMu.Lock()
ov := a.sessionOverlay
a.sessionMu.Unlock()
if ov != nil && !a.isCompletedOverlay(vmKey) {
ov.Remove(vmKey)
}
return
}
pid := pidHint
vmStopped := false
if pid == 0 {
if polled, ok := a.polledVMForDriver(target.DriverID, target.VMName); ok {
if polled.State == "running" && polled.PID != nil && *polled.PID > 0 {
pid = uint32(*polled.PID)
} else if polled.State == "stopped" || polled.State == "suspended" {
vmStopped = true
}
}
}
probed := false
if pid == 0 {
// Bypass the stale 13s polled cache right after VM start/restart so the
// floating island attaches to the QEMU window immediately.
pid, probed = a.probeFreshVMPID(vmKey, target.DriverID, target.VMName)
}
a.sessionMu.Lock()
if sess := a.agentSessions[vmKey]; sess != nil {
if pid > 0 {
sess.lastOverlayPID = pid
sess.unboundSince = time.Time{}
} else if probed || vmStopped {
if sess.lastOverlayPID != 0 {
sess.unboundSince = time.Now()
}
sess.lastOverlayPID = 0
} else {
// Probe was rate-limited or transiently failed; preserve any already-bound PID
// so concurrent refreshes cannot clobber a freshly bound live PID back to 0.
pid = sess.lastOverlayPID
}
}
a.sessionMu.Unlock()
loc := a.computerUseLocale()
completed := strings.EqualFold(strings.TrimSpace(target.Status), "completed")
title, _ := a.sessionBannerText(loc, *target)
if completed {
if strings.TrimSpace(target.PluginName) != "" {
title = strings.TrimSpace(target.PluginName)
} else {
title = i18n.T(loc, "agent.session.completed_title")
}
}
stepText := a.sessionOverlayStep(loc, *target)
status := a.sessionOverlayStatusLine(loc, *target, stepText)
paused := target.PausedForUser || target.TakeoverPaused
if ov := a.ensureSessionOverlay(); ov != nil {
ov.Upsert(sessionoverlay.State{
VMKey: vmKey,
PID: pid,
Locale: string(loc),
Title: title,
StepBadge: i18n.T(loc, "agent.session.step_badge"),
StepText: stepText,
StatusLine: status,
Completed: completed,
CanPause: !paused && !completed,
PauseLabel: i18n.T(loc, "agent.session.pause"),
CanResume: paused && !completed,
ResumeLabel: i18n.T(loc, "agent.session.resume"),
StopLabel: i18n.T(loc, "agent.session.stop"),
CloseLabel: i18n.T(loc, "agent.session.close"),
CollapseLabel: i18n.T(loc, "agent.session.collapse"),
InputLocked: target.InputLocked && !completed,
Dark: dark,
})
}
}
func (a *App) syncTakeoverTargets() {
a.mu.Lock()
hasWindow := a.ctx != nil
a.mu.Unlock()
if !hasWindow {
return
}
sessions := a.activeAgentSessions()
targets := make(map[uint32]host.TakeoverTarget, len(sessions))
for _, s := range sessions {
var pid uint32
if polled, ok := a.polledVMForDriver(s.DriverID, s.VMName); ok && polled.State == "running" && polled.PID != nil && *polled.PID > 0 {
pid = uint32(*polled.PID)
} else {
a.sessionMu.Lock()
if live := a.agentSessions[s.VMKey]; live != nil {
pid = live.lastOverlayPID
}
a.sessionMu.Unlock()
}
if pid == 0 {
continue
}
if s.TakeoverPolicy == "lock" {
// Locked sessions only intercept input while actively running; pausing
// removes the PID immediately so the user can interact freely.
if s.InputLocked {
targets[pid] = host.TakeoverTarget{VMKey: s.VMKey, LockInput: true}
}
continue
}
targets[pid] = host.TakeoverTarget{VMKey: s.VMKey, LockInput: false}
}
a.sessionMu.Lock()
if a.sessionShuttingDown {
a.sessionMu.Unlock()
return
}
if a.takeoverMon == nil && len(targets) > 0 {
mon := host.NewTakeoverMonitor(a.handlePhysicalUserTakeover)
mon.SetOnHookError(func(err error) {
a.emitLog("", "[agent] takeover hook error: "+err.Error())
})
a.takeoverMon = mon
}
mon := a.takeoverMon
a.sessionMu.Unlock()
if mon != nil {
mon.SetTargetRules(targets)
}
}
func (a *App) syncAgentSessionsOnPoll() {
a.cleanupStaleCompletedOverlays()
sessions := a.activeAgentSessions()
if len(sessions) == 0 {
return
}
a.syncTakeoverTargets()
for _, s := range sessions {
a.refreshAgentSessionVisuals(s.VMKey)
}
}
func (a *App) cleanupStaleCompletedOverlays() {
a.sessionMu.Lock()
if len(a.completedOverlays) == 0 {
a.sessionMu.Unlock()
return
}
snapshot := make(map[string]completedOverlayEntry, len(a.completedOverlays))
for k, v := range a.completedOverlays {
snapshot[k] = v
}
a.sessionMu.Unlock()
for key, ent := range snapshot {
polled, ok := a.polledVMForDriver(ent.driverID, ent.vmName)
alive := ok && polled.State == "running" && polled.PID != nil && *polled.PID > 0
if !alive || (ent.pid > 0 && uint32(*polled.PID) != ent.pid) {
a.dismissCompletedOverlay(key)
}
}
}
func (a *App) closeAgentSessions() {
a.sessionMu.Lock()
a.sessionShuttingDown = true
mon := a.takeoverMon
a.takeoverMon = nil
ov := a.sessionOverlay
a.sessionOverlay = nil
sessions := a.agentSessions
a.agentSessions = nil
a.completedOverlays = nil
a.ephemeralVMAccess = nil
a.sessionMu.Unlock()
for _, s := range sessions {
s.cancel()
}
if mon != nil {
mon.Close()
}
if ov != nil {
ov.Close()
}
}
func (a *App) emitStateChangedEvent() {
a.emitStateChanged()
}
func (a *App) effectiveVMPhase(vm driver.VMInfo) string {
phase, err := a.effectiveVMPhaseStrict(vm)
if err != nil {
return computerUseVMPhase(vm)
}
return phase
}
// effectiveVMPhaseStrict resolves the VM's phase and fails closed when a
// PhaseReporter driver returns an error, except when an older sidecar driver
// reports RPCMethodNotFound (no `driver/phase` method), which is treated as no
// protected phase for backwards compatibility.
func (a *App) effectiveVMPhaseStrict(vm driver.VMInfo) (string, error) {
if vm.Phase == "" {
if pr, ok := a.driverFor(vm).(driver.PhaseReporter); ok {
pctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
phase, err := pr.Phase(pctx, vm.Name)
cancel()
if err != nil {
var rpcErr *plugin.RPCError
if errors.As(err, &rpcErr) && rpcErr.Code == plugin.RPCMethodNotFound {
return computerUseVMPhase(vm), nil
}
return "", err
}
vm.Phase = phase
}
}
// A Stambha boot volume or RAW image can start both Recovery and an installed
// system. Its presence alone cannot establish that automation is safe.
if vm.DriverID == driver.BuiltinStambhaDriverID && vm.Phase == "" {
return "", errors.New("Stambha does not report the guest installation phase")
}
return computerUseVMPhase(vm), nil
}