| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "reasonix/internal/control" |
| 7 | ) |
| 8 | |
| 9 | type imageCapabilitySnapshot interface{ ImageCapabilityChanged() bool } |
| 10 | |
| 11 | // Use the existing build/swap/lease boundary before accepting a new turn. |
| 12 | // A failed rebuild leaves the previous snapshot visible and rejects this turn. |
| 13 | func (a *App) refreshTabImageCapability(tab *WorkspaceTab) error { |
| 14 | a.runtimeRebuildMu.Lock() |
| 15 | defer a.runtimeRebuildMu.Unlock() |
| 16 | tab.turnStartMu.Lock() |
| 17 | defer tab.turnStartMu.Unlock() |
| 18 | current, ok := a.controllerForTab(tab).(imageCapabilitySnapshot) |
| 19 | if !ok || !current.ImageCapabilityChanged() { |
| 20 | return nil |
| 21 | } |
| 22 | if err := a.rebuildSettingTurnLocked("image input", tab, false, false); err != nil { |
| 23 | return fmt.Errorf("refresh image input configuration: %w", err) |
| 24 | } |
| 25 | return nil |
| 26 | } |
| 27 | |
| 28 | // tabTurnAdmission owns both locks acquired while a foreground turn starts. |
| 29 | type tabTurnAdmission struct { |
| 30 | app *App |
| 31 | tab *WorkspaceTab |
| 32 | released bool |
| 33 | } |
| 34 | |
| 35 | type turnFinishingWaiter interface { |
| 36 | TurnFinishingDone() (<-chan struct{}, bool) |
| 37 | } |
| 38 | |
| 39 | func (admission *tabTurnAdmission) finish(ctrl control.SessionAPI) bool { |
| 40 | if admission == nil || admission.released { |
| 41 | return false |
| 42 | } |
| 43 | admission.released = true |
| 44 | tab := admission.tab |
| 45 | if tab != nil { |
| 46 | // Defers preserve lock release if RuntimeStatus panics. |
| 47 | defer admission.app.runtimeAdmissionMu.RUnlock() |
| 48 | defer tab.turnStartMu.Unlock() |
| 49 | } |
| 50 | started := false |
| 51 | if runtime, ok := ctrl.(control.RuntimeStateReader); ok { |
| 52 | // Maintenance is foreground work, but ends with SessionOperation rather |
| 53 | // than TurnDone. Read both fields from one snapshot so completion cannot |
| 54 | // leave a stale turn reservation between separate status reads. |
| 55 | state := runtime.RuntimeStateSnapshot() |
| 56 | started = state.Running && state.Maintenance == nil |
| 57 | } else if ctrl != nil { |
| 58 | started = ctrl.RuntimeStatus().Running |
| 59 | } |
| 60 | if !started && tab != nil && tab.sink != nil { |
| 61 | tab.sink.cancelTurnStart() |
| 62 | } |
| 63 | return started |
| 64 | } |
| 65 | |
| 66 | func (admission *tabTurnAdmission) abort() { |
| 67 | admission.finish(nil) |
| 68 | } |
| 69 | |
| 70 | // beginTabTurn reserves one tab until its TurnDone fan-out completes. |
| 71 | func (a *App) beginTabTurn(tabID string, reclaim bool, submissionID ...string) (*tabTurnAdmission, control.SessionAPI, error) { |
| 72 | return a.beginRuntimeTurnChecked(tabID, reclaim, false, identifiedSubmissionCheck(submissionID), submissionID...) |
| 73 | } |
| 74 | |
| 75 | func (a *App) beginRuntimeTurn(tabID string, reclaim, detached bool, submissionID ...string) (*tabTurnAdmission, control.SessionAPI, error) { |
| 76 | return a.beginRuntimeTurnChecked(tabID, reclaim, detached, nil, submissionID...) |
| 77 | } |
| 78 | |
| 79 | func checkRuntimeAdmission(ctrl control.SessionAPI, check func(control.SessionAPI) error) error { |
| 80 | if check == nil { |
| 81 | return nil |
| 82 | } |
| 83 | return check(ctrl) |
| 84 | } |
| 85 | |
| 86 | func controllerAuthenticationError(ctrl control.SessionAPI) error { |
| 87 | authentication, ok := ctrl.(interface { |
| 88 | AuthenticationState() control.AuthenticationState |
| 89 | }) |
| 90 | if !ok { |
| 91 | return nil |
| 92 | } |
| 93 | state := authentication.AuthenticationState() |
| 94 | if state.Ready() { |
| 95 | return nil |
| 96 | } |
| 97 | return &control.AuthenticationError{State: state} |
| 98 | } |
| 99 | |
| 100 | // check observes the selected controller under the same admission locks as the |
| 101 | // running check and submit. A refusal must carry this owner's identity with it. |
| 102 | func (a *App) beginRuntimeTurnChecked(tabID string, reclaim, detached bool, check func(control.SessionAPI) error, submissionID ...string) (*tabTurnAdmission, control.SessionAPI, error) { |
| 103 | return a.beginRuntimeTurnWithModelChoice(tabID, reclaim, detached, check, nil, submissionID...) |
| 104 | } |
| 105 | |
| 106 | func (a *App) beginRuntimeTurnWithModelChoice(tabID string, reclaim, detached bool, check func(control.SessionAPI) error, choice *control.ModelApplicationChoice, submissionID ...string) (*tabTurnAdmission, control.SessionAPI, error) { |
| 107 | for { |
| 108 | tab, ctrl := a.tabAndCtrlByID(tabID) |
| 109 | if detached { |
| 110 | a.mu.RLock() |
| 111 | tab = a.tabByEventSinkIDLocked(tabID) |
| 112 | ctrl = nil |
| 113 | if tab != nil { |
| 114 | ctrl = tab.Ctrl |
| 115 | } |
| 116 | a.mu.RUnlock() |
| 117 | } |
| 118 | if a.tabIsReadOnly(tab) { |
| 119 | return nil, nil, readOnlyChannelErr() |
| 120 | } |
| 121 | if err := a.workspaceRuntimeAdmissionErr(tab, ctrl); err != nil { |
| 122 | return nil, nil, err |
| 123 | } |
| 124 | // Slow workspace repair stays outside the runtime admission barrier. |
| 125 | if err := a.ensureTabControllerWorkspace(tab); err != nil { |
| 126 | return nil, nil, err |
| 127 | } |
| 128 | |
| 129 | a.runtimeAdmissionMu.RLock() |
| 130 | abort := func() { |
| 131 | tab.turnStartMu.Unlock() |
| 132 | a.runtimeAdmissionMu.RUnlock() |
| 133 | } |
| 134 | tab.turnStartMu.Lock() |
| 135 | if err := a.validateDraftAdmission(tab, firstSubmissionID(submissionID)); err != nil { |
| 136 | abort() |
| 137 | return nil, nil, err |
| 138 | } |
| 139 | if a.tabIsReadOnly(tab) { |
| 140 | abort() |
| 141 | return nil, nil, readOnlyChannelErr() |
| 142 | } |
| 143 | if reclaim && a.botBridge != nil { |
| 144 | a.botBridge.reclaimFromDesktop(tab.ID) |
| 145 | } |
| 146 | ctrl = a.controllerForTab(tab) |
| 147 | if err := a.workspaceRuntimeAdmissionErr(tab, ctrl); err != nil { |
| 148 | abort() |
| 149 | return nil, nil, err |
| 150 | } |
| 151 | ctrl = a.controllerForTab(tab) |
| 152 | if err := a.workspaceRuntimeAdmissionErr(tab, ctrl); err != nil { |
| 153 | abort() |
| 154 | return nil, nil, err |
| 155 | } |
| 156 | running := ctrl.RuntimeStatus().Running |
| 157 | if err := checkRuntimeAdmission(ctrl, check); err != nil { |
| 158 | abort() |
| 159 | return nil, nil, err |
| 160 | } |
| 161 | if running { |
| 162 | if waiter, ok := ctrl.(turnFinishingWaiter); ok { |
| 163 | if done, finishing := waiter.TurnFinishingDone(); finishing { |
| 164 | // Re-resolve after waiting so close/switch cannot misroute retry. |
| 165 | abort() |
| 166 | <-done |
| 167 | continue |
| 168 | } |
| 169 | // Fan-out can end between RuntimeStatus and TurnFinishingDone. |
| 170 | // Re-check before reporting busy so that completed boundary retries |
| 171 | // instead of preserving the original false rejection window. |
| 172 | if !ctrl.RuntimeStatus().Running { |
| 173 | abort() |
| 174 | continue |
| 175 | } |
| 176 | } |
| 177 | abort() |
| 178 | return nil, nil, control.ErrTurnRunning |
| 179 | } |
| 180 | usingApplied, choiceErr := validateModelApplicationChoice(ctrl, choice) |
| 181 | if choiceErr != nil { |
| 182 | abort() |
| 183 | return nil, nil, choiceErr |
| 184 | } |
| 185 | if retry, err := a.applyTurnModelSettings(tab, ctrl, usingApplied, abort); retry || err != nil { |
| 186 | if err != nil { |
| 187 | return nil, nil, err |
| 188 | } |
| 189 | continue |
| 190 | } |
| 191 | if snapshot, ok := ctrl.(imageCapabilitySnapshot); a.ctx != nil && !usingApplied && ok && snapshot.ImageCapabilityChanged() { |
| 192 | a.mu.RLock() |
| 193 | draftPending := tab.PendingCreateOperationID != "" |
| 194 | a.mu.RUnlock() |
| 195 | abort() |
| 196 | if draftPending { |
| 197 | return nil, nil, fmt.Errorf("image configuration changed before draft admission") |
| 198 | } |
| 199 | if err := a.refreshTabImageCapability(tab); err != nil { |
| 200 | return nil, nil, err |
| 201 | } |
| 202 | continue |
| 203 | } |
| 204 | if err := controllerAuthenticationError(ctrl); err != nil { |
| 205 | abort() |
| 206 | return nil, nil, err |
| 207 | } |
| 208 | if tab.sink != nil && !tab.sink.tryBeginTurn(submissionID...) { |
| 209 | abort() |
| 210 | return nil, nil, control.ErrTurnRunning |
| 211 | } |
| 212 | if metadata, ok := ctrl.(interface { |
| 213 | SetTurnEventRoutingMetadata(runtimeEpoch, submissionID string) |
| 214 | }); ok { |
| 215 | epoch := "" |
| 216 | if tab.sink != nil { |
| 217 | epoch = tab.sink.runtimeEpochSnapshot() |
| 218 | } |
| 219 | metadata.SetTurnEventRoutingMetadata(epoch, firstSubmissionID(submissionID)) |
| 220 | } |
| 221 | return &tabTurnAdmission{app: a, tab: tab}, ctrl, nil |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // Durable follow-ups are new runs even when a controller dispatches them on |
| 226 | // its own after TurnDone. Resolve the runtime owner again after detach/attach. |
| 227 | func (a *App) beforeInboxDispatch(ctrl *control.Controller) (func(), error) { |
| 228 | a.mu.RLock() |
| 229 | var owner *WorkspaceTab |
| 230 | for _, tab := range a.runtimeTabsLocked() { |
| 231 | if tab.Ctrl == ctrl { |
| 232 | owner = tab |
| 233 | break |
| 234 | } |
| 235 | } |
| 236 | a.mu.RUnlock() |
| 237 | if owner == nil { |
| 238 | return nil, control.ErrInboxRuntimeUnpublished |
| 239 | } |
| 240 | admission, current, err := a.beginRuntimeTurn(owner.ID, false, true) |
| 241 | if err != nil { |
| 242 | return nil, err |
| 243 | } |
| 244 | if current != ctrl { |
| 245 | admission.abort() |
| 246 | if replacement, ok := current.(*control.Controller); ok { |
| 247 | go replacement.NotifyInboxRuntimeReady() |
| 248 | } |
| 249 | return nil, control.ErrInboxRuntimeUnpublished |
| 250 | } |
| 251 | return func() { admission.finish(ctrl) }, nil |
| 252 | } |
| 253 |