| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | tea "charm.land/bubbletea/v2" |
| 5 | |
| 6 | "reasonix/internal/control" |
| 7 | ) |
| 8 | |
| 9 | // An intent has not created a turn or run any submission hook. Its callback |
| 10 | // receives the activated controller, never the controller captured before I/O. |
| 11 | type controllerTurnIntent struct { |
| 12 | displayed, restore, queued string |
| 13 | start func(control.SessionAPI) |
| 14 | } |
| 15 | |
| 16 | type turnModelSettingsMsg struct { |
| 17 | ctrl control.SessionAPI |
| 18 | intent *controllerTurnIntent |
| 19 | changed bool |
| 20 | err error |
| 21 | } |
| 22 | |
| 23 | func (m *chatTUI) checkTurnModelSettings(intent controllerTurnIntent) (tea.Cmd, bool) { |
| 24 | if m.modelSwitchPending || m.turnSettingsIntent != nil { |
| 25 | m.restoreTurnDraft(intent) |
| 26 | m.notice("model settings are being applied; your draft has been preserved") |
| 27 | return nil, true |
| 28 | } |
| 29 | if owner, ok := m.ctrl.(interface{ TracksModelSettings() bool }); ok && !owner.TracksModelSettings() { |
| 30 | return nil, false |
| 31 | } |
| 32 | reader, ok := m.ctrl.(interface { |
| 33 | ModelSettingsState() (string, string, error) |
| 34 | }) |
| 35 | if !ok { |
| 36 | return nil, false |
| 37 | } |
| 38 | ctrl := m.ctrl |
| 39 | m.turnSettingsIntent = &intent |
| 40 | m.restoreTurnDraft(intent) |
| 41 | return func() tea.Msg { |
| 42 | applied, desired, err := reader.ModelSettingsState() |
| 43 | return turnModelSettingsMsg{ctrl: ctrl, intent: &intent, changed: applied != desired, err: err} |
| 44 | }, true |
| 45 | } |
| 46 | |
| 47 | func (m *chatTUI) restoreTurnDraft(intent controllerTurnIntent) { |
| 48 | if m.input.Value() == "" { |
| 49 | m.input.SetValue(intent.restore) |
| 50 | m.growInputToFit() |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | func (m *chatTUI) handleTurnModelSettings(msg turnModelSettingsMsg) tea.Cmd { |
| 55 | if m.turnSettingsIntent != msg.intent { |
| 56 | return nil |
| 57 | } |
| 58 | m.turnSettingsIntent = nil |
| 59 | if m.ctrl != msg.ctrl || m.modelSwitchPending { |
| 60 | return nil |
| 61 | } |
| 62 | if msg.err != nil { |
| 63 | m.notice("model settings: " + msg.err.Error()) |
| 64 | return nil |
| 65 | } |
| 66 | if msg.changed { |
| 67 | if !m.runtimeSettingChangeReady() { |
| 68 | return nil |
| 69 | } |
| 70 | cmd := m.scheduleCurrentControllerRebuild("model settings", "saved model settings applied") |
| 71 | if cmd == nil { |
| 72 | return nil |
| 73 | } |
| 74 | return func() tea.Msg { |
| 75 | result := cmd().(modelSwitchMsg) |
| 76 | result.resumeTurn = msg.intent |
| 77 | return result |
| 78 | } |
| 79 | } |
| 80 | return m.resumeControllerTurn(*msg.intent, true) |
| 81 | } |
| 82 | |
| 83 | func (m *chatTUI) resumeControllerTurn(intent controllerTurnIntent, checked bool) tea.Cmd { |
| 84 | if m.input.Value() == intent.restore { |
| 85 | m.input.SetValue("") |
| 86 | } |
| 87 | return m.prepareControllerTurn(intent, checked) |
| 88 | } |
| 89 |